gdb/monitor.c - gdb

Global variables defined

Functions defined

Macros defined

Source code

  1. /* Remote debugging interface for boot monitors, for GDB.

  2.    Copyright (C) 1990-2015 Free Software Foundation, Inc.

  3.    Contributed by Cygnus Support.  Written by Rob Savoye for Cygnus.
  4.    Resurrected from the ashes by Stu Grossman.

  5.    This file is part of GDB.

  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 3 of the License, or
  9.    (at your option) any later version.

  10.    This program is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.    GNU General Public License for more details.

  14.    You should have received a copy of the GNU General Public License
  15.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  16. /* This file was derived from various remote-* modules.  It is a collection
  17.    of generic support functions so GDB can talk directly to a ROM based
  18.    monitor.  This saves use from having to hack an exception based handler
  19.    into existence, and makes for quick porting.

  20.    This module talks to a debug monitor called 'MONITOR', which
  21.    We communicate with MONITOR via either a direct serial line, or a TCP
  22.    (or possibly TELNET) stream to a terminal multiplexor,
  23.    which in turn talks to the target board.  */

  24. /* FIXME 32x64: This code assumes that registers and addresses are at
  25.    most 32 bits long.  If they can be larger, you will need to declare
  26.    values as LONGEST and use %llx or some such to print values when
  27.    building commands to send to the monitor.  Since we don't know of
  28.    any actual 64-bit targets with ROM monitors that use this code,
  29.    it's not an issue right now.  -sts 4/18/96  */

  30. #include "defs.h"
  31. #include "gdbcore.h"
  32. #include "target.h"
  33. #include <signal.h>
  34. #include <ctype.h>
  35. #include <sys/types.h>
  36. #include "command.h"
  37. #include "serial.h"
  38. #include "monitor.h"
  39. #include "gdbcmd.h"
  40. #include "inferior.h"
  41. #include "infrun.h"
  42. #include "gdb_regex.h"
  43. #include "srec.h"
  44. #include "regcache.h"
  45. #include "gdbthread.h"
  46. #include "readline/readline.h"

  47. static char *dev_name;
  48. static struct target_ops *targ_ops;

  49. static void monitor_interrupt_query (void);
  50. static void monitor_interrupt_twice (int);
  51. static void monitor_stop (struct target_ops *self, ptid_t);
  52. static void monitor_dump_regs (struct regcache *regcache);

  53. #if 0
  54. static int from_hex (int a);
  55. #endif

  56. static struct monitor_ops *current_monitor;

  57. static int hashmark;                /* flag set by "set hash".  */

  58. static int timeout = 30;

  59. static int in_monitor_wait = 0;        /* Non-zero means we are in monitor_wait().  */

  60. static void (*ofunc) ();        /* Old SIGINT signal handler.  */

  61. static CORE_ADDR *breakaddr;

  62. /* Descriptor for I/O to remote machine.  Initialize it to NULL so
  63.    that monitor_open knows that we don't have a file open when the
  64.    program starts.  */

  65. static struct serial *monitor_desc = NULL;

  66. /* Pointer to regexp pattern matching data.  */

  67. static struct re_pattern_buffer register_pattern;
  68. static char register_fastmap[256];

  69. static struct re_pattern_buffer getmem_resp_delim_pattern;
  70. static char getmem_resp_delim_fastmap[256];

  71. static struct re_pattern_buffer setmem_resp_delim_pattern;
  72. static char setmem_resp_delim_fastmap[256];

  73. static struct re_pattern_buffer setreg_resp_delim_pattern;
  74. static char setreg_resp_delim_fastmap[256];

  75. static int dump_reg_flag;        /* Non-zero means do a dump_registers cmd when
  76.                                    monitor_wait wakes up.  */

  77. static int first_time = 0;        /* Is this the first time we're
  78.                                    executing after gaving created the
  79.                                    child proccess?  */


  80. /* This is the ptid we use while we're connected to a monitor.  Its
  81.    value is arbitrary, as monitor targets don't have a notion of
  82.    processes or threads, but we need something non-null to place in
  83.    inferior_ptid.  */
  84. static ptid_t monitor_ptid;

  85. #define TARGET_BUF_SIZE 2048

  86. /* Monitor specific debugging information.  Typically only useful to
  87.    the developer of a new monitor interface.  */

  88. static void monitor_debug (const char *fmt, ...) ATTRIBUTE_PRINTF (1, 2);

  89. static unsigned int monitor_debug_p = 0;

  90. /* NOTE: This file alternates between monitor_debug_p and remote_debug
  91.    when determining if debug information is printed.  Perhaps this
  92.    could be simplified.  */

  93. static void
  94. monitor_debug (const char *fmt, ...)
  95. {
  96.   if (monitor_debug_p)
  97.     {
  98.       va_list args;

  99.       va_start (args, fmt);
  100.       vfprintf_filtered (gdb_stdlog, fmt, args);
  101.       va_end (args);
  102.     }
  103. }


  104. /* Convert a string into a printable representation, Return # byte in
  105.    the new string.  When LEN is >0 it specifies the size of the
  106.    string.  Otherwize strlen(oldstr) is used.  */

  107. static void
  108. monitor_printable_string (char *newstr, char *oldstr, int len)
  109. {
  110.   int ch;
  111.   int i;

  112.   if (len <= 0)
  113.     len = strlen (oldstr);

  114.   for (i = 0; i < len; i++)
  115.     {
  116.       ch = oldstr[i];
  117.       switch (ch)
  118.         {
  119.         default:
  120.           if (isprint (ch))
  121.             *newstr++ = ch;

  122.           else
  123.             {
  124.               sprintf (newstr, "\\x%02x", ch & 0xff);
  125.               newstr += 4;
  126.             }
  127.           break;

  128.         case '\\':
  129.           *newstr++ = '\\';
  130.           *newstr++ = '\\';
  131.           break;
  132.         case '\b':
  133.           *newstr++ = '\\';
  134.           *newstr++ = 'b';
  135.           break;
  136.         case '\f':
  137.           *newstr++ = '\\';
  138.           *newstr++ = 't';
  139.           break;
  140.         case '\n':
  141.           *newstr++ = '\\';
  142.           *newstr++ = 'n';
  143.           break;
  144.         case '\r':
  145.           *newstr++ = '\\';
  146.           *newstr++ = 'r';
  147.           break;
  148.         case '\t':
  149.           *newstr++ = '\\';
  150.           *newstr++ = 't';
  151.           break;
  152.         case '\v':
  153.           *newstr++ = '\\';
  154.           *newstr++ = 'v';
  155.           break;
  156.         }
  157.     }

  158.   *newstr++ = '\0';
  159. }

  160. /* Print monitor errors with a string, converting the string to printable
  161.    representation.  */

  162. static void
  163. monitor_error (char *function, char *message,
  164.                CORE_ADDR memaddr, int len, char *string, int final_char)
  165. {
  166.   int real_len = (len == 0 && string != (char *) 0) ? strlen (string) : len;
  167.   char *safe_string = alloca ((real_len * 4) + 1);

  168.   monitor_printable_string (safe_string, string, real_len);

  169.   if (final_char)
  170.     error (_("%s (%s): %s: %s%c"),
  171.            function, paddress (target_gdbarch (), memaddr),
  172.            message, safe_string, final_char);
  173.   else
  174.     error (_("%s (%s): %s: %s"),
  175.            function, paddress (target_gdbarch (), memaddr),
  176.            message, safe_string);
  177. }

  178. /* Convert hex digit A to a number.  */

  179. static int
  180. fromhex (int a)
  181. {
  182.   if (a >= '0' && a <= '9')
  183.     return a - '0';
  184.   else if (a >= 'a' && a <= 'f')
  185.     return a - 'a' + 10;
  186.   else if (a >= 'A' && a <= 'F')
  187.     return a - 'A' + 10;
  188.   else
  189.     error (_("Invalid hex digit %d"), a);
  190. }

  191. /* monitor_vsprintf - similar to vsprintf but handles 64-bit addresses

  192.    This function exists to get around the problem that many host platforms
  193.    don't have a printf that can print 64-bit addresses.  The %A format
  194.    specification is recognized as a special case, and causes the argument
  195.    to be printed as a 64-bit hexadecimal address.

  196.    Only format specifiers of the form "[0-9]*[a-z]" are recognized.
  197.    If it is a '%s' format, the argument is a string; otherwise the
  198.    argument is assumed to be a long integer.

  199.    %% is also turned into a single %.  */

  200. static void
  201. monitor_vsprintf (char *sndbuf, char *pattern, va_list args)
  202. {
  203.   int addr_bit = gdbarch_addr_bit (target_gdbarch ());
  204.   char format[10];
  205.   char fmt;
  206.   char *p;
  207.   int i;
  208.   long arg_int;
  209.   CORE_ADDR arg_addr;
  210.   char *arg_string;

  211.   for (p = pattern; *p; p++)
  212.     {
  213.       if (*p == '%')
  214.         {
  215.           /* Copy the format specifier to a separate buffer.  */
  216.           format[0] = *p++;
  217.           for (i = 1; *p >= '0' && *p <= '9' && i < (int) sizeof (format) - 2;
  218.                i++, p++)
  219.             format[i] = *p;
  220.           format[i] = fmt = *p;
  221.           format[i + 1] = '\0';

  222.           /* Fetch the next argument and print it.  */
  223.           switch (fmt)
  224.             {
  225.             case '%':
  226.               strcpy (sndbuf, "%");
  227.               break;
  228.             case 'A':
  229.               arg_addr = va_arg (args, CORE_ADDR);
  230.               strcpy (sndbuf, phex_nz (arg_addr, addr_bit / 8));
  231.               break;
  232.             case 's':
  233.               arg_string = va_arg (args, char *);
  234.               sprintf (sndbuf, format, arg_string);
  235.               break;
  236.             default:
  237.               arg_int = va_arg (args, long);
  238.               sprintf (sndbuf, format, arg_int);
  239.               break;
  240.             }
  241.           sndbuf += strlen (sndbuf);
  242.         }
  243.       else
  244.         *sndbuf++ = *p;
  245.     }
  246.   *sndbuf = '\0';
  247. }


  248. /* monitor_printf_noecho -- Send data to monitor, but don't expect an echo.
  249.    Works just like printf.  */

  250. void
  251. monitor_printf_noecho (char *pattern,...)
  252. {
  253.   va_list args;
  254.   char sndbuf[2000];
  255.   int len;

  256.   va_start (args, pattern);

  257.   monitor_vsprintf (sndbuf, pattern, args);

  258.   len = strlen (sndbuf);
  259.   if (len + 1 > sizeof sndbuf)
  260.     internal_error (__FILE__, __LINE__,
  261.                     _("failed internal consistency check"));

  262.   if (monitor_debug_p)
  263.     {
  264.       char *safe_string = (char *) alloca ((strlen (sndbuf) * 4) + 1);

  265.       monitor_printable_string (safe_string, sndbuf, 0);
  266.       fprintf_unfiltered (gdb_stdlog, "sent[%s]\n", safe_string);
  267.     }

  268.   monitor_write (sndbuf, len);
  269. }

  270. /* monitor_printf -- Send data to monitor and check the echo.  Works just like
  271.    printf.  */

  272. void
  273. monitor_printf (char *pattern,...)
  274. {
  275.   va_list args;
  276.   char sndbuf[2000];
  277.   int len;

  278.   va_start (args, pattern);

  279.   monitor_vsprintf (sndbuf, pattern, args);

  280.   len = strlen (sndbuf);
  281.   if (len + 1 > sizeof sndbuf)
  282.     internal_error (__FILE__, __LINE__,
  283.                     _("failed internal consistency check"));

  284.   if (monitor_debug_p)
  285.     {
  286.       char *safe_string = (char *) alloca ((len * 4) + 1);

  287.       monitor_printable_string (safe_string, sndbuf, 0);
  288.       fprintf_unfiltered (gdb_stdlog, "sent[%s]\n", safe_string);
  289.     }

  290.   monitor_write (sndbuf, len);

  291.   /* We used to expect that the next immediate output was the
  292.      characters we just output, but sometimes some extra junk appeared
  293.      before the characters we expected, like an extra prompt, or a
  294.      portmaster sending telnet negotiations.  So, just start searching
  295.      for what we sent, and skip anything unknown.  */
  296.   monitor_debug ("ExpectEcho\n");
  297.   monitor_expect (sndbuf, (char *) 0, 0);
  298. }


  299. /* Write characters to the remote system.  */

  300. void
  301. monitor_write (char *buf, int buflen)
  302. {
  303.   if (serial_write (monitor_desc, buf, buflen))
  304.     fprintf_unfiltered (gdb_stderr, "serial_write failed: %s\n",
  305.                         safe_strerror (errno));
  306. }


  307. /* Read a binary character from the remote system, doing all the fancy
  308.    timeout stuff, but without interpreting the character in any way,
  309.    and without printing remote debug information.  */

  310. int
  311. monitor_readchar (void)
  312. {
  313.   int c;
  314.   int looping;

  315.   do
  316.     {
  317.       looping = 0;
  318.       c = serial_readchar (monitor_desc, timeout);

  319.       if (c >= 0)
  320.         c &= 0xff;                /* don't lose bit 7 */
  321.     }
  322.   while (looping);

  323.   if (c >= 0)
  324.     return c;

  325.   if (c == SERIAL_TIMEOUT)
  326.     error (_("Timeout reading from remote system."));

  327.   perror_with_name (_("remote-monitor"));
  328. }


  329. /* Read a character from the remote system, doing all the fancy
  330.    timeout stuff.  */

  331. static int
  332. readchar (int timeout)
  333. {
  334.   int c;
  335.   static enum
  336.     {
  337.       last_random, last_nl, last_cr, last_crnl
  338.     }
  339.   state = last_random;
  340.   int looping;

  341.   do
  342.     {
  343.       looping = 0;
  344.       c = serial_readchar (monitor_desc, timeout);

  345.       if (c >= 0)
  346.         {
  347.           c &= 0x7f;
  348.           /* This seems to interfere with proper function of the
  349.              input stream.  */
  350.           if (monitor_debug_p || remote_debug)
  351.             {
  352.               char buf[2];

  353.               buf[0] = c;
  354.               buf[1] = '\0';
  355.               puts_debug ("read -->", buf, "<--");
  356.             }

  357.         }

  358.       /* Canonicialize \n\r combinations into one \r.  */
  359.       if ((current_monitor->flags & MO_HANDLE_NL) != 0)
  360.         {
  361.           if ((c == '\r' && state == last_nl)
  362.               || (c == '\n' && state == last_cr))
  363.             {
  364.               state = last_crnl;
  365.               looping = 1;
  366.             }
  367.           else if (c == '\r')
  368.             state = last_cr;
  369.           else if (c != '\n')
  370.             state = last_random;
  371.           else
  372.             {
  373.               state = last_nl;
  374.               c = '\r';
  375.             }
  376.         }
  377.     }
  378.   while (looping);

  379.   if (c >= 0)
  380.     return c;

  381.   if (c == SERIAL_TIMEOUT)
  382. #if 0
  383.     /* I fail to see how detaching here can be useful.  */
  384.     if (in_monitor_wait)        /* Watchdog went off.  */
  385.       {
  386.         target_mourn_inferior ();
  387.         error (_("GDB serial timeout has expired.  Target detached."));
  388.       }
  389.     else
  390. #endif
  391.       error (_("Timeout reading from remote system."));

  392.   perror_with_name (_("remote-monitor"));
  393. }

  394. /* Scan input from the remote system, until STRING is found.  If BUF is non-
  395.    zero, then collect input until we have collected either STRING or BUFLEN-1
  396.    chars.  In either case we terminate BUF with a 0.  If input overflows BUF
  397.    because STRING can't be found, return -1, else return number of chars in BUF
  398.    (minus the terminating NUL).  Note that in the non-overflow case, STRING
  399.    will be at the end of BUF.  */

  400. int
  401. monitor_expect (char *string, char *buf, int buflen)
  402. {
  403.   char *p = string;
  404.   int obuflen = buflen;
  405.   int c;

  406.   if (monitor_debug_p)
  407.     {
  408.       char *safe_string = (char *) alloca ((strlen (string) * 4) + 1);
  409.       monitor_printable_string (safe_string, string, 0);
  410.       fprintf_unfiltered (gdb_stdlog, "MON Expecting '%s'\n", safe_string);
  411.     }

  412.   immediate_quit++;
  413.   QUIT;
  414.   while (1)
  415.     {
  416.       if (buf)
  417.         {
  418.           if (buflen < 2)
  419.             {
  420.               *buf = '\000';
  421.               immediate_quit--;
  422.               return -1;
  423.             }

  424.           c = readchar (timeout);
  425.           if (c == '\000')
  426.             continue;
  427.           *buf++ = c;
  428.           buflen--;
  429.         }
  430.       else
  431.         c = readchar (timeout);

  432.       /* Don't expect any ^C sent to be echoed.  */

  433.       if (*p == '\003' || c == *p)
  434.         {
  435.           p++;
  436.           if (*p == '\0')
  437.             {
  438.               immediate_quit--;

  439.               if (buf)
  440.                 {
  441.                   *buf++ = '\000';
  442.                   return obuflen - buflen;
  443.                 }
  444.               else
  445.                 return 0;
  446.             }
  447.         }
  448.       else
  449.         {
  450.           /* We got a character that doesn't match the string.  We need to
  451.              back up p, but how far?  If we're looking for "..howdy" and the
  452.              monitor sends "...howdy"?  There's certainly a match in there,
  453.              but when we receive the third ".", we won't find it if we just
  454.              restart the matching at the beginning of the string.

  455.              This is a Boyer-Moore kind of situation.  We want to reset P to
  456.              the end of the longest prefix of STRING that is a suffix of
  457.              what we've read so far.  In the example above, that would be
  458.              ".." --- the longest prefix of "..howdy" that is a suffix of
  459.              "...".  This longest prefix could be the empty string, if C
  460.              is nowhere to be found in STRING.

  461.              If this longest prefix is not the empty string, it must contain
  462.              C, so let's search from the end of STRING for instances of C,
  463.              and see if the portion of STRING before that is a suffix of
  464.              what we read before C.  Actually, we can search backwards from
  465.              p, since we know no prefix can be longer than that.

  466.              Note that we can use STRING itself, along with C, as a record
  467.              of what we've received so far.  :)  */
  468.           int i;

  469.           for (i = (p - string) - 1; i >= 0; i--)
  470.             if (string[i] == c)
  471.               {
  472.                 /* Is this prefix a suffix of what we've read so far?
  473.                    In other words, does
  474.                      string[0 .. i-1] == string[p - i, p - 1]?  */
  475.                 if (! memcmp (string, p - i, i))
  476.                   {
  477.                     p = string + i + 1;
  478.                     break;
  479.                   }
  480.               }
  481.           if (i < 0)
  482.             p = string;
  483.         }
  484.     }
  485. }

  486. /* Search for a regexp.  */

  487. static int
  488. monitor_expect_regexp (struct re_pattern_buffer *pat, char *buf, int buflen)
  489. {
  490.   char *mybuf;
  491.   char *p;

  492.   monitor_debug ("MON Expecting regexp\n");
  493.   if (buf)
  494.     mybuf = buf;
  495.   else
  496.     {
  497.       mybuf = alloca (TARGET_BUF_SIZE);
  498.       buflen = TARGET_BUF_SIZE;
  499.     }

  500.   p = mybuf;
  501.   while (1)
  502.     {
  503.       int retval;

  504.       if (p - mybuf >= buflen)
  505.         {                        /* Buffer about to overflow.  */

  506. /* On overflow, we copy the upper half of the buffer to the lower half.  Not
  507.    great, but it usually works...  */

  508.           memcpy (mybuf, mybuf + buflen / 2, buflen / 2);
  509.           p = mybuf + buflen / 2;
  510.         }

  511.       *p++ = readchar (timeout);

  512.       retval = re_search (pat, mybuf, p - mybuf, 0, p - mybuf, NULL);
  513.       if (retval >= 0)
  514.         return 1;
  515.     }
  516. }

  517. /* Keep discarding input until we see the MONITOR prompt.

  518.    The convention for dealing with the prompt is that you
  519.    o give your command
  520.    o *then* wait for the prompt.

  521.    Thus the last thing that a procedure does with the serial line will
  522.    be an monitor_expect_prompt().  Exception: monitor_resume does not
  523.    wait for the prompt, because the terminal is being handed over to
  524.    the inferior.  However, the next thing which happens after that is
  525.    a monitor_wait which does wait for the prompt.  Note that this
  526.    includes abnormal exit, e.g. error().  This is necessary to prevent
  527.    getting into states from which we can't recover.  */

  528. int
  529. monitor_expect_prompt (char *buf, int buflen)
  530. {
  531.   monitor_debug ("MON Expecting prompt\n");
  532.   return monitor_expect (current_monitor->prompt, buf, buflen);
  533. }

  534. /* Get N 32-bit words from remote, each preceded by a space, and put
  535.    them in registers starting at REGNO.  */

  536. #if 0
  537. static unsigned long
  538. get_hex_word (void)
  539. {
  540.   unsigned long val;
  541.   int i;
  542.   int ch;

  543.   do
  544.     ch = readchar (timeout);
  545.   while (isspace (ch));

  546.   val = from_hex (ch);

  547.   for (i = 7; i >= 1; i--)
  548.     {
  549.       ch = readchar (timeout);
  550.       if (!isxdigit (ch))
  551.         break;
  552.       val = (val << 4) | from_hex (ch);
  553.     }

  554.   return val;
  555. }
  556. #endif

  557. static void
  558. compile_pattern (char *pattern, struct re_pattern_buffer *compiled_pattern,
  559.                  char *fastmap)
  560. {
  561.   int tmp;
  562.   const char *val;

  563.   compiled_pattern->fastmap = fastmap;

  564.   tmp = re_set_syntax (RE_SYNTAX_EMACS);
  565.   val = re_compile_pattern (pattern,
  566.                             strlen (pattern),
  567.                             compiled_pattern);
  568.   re_set_syntax (tmp);

  569.   if (val)
  570.     error (_("compile_pattern: Can't compile pattern string `%s': %s!"),
  571.            pattern, val);

  572.   if (fastmap)
  573.     re_compile_fastmap (compiled_pattern);
  574. }

  575. /* Open a connection to a remote debugger.  NAME is the filename used
  576.    for communication.  */

  577. void
  578. monitor_open (const char *args, struct monitor_ops *mon_ops, int from_tty)
  579. {
  580.   const char *name;
  581.   char **p;
  582.   struct inferior *inf;

  583.   if (mon_ops->magic != MONITOR_OPS_MAGIC)
  584.     error (_("Magic number of monitor_ops struct wrong."));

  585.   targ_ops = mon_ops->target;
  586.   name = targ_ops->to_shortname;

  587.   if (!args)
  588.     error (_("Use `target %s DEVICE-NAME' to use a serial port, or\n\
  589. `target %s HOST-NAME:PORT-NUMBER' to use a network connection."), name, name);

  590.   target_preopen (from_tty);

  591.   /* Setup pattern for register dump.  */

  592.   if (mon_ops->register_pattern)
  593.     compile_pattern (mon_ops->register_pattern, &register_pattern,
  594.                      register_fastmap);

  595.   if (mon_ops->getmem.resp_delim)
  596.     compile_pattern (mon_ops->getmem.resp_delim, &getmem_resp_delim_pattern,
  597.                      getmem_resp_delim_fastmap);

  598.   if (mon_ops->setmem.resp_delim)
  599.     compile_pattern (mon_ops->setmem.resp_delim, &setmem_resp_delim_pattern,
  600.                      setmem_resp_delim_fastmap);

  601.   if (mon_ops->setreg.resp_delim)
  602.     compile_pattern (mon_ops->setreg.resp_delim, &setreg_resp_delim_pattern,
  603.                      setreg_resp_delim_fastmap);

  604.   unpush_target (targ_ops);

  605.   if (dev_name)
  606.     xfree (dev_name);
  607.   dev_name = xstrdup (args);

  608.   monitor_desc = serial_open (dev_name);

  609.   if (!monitor_desc)
  610.     perror_with_name (dev_name);

  611.   if (baud_rate != -1)
  612.     {
  613.       if (serial_setbaudrate (monitor_desc, baud_rate))
  614.         {
  615.           serial_close (monitor_desc);
  616.           perror_with_name (dev_name);
  617.         }
  618.     }

  619.   serial_raw (monitor_desc);

  620.   serial_flush_input (monitor_desc);

  621.   /* some systems only work with 2 stop bits.  */

  622.   serial_setstopbits (monitor_desc, mon_ops->stopbits);

  623.   current_monitor = mon_ops;

  624.   /* See if we can wake up the monitor.  First, try sending a stop sequence,
  625.      then send the init strings.  Last, remove all breakpoints.  */

  626.   if (current_monitor->stop)
  627.     {
  628.       monitor_stop (targ_ops, inferior_ptid);
  629.       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
  630.         {
  631.           monitor_debug ("EXP Open echo\n");
  632.           monitor_expect_prompt (NULL, 0);
  633.         }
  634.     }

  635.   /* wake up the monitor and see if it's alive.  */
  636.   for (p = mon_ops->init; *p != NULL; p++)
  637.     {
  638.       /* Some of the characters we send may not be echoed,
  639.          but we hope to get a prompt at the end of it all.  */

  640.       if ((current_monitor->flags & MO_NO_ECHO_ON_OPEN) == 0)
  641.         monitor_printf (*p);
  642.       else
  643.         monitor_printf_noecho (*p);
  644.       monitor_expect_prompt (NULL, 0);
  645.     }

  646.   serial_flush_input (monitor_desc);

  647.   /* Alloc breakpoints */
  648.   if (mon_ops->set_break != NULL)
  649.     {
  650.       if (mon_ops->num_breakpoints == 0)
  651.         mon_ops->num_breakpoints = 8;

  652.       breakaddr = (CORE_ADDR *)
  653.         xmalloc (mon_ops->num_breakpoints * sizeof (CORE_ADDR));
  654.       memset (breakaddr, 0, mon_ops->num_breakpoints * sizeof (CORE_ADDR));
  655.     }

  656.   /* Remove all breakpoints.  */

  657.   if (mon_ops->clr_all_break)
  658.     {
  659.       monitor_printf (mon_ops->clr_all_break);
  660.       monitor_expect_prompt (NULL, 0);
  661.     }

  662.   if (from_tty)
  663.     printf_unfiltered (_("Remote target %s connected to %s\n"),
  664.                        name, dev_name);

  665.   push_target (targ_ops);

  666.   /* Start afresh.  */
  667.   init_thread_list ();

  668.   /* Make run command think we are busy...  */
  669.   inferior_ptid = monitor_ptid;
  670.   inf = current_inferior ();
  671.   inferior_appeared (inf, ptid_get_pid (inferior_ptid));
  672.   add_thread_silent (inferior_ptid);

  673.   /* Give monitor_wait something to read.  */

  674.   monitor_printf (current_monitor->line_term);

  675.   init_wait_for_inferior ();

  676.   start_remote (from_tty);
  677. }

  678. /* Close out all files and local state before this target loses
  679.    control.  */

  680. void
  681. monitor_close (struct target_ops *self)
  682. {
  683.   if (monitor_desc)
  684.     serial_close (monitor_desc);

  685.   /* Free breakpoint memory.  */
  686.   if (breakaddr != NULL)
  687.     {
  688.       xfree (breakaddr);
  689.       breakaddr = NULL;
  690.     }

  691.   monitor_desc = NULL;

  692.   delete_thread_silent (monitor_ptid);
  693.   delete_inferior_silent (ptid_get_pid (monitor_ptid));
  694. }

  695. /* Terminate the open connection to the remote debugger.  Use this
  696.    when you want to detach and do something else with your gdb.  */

  697. static void
  698. monitor_detach (struct target_ops *ops, const char *args, int from_tty)
  699. {
  700.   unpush_target (ops);                /* calls monitor_close to do the real work.  */
  701.   if (from_tty)
  702.     printf_unfiltered (_("Ending remote %s debugging\n"), target_shortname);
  703. }

  704. /* Convert VALSTR into the target byte-ordered value of REGNO and store it.  */

  705. char *
  706. monitor_supply_register (struct regcache *regcache, int regno, char *valstr)
  707. {
  708.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  709.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  710.   ULONGEST val;
  711.   unsigned char regbuf[MAX_REGISTER_SIZE];
  712.   char *p;

  713.   val = 0;
  714.   p = valstr;
  715.   while (p && *p != '\0')
  716.     {
  717.       if (*p == '\r' || *p == '\n')
  718.         {
  719.           while (*p != '\0')
  720.               p++;
  721.           break;
  722.         }
  723.       if (isspace (*p))
  724.         {
  725.           p++;
  726.           continue;
  727.         }
  728.       if (!isxdigit (*p) && *p != 'x')
  729.         {
  730.           break;
  731.         }

  732.       val <<= 4;
  733.       val += fromhex (*p++);
  734.     }
  735.   monitor_debug ("Supplying Register %d %s\n", regno, valstr);

  736.   if (val == 0 && valstr == p)
  737.     error (_("monitor_supply_register (%d):  bad value from monitor: %s."),
  738.            regno, valstr);

  739.   /* supply register stores in target byte order, so swap here.  */

  740.   store_unsigned_integer (regbuf, register_size (gdbarch, regno), byte_order,
  741.                           val);

  742.   regcache_raw_supply (regcache, regno, regbuf);

  743.   return p;
  744. }

  745. /* Tell the remote machine to resume.  */

  746. static void
  747. monitor_resume (struct target_ops *ops,
  748.                 ptid_t ptid, int step, enum gdb_signal sig)
  749. {
  750.   /* Some monitors require a different command when starting a program.  */
  751.   monitor_debug ("MON resume\n");
  752.   if (current_monitor->flags & MO_RUN_FIRST_TIME && first_time == 1)
  753.     {
  754.       first_time = 0;
  755.       monitor_printf ("run\r");
  756.       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
  757.         dump_reg_flag = 1;
  758.       return;
  759.     }
  760.   if (step)
  761.     monitor_printf (current_monitor->step);
  762.   else
  763.     {
  764.       if (current_monitor->continue_hook)
  765.         (*current_monitor->continue_hook) ();
  766.       else
  767.         monitor_printf (current_monitor->cont);
  768.       if (current_monitor->flags & MO_NEED_REGDUMP_AFTER_CONT)
  769.         dump_reg_flag = 1;
  770.     }
  771. }

  772. /* Parse the output of a register dump command.  A monitor specific
  773.    regexp is used to extract individual register descriptions of the
  774.    form REG=VAL.  Each description is split up into a name and a value
  775.    string which are passed down to monitor specific code.  */

  776. static void
  777. parse_register_dump (struct regcache *regcache, char *buf, int len)
  778. {
  779.   monitor_debug ("MON Parsing  register dump\n");
  780.   while (1)
  781.     {
  782.       int regnamelen, vallen;
  783.       char *regname, *val;

  784.       /* Element 0 points to start of register name, and element 1
  785.          points to the start of the register value.  */
  786.       struct re_registers register_strings;

  787.       memset (&register_strings, 0, sizeof (struct re_registers));

  788.       if (re_search (&register_pattern, buf, len, 0, len,
  789.                      &register_strings) == -1)
  790.         break;

  791.       regnamelen = register_strings.end[1] - register_strings.start[1];
  792.       regname = buf + register_strings.start[1];
  793.       vallen = register_strings.end[2] - register_strings.start[2];
  794.       val = buf + register_strings.start[2];

  795.       current_monitor->supply_register (regcache, regname, regnamelen,
  796.                                         val, vallen);

  797.       buf += register_strings.end[0];
  798.       len -= register_strings.end[0];
  799.     }
  800. }

  801. /* Send ^C to target to halt it.  Target will respond, and send us a
  802.    packet.  */

  803. static void
  804. monitor_interrupt (int signo)
  805. {
  806.   /* If this doesn't work, try more severe steps.  */
  807.   signal (signo, monitor_interrupt_twice);

  808.   if (monitor_debug_p || remote_debug)
  809.     fprintf_unfiltered (gdb_stdlog, "monitor_interrupt called\n");

  810.   target_stop (inferior_ptid);
  811. }

  812. /* The user typed ^C twice.  */

  813. static void
  814. monitor_interrupt_twice (int signo)
  815. {
  816.   signal (signo, ofunc);

  817.   monitor_interrupt_query ();

  818.   signal (signo, monitor_interrupt);
  819. }

  820. /* Ask the user what to do when an interrupt is received.  */

  821. static void
  822. monitor_interrupt_query (void)
  823. {
  824.   target_terminal_ours ();

  825.   if (query (_("Interrupted while waiting for the program.\n\
  826. Give up (and stop debugging it)? ")))
  827.     {
  828.       target_mourn_inferior ();
  829.       quit ();
  830.     }

  831.   target_terminal_inferior ();
  832. }

  833. static void
  834. monitor_wait_cleanup (void *old_timeout)
  835. {
  836.   timeout = *(int *) old_timeout;
  837.   signal (SIGINT, ofunc);
  838.   in_monitor_wait = 0;
  839. }



  840. static void
  841. monitor_wait_filter (char *buf,
  842.                      int bufmax,
  843.                      int *ext_resp_len,
  844.                      struct target_waitstatus *status)
  845. {
  846.   int resp_len;

  847.   do
  848.     {
  849.       resp_len = monitor_expect_prompt (buf, bufmax);
  850.       *ext_resp_len = resp_len;

  851.       if (resp_len <= 0)
  852.         fprintf_unfiltered (gdb_stderr,
  853.                             "monitor_wait:  excessive "
  854.                             "response from monitor: %s.", buf);
  855.     }
  856.   while (resp_len < 0);

  857.   /* Print any output characters that were preceded by ^O.  */
  858.   /* FIXME - This would be great as a user settabgle flag.  */
  859.   if (monitor_debug_p || remote_debug
  860.       || current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
  861.     {
  862.       int i;

  863.       for (i = 0; i < resp_len - 1; i++)
  864.         if (buf[i] == 0x0f)
  865.           putchar_unfiltered (buf[++i]);
  866.     }
  867. }



  868. /* Wait until the remote machine stops, then return, storing status in
  869.    status just as `wait' would.  */

  870. static ptid_t
  871. monitor_wait (struct target_ops *ops,
  872.               ptid_t ptid, struct target_waitstatus *status, int options)
  873. {
  874.   int old_timeout = timeout;
  875.   char buf[TARGET_BUF_SIZE];
  876.   int resp_len;
  877.   struct cleanup *old_chain;

  878.   status->kind = TARGET_WAITKIND_EXITED;
  879.   status->value.integer = 0;

  880.   old_chain = make_cleanup (monitor_wait_cleanup, &old_timeout);
  881.   monitor_debug ("MON wait\n");

  882. #if 0
  883.   /* This is somthing other than a maintenance command.  */
  884.     in_monitor_wait = 1;
  885.   timeout = watchdog > 0 ? watchdog : -1;
  886. #else
  887.   timeout = -1;                /* Don't time out -- user program is running.  */
  888. #endif

  889.   ofunc = (void (*)()) signal (SIGINT, monitor_interrupt);

  890.   if (current_monitor->wait_filter)
  891.     (*current_monitor->wait_filter) (buf, sizeof (buf), &resp_len, status);
  892.   else
  893.     monitor_wait_filter (buf, sizeof (buf), &resp_len, status);

  894. #if 0                                /* Transferred to monitor wait filter.  */
  895.   do
  896.     {
  897.       resp_len = monitor_expect_prompt (buf, sizeof (buf));

  898.       if (resp_len <= 0)
  899.         fprintf_unfiltered (gdb_stderr,
  900.                             "monitor_wait:  excessive "
  901.                             "response from monitor: %s.", buf);
  902.     }
  903.   while (resp_len < 0);

  904.   /* Print any output characters that were preceded by ^O.  */
  905.   /* FIXME - This would be great as a user settabgle flag.  */
  906.   if (monitor_debug_p || remote_debug
  907.       || current_monitor->flags & MO_PRINT_PROGRAM_OUTPUT)
  908.     {
  909.       int i;

  910.       for (i = 0; i < resp_len - 1; i++)
  911.         if (buf[i] == 0x0f)
  912.           putchar_unfiltered (buf[++i]);
  913.     }
  914. #endif

  915.   signal (SIGINT, ofunc);

  916.   timeout = old_timeout;
  917. #if 0
  918.   if (dump_reg_flag && current_monitor->dump_registers)
  919.     {
  920.       dump_reg_flag = 0;
  921.       monitor_printf (current_monitor->dump_registers);
  922.       resp_len = monitor_expect_prompt (buf, sizeof (buf));
  923.     }

  924.   if (current_monitor->register_pattern)
  925.     parse_register_dump (get_current_regcache (), buf, resp_len);
  926. #else
  927.   monitor_debug ("Wait fetching registers after stop\n");
  928.   monitor_dump_regs (get_current_regcache ());
  929. #endif

  930.   status->kind = TARGET_WAITKIND_STOPPED;
  931.   status->value.sig = GDB_SIGNAL_TRAP;

  932.   discard_cleanups (old_chain);

  933.   in_monitor_wait = 0;

  934.   return inferior_ptid;
  935. }

  936. /* Fetch register REGNO, or all registers if REGNO is -1.  Returns
  937.    errno value.  */

  938. static void
  939. monitor_fetch_register (struct regcache *regcache, int regno)
  940. {
  941.   const char *name;
  942.   char *zerobuf;
  943.   char *regbuf;
  944.   int i;

  945.   regbuf  = alloca (MAX_REGISTER_SIZE * 2 + 1);
  946.   zerobuf = alloca (MAX_REGISTER_SIZE);
  947.   memset (zerobuf, 0, MAX_REGISTER_SIZE);

  948.   if (current_monitor->regname != NULL)
  949.     name = current_monitor->regname (regno);
  950.   else
  951.     name = current_monitor->regnames[regno];
  952.   monitor_debug ("MON fetchreg %d '%s'\n", regno, name ? name : "(null name)");

  953.   if (!name || (*name == '\0'))
  954.     {
  955.       monitor_debug ("No register known for %d\n", regno);
  956.       regcache_raw_supply (regcache, regno, zerobuf);
  957.       return;
  958.     }

  959.   /* Send the register examine command.  */

  960.   monitor_printf (current_monitor->getreg.cmd, name);

  961.   /* If RESP_DELIM is specified, we search for that as a leading
  962.      delimiter for the register value.  Otherwise, we just start
  963.      searching from the start of the buf.  */

  964.   if (current_monitor->getreg.resp_delim)
  965.     {
  966.       monitor_debug ("EXP getreg.resp_delim\n");
  967.       monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
  968.       /* Handle case of first 32 registers listed in pairs.  */
  969.       if (current_monitor->flags & MO_32_REGS_PAIRED
  970.           && (regno & 1) != 0 && regno < 32)
  971.         {
  972.           monitor_debug ("EXP getreg.resp_delim\n");
  973.           monitor_expect (current_monitor->getreg.resp_delim, NULL, 0);
  974.         }
  975.     }

  976.   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set.  */
  977.   if (current_monitor->flags & MO_HEX_PREFIX)
  978.     {
  979.       int c;

  980.       c = readchar (timeout);
  981.       while (c == ' ')
  982.         c = readchar (timeout);
  983.       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
  984.         ;
  985.       else
  986.         error (_("Bad value returned from monitor "
  987.                  "while fetching register %x."),
  988.                regno);
  989.     }

  990.   /* Read upto the maximum number of hex digits for this register, skipping
  991.      spaces, but stop reading if something else is seen.  Some monitors
  992.      like to drop leading zeros.  */

  993.   for (i = 0; i < register_size (get_regcache_arch (regcache), regno) * 2; i++)
  994.     {
  995.       int c;

  996.       c = readchar (timeout);
  997.       while (c == ' ')
  998.         c = readchar (timeout);

  999.       if (!isxdigit (c))
  1000.         break;

  1001.       regbuf[i] = c;
  1002.     }

  1003.   regbuf[i] = '\000';                /* Terminate the number.  */
  1004.   monitor_debug ("REGVAL '%s'\n", regbuf);

  1005.   /* If TERM is present, we wait for that to show up.  Also, (if TERM
  1006.      is present), we will send TERM_CMD if that is present.  In any
  1007.      case, we collect all of the output into buf, and then wait for
  1008.      the normal prompt.  */

  1009.   if (current_monitor->getreg.term)
  1010.     {
  1011.       monitor_debug ("EXP getreg.term\n");
  1012.       monitor_expect (current_monitor->getreg.term, NULL, 0); /* Get
  1013.                                                                  response.  */
  1014.     }

  1015.   if (current_monitor->getreg.term_cmd)
  1016.     {
  1017.       monitor_debug ("EMIT getreg.term.cmd\n");
  1018.       monitor_printf (current_monitor->getreg.term_cmd);
  1019.     }
  1020.   if (!current_monitor->getreg.term ||        /* Already expected or */
  1021.       current_monitor->getreg.term_cmd)                /* ack expected.  */
  1022.     monitor_expect_prompt (NULL, 0);        /* Get response.  */

  1023.   monitor_supply_register (regcache, regno, regbuf);
  1024. }

  1025. /* Sometimes, it takes several commands to dump the registers.  */
  1026. /* This is a primitive for use by variations of monitor interfaces in
  1027.    case they need to compose the operation.  */

  1028. int
  1029. monitor_dump_reg_block (struct regcache *regcache, char *block_cmd)
  1030. {
  1031.   char buf[TARGET_BUF_SIZE];
  1032.   int resp_len;

  1033.   monitor_printf (block_cmd);
  1034.   resp_len = monitor_expect_prompt (buf, sizeof (buf));
  1035.   parse_register_dump (regcache, buf, resp_len);
  1036.   return 1;
  1037. }


  1038. /* Read the remote registers into the block regs.  */
  1039. /* Call the specific function if it has been provided.  */

  1040. static void
  1041. monitor_dump_regs (struct regcache *regcache)
  1042. {
  1043.   char buf[TARGET_BUF_SIZE];
  1044.   int resp_len;

  1045.   if (current_monitor->dumpregs)
  1046.     (*(current_monitor->dumpregs)) (regcache);        /* Call supplied function.  */
  1047.   else if (current_monitor->dump_registers)        /* Default version.  */
  1048.     {
  1049.       monitor_printf (current_monitor->dump_registers);
  1050.       resp_len = monitor_expect_prompt (buf, sizeof (buf));
  1051.       parse_register_dump (regcache, buf, resp_len);
  1052.     }
  1053.   else
  1054.     /* Need some way to read registers.  */
  1055.     internal_error (__FILE__, __LINE__,
  1056.                     _("failed internal consistency check"));
  1057. }

  1058. static void
  1059. monitor_fetch_registers (struct target_ops *ops,
  1060.                          struct regcache *regcache, int regno)
  1061. {
  1062.   monitor_debug ("MON fetchregs\n");
  1063.   if (current_monitor->getreg.cmd)
  1064.     {
  1065.       if (regno >= 0)
  1066.         {
  1067.           monitor_fetch_register (regcache, regno);
  1068.           return;
  1069.         }

  1070.       for (regno = 0; regno < gdbarch_num_regs (get_regcache_arch (regcache));
  1071.            regno++)
  1072.         monitor_fetch_register (regcache, regno);
  1073.     }
  1074.   else
  1075.     {
  1076.       monitor_dump_regs (regcache);
  1077.     }
  1078. }

  1079. /* Store register REGNO, or all if REGNO == 0.  Return errno value.  */

  1080. static void
  1081. monitor_store_register (struct regcache *regcache, int regno)
  1082. {
  1083.   int reg_size = register_size (get_regcache_arch (regcache), regno);
  1084.   const char *name;
  1085.   ULONGEST val;

  1086.   if (current_monitor->regname != NULL)
  1087.     name = current_monitor->regname (regno);
  1088.   else
  1089.     name = current_monitor->regnames[regno];

  1090.   if (!name || (*name == '\0'))
  1091.     {
  1092.       monitor_debug ("MON Cannot store unknown register\n");
  1093.       return;
  1094.     }

  1095.   regcache_cooked_read_unsigned (regcache, regno, &val);
  1096.   monitor_debug ("MON storeg %d %s\n", regno, phex (val, reg_size));

  1097.   /* Send the register deposit command.  */

  1098.   if (current_monitor->flags & MO_REGISTER_VALUE_FIRST)
  1099.     monitor_printf (current_monitor->setreg.cmd, val, name);
  1100.   else if (current_monitor->flags & MO_SETREG_INTERACTIVE)
  1101.     monitor_printf (current_monitor->setreg.cmd, name);
  1102.   else
  1103.     monitor_printf (current_monitor->setreg.cmd, name, val);

  1104.   if (current_monitor->setreg.resp_delim)
  1105.     {
  1106.       monitor_debug ("EXP setreg.resp_delim\n");
  1107.       monitor_expect_regexp (&setreg_resp_delim_pattern, NULL, 0);
  1108.       if (current_monitor->flags & MO_SETREG_INTERACTIVE)
  1109.         monitor_printf ("%s\r", phex_nz (val, reg_size));
  1110.     }
  1111.   if (current_monitor->setreg.term)
  1112.     {
  1113.       monitor_debug ("EXP setreg.term\n");
  1114.       monitor_expect (current_monitor->setreg.term, NULL, 0);
  1115.       if (current_monitor->flags & MO_SETREG_INTERACTIVE)
  1116.         monitor_printf ("%s\r", phex_nz (val, reg_size));
  1117.       monitor_expect_prompt (NULL, 0);
  1118.     }
  1119.   else
  1120.     monitor_expect_prompt (NULL, 0);
  1121.   if (current_monitor->setreg.term_cmd)                /* Mode exit required.  */
  1122.     {
  1123.       monitor_debug ("EXP setreg_termcmd\n");
  1124.       monitor_printf ("%s", current_monitor->setreg.term_cmd);
  1125.       monitor_expect_prompt (NULL, 0);
  1126.     }
  1127. }                                /* monitor_store_register */

  1128. /* Store the remote registers.  */

  1129. static void
  1130. monitor_store_registers (struct target_ops *ops,
  1131.                          struct regcache *regcache, int regno)
  1132. {
  1133.   if (regno >= 0)
  1134.     {
  1135.       monitor_store_register (regcache, regno);
  1136.       return;
  1137.     }

  1138.   for (regno = 0; regno < gdbarch_num_regs (get_regcache_arch (regcache));
  1139.        regno++)
  1140.     monitor_store_register (regcache, regno);
  1141. }

  1142. /* Get ready to modify the registers array.  On machines which store
  1143.    individual registers, this doesn't need to do anything.  On machines
  1144.    which store all the registers in one fell swoop, this makes sure
  1145.    that registers contains all the registers from the program being
  1146.    debugged.  */

  1147. static void
  1148. monitor_prepare_to_store (struct target_ops *self, struct regcache *regcache)
  1149. {
  1150.   /* Do nothing, since we can store individual regs.  */
  1151. }

  1152. static void
  1153. monitor_files_info (struct target_ops *ops)
  1154. {
  1155.   printf_unfiltered (_("\tAttached to %s at %d baud.\n"), dev_name, baud_rate);
  1156. }

  1157. static int
  1158. monitor_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
  1159. {
  1160.   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
  1161.   unsigned int val, hostval;
  1162.   char *cmd;
  1163.   int i;

  1164.   monitor_debug ("MON write %d %s\n", len, paddress (target_gdbarch (), memaddr));

  1165.   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
  1166.     memaddr = gdbarch_addr_bits_remove (target_gdbarch (), memaddr);

  1167.   /* Use memory fill command for leading 0 bytes.  */

  1168.   if (current_monitor->fill)
  1169.     {
  1170.       for (i = 0; i < len; i++)
  1171.         if (myaddr[i] != 0)
  1172.           break;

  1173.       if (i > 4)                /* More than 4 zeros is worth doing.  */
  1174.         {
  1175.           monitor_debug ("MON FILL %d\n", i);
  1176.           if (current_monitor->flags & MO_FILL_USES_ADDR)
  1177.             monitor_printf (current_monitor->fill, memaddr,
  1178.                             (memaddr + i) - 1, 0);
  1179.           else
  1180.             monitor_printf (current_monitor->fill, memaddr, i, 0);

  1181.           monitor_expect_prompt (NULL, 0);

  1182.           return i;
  1183.         }
  1184.     }

  1185. #if 0
  1186.   /* Can't actually use long longs if VAL is an int (nice idea, though).  */
  1187.   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->setmem.cmdll)
  1188.     {
  1189.       len = 8;
  1190.       cmd = current_monitor->setmem.cmdll;
  1191.     }
  1192.   else
  1193. #endif
  1194.   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->setmem.cmdl)
  1195.     {
  1196.       len = 4;
  1197.       cmd = current_monitor->setmem.cmdl;
  1198.     }
  1199.   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->setmem.cmdw)
  1200.     {
  1201.       len = 2;
  1202.       cmd = current_monitor->setmem.cmdw;
  1203.     }
  1204.   else
  1205.     {
  1206.       len = 1;
  1207.       cmd = current_monitor->setmem.cmdb;
  1208.     }

  1209.   val = extract_unsigned_integer (myaddr, len, byte_order);

  1210.   if (len == 4)
  1211.     {
  1212.       hostval = *(unsigned int *) myaddr;
  1213.       monitor_debug ("Hostval(%08x) val(%08x)\n", hostval, val);
  1214.     }


  1215.   if (current_monitor->flags & MO_NO_ECHO_ON_SETMEM)
  1216.     monitor_printf_noecho (cmd, memaddr, val);
  1217.   else if (current_monitor->flags & MO_SETMEM_INTERACTIVE)
  1218.     {
  1219.       monitor_printf_noecho (cmd, memaddr);

  1220.       if (current_monitor->setmem.resp_delim)
  1221.         {
  1222.           monitor_debug ("EXP setmem.resp_delim");
  1223.           monitor_expect_regexp (&setmem_resp_delim_pattern, NULL, 0);
  1224.           monitor_printf ("%x\r", val);
  1225.        }
  1226.       if (current_monitor->setmem.term)
  1227.         {
  1228.           monitor_debug ("EXP setmem.term");
  1229.           monitor_expect (current_monitor->setmem.term, NULL, 0);
  1230.           monitor_printf ("%x\r", val);
  1231.         }
  1232.       if (current_monitor->setmem.term_cmd)
  1233.         {        /* Emit this to get out of the memory editing state.  */
  1234.           monitor_printf ("%s", current_monitor->setmem.term_cmd);
  1235.           /* Drop through to expecting a prompt.  */
  1236.         }
  1237.     }
  1238.   else
  1239.     monitor_printf (cmd, memaddr, val);

  1240.   monitor_expect_prompt (NULL, 0);

  1241.   return len;
  1242. }


  1243. static int
  1244. monitor_write_memory_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
  1245. {
  1246.   unsigned char val;
  1247.   int written = 0;

  1248.   if (len == 0)
  1249.     return 0;
  1250.   /* Enter the sub mode.  */
  1251.   monitor_printf (current_monitor->setmem.cmdb, memaddr);
  1252.   monitor_expect_prompt (NULL, 0);
  1253.   while (len)
  1254.     {
  1255.       val = *myaddr;
  1256.       monitor_printf ("%x\r", val);
  1257.       myaddr++;
  1258.       memaddr++;
  1259.       written++;
  1260.       /* If we wanted to, here we could validate the address.  */
  1261.       monitor_expect_prompt (NULL, 0);
  1262.       len--;
  1263.     }
  1264.   /* Now exit the sub mode.  */
  1265.   monitor_printf (current_monitor->getreg.term_cmd);
  1266.   monitor_expect_prompt (NULL, 0);
  1267.   return written;
  1268. }


  1269. static void
  1270. longlongendswap (unsigned char *a)
  1271. {
  1272.   int i, j;
  1273.   unsigned char x;

  1274.   i = 0;
  1275.   j = 7;
  1276.   while (i < 4)
  1277.     {
  1278.       x = *(a + i);
  1279.       *(a + i) = *(a + j);
  1280.       *(a + j) = x;
  1281.       i++, j--;
  1282.     }
  1283. }
  1284. /* Format 32 chars of long long value, advance the pointer.  */
  1285. static char *hexlate = "0123456789abcdef";
  1286. static char *
  1287. longlong_hexchars (unsigned long long value,
  1288.                    char *outbuff)
  1289. {
  1290.   if (value == 0)
  1291.     {
  1292.       *outbuff++ = '0';
  1293.       return outbuff;
  1294.     }
  1295.   else
  1296.     {
  1297.       static unsigned char disbuf[8];        /* disassembly buffer */
  1298.       unsigned char *scan, *limit;        /* loop controls */
  1299.       unsigned char c, nib;
  1300.       int leadzero = 1;

  1301.       scan = disbuf;
  1302.       limit = scan + 8;
  1303.       {
  1304.         unsigned long long *dp;

  1305.         dp = (unsigned long long *) scan;
  1306.         *dp = value;
  1307.       }
  1308.       longlongendswap (disbuf);        /* FIXME: ONly on big endian hosts.  */
  1309.       while (scan < limit)
  1310.         {
  1311.           c = *scan++;                /* A byte of our long long value.  */
  1312.           if (leadzero)
  1313.             {
  1314.               if (c == 0)
  1315.                 continue;
  1316.               else
  1317.                 leadzero = 0;        /* Henceforth we print even zeroes.  */
  1318.             }
  1319.           nib = c >> 4;                /* high nibble bits */
  1320.           *outbuff++ = hexlate[nib];
  1321.           nib = c & 0x0f;        /* low nibble bits */
  1322.           *outbuff++ = hexlate[nib];
  1323.         }
  1324.       return outbuff;
  1325.     }
  1326. }                                /* longlong_hexchars */



  1327. /* I am only going to call this when writing virtual byte streams.
  1328.    Which possably entails endian conversions.  */

  1329. static int
  1330. monitor_write_memory_longlongs (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
  1331. {
  1332.   static char hexstage[20];        /* At least 16 digits required, plus null.  */
  1333.   char *endstring;
  1334.   long long *llptr;
  1335.   long long value;
  1336.   int written = 0;

  1337.   llptr = (long long *) myaddr;
  1338.   if (len == 0)
  1339.     return 0;
  1340.   monitor_printf (current_monitor->setmem.cmdll, memaddr);
  1341.   monitor_expect_prompt (NULL, 0);
  1342.   while (len >= 8)
  1343.     {
  1344.       value = *llptr;
  1345.       endstring = longlong_hexchars (*llptr, hexstage);
  1346.       *endstring = '\0';        /* NUll terminate for printf.  */
  1347.       monitor_printf ("%s\r", hexstage);
  1348.       llptr++;
  1349.       memaddr += 8;
  1350.       written += 8;
  1351.       /* If we wanted to, here we could validate the address.  */
  1352.       monitor_expect_prompt (NULL, 0);
  1353.       len -= 8;
  1354.     }
  1355.   /* Now exit the sub mode.  */
  1356.   monitor_printf (current_monitor->getreg.term_cmd);
  1357.   monitor_expect_prompt (NULL, 0);
  1358.   return written;
  1359. }                                /* */



  1360. /* ----- MONITOR_WRITE_MEMORY_BLOCK ---------------------------- */
  1361. /* This is for the large blocks of memory which may occur in downloading.
  1362.    And for monitors which use interactive entry,
  1363.    And for monitors which do not have other downloading methods.
  1364.    Without this, we will end up calling monitor_write_memory many times
  1365.    and do the entry and exit of the sub mode many times
  1366.    This currently assumes...
  1367.    MO_SETMEM_INTERACTIVE
  1368.    ! MO_NO_ECHO_ON_SETMEM
  1369.    To use this, the you have to patch the monitor_cmds block with
  1370.    this function.  Otherwise, its not tuned up for use by all
  1371.    monitor variations.  */

  1372. static int
  1373. monitor_write_memory_block (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
  1374. {
  1375.   int written;

  1376.   written = 0;
  1377.   /* FIXME: This would be a good place to put the zero test.  */
  1378. #if 1
  1379.   if ((len > 8) && (((len & 0x07)) == 0) && current_monitor->setmem.cmdll)
  1380.     {
  1381.       return monitor_write_memory_longlongs (memaddr, myaddr, len);
  1382.     }
  1383. #endif
  1384.   written = monitor_write_memory_bytes (memaddr, myaddr, len);
  1385.   return written;
  1386. }

  1387. /* This is an alternate form of monitor_read_memory which is used for monitors
  1388.    which can only read a single byte/word/etc. at a time.  */

  1389. static int
  1390. monitor_read_memory_single (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
  1391. {
  1392.   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
  1393.   unsigned int val;
  1394.   char membuf[sizeof (int) * 2 + 1];
  1395.   char *p;
  1396.   char *cmd;

  1397.   monitor_debug ("MON read single\n");
  1398. #if 0
  1399.   /* Can't actually use long longs (nice idea, though).  In fact, the
  1400.      call to strtoul below will fail if it tries to convert a value
  1401.      that's too big to fit in a long.  */
  1402.   if ((memaddr & 0x7) == 0 && len >= 8 && current_monitor->getmem.cmdll)
  1403.     {
  1404.       len = 8;
  1405.       cmd = current_monitor->getmem.cmdll;
  1406.     }
  1407.   else
  1408. #endif
  1409.   if ((memaddr & 0x3) == 0 && len >= 4 && current_monitor->getmem.cmdl)
  1410.     {
  1411.       len = 4;
  1412.       cmd = current_monitor->getmem.cmdl;
  1413.     }
  1414.   else if ((memaddr & 0x1) == 0 && len >= 2 && current_monitor->getmem.cmdw)
  1415.     {
  1416.       len = 2;
  1417.       cmd = current_monitor->getmem.cmdw;
  1418.     }
  1419.   else
  1420.     {
  1421.       len = 1;
  1422.       cmd = current_monitor->getmem.cmdb;
  1423.     }

  1424.   /* Send the examine command.  */

  1425.   monitor_printf (cmd, memaddr);

  1426.   /* If RESP_DELIM is specified, we search for that as a leading
  1427.      delimiter for the memory value.  Otherwise, we just start
  1428.      searching from the start of the buf.  */

  1429.   if (current_monitor->getmem.resp_delim)
  1430.     {
  1431.       monitor_debug ("EXP getmem.resp_delim\n");
  1432.       monitor_expect_regexp (&getmem_resp_delim_pattern, NULL, 0);
  1433.     }

  1434.   /* Now, read the appropriate number of hex digits for this loc,
  1435.      skipping spaces.  */

  1436.   /* Skip leading spaces and "0x" if MO_HEX_PREFIX flag is set.  */
  1437.   if (current_monitor->flags & MO_HEX_PREFIX)
  1438.     {
  1439.       int c;

  1440.       c = readchar (timeout);
  1441.       while (c == ' ')
  1442.         c = readchar (timeout);
  1443.       if ((c == '0') && ((c = readchar (timeout)) == 'x'))
  1444.         ;
  1445.       else
  1446.         monitor_error ("monitor_read_memory_single",
  1447.                        "bad response from monitor",
  1448.                        memaddr, 0, NULL, 0);
  1449.     }

  1450.   {
  1451.     int i;

  1452.     for (i = 0; i < len * 2; i++)
  1453.       {
  1454.         int c;

  1455.         while (1)
  1456.           {
  1457.             c = readchar (timeout);
  1458.             if (isxdigit (c))
  1459.               break;
  1460.             if (c == ' ')
  1461.               continue;

  1462.             monitor_error ("monitor_read_memory_single",
  1463.                            "bad response from monitor",
  1464.                            memaddr, i, membuf, 0);
  1465.           }
  1466.       membuf[i] = c;
  1467.     }
  1468.     membuf[i] = '\000';                /* Terminate the number.  */
  1469.   }

  1470. /* If TERM is present, we wait for that to show up.  Also, (if TERM is
  1471.    present), we will send TERM_CMD if that is present.  In any case, we collect
  1472.    all of the output into buf, and then wait for the normal prompt.  */

  1473.   if (current_monitor->getmem.term)
  1474.     {
  1475.       monitor_expect (current_monitor->getmem.term, NULL, 0); /* Get
  1476.                                                                  response.  */

  1477.       if (current_monitor->getmem.term_cmd)
  1478.         {
  1479.           monitor_printf (current_monitor->getmem.term_cmd);
  1480.           monitor_expect_prompt (NULL, 0);
  1481.         }
  1482.     }
  1483.   else
  1484.     monitor_expect_prompt (NULL, 0);        /* Get response.  */

  1485.   p = membuf;
  1486.   val = strtoul (membuf, &p, 16);

  1487.   if (val == 0 && membuf == p)
  1488.     monitor_error ("monitor_read_memory_single",
  1489.                    "bad value from monitor",
  1490.                    memaddr, 0, membuf, 0);

  1491.   /* supply register stores in target byte order, so swap here.  */

  1492.   store_unsigned_integer (myaddr, len, byte_order, val);

  1493.   return len;
  1494. }

  1495. /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's
  1496.    memory at MEMADDR.  Returns length moved.  Currently, we do no more
  1497.    than 16 bytes at a time.  */

  1498. static int
  1499. monitor_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
  1500. {
  1501.   unsigned int val;
  1502.   char buf[512];
  1503.   char *p, *p1;
  1504.   int resp_len;
  1505.   int i;
  1506.   CORE_ADDR dumpaddr;

  1507.   if (len <= 0)
  1508.     {
  1509.       monitor_debug ("Zero length call to monitor_read_memory\n");
  1510.       return 0;
  1511.     }

  1512.   monitor_debug ("MON read block ta(%s) ha(%s) %d\n",
  1513.                  paddress (target_gdbarch (), memaddr),
  1514.                  host_address_to_string (myaddr), len);

  1515.   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
  1516.     memaddr = gdbarch_addr_bits_remove (target_gdbarch (), memaddr);

  1517.   if (current_monitor->flags & MO_GETMEM_READ_SINGLE)
  1518.     return monitor_read_memory_single (memaddr, myaddr, len);

  1519.   len = min (len, 16);

  1520.   /* Some dumpers align the first data with the preceding 16
  1521.      byte boundary.  Some print blanks and start at the
  1522.      requested boundary.  EXACT_DUMPADDR  */

  1523.   dumpaddr = (current_monitor->flags & MO_EXACT_DUMPADDR)
  1524.     ? memaddr : memaddr & ~0x0f;

  1525.   /* See if xfer would cross a 16 byte boundary.  If so, clip it.  */
  1526.   if (((memaddr ^ (memaddr + len - 1)) & ~0xf) != 0)
  1527.     len = ((memaddr + len) & ~0xf) - memaddr;

  1528.   /* Send the memory examine command.  */

  1529.   if (current_monitor->flags & MO_GETMEM_NEEDS_RANGE)
  1530.     monitor_printf (current_monitor->getmem.cmdb, memaddr, memaddr + len);
  1531.   else if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
  1532.     monitor_printf (current_monitor->getmem.cmdb, dumpaddr);
  1533.   else
  1534.     monitor_printf (current_monitor->getmem.cmdb, memaddr, len);

  1535.   /* If TERM is present, we wait for that to show up.  Also, (if TERM
  1536.      is present), we will send TERM_CMD if that is present.  In any
  1537.      case, we collect all of the output into buf, and then wait for
  1538.      the normal prompt.  */

  1539.   if (current_monitor->getmem.term)
  1540.     {
  1541.       resp_len = monitor_expect (current_monitor->getmem.term,
  1542.                                  buf, sizeof buf);        /* Get response.  */

  1543.       if (resp_len <= 0)
  1544.         monitor_error ("monitor_read_memory",
  1545.                        "excessive response from monitor",
  1546.                        memaddr, resp_len, buf, 0);

  1547.       if (current_monitor->getmem.term_cmd)
  1548.         {
  1549.           serial_write (monitor_desc, current_monitor->getmem.term_cmd,
  1550.                         strlen (current_monitor->getmem.term_cmd));
  1551.           monitor_expect_prompt (NULL, 0);
  1552.         }
  1553.     }
  1554.   else
  1555.     resp_len = monitor_expect_prompt (buf, sizeof buf);         /* Get response.  */

  1556.   p = buf;

  1557.   /* If RESP_DELIM is specified, we search for that as a leading
  1558.      delimiter for the values.  Otherwise, we just start searching
  1559.      from the start of the buf.  */

  1560.   if (current_monitor->getmem.resp_delim)
  1561.     {
  1562.       int retval, tmp;
  1563.       struct re_registers resp_strings;

  1564.       monitor_debug ("MON getmem.resp_delim %s\n",
  1565.                      current_monitor->getmem.resp_delim);

  1566.       memset (&resp_strings, 0, sizeof (struct re_registers));
  1567.       tmp = strlen (p);
  1568.       retval = re_search (&getmem_resp_delim_pattern, p, tmp, 0, tmp,
  1569.                           &resp_strings);

  1570.       if (retval < 0)
  1571.         monitor_error ("monitor_read_memory",
  1572.                        "bad response from monitor",
  1573.                        memaddr, resp_len, buf, 0);

  1574.       p += resp_strings.end[0];
  1575. #if 0
  1576.       p = strstr (p, current_monitor->getmem.resp_delim);
  1577.       if (!p)
  1578.         monitor_error ("monitor_read_memory",
  1579.                        "bad response from monitor",
  1580.                        memaddr, resp_len, buf, 0);
  1581.       p += strlen (current_monitor->getmem.resp_delim);
  1582. #endif
  1583.     }
  1584.   monitor_debug ("MON scanning  %d ,%s '%s'\n", len,
  1585.                  host_address_to_string (p), p);
  1586.   if (current_monitor->flags & MO_GETMEM_16_BOUNDARY)
  1587.     {
  1588.       char c;
  1589.       int fetched = 0;
  1590.       i = len;
  1591.       c = *p;


  1592.       while (!(c == '\000' || c == '\n' || c == '\r') && i > 0)
  1593.         {
  1594.           if (isxdigit (c))
  1595.             {
  1596.               if ((dumpaddr >= memaddr) && (i > 0))
  1597.                 {
  1598.                   val = fromhex (c) * 16 + fromhex (*(p + 1));
  1599.                   *myaddr++ = val;
  1600.                   if (monitor_debug_p || remote_debug)
  1601.                     fprintf_unfiltered (gdb_stdlog, "[%02x]", val);
  1602.                   --i;
  1603.                   fetched++;
  1604.                 }
  1605.               ++dumpaddr;
  1606.               ++p;
  1607.             }
  1608.           ++p;                        /* Skip a blank or other non hex char.  */
  1609.           c = *p;
  1610.         }
  1611.       if (fetched == 0)
  1612.         error (_("Failed to read via monitor"));
  1613.       if (monitor_debug_p || remote_debug)
  1614.         fprintf_unfiltered (gdb_stdlog, "\n");
  1615.       return fetched;                /* Return the number of bytes actually
  1616.                                    read.  */
  1617.     }
  1618.   monitor_debug ("MON scanning bytes\n");

  1619.   for (i = len; i > 0; i--)
  1620.     {
  1621.       /* Skip non-hex chars, but bomb on end of string and newlines.  */

  1622.       while (1)
  1623.         {
  1624.           if (isxdigit (*p))
  1625.             break;

  1626.           if (*p == '\000' || *p == '\n' || *p == '\r')
  1627.             monitor_error ("monitor_read_memory",
  1628.                            "badly terminated response from monitor",
  1629.                            memaddr, resp_len, buf, 0);
  1630.           p++;
  1631.         }

  1632.       val = strtoul (p, &p1, 16);

  1633.       if (val == 0 && p == p1)
  1634.         monitor_error ("monitor_read_memory",
  1635.                        "bad value from monitor",
  1636.                        memaddr, resp_len, buf, 0);

  1637.       *myaddr++ = val;

  1638.       if (i == 1)
  1639.         break;

  1640.       p = p1;
  1641.     }

  1642.   return len;
  1643. }

  1644. /* Helper for monitor_xfer_partial that handles memory transfers.
  1645.    Arguments are like target_xfer_partial.  */

  1646. static enum target_xfer_status
  1647. monitor_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  1648.                      ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  1649. {
  1650.   int res;

  1651.   if (writebuf != NULL)
  1652.     {
  1653.       if (current_monitor->flags & MO_HAS_BLOCKWRITES)
  1654.         res = monitor_write_memory_block (memaddr, writebuf, len);
  1655.       else
  1656.         res = monitor_write_memory (memaddr, writebuf, len);
  1657.     }
  1658.   else
  1659.     {
  1660.       res = monitor_read_memory (memaddr, readbuf, len);
  1661.     }

  1662.   if (res <= 0)
  1663.     return TARGET_XFER_E_IO;
  1664.   else
  1665.     {
  1666.       *xfered_len = (ULONGEST) res;
  1667.       return TARGET_XFER_OK;
  1668.     }
  1669. }

  1670. /* Target to_xfer_partial implementation.  */

  1671. static enum target_xfer_status
  1672. monitor_xfer_partial (struct target_ops *ops, enum target_object object,
  1673.                       const char *annex, gdb_byte *readbuf,
  1674.                       const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  1675.                       ULONGEST *xfered_len)
  1676. {
  1677.   switch (object)
  1678.     {
  1679.     case TARGET_OBJECT_MEMORY:
  1680.       return monitor_xfer_memory (readbuf, writebuf, offset, len, xfered_len);

  1681.     default:
  1682.       return TARGET_XFER_E_IO;
  1683.     }
  1684. }

  1685. static void
  1686. monitor_kill (struct target_ops *ops)
  1687. {
  1688.   return;                        /* Ignore attempts to kill target system.  */
  1689. }

  1690. /* All we actually do is set the PC to the start address of exec_bfd.  */

  1691. static void
  1692. monitor_create_inferior (struct target_ops *ops, char *exec_file,
  1693.                          char *args, char **env, int from_tty)
  1694. {
  1695.   if (args && (*args != '\000'))
  1696.     error (_("Args are not supported by the monitor."));

  1697.   first_time = 1;
  1698.   clear_proceed_status (0);
  1699.   regcache_write_pc (get_current_regcache (),
  1700.                      bfd_get_start_address (exec_bfd));
  1701. }

  1702. /* Clean up when a program exits.
  1703.    The program actually lives on in the remote processor's RAM, and may be
  1704.    run again without a download.  Don't leave it full of breakpoint
  1705.    instructions.  */

  1706. static void
  1707. monitor_mourn_inferior (struct target_ops *ops)
  1708. {
  1709.   unpush_target (targ_ops);
  1710.   generic_mourn_inferior ();        /* Do all the proper things now.  */
  1711.   delete_thread_silent (monitor_ptid);
  1712. }

  1713. /* Tell the monitor to add a breakpoint.  */

  1714. static int
  1715. monitor_insert_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
  1716.                            struct bp_target_info *bp_tgt)
  1717. {
  1718.   CORE_ADDR addr = bp_tgt->placed_address = bp_tgt->reqstd_address;
  1719.   int i;
  1720.   int bplen;

  1721.   monitor_debug ("MON inst bkpt %s\n", paddress (gdbarch, addr));
  1722.   if (current_monitor->set_break == NULL)
  1723.     error (_("No set_break defined for this monitor"));

  1724.   if (current_monitor->flags & MO_ADDR_BITS_REMOVE)
  1725.     addr = gdbarch_addr_bits_remove (gdbarch, addr);

  1726.   /* Determine appropriate breakpoint size for this address.  */
  1727.   gdbarch_breakpoint_from_pc (gdbarch, &addr, &bplen);
  1728.   bp_tgt->placed_address = addr;
  1729.   bp_tgt->placed_size = bplen;

  1730.   for (i = 0; i < current_monitor->num_breakpoints; i++)
  1731.     {
  1732.       if (breakaddr[i] == 0)
  1733.         {
  1734.           breakaddr[i] = addr;
  1735.           monitor_printf (current_monitor->set_break, addr);
  1736.           monitor_expect_prompt (NULL, 0);
  1737.           return 0;
  1738.         }
  1739.     }

  1740.   error (_("Too many breakpoints (> %d) for monitor."),
  1741.          current_monitor->num_breakpoints);
  1742. }

  1743. /* Tell the monitor to remove a breakpoint.  */

  1744. static int
  1745. monitor_remove_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
  1746.                            struct bp_target_info *bp_tgt)
  1747. {
  1748.   CORE_ADDR addr = bp_tgt->placed_address;
  1749.   int i;

  1750.   monitor_debug ("MON rmbkpt %s\n", paddress (gdbarch, addr));
  1751.   if (current_monitor->clr_break == NULL)
  1752.     error (_("No clr_break defined for this monitor"));

  1753.   for (i = 0; i < current_monitor->num_breakpoints; i++)
  1754.     {
  1755.       if (breakaddr[i] == addr)
  1756.         {
  1757.           breakaddr[i] = 0;
  1758.           /* Some monitors remove breakpoints based on the address.  */
  1759.           if (current_monitor->flags & MO_CLR_BREAK_USES_ADDR)
  1760.             monitor_printf (current_monitor->clr_break, addr);
  1761.           else if (current_monitor->flags & MO_CLR_BREAK_1_BASED)
  1762.             monitor_printf (current_monitor->clr_break, i + 1);
  1763.           else
  1764.             monitor_printf (current_monitor->clr_break, i);
  1765.           monitor_expect_prompt (NULL, 0);
  1766.           return 0;
  1767.         }
  1768.     }
  1769.   fprintf_unfiltered (gdb_stderr,
  1770.                       "Can't find breakpoint associated with %s\n",
  1771.                       paddress (gdbarch, addr));
  1772.   return 1;
  1773. }

  1774. /* monitor_wait_srec_ack -- wait for the target to send an acknowledgement for
  1775.    an S-record.  Return non-zero if the ACK is received properly.  */

  1776. static int
  1777. monitor_wait_srec_ack (void)
  1778. {
  1779.   int ch;

  1780.   if (current_monitor->flags & MO_SREC_ACK_PLUS)
  1781.     {
  1782.       return (readchar (timeout) == '+');
  1783.     }
  1784.   else if (current_monitor->flags & MO_SREC_ACK_ROTATE)
  1785.     {
  1786.       /* Eat two backspaces, a "rotating" char (|/-\), and a space.  */
  1787.       if ((ch = readchar (1)) < 0)
  1788.         return 0;
  1789.       if ((ch = readchar (1)) < 0)
  1790.         return 0;
  1791.       if ((ch = readchar (1)) < 0)
  1792.         return 0;
  1793.       if ((ch = readchar (1)) < 0)
  1794.         return 0;
  1795.     }
  1796.   return 1;
  1797. }

  1798. /* monitor_load -- download a file.  */

  1799. static void
  1800. monitor_load (struct target_ops *self, const char *args, int from_tty)
  1801. {
  1802.   CORE_ADDR load_offset = 0;
  1803.   char **argv;
  1804.   struct cleanup *old_cleanups;
  1805.   char *filename;

  1806.   monitor_debug ("MON load\n");

  1807.   if (args == NULL)
  1808.     error_no_arg (_("file to load"));

  1809.   argv = gdb_buildargv (args);
  1810.   old_cleanups = make_cleanup_freeargv (argv);

  1811.   filename = tilde_expand (argv[0]);
  1812.   make_cleanup (xfree, filename);

  1813.   /* Enable user to specify address for downloading as 2nd arg to load.  */
  1814.   if (argv[1] != NULL)
  1815.     {
  1816.       const char *endptr;

  1817.       load_offset = strtoulst (argv[1], &endptr, 0);

  1818.       /* If the last word was not a valid number then
  1819.          treat it as a file name with spaces in.  */
  1820.       if (argv[1] == endptr)
  1821.         error (_("Invalid download offset:%s."), argv[1]);

  1822.       if (argv[2] != NULL)
  1823.         error (_("Too many parameters."));
  1824.     }

  1825.   monitor_printf (current_monitor->load);
  1826.   if (current_monitor->loadresp)
  1827.     monitor_expect (current_monitor->loadresp, NULL, 0);

  1828.   load_srec (monitor_desc, filename, load_offset,
  1829.              32, SREC_ALL, hashmark,
  1830.              current_monitor->flags & MO_SREC_ACK ?
  1831.              monitor_wait_srec_ack : NULL);

  1832.   monitor_expect_prompt (NULL, 0);

  1833.   do_cleanups (old_cleanups);

  1834.   /* Finally, make the PC point at the start address.  */
  1835.   if (exec_bfd)
  1836.     regcache_write_pc (get_current_regcache (),
  1837.                        bfd_get_start_address (exec_bfd));

  1838.   /* There used to be code here which would clear inferior_ptid and
  1839.      call clear_symtab_users.  None of that should be necessary:
  1840.      monitor targets should behave like remote protocol targets, and
  1841.      since generic_load does none of those things, this function
  1842.      shouldn't either.

  1843.      Furthermore, clearing inferior_ptid is *incorrect*.  After doing
  1844.      a load, we still have a valid connection to the monitor, with a
  1845.      live processor state to fiddle with.  The user can type
  1846.      `continue' or `jump *start' and make the program run.  If they do
  1847.      these things, however, GDB will be talking to a running program
  1848.      while inferior_ptid is null_ptid; this makes things like
  1849.      reinit_frame_cache very confused.  */
  1850. }

  1851. static void
  1852. monitor_stop (struct target_ops *self, ptid_t ptid)
  1853. {
  1854.   monitor_debug ("MON stop\n");
  1855.   if ((current_monitor->flags & MO_SEND_BREAK_ON_STOP) != 0)
  1856.     serial_send_break (monitor_desc);
  1857.   if (current_monitor->stop)
  1858.     monitor_printf_noecho (current_monitor->stop);
  1859. }

  1860. /* Put a COMMAND string out to MONITOR.  Output from MONITOR is placed
  1861.    in OUTPUT until the prompt is seen.  FIXME: We read the characters
  1862.    ourseleves here cause of a nasty echo.  */

  1863. static void
  1864. monitor_rcmd (struct target_ops *self, const char *command,
  1865.               struct ui_file *outbuf)
  1866. {
  1867.   char *p;
  1868.   int resp_len;
  1869.   char buf[1000];

  1870.   if (monitor_desc == NULL)
  1871.     error (_("monitor target not open."));

  1872.   p = current_monitor->prompt;

  1873.   /* Send the command.  Note that if no args were supplied, then we're
  1874.      just sending the monitor a newline, which is sometimes useful.  */

  1875.   monitor_printf ("%s\r", (command ? command : ""));

  1876.   resp_len = monitor_expect_prompt (buf, sizeof buf);

  1877.   fputs_unfiltered (buf, outbuf);        /* Output the response.  */
  1878. }

  1879. /* Convert hex digit A to a number.  */

  1880. #if 0
  1881. static int
  1882. from_hex (int a)
  1883. {
  1884.   if (a >= '0' && a <= '9')
  1885.     return a - '0';
  1886.   if (a >= 'a' && a <= 'f')
  1887.     return a - 'a' + 10;
  1888.   if (a >= 'A' && a <= 'F')
  1889.     return a - 'A' + 10;

  1890.   error (_("Reply contains invalid hex digit 0x%x"), a);
  1891. }
  1892. #endif

  1893. char *
  1894. monitor_get_dev_name (void)
  1895. {
  1896.   return dev_name;
  1897. }

  1898. /* Check to see if a thread is still alive.  */

  1899. static int
  1900. monitor_thread_alive (struct target_ops *ops, ptid_t ptid)
  1901. {
  1902.   if (ptid_equal (ptid, monitor_ptid))
  1903.     /* The monitor's task is always alive.  */
  1904.     return 1;

  1905.   return 0;
  1906. }

  1907. /* Convert a thread ID to a string.  Returns the string in a static
  1908.    buffer.  */

  1909. static char *
  1910. monitor_pid_to_str (struct target_ops *ops, ptid_t ptid)
  1911. {
  1912.   static char buf[64];

  1913.   if (ptid_equal (monitor_ptid, ptid))
  1914.     {
  1915.       xsnprintf (buf, sizeof buf, "Thread <main>");
  1916.       return buf;
  1917.     }

  1918.   return normal_pid_to_str (ptid);
  1919. }

  1920. static struct target_ops monitor_ops;

  1921. static void
  1922. init_base_monitor_ops (void)
  1923. {
  1924.   monitor_ops.to_close = monitor_close;
  1925.   monitor_ops.to_detach = monitor_detach;
  1926.   monitor_ops.to_resume = monitor_resume;
  1927.   monitor_ops.to_wait = monitor_wait;
  1928.   monitor_ops.to_fetch_registers = monitor_fetch_registers;
  1929.   monitor_ops.to_store_registers = monitor_store_registers;
  1930.   monitor_ops.to_prepare_to_store = monitor_prepare_to_store;
  1931.   monitor_ops.to_xfer_partial = monitor_xfer_partial;
  1932.   monitor_ops.to_files_info = monitor_files_info;
  1933.   monitor_ops.to_insert_breakpoint = monitor_insert_breakpoint;
  1934.   monitor_ops.to_remove_breakpoint = monitor_remove_breakpoint;
  1935.   monitor_ops.to_kill = monitor_kill;
  1936.   monitor_ops.to_load = monitor_load;
  1937.   monitor_ops.to_create_inferior = monitor_create_inferior;
  1938.   monitor_ops.to_mourn_inferior = monitor_mourn_inferior;
  1939.   monitor_ops.to_stop = monitor_stop;
  1940.   monitor_ops.to_rcmd = monitor_rcmd;
  1941.   monitor_ops.to_log_command = serial_log_command;
  1942.   monitor_ops.to_thread_alive = monitor_thread_alive;
  1943.   monitor_ops.to_pid_to_str = monitor_pid_to_str;
  1944.   monitor_ops.to_stratum = process_stratum;
  1945.   monitor_ops.to_has_all_memory = default_child_has_all_memory;
  1946.   monitor_ops.to_has_memory = default_child_has_memory;
  1947.   monitor_ops.to_has_stack = default_child_has_stack;
  1948.   monitor_ops.to_has_registers = default_child_has_registers;
  1949.   monitor_ops.to_has_execution = default_child_has_execution;
  1950.   monitor_ops.to_magic = OPS_MAGIC;
  1951. }                                /* init_base_monitor_ops */

  1952. /* Init the target_ops structure pointed at by OPS.  */

  1953. void
  1954. init_monitor_ops (struct target_ops *ops)
  1955. {
  1956.   if (monitor_ops.to_magic != OPS_MAGIC)
  1957.     init_base_monitor_ops ();

  1958.   memcpy (ops, &monitor_ops, sizeof monitor_ops);
  1959. }

  1960. /* Define additional commands that are usually only used by monitors.  */

  1961. /* -Wmissing-prototypes */
  1962. extern initialize_file_ftype _initialize_remote_monitors;

  1963. void
  1964. _initialize_remote_monitors (void)
  1965. {
  1966.   init_base_monitor_ops ();
  1967.   add_setshow_boolean_cmd ("hash", no_class, &hashmark, _("\
  1968. Set display of activity while downloading a file."), _("\
  1969. Show display of activity while downloading a file."), _("\
  1970. When enabled, a hashmark \'#\' is displayed."),
  1971.                            NULL,
  1972.                            NULL, /* FIXME: i18n: */
  1973.                            &setlist, &showlist);

  1974.   add_setshow_zuinteger_cmd ("monitor", no_class, &monitor_debug_p, _("\
  1975. Set debugging of remote monitor communication."), _("\
  1976. Show debugging of remote monitor communication."), _("\
  1977. When enabled, communication between GDB and the remote monitor\n\
  1978. is displayed."),
  1979.                              NULL,
  1980.                              NULL, /* FIXME: i18n: */
  1981.                              &setdebuglist, &showdebuglist);

  1982.   /* Yes, 42000 is arbitrary.  The only sense out of it, is that it
  1983.      isn't 0.  */
  1984.   monitor_ptid = ptid_build (42000, 0, 42000);
  1985. }