gdb/remote-mips.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Remote debugging interface for MIPS remote debugging protocol.

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

  3.    Contributed by Cygnus Support.  Written by Ian Lance Taylor
  4.    <ian@cygnus.com>.

  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. #include "defs.h"
  17. #include "inferior.h"
  18. #include "infrun.h"
  19. #include "bfd.h"
  20. #include "symfile.h"
  21. #include "gdbcmd.h"
  22. #include "gdbcore.h"
  23. #include "serial.h"
  24. #include "target.h"
  25. #include <sys/stat.h>
  26. #include "gdb_usleep.h"
  27. #include "regcache.h"
  28. #include <ctype.h>
  29. #include "mips-tdep.h"
  30. #include "gdbthread.h"
  31. #include "gdb_bfd.h"


  32. /* Breakpoint types.  Values 0, 1, and 2 must agree with the watch
  33.    types passed by breakpoint.c to target_insert_watchpoint.
  34.    Value 3 is our own invention, and is used for ordinary instruction
  35.    breakpoints.  Value 4 is used to mark an unused watchpoint in tables.  */
  36. enum break_type
  37.   {
  38.     BREAK_WRITE,                /* 0 */
  39.     BREAK_READ,                        /* 1 */
  40.     BREAK_ACCESS,                /* 2 */
  41.     BREAK_FETCH,                /* 3 */
  42.     BREAK_UNUSED                /* 4 */
  43.   };

  44. /* Prototypes for local functions.  */

  45. static int mips_readchar (int timeout);

  46. static int mips_receive_header (unsigned char *hdr, int *pgarbage,
  47.                                 int ch, int timeout);

  48. static int mips_receive_trailer (unsigned char *trlr, int *pgarbage,
  49.                                  int *pch, int timeout);

  50. static int mips_cksum (const unsigned char *hdr,
  51.                        const char *data, int len);

  52. static void mips_send_packet (const char *s, int get_ack);

  53. static void mips_send_command (const char *cmd, int prompt);

  54. static int mips_receive_packet (char *buff, int throw_error, int timeout);

  55. static ULONGEST mips_request (int cmd, ULONGEST addr, ULONGEST data,
  56.                               int *perr, int timeout, char *buff);

  57. static void mips_initialize (void);

  58. static void mips_close (struct target_ops *self);

  59. static int mips_map_regno (struct gdbarch *, int);

  60. static void mips_set_register (int regno, ULONGEST value);

  61. static void mips_prepare_to_store (struct target_ops *self,
  62.                                    struct regcache *regcache);

  63. static int mips_fetch_word (CORE_ADDR addr, unsigned int *valp);

  64. static int mips_store_word (CORE_ADDR addr, unsigned int value,
  65.                             int *old_contents);

  66. static enum target_xfer_status mips_xfer_memory (gdb_byte *readbuf,
  67.                                                  const gdb_byte *writebuf,
  68.                                                  ULONGEST memaddr,
  69.                                                  ULONGEST len,
  70.                                                  ULONGEST *xfered_len);

  71. static void mips_files_info (struct target_ops *ignore);

  72. static void mips_mourn_inferior (struct target_ops *ops);

  73. static int pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum);

  74. static int pmon_zeroset (int recsize, char **buff, unsigned int *amount,
  75.                          unsigned int *chksum);

  76. static int pmon_checkset (int recsize, char **buff, unsigned int *value);

  77. static void pmon_make_fastrec (char **outbuf, unsigned char *inbuf,
  78.                                int *inptr, int inamount, int *recsize,
  79.                                unsigned int *csum, unsigned int *zerofill);

  80. static int pmon_check_ack (char *mesg);

  81. static void pmon_start_download (void);

  82. static void pmon_end_download (int final, int bintotal);

  83. static void pmon_download (char *buffer, int length);

  84. static void mips_load (struct target_ops *self, const char *file, int from_tty);

  85. static int mips_make_srec (char *buffer, int type, CORE_ADDR memaddr,
  86.                            unsigned char *myaddr, int len);

  87. static int mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type);

  88. static int mips_clear_breakpoint (CORE_ADDR addr, int len,
  89.                                   enum break_type type);

  90. static int mips_common_breakpoint (int set, CORE_ADDR addr, int len,
  91.                                    enum break_type type);

  92. /* Forward declarations.  */
  93. extern struct target_ops mips_ops;
  94. extern struct target_ops pmon_ops;
  95. extern struct target_ops ddb_ops;
  96. extern struct target_ops rockhopper_ops;
  97. /* *INDENT-OFF* */
  98. /* The MIPS remote debugging interface is built on top of a simple
  99.    packet protocol.  Each packet is organized as follows:

  100.    SYN  The first character is always a SYN (ASCII 026, or ^V).  SYN
  101.    may not appear anywhere else in the packet.  Any time a SYN is
  102.    seen, a new packet should be assumed to have begun.

  103.    TYPE_LEN
  104.    This byte contains the upper five bits of the logical length
  105.    of the data section, plus a single bit indicating whether this
  106.    is a data packet or an acknowledgement.  The documentation
  107.    indicates that this bit is 1 for a data packet, but the actual
  108.    board uses 1 for an acknowledgement.  The value of the byte is
  109.    0x40 + (ack ? 0x20 : 0) + (len >> 6)
  110.    (we always have 0 <= len < 1024).  Acknowledgement packets do
  111.    not carry data, and must have a data length of 0.

  112.    LEN1 This byte contains the lower six bits of the logical length of
  113.    the data section.  The value is
  114.    0x40 + (len & 0x3f)

  115.    SEQ  This byte contains the six bit sequence number of the packet.
  116.    The value is
  117.    0x40 + seq
  118.    An acknowlegment packet contains the sequence number of the
  119.    packet being acknowledged plus 1 modulo 64.  Data packets are
  120.    transmitted in sequence.  There may only be one outstanding
  121.    unacknowledged data packet at a time.  The sequence numbers
  122.    are independent in each direction.  If an acknowledgement for
  123.    the previous packet is received (i.e., an acknowledgement with
  124.    the sequence number of the packet just sent) the packet just
  125.    sent should be retransmitted.  If no acknowledgement is
  126.    received within a timeout period, the packet should be
  127.    retransmitted.  This has an unfortunate failure condition on a
  128.    high-latency line, as a delayed acknowledgement may lead to an
  129.    endless series of duplicate packets.

  130.    DATA The actual data bytes follow.  The following characters are
  131.    escaped inline with DLE (ASCII 020, or ^P):
  132.    SYN (026)    DLE S
  133.    DLE (020)    DLE D
  134.    ^C  (003)    DLE C
  135.    ^S  (023)    DLE s
  136.    ^Q  (021)    DLE q
  137.    The additional DLE characters are not counted in the logical
  138.    length stored in the TYPE_LEN and LEN1 bytes.

  139.    CSUM1
  140.    CSUM2
  141.    CSUM3
  142.    These bytes contain an 18 bit checksum of the complete
  143.    contents of the packet excluding the SEQ byte and the
  144.    CSUM[123] bytes.  The checksum is simply the twos complement
  145.    addition of all the bytes treated as unsigned characters.  The
  146.    values of the checksum bytes are:
  147.    CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
  148.    CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
  149.    CSUM3: 0x40 + (cksum & 0x3f)

  150.    It happens that the MIPS remote debugging protocol always
  151.    communicates with ASCII strings.  Because of this, this
  152.    implementation doesn't bother to handle the DLE quoting mechanism,
  153.    since it will never be required.  */
  154. /* *INDENT-ON* */


  155. /* The SYN character which starts each packet.  */
  156. #define SYN '\026'

  157. /* The 0x40 used to offset each packet (this value ensures that all of
  158.    the header and trailer bytes, other than SYN, are printable ASCII
  159.    characters).  */
  160. #define HDR_OFFSET 0x40

  161. /* The indices of the bytes in the packet header.  */
  162. #define HDR_INDX_SYN 0
  163. #define HDR_INDX_TYPE_LEN 1
  164. #define HDR_INDX_LEN1 2
  165. #define HDR_INDX_SEQ 3
  166. #define HDR_LENGTH 4

  167. /* The data/ack bit in the TYPE_LEN header byte.  */
  168. #define TYPE_LEN_DA_BIT 0x20
  169. #define TYPE_LEN_DATA 0
  170. #define TYPE_LEN_ACK TYPE_LEN_DA_BIT

  171. /* How to compute the header bytes.  */
  172. #define HDR_SET_SYN(data, len, seq) (SYN)
  173. #define HDR_SET_TYPE_LEN(data, len, seq) \
  174.   (HDR_OFFSET \
  175.    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
  176.    + (((len) >> 6) & 0x1f))
  177. #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
  178. #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))

  179. /* Check that a header byte is reasonable.  */
  180. #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)

  181. /* Get data from the header.  These macros evaluate their argument
  182.    multiple times.  */
  183. #define HDR_IS_DATA(hdr) \
  184.   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
  185. #define HDR_GET_LEN(hdr) \
  186.   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
  187. #define HDR_GET_SEQ(hdr) ((unsigned int)(hdr)[HDR_INDX_SEQ] & 0x3f)

  188. /* The maximum data length.  */
  189. #define DATA_MAXLEN 1023

  190. /* The trailer offset.  */
  191. #define TRLR_OFFSET HDR_OFFSET

  192. /* The indices of the bytes in the packet trailer.  */
  193. #define TRLR_INDX_CSUM1 0
  194. #define TRLR_INDX_CSUM2 1
  195. #define TRLR_INDX_CSUM3 2
  196. #define TRLR_LENGTH 3

  197. /* How to compute the trailer bytes.  */
  198. #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
  199. #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
  200. #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))

  201. /* Check that a trailer byte is reasonable.  */
  202. #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)

  203. /* Get data from the trailer.  This evaluates its argument multiple
  204.    times.  */
  205. #define TRLR_GET_CKSUM(trlr) \
  206.   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
  207.    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
  208.    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))

  209. /* The sequence number modulos.  */
  210. #define SEQ_MODULOS (64)

  211. /* PMON commands to load from the serial port or UDP socket.  */
  212. #define LOAD_CMD        "load -b -s tty0\r"
  213. #define LOAD_CMD_UDP        "load -b -s udp\r"

  214. /* The target vectors for the four different remote MIPS targets.
  215.    These are initialized with code in _initialize_remote_mips instead
  216.    of static initializers, to make it easier to extend the target_ops
  217.    vector later.  */
  218. struct target_ops mips_ops, pmon_ops, ddb_ops, rockhopper_ops, lsi_ops;

  219. enum mips_monitor_type
  220.   {
  221.     /* IDT/SIM monitor being used: */
  222.     MON_IDT,
  223.     /* PMON monitor being used: */
  224.     MON_PMON,                        /* 3.0.83 [COGENT,EB,FP,NET]
  225.                                    Algorithmics Ltd. Nov  9 1995 17:19:50 */
  226.     MON_DDB,                        /* 2.7.473 [DDBVR4300,EL,FP,NET]
  227.                                    Risq Modular Systems,
  228.                                    Thu Jun 6 09:28:40 PDT 1996 */
  229.     MON_LSI,                        /* 4.3.12 [EB,FP],
  230.                                    LSI LOGIC Corp. Tue Feb 25 13:22:14 1997 */
  231.     MON_ROCKHOPPER,
  232.     /* Last and unused value, for sizing vectors, etc.  */
  233.     MON_LAST
  234.   };
  235. static enum mips_monitor_type mips_monitor = MON_LAST;

  236. /* The monitor prompt text.  If the user sets the PMON prompt
  237.    to some new value, the GDB `set monitor-prompt' command must also
  238.    be used to inform GDB about the expected prompt.  Otherwise, GDB
  239.    will not be able to connect to PMON in mips_initialize().
  240.    If the `set monitor-prompt' command is not used, the expected
  241.    default prompt will be set according the target:
  242.    target               prompt
  243.    -----                -----
  244.    pmon         PMON>
  245.    ddb          NEC010>
  246.    lsi          PMON>
  247. */
  248. static char *mips_monitor_prompt;

  249. /* Set to 1 if the target is open.  */
  250. static int mips_is_open;

  251. /* Currently active target description (if mips_is_open == 1).  */
  252. static struct target_ops *current_ops;

  253. /* Set to 1 while the connection is being initialized.  */
  254. static int mips_initializing;

  255. /* Set to 1 while the connection is being brought down.  */
  256. static int mips_exiting;

  257. /* The next sequence number to send.  */
  258. static unsigned int mips_send_seq;

  259. /* The next sequence number we expect to receive.  */
  260. static unsigned int mips_receive_seq;

  261. /* The time to wait before retransmitting a packet, in seconds.  */
  262. static int mips_retransmit_wait = 3;

  263. /* The number of times to try retransmitting a packet before giving up.  */
  264. static int mips_send_retries = 10;

  265. /* The number of garbage characters to accept when looking for an
  266.    SYN for the next packet.  */
  267. static int mips_syn_garbage = 10;

  268. /* The time to wait for a packet, in seconds.  */
  269. static int mips_receive_wait = 5;

  270. /* Set if we have sent a packet to the board but have not yet received
  271.    a reply.  */
  272. static int mips_need_reply = 0;

  273. /* Handle used to access serial I/O stream.  */
  274. static struct serial *mips_desc;

  275. /* UDP handle used to download files to target.  */
  276. static struct serial *udp_desc;
  277. static int udp_in_use;

  278. /* TFTP filename used to download files to DDB board, in the form
  279.    host:filename.  */
  280. static char *tftp_name;                /* host:filename */
  281. static char *tftp_localname;        /* filename portion of above */
  282. static int tftp_in_use;
  283. static FILE *tftp_file;

  284. /* Counts the number of times the user tried to interrupt the target (usually
  285.    via ^C.  */
  286. static int interrupt_count;

  287. /* If non-zero, means that the target is running.  */
  288. static int mips_wait_flag = 0;

  289. /* If non-zero, monitor supports breakpoint commands.  */
  290. static int monitor_supports_breakpoints = 0;

  291. /* Data cache header.  */

  292. #if 0                                /* not used (yet?)  */
  293. static DCACHE *mips_dcache;
  294. #endif

  295. /* Non-zero means that we've just hit a read or write watchpoint.  */
  296. static int hit_watchpoint;

  297. /* Table of breakpoints/watchpoints (used only on LSI PMON target).
  298.    The table is indexed by a breakpoint number, which is an integer
  299.    from 0 to 255 returned by the LSI PMON when a breakpoint is set.  */

  300. #define MAX_LSI_BREAKPOINTS 256
  301. struct lsi_breakpoint_info
  302.   {
  303.     enum break_type type;        /* type of breakpoint */
  304.     CORE_ADDR addr;                /* address of breakpoint */
  305.     int len;                        /* length of region being watched */
  306.     unsigned long value;        /* value to watch */
  307.   }
  308. lsi_breakpoints[MAX_LSI_BREAKPOINTS];

  309. /* Error/warning codes returned by LSI PMON for breakpoint commands.
  310.    Warning values may be ORed together; error values may not.  */
  311. #define W_WARN        0x100                /* This bit is set if the error code
  312.                                    is a warning */
  313. #define W_MSK   0x101                /* warning: Range feature is supported
  314.                                    via mask */
  315. #define W_VAL   0x102                /* warning: Value check is not
  316.                                    supported in hardware */
  317. #define W_QAL   0x104                /* warning: Requested qualifiers are
  318.                                    not supported in hardware */

  319. #define E_ERR        0x200                /* This bit is set if the error code
  320.                                    is an error */
  321. #define E_BPT   0x200                /* error: No such breakpoint number */
  322. #define E_RGE   0x201                /* error: Range is not supported */
  323. #define E_QAL   0x202                /* error: The requested qualifiers can
  324.                                    not be used */
  325. #define E_OUT   0x203                /* error: Out of hardware resources */
  326. #define E_NON   0x204                /* error: Hardware breakpoint not supported */

  327. struct lsi_error
  328.   {
  329.     int code;                        /* error code */
  330.     char *string;                /* string associated with this code */
  331.   };

  332. struct lsi_error lsi_warning_table[] =
  333. {
  334.   {W_MSK, "Range feature is supported via mask"},
  335.   {W_VAL, "Value check is not supported in hardware"},
  336.   {W_QAL, "Requested qualifiers are not supported in hardware"},
  337.   {0, NULL}
  338. };

  339. struct lsi_error lsi_error_table[] =
  340. {
  341.   {E_BPT, "No such breakpoint number"},
  342.   {E_RGE, "Range is not supported"},
  343.   {E_QAL, "The requested qualifiers can not be used"},
  344.   {E_OUT, "Out of hardware resources"},
  345.   {E_NON, "Hardware breakpoint not supported"},
  346.   {0, NULL}
  347. };

  348. /* Set to 1 with the 'set monitor-warnings' command to enable printing
  349.    of warnings returned by PMON when hardware breakpoints are used.  */
  350. static int monitor_warnings;

  351. /* This is the ptid we use while we're connected to the remote.  Its
  352.    value is arbitrary, as the remote-mips target doesn't have a notion of
  353.    processes or threads, but we need something non-null to place in
  354.    inferior_ptid.  */
  355. static ptid_t remote_mips_ptid;

  356. /* Close any ports which might be open.  Reset certain globals indicating
  357.    the state of those ports.  */

  358. static void
  359. close_ports (void)
  360. {
  361.   mips_is_open = 0;
  362.   serial_close (mips_desc);

  363.   if (udp_in_use)
  364.     {
  365.       serial_close (udp_desc);
  366.       udp_in_use = 0;
  367.     }
  368.   tftp_in_use = 0;
  369. }

  370. /* Handle low-level error that we can't recover from.  Note that just
  371.    error()ing out from target_wait or some such low-level place will cause
  372.    all hell to break loose--the rest of GDB will tend to get left in an
  373.    inconsistent state.  */

  374. static void ATTRIBUTE_NORETURN
  375. mips_error (char *string,...)
  376. {
  377.   va_list args;
  378.   char *fmt;

  379.   target_terminal_ours ();
  380.   wrap_here ("");                /* Force out any buffered output.  */
  381.   gdb_flush (gdb_stdout);
  382.   gdb_flush (gdb_stderr);

  383.   /* Clean up in such a way that mips_close won't try to talk to the
  384.      board (it almost surely won't work since we weren't able to talk to
  385.      it).  */
  386.   close_ports ();

  387.   if (!ptid_equal (inferior_ptid, null_ptid))
  388.     target_mourn_inferior ();

  389.   fmt = concat (_("Ending remote MIPS debugging: "),
  390.                 string, (char *) NULL);
  391.   make_cleanup (xfree, fmt);

  392.   va_start (args, string);
  393.   throw_verror (TARGET_CLOSE_ERROR, fmt, args);
  394.   va_end (args);
  395. }

  396. /* putc_readable - print a character, displaying non-printable chars in
  397.    ^x notation or in hex.  */

  398. static void
  399. fputc_readable (int ch, struct ui_file *file)
  400. {
  401.   if (ch == '\n')
  402.     fputc_unfiltered ('\n', file);
  403.   else if (ch == '\r')
  404.     fprintf_unfiltered (file, "\\r");
  405.   else if (ch < 0x20)                /* ASCII control character */
  406.     fprintf_unfiltered (file, "^%c", ch + '@');
  407.   else if (ch >= 0x7f)                /* non-ASCII characters (rubout or greater) */
  408.     fprintf_unfiltered (file, "[%02x]", ch & 0xff);
  409.   else
  410.     fputc_unfiltered (ch, file);
  411. }


  412. /* puts_readable - print a string, displaying non-printable chars in
  413.    ^x notation or in hex.  */

  414. static void
  415. fputs_readable (const char *string, struct ui_file *file)
  416. {
  417.   int c;

  418.   while ((c = *string++) != '\0')
  419.     fputc_readable (c, file);
  420. }


  421. /* Read P as a hex value.  Return true if every character made sense,
  422.    storing the result in *RESULT.  Leave *RESULT unchanged otherwise.  */

  423. static int
  424. read_hex_value (const char *p, ULONGEST *result)
  425. {
  426.   ULONGEST retval;

  427.   retval = 0;
  428.   while (*p != 0)
  429.     {
  430.       retval <<= 4;
  431.       if (*p >= '0' && *p <= '9')
  432.         retval |= *p - '0';
  433.       else if (*p >= 'A' && *p <= 'F')
  434.         retval |= *p - 'A' + 10;
  435.       else if (*p >= 'a' && *p <= 'f')
  436.         retval |= *p - 'a' + 10;
  437.       else
  438.         return 0;
  439.       p++;
  440.     }
  441.   *result = retval;
  442.   return 1;
  443. }


  444. /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
  445.    timed out.  TIMEOUT specifies timeout value in seconds.  */

  446. static int
  447. mips_expect_timeout (const char *string, int timeout)
  448. {
  449.   const char *p = string;

  450.   if (remote_debug)
  451.     {
  452.       fprintf_unfiltered (gdb_stdlog, "Expected \"");
  453.       fputs_readable (string, gdb_stdlog);
  454.       fprintf_unfiltered (gdb_stdlog, "\", got \"");
  455.     }

  456.   immediate_quit++;
  457.   QUIT;
  458.   while (1)
  459.     {
  460.       int c;

  461.       /* Must use serial_readchar() here cuz mips_readchar would get
  462.          confused if we were waiting for the mips_monitor_prompt...  */

  463.       c = serial_readchar (mips_desc, timeout);

  464.       if (c == SERIAL_TIMEOUT)
  465.         {
  466.           if (remote_debug)
  467.             fprintf_unfiltered (gdb_stdlog, "\": FAIL\n");
  468.           return 0;
  469.         }

  470.       if (remote_debug)
  471.         fputc_readable (c, gdb_stdlog);

  472.       if (c == *p++)
  473.         {
  474.           if (*p == '\0')
  475.             {
  476.               immediate_quit--;
  477.               if (remote_debug)
  478.                 fprintf_unfiltered (gdb_stdlog, "\": OK\n");
  479.               return 1;
  480.             }
  481.         }
  482.       else
  483.         {
  484.           p = string;
  485.           if (c == *p)
  486.             p++;
  487.         }
  488.     }
  489. }

  490. /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
  491.    timed out.  The timeout value is hard-coded to 2 seconds.  Use
  492.    mips_expect_timeout if a different timeout value is needed.  */

  493. static int
  494. mips_expect (const char *string)
  495. {
  496.   return mips_expect_timeout (string, remote_timeout);
  497. }

  498. /* Read a character from the remote, aborting on error.  Returns
  499.    SERIAL_TIMEOUT on timeout (since that's what serial_readchar()
  500.    returns).  FIXME: If we see the string mips_monitor_prompt from the
  501.    board, then we are debugging on the main console port, and we have
  502.    somehow dropped out of remote debugging mode.  In this case, we
  503.    automatically go back in to remote debugging mode.  This is a hack,
  504.    put in because I can't find any way for a program running on the
  505.    remote board to terminate without also ending remote debugging
  506.    mode.  I assume users won't have any trouble with this; for one
  507.    thing, the IDT documentation generally assumes that the remote
  508.    debugging port is not the console port.  This is, however, very
  509.    convenient for DejaGnu when you only have one connected serial
  510.    port.  */

  511. static int
  512. mips_readchar (int timeout)
  513. {
  514.   int ch;
  515.   static int state = 0;
  516.   int mips_monitor_prompt_len = strlen (mips_monitor_prompt);

  517.   { /* FIXME this whole block is dead code!  */
  518.     int i;

  519.     i = timeout;
  520.     if (i == -1 && watchdog > 0)
  521.       i = watchdog;
  522.   }

  523.   if (state == mips_monitor_prompt_len)
  524.     timeout = 1;
  525.   ch = serial_readchar (mips_desc, timeout);

  526.   if (ch == SERIAL_TIMEOUT && timeout == -1)        /* Watchdog went off.  */
  527.     {
  528.       target_mourn_inferior ();
  529.       error (_("Watchdog has expired.  Target detached."));
  530.     }

  531.   if (ch == SERIAL_EOF)
  532.     mips_error (_("End of file from remote"));
  533.   if (ch == SERIAL_ERROR)
  534.     mips_error (_("Error reading from remote: %s"), safe_strerror (errno));
  535.   if (remote_debug > 1)
  536.     {
  537.       /* Don't use _filtered; we can't deal with a QUIT out of
  538.          target_wait, and I think this might be called from there.  */
  539.       if (ch != SERIAL_TIMEOUT)
  540.         fprintf_unfiltered (gdb_stdlog, "Read '%c' %d 0x%x\n", ch, ch, ch);
  541.       else
  542.         fprintf_unfiltered (gdb_stdlog, "Timed out in read\n");
  543.     }

  544.   /* If we have seen mips_monitor_prompt and we either time out, or
  545.      we see a @ (which was echoed from a packet we sent), reset the
  546.      board as described above.  The first character in a packet after
  547.      the SYN (which is not echoed) is always an @ unless the packet is
  548.      more than 64 characters long, which ours never are.  */
  549.   if ((ch == SERIAL_TIMEOUT || ch == '@')
  550.       && state == mips_monitor_prompt_len
  551.       && !mips_initializing
  552.       && !mips_exiting)
  553.     {
  554.       if (remote_debug > 0)
  555.         /* Don't use _filtered; we can't deal with a QUIT out of
  556.            target_wait, and I think this might be called from there.  */
  557.         fprintf_unfiltered (gdb_stdlog,
  558.                             "Reinitializing MIPS debugging mode\n");

  559.       mips_need_reply = 0;
  560.       mips_initialize ();

  561.       state = 0;

  562.       /* At this point, about the only thing we can do is abort the command
  563.          in progress and get back to command level as quickly as possible.  */

  564.       error (_("Remote board reset, debug protocol re-initialized."));
  565.     }

  566.   if (ch == mips_monitor_prompt[state])
  567.     ++state;
  568.   else
  569.     state = 0;

  570.   return ch;
  571. }

  572. /* Get a packet header, putting the data in the supplied buffer.
  573.    PGARBAGE is a pointer to the number of garbage characters received
  574.    so far.  CH is the last character received.  Returns 0 for success,
  575.    or -1 for timeout.  */

  576. static int
  577. mips_receive_header (unsigned char *hdr, int *pgarbage, int ch, int timeout)
  578. {
  579.   int i;

  580.   while (1)
  581.     {
  582.       /* Wait for a SYNmips_syn_garbage is intended to prevent
  583.          sitting here indefinitely if the board sends us one garbage
  584.          character per secondch may already have a value from the
  585.          last time through the loop.  */
  586.       while (ch != SYN)
  587.         {
  588.           ch = mips_readchar (timeout);
  589.           if (ch == SERIAL_TIMEOUT)
  590.             return -1;
  591.           if (ch != SYN)
  592.             {
  593.               /* Printing the character here lets the user of gdb see
  594.                  what the program is outputting, if the debugging is
  595.                  being done on the console port.  Don't use _filtered:
  596.                  we can't deal with a QUIT out of target_wait and
  597.                  buffered target output confuses the user.  */
  598.                if (!mips_initializing || remote_debug > 0)
  599.                   {
  600.                   if (isprint (ch) || isspace (ch))
  601.                     {
  602.                       fputc_unfiltered (ch, gdb_stdtarg);
  603.                     }
  604.                   else
  605.                     {
  606.                       fputc_readable (ch, gdb_stdtarg);
  607.                     }
  608.                   gdb_flush (gdb_stdtarg);
  609.                   }

  610.               /* Only count unprintable characters.  */
  611.               if (! (isprint (ch) || isspace (ch)))
  612.                 (*pgarbage) += 1;

  613.               if (mips_syn_garbage > 0
  614.                   && *pgarbage > mips_syn_garbage)
  615.                 mips_error (_("Debug protocol failure:  more "
  616.                             "than %d characters before a sync."),
  617.                             mips_syn_garbage);
  618.             }
  619.         }

  620.       /* Get the packet header following the SYN.  */
  621.       for (i = 1; i < HDR_LENGTH; i++)
  622.         {
  623.           ch = mips_readchar (timeout);
  624.           if (ch == SERIAL_TIMEOUT)
  625.             return -1;
  626.           /* Make sure this is a header byte.  */
  627.           if (ch == SYN || !HDR_CHECK (ch))
  628.             break;

  629.           hdr[i] = ch;
  630.         }

  631.       /* If we got the complete header, we can return.  Otherwise we
  632.          loop around and keep looking for SYN.  */
  633.       if (i >= HDR_LENGTH)
  634.         return 0;
  635.     }
  636. }

  637. /* Get a packet header, putting the data in the supplied buffer.
  638.    PGARBAGE is a pointer to the number of garbage characters received
  639.    so far.  The last character read is returned in *PCH.  Returns 0
  640.    for success, -1 for timeout, -2 for error.  */

  641. static int
  642. mips_receive_trailer (unsigned char *trlr, int *pgarbage,
  643.                       int *pch, int timeout)
  644. {
  645.   int i;
  646.   int ch;

  647.   for (i = 0; i < TRLR_LENGTH; i++)
  648.     {
  649.       ch = mips_readchar (timeout);
  650.       *pch = ch;
  651.       if (ch == SERIAL_TIMEOUT)
  652.         return -1;
  653.       if (!TRLR_CHECK (ch))
  654.         return -2;
  655.       trlr[i] = ch;
  656.     }
  657.   return 0;
  658. }

  659. /* Get the checksum of a packet.  HDR points to the packet header.
  660.    DATASTR points to the packet data.  LEN is the length of DATASTR.  */

  661. static int
  662. mips_cksum (const unsigned char *hdr, const char *datastr, int len)
  663. {
  664.   const unsigned char *p;
  665.   const unsigned char *data = (const unsigned char *) datastr;
  666.   int c;
  667.   int cksum;

  668.   cksum = 0;

  669.   /* The initial SYN is not included in the checksum.  */
  670.   c = HDR_LENGTH - 1;
  671.   p = hdr + 1;
  672.   while (c-- != 0)
  673.     cksum += *p++;

  674.   c = len;
  675.   p = data;
  676.   while (c-- != 0)
  677.     cksum += *p++;

  678.   return cksum;
  679. }

  680. /* Send a packet containing the given ASCII string.  */

  681. static void
  682. mips_send_packet (const char *s, int get_ack)
  683. {
  684.   /* unsigned */ int len;
  685.   unsigned char *packet;
  686.   int cksum;
  687.   int try;

  688.   len = strlen (s);
  689.   if (len > DATA_MAXLEN)
  690.     mips_error (_("MIPS protocol data packet too long: %s"), s);

  691.   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);

  692.   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
  693.   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
  694.   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
  695.   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);

  696.   memcpy (packet + HDR_LENGTH, s, len);

  697.   cksum = mips_cksum (packet, (char *) packet + HDR_LENGTH, len);
  698.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  699.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  700.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);

  701.   /* Increment the sequence number.  This will set mips_send_seq to
  702.      the sequence number we expect in the acknowledgement.  */
  703.   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;

  704.   /* We can only have one outstanding data packet, so we just wait for
  705.      the acknowledgement here.  Keep retransmitting the packet until
  706.      we get one, or until we've tried too many times.  */
  707.   for (try = 0; try < mips_send_retries; try++)
  708.     {
  709.       int garbage;
  710.       int ch;

  711.       if (remote_debug > 0)
  712.         {
  713.           /* Don't use _filtered; we can't deal with a QUIT out of
  714.              target_wait, and I think this might be called from there.  */
  715.           packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
  716.           fprintf_unfiltered (gdb_stdlog, "Writing \"%s\"\n", packet + 1);
  717.         }

  718.       if (serial_write (mips_desc, packet,
  719.                         HDR_LENGTH + len + TRLR_LENGTH) != 0)
  720.         mips_error (_("write to target failed: %s"), safe_strerror (errno));

  721.       if (!get_ack)
  722.         return;

  723.       garbage = 0;
  724.       ch = 0;
  725.       while (1)
  726.         {
  727.           unsigned char hdr[HDR_LENGTH + 1];
  728.           unsigned char trlr[TRLR_LENGTH + 1];
  729.           int err;
  730.           unsigned int seq;

  731.           /* Get the packet header.  If we time out, resend the data
  732.              packet.  */
  733.           err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
  734.           if (err != 0)
  735.             break;

  736.           ch = 0;

  737.           /* If we get a data packet, assume it is a duplicate and
  738.              ignore it.  FIXME: If the acknowledgement is lost, this
  739.              data packet may be the packet the remote sends after the
  740.              acknowledgement.  */
  741.           if (HDR_IS_DATA (hdr))
  742.             {
  743.               int i;

  744.               /* Ignore any errors raised whilst attempting to ignore
  745.                  packet.  */

  746.               len = HDR_GET_LEN (hdr);

  747.               for (i = 0; i < len; i++)
  748.                 {
  749.                   int rch;

  750.                   rch = mips_readchar (remote_timeout);
  751.                   if (rch == SYN)
  752.                     {
  753.                       ch = SYN;
  754.                       break;
  755.                     }
  756.                   if (rch == SERIAL_TIMEOUT)
  757.                     break;
  758.                   /* Ignore the character.  */
  759.                 }

  760.               if (i == len)
  761.                 (void) mips_receive_trailer (trlr, &garbage, &ch,
  762.                                              remote_timeout);

  763.               /* We don't bother checking the checksum, or providing an
  764.                  ACK to the packet.  */
  765.               continue;
  766.             }

  767.           /* If the length is not 0, this is a garbled packet.  */
  768.           if (HDR_GET_LEN (hdr) != 0)
  769.             continue;

  770.           /* Get the packet trailer.  */
  771.           err = mips_receive_trailer (trlr, &garbage, &ch,
  772.                                       mips_retransmit_wait);

  773.           /* If we timed out, resend the data packet.  */
  774.           if (err == -1)
  775.             break;

  776.           /* If we got a bad character, reread the header.  */
  777.           if (err != 0)
  778.             continue;

  779.           /* If the checksum does not match the trailer checksum, this
  780.              is a bad packet; ignore it.  */
  781.           if (mips_cksum (hdr, NULL, 0) != TRLR_GET_CKSUM (trlr))
  782.             continue;

  783.           if (remote_debug > 0)
  784.             {
  785.               hdr[HDR_LENGTH] = '\0';
  786.               trlr[TRLR_LENGTH] = '\0';
  787.               /* Don't use _filtered; we can't deal with a QUIT out of
  788.                  target_wait, and I think this might be called from there.  */
  789.               fprintf_unfiltered (gdb_stdlog, "Got ack %d \"%s%s\"\n",
  790.                                   HDR_GET_SEQ (hdr), hdr + 1, trlr);
  791.             }

  792.           /* If this ack is for the current packet, we're done.  */
  793.           seq = HDR_GET_SEQ (hdr);
  794.           if (seq == mips_send_seq)
  795.             return;

  796.           /* If this ack is for the last packet, resend the current
  797.              packet.  */
  798.           if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
  799.             break;

  800.           /* Otherwise this is a bad ack; ignore it.  Increment the
  801.              garbage count to ensure that we do not stay in this loop
  802.              forever.  */
  803.           ++garbage;
  804.         }
  805.     }

  806.   mips_error (_("Remote did not acknowledge packet"));
  807. }

  808. /* Receive and acknowledge a packet, returning the data in BUFF (which
  809.    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
  810.    implies that only the sender retransmits packets, so this code just
  811.    waits silently for a packet.  It returns the length of the received
  812.    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
  813.    don't print an error message and return -1.  */

  814. static int
  815. mips_receive_packet (char *buff, int throw_error, int timeout)
  816. {
  817.   int ch;
  818.   int garbage;
  819.   int len;
  820.   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
  821.   int cksum;

  822.   ch = 0;
  823.   garbage = 0;
  824.   while (1)
  825.     {
  826.       unsigned char hdr[HDR_LENGTH];
  827.       unsigned char trlr[TRLR_LENGTH];
  828.       int i;
  829.       int err;

  830.       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
  831.         {
  832.           if (throw_error)
  833.             mips_error (_("Timed out waiting for remote packet"));
  834.           else
  835.             return -1;
  836.         }

  837.       ch = 0;

  838.       /* An acknowledgement is probably a duplicate; ignore it.  */
  839.       if (!HDR_IS_DATA (hdr))
  840.         {
  841.           len = HDR_GET_LEN (hdr);
  842.           /* Check if the length is valid for an ACK, we may aswell
  843.              try and read the remainder of the packet: */
  844.           if (len == 0)
  845.             {
  846.               /* Ignore the error condition, since we are going to
  847.                  ignore the packet anyway.  */
  848.               (void) mips_receive_trailer (trlr, &garbage, &ch, timeout);
  849.             }
  850.           /* Don't use _filtered; we can't deal with a QUIT out of
  851.              target_wait, and I think this might be called from there.  */
  852.           if (remote_debug > 0)
  853.             fprintf_unfiltered (gdb_stdlog, "Ignoring unexpected ACK\n");
  854.           continue;
  855.         }

  856.       len = HDR_GET_LEN (hdr);
  857.       for (i = 0; i < len; i++)
  858.         {
  859.           int rch;

  860.           rch = mips_readchar (timeout);
  861.           if (rch == SYN)
  862.             {
  863.               ch = SYN;
  864.               break;
  865.             }
  866.           if (rch == SERIAL_TIMEOUT)
  867.             {
  868.               if (throw_error)
  869.                 mips_error (_("Timed out waiting for remote packet"));
  870.               else
  871.                 return -1;
  872.             }
  873.           buff[i] = rch;
  874.         }

  875.       if (i < len)
  876.         {
  877.           /* Don't use _filtered; we can't deal with a QUIT out of
  878.              target_wait, and I think this might be called from there.  */
  879.           if (remote_debug > 0)
  880.             fprintf_unfiltered (gdb_stdlog,
  881.                                 "Got new SYN after %d chars (wanted %d)\n",
  882.                                 i, len);
  883.           continue;
  884.         }

  885.       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
  886.       if (err == -1)
  887.         {
  888.           if (throw_error)
  889.             mips_error (_("Timed out waiting for packet"));
  890.           else
  891.             return -1;
  892.         }
  893.       if (err == -2)
  894.         {
  895.           /* Don't use _filtered; we can't deal with a QUIT out of
  896.              target_wait, and I think this might be called from there.  */
  897.           if (remote_debug > 0)
  898.             fprintf_unfiltered (gdb_stdlog, "Got SYN when wanted trailer\n");
  899.           continue;
  900.         }

  901.       /* If this is the wrong sequence number, ignore it.  */
  902.       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
  903.         {
  904.           /* Don't use _filtered; we can't deal with a QUIT out of
  905.              target_wait, and I think this might be called from there.  */
  906.           if (remote_debug > 0)
  907.             fprintf_unfiltered (gdb_stdlog,
  908.                                 "Ignoring sequence number %d (want %d)\n",
  909.                                 HDR_GET_SEQ (hdr), mips_receive_seq);
  910.           continue;
  911.         }

  912.       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
  913.         break;

  914.       if (remote_debug > 0)
  915.         /* Don't use _filtered; we can't deal with a QUIT out of
  916.            target_wait, and I think this might be called from there.  */
  917.         printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
  918.                            mips_cksum (hdr, buff, len),
  919.                            TRLR_GET_CKSUM (trlr));

  920.       /* The checksum failed.  Send an acknowledgement for the
  921.          previous packet to tell the remote to resend the packet.  */
  922.       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
  923.       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
  924.       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
  925.       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);

  926.       cksum = mips_cksum (ack, NULL, 0);

  927.       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  928.       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  929.       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);

  930.       if (remote_debug > 0)
  931.         {
  932.           ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
  933.           /* Don't use _filtered; we can't deal with a QUIT out of
  934.              target_wait, and I think this might be called from there.  */
  935.           printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
  936.                              ack + 1);
  937.         }

  938.       if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
  939.         {
  940.           if (throw_error)
  941.             mips_error (_("write to target failed: %s"),
  942.                         safe_strerror (errno));
  943.           else
  944.             return -1;
  945.         }
  946.     }

  947.   if (remote_debug > 0)
  948.     {
  949.       buff[len] = '\0';
  950.       /* Don't use _filtered; we can't deal with a QUIT out of
  951.          target_wait, and I think this might be called from there.  */
  952.       printf_unfiltered ("Got packet \"%s\"\n", buff);
  953.     }

  954.   /* We got the packet.  Send an acknowledgement.  */
  955.   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;

  956.   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
  957.   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
  958.   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
  959.   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);

  960.   cksum = mips_cksum (ack, NULL, 0);

  961.   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  962.   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  963.   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);

  964.   if (remote_debug > 0)
  965.     {
  966.       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
  967.       /* Don't use _filtered; we can't deal with a QUIT out of
  968.          target_wait, and I think this might be called from there.  */
  969.       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
  970.                          ack + 1);
  971.     }

  972.   if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
  973.     {
  974.       if (throw_error)
  975.         mips_error (_("write to target failed: %s"), safe_strerror (errno));
  976.       else
  977.         return -1;
  978.     }

  979.   return len;
  980. }

  981. /* Optionally send a request to the remote system and optionally wait
  982.    for the reply.  This implements the remote debugging protocol,
  983.    which is built on top of the packet protocol defined above.  Each
  984.    request has an ADDR argument and a DATA argument.  The following
  985.    requests are defined:

  986.    \0   don't send a request; just wait for a reply
  987.    i    read word from instruction space at ADDR
  988.    d    read word from data space at ADDR
  989.    I    write DATA to instruction space at ADDR
  990.    D    write DATA to data space at ADDR
  991.    r    read register number ADDR
  992.    R    set register number ADDR to value DATA
  993.    c    continue execution (if ADDR != 1, set pc to ADDR)
  994.    s    single step (if ADDR != 1, set pc to ADDR)

  995.    The read requests return the value requested.  The write requests
  996.    return the previous value in the changed location.  The execution
  997.    requests return a UNIX wait value (the approximate signal which
  998.    caused execution to stop is in the upper eight bits).

  999.    If PERR is not NULL, this function waits for a reply.  If an error
  1000.    occurs, it sets *PERR to 1 and sets errno according to what the
  1001.    target board reports.  */

  1002. static ULONGEST
  1003. mips_request (int cmd,
  1004.               ULONGEST addr,
  1005.               ULONGEST data,
  1006.               int *perr,
  1007.               int timeout,
  1008.               char *buff)
  1009. {
  1010.   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
  1011.   char myBuff[DATA_MAXLEN + 1];
  1012.   char response_string[17];
  1013.   int len;
  1014.   int rpid;
  1015.   char rcmd;
  1016.   int rerrflg;
  1017.   ULONGEST rresponse;

  1018.   if (buff == (char *) NULL)
  1019.     buff = myBuff;

  1020.   if (cmd != '\0')
  1021.     {
  1022.       if (mips_need_reply)
  1023.         internal_error (__FILE__, __LINE__,
  1024.                         _("mips_request: Trying to send "
  1025.                           "command before reply"));
  1026.       /* 'T' sets a register to a 64-bit value, so make sure we use
  1027.          the right conversion function.  */
  1028.       if (cmd == 'T')
  1029.         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
  1030.                  phex_nz (addr, addr_size), phex_nz (data, 8));
  1031.       else
  1032.         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
  1033.                  phex_nz (addr, addr_size), phex_nz (data, addr_size));

  1034.       mips_send_packet (buff, 1);
  1035.       mips_need_reply = 1;
  1036.     }

  1037.   if (perr == (int *) NULL)
  1038.     return 0;

  1039.   if (!mips_need_reply)
  1040.     internal_error (__FILE__, __LINE__,
  1041.                     _("mips_request: Trying to get reply before command"));

  1042.   mips_need_reply = 0;

  1043.   len = mips_receive_packet (buff, 1, timeout);
  1044.   buff[len] = '\0';

  1045.   if (sscanf (buff, "0x%x %c 0x%x 0x%16s",
  1046.               &rpid, &rcmd, &rerrflg, response_string) != 4
  1047.       || !read_hex_value (response_string, &rresponse)
  1048.       || (cmd != '\0' && rcmd != cmd))
  1049.     mips_error (_("Bad response from remote board"));

  1050.   if (rerrflg != 0)
  1051.     {
  1052.       *perr = 1;

  1053.       /* FIXME: This will returns MIPS errno numbers, which may or may
  1054.          not be the same as errno values used on other systems.  If
  1055.          they stick to common errno values, they will be the same, but
  1056.          if they don't, they must be translated.  */
  1057.       errno = rresponse;

  1058.       return 0;
  1059.     }

  1060.   *perr = 0;
  1061.   return rresponse;
  1062. }

  1063. /* Cleanup associated with mips_initialize().  */

  1064. static void
  1065. mips_initialize_cleanups (void *arg)
  1066. {
  1067.   mips_initializing = 0;
  1068. }

  1069. /* Cleanup associated with mips_exit_debug().  */

  1070. static void
  1071. mips_exit_cleanups (void *arg)
  1072. {
  1073.   mips_exiting = 0;
  1074. }

  1075. /* Send a command and wait for that command to be echoed back.  Wait,
  1076.    too, for the following prompt.  */

  1077. static void
  1078. mips_send_command (const char *cmd, int prompt)
  1079. {
  1080.   serial_write (mips_desc, cmd, strlen (cmd));
  1081.   mips_expect (cmd);
  1082.   mips_expect ("\n");
  1083.   if (prompt)
  1084.     mips_expect (mips_monitor_prompt);
  1085. }

  1086. /* Enter remote (dbx) debug mode: */

  1087. static void
  1088. mips_enter_debug (void)
  1089. {
  1090.   /* Reset the sequence numbers, ready for the new debug sequence: */
  1091.   mips_send_seq = 0;
  1092.   mips_receive_seq = 0;

  1093.   if (mips_monitor != MON_IDT)
  1094.     mips_send_command ("debug\r", 0);
  1095.   else                                /* Assume IDT monitor by default.  */
  1096.     mips_send_command ("db tty0\r", 0);

  1097.   gdb_usleep (1000000);
  1098.   serial_write (mips_desc, "\r", sizeof "\r" - 1);

  1099.   /* We don't need to absorb any spurious characters here, since the
  1100.      mips_receive_header will eat up a reasonable number of characters
  1101.      whilst looking for the SYN, however this avoids the "garbage"
  1102.      being displayed to the user.  */
  1103.   if (mips_monitor != MON_IDT)
  1104.     mips_expect ("\r");

  1105.   {
  1106.     char buff[DATA_MAXLEN + 1];

  1107.     if (mips_receive_packet (buff, 1, 3) < 0)
  1108.       mips_error (_("Failed to initialize (didn't receive packet)."));
  1109.   }
  1110. }

  1111. /* Exit remote (dbx) debug mode, returning to the monitor prompt: */

  1112. static int
  1113. mips_exit_debug (void)
  1114. {
  1115.   int err;
  1116.   struct cleanup *old_cleanups = make_cleanup (mips_exit_cleanups, NULL);

  1117.   mips_exiting = 1;

  1118.   if (mips_monitor != MON_IDT && mips_monitor != MON_ROCKHOPPER)
  1119.     {
  1120.       /* The DDB (NEC) and MiniRISC (LSI) versions of PMON exit immediately,
  1121.          so we do not get a reply to this command: */
  1122.       mips_request ('x', 0, 0, NULL, mips_receive_wait, NULL);
  1123.       mips_need_reply = 0;
  1124.       if (!mips_expect (" break!"))
  1125.         {
  1126.           do_cleanups (old_cleanups);
  1127.           return -1;
  1128.         }
  1129.     }
  1130.   else
  1131.     mips_request ('x', 0, 0, &err, mips_receive_wait, NULL);

  1132.   if (!mips_expect (mips_monitor_prompt))
  1133.     {
  1134.       do_cleanups (old_cleanups);
  1135.       return -1;
  1136.     }

  1137.   do_cleanups (old_cleanups);

  1138.   return 0;
  1139. }

  1140. /* Initialize a new connection to the MIPS board, and make sure we are
  1141.    really connected.  */

  1142. static void
  1143. mips_initialize (void)
  1144. {
  1145.   int err;
  1146.   struct cleanup *old_cleanups;
  1147.   int j;

  1148.   /* What is this code doing here?  I don't see any way it can happen, and
  1149.      it might mean mips_initializing didn't get cleared properly.
  1150.      So I'll make it a warning.  */

  1151.   if (mips_initializing)
  1152.     {
  1153.       warning (_("internal error: mips_initialize called twice"));
  1154.       return;
  1155.     }

  1156.   old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);

  1157.   mips_wait_flag = 0;
  1158.   mips_initializing = 1;

  1159.   /* At this point, the packit protocol isn't responding.  We'll try getting
  1160.      into the monitor, and restarting the protocol.  */

  1161.   /* Force the system into the monitor.  After this we *should* be at
  1162.      the mips_monitor_prompt.  */
  1163.   if (mips_monitor != MON_IDT)
  1164.     j = 0;                        /* Start by checking if we are already
  1165.                                    at the prompt.  */
  1166.   else
  1167.     j = 1;                        /* Start by sending a break.  */
  1168.   for (; j <= 4; j++)
  1169.     {
  1170.       switch (j)
  1171.         {
  1172.         case 0:                /* First, try sending a CR.  */
  1173.           serial_flush_input (mips_desc);
  1174.           serial_write (mips_desc, "\r", 1);
  1175.           break;
  1176.         case 1:                /* First, try sending a break.  */
  1177.           serial_send_break (mips_desc);
  1178.           break;
  1179.         case 2:                /* Then, try a ^C.  */
  1180.           serial_write (mips_desc, "\003", 1);
  1181.           break;
  1182.         case 3:                /* Then, try escaping from download.  */
  1183.           {
  1184.             if (mips_monitor != MON_IDT)
  1185.               {
  1186.                 char tbuff[7];

  1187.                 /* We shouldn't need to send multiple termination
  1188.                    sequences, since the target performs line (or
  1189.                    block) reads, and then processes those
  1190.                    packets.  In-case we were downloading a large packet
  1191.                    we flush the output buffer before inserting a
  1192.                    termination sequence.  */
  1193.                 serial_flush_output (mips_desc);
  1194.                 sprintf (tbuff, "\r/E/E\r");
  1195.                 serial_write (mips_desc, tbuff, 6);
  1196.               }
  1197.             else
  1198.               {
  1199.                 char srec[10];
  1200.                 int i;

  1201.                 /* We are possibly in binary download mode, having
  1202.                    aborted in the middle of an S-record.  ^C won't
  1203.                    work because of binary mode.  The only reliable way
  1204.                    out is to send enough termination packets (8 bytes)
  1205.                    to fill up and then overflow the largest size
  1206.                    S-record (255 bytes in this case).  This amounts to
  1207.                    256/8 + 1 packets.  */

  1208.                 mips_make_srec (srec, '7', 0, NULL, 0);

  1209.                 for (i = 1; i <= 33; i++)
  1210.                   {
  1211.                     serial_write (mips_desc, srec, 8);

  1212.                     if (serial_readchar (mips_desc, 0) >= 0)
  1213.                       break;        /* Break immediatly if we get something from
  1214.                                    the board.  */
  1215.                   }
  1216.               }
  1217.           }
  1218.           break;
  1219.         case 4:
  1220.           mips_error (_("Failed to initialize."));
  1221.         }

  1222.       if (mips_expect (mips_monitor_prompt))
  1223.         break;
  1224.     }

  1225.   if (mips_monitor != MON_IDT)
  1226.     {
  1227.       /* Sometimes PMON ignores the first few characters in the first
  1228.          command sent after a load.  Sending a blank command gets
  1229.          around that.  */
  1230.       mips_send_command ("\r", -1);

  1231.       /* Ensure the correct target state: */
  1232.       if (mips_monitor != MON_LSI)
  1233.         mips_send_command ("set regsize 64\r", -1);
  1234.       mips_send_command ("set hostport tty0\r", -1);
  1235.       mips_send_command ("set brkcmd \"\"\r", -1);
  1236.       /* Delete all the current breakpoints: */
  1237.       mips_send_command ("db *\r", -1);
  1238.       /* NOTE: PMON does not have breakpoint support through the
  1239.          "debug" mode, only at the monitor command-line.  */
  1240.     }

  1241.   mips_enter_debug ();

  1242.   /* Clear all breakpoints: */
  1243.   if ((mips_monitor == MON_IDT
  1244.        && mips_clear_breakpoint (-1, 0, BREAK_UNUSED) == 0)
  1245.       || mips_monitor == MON_LSI)
  1246.     monitor_supports_breakpoints = 1;
  1247.   else
  1248.     monitor_supports_breakpoints = 0;

  1249.   do_cleanups (old_cleanups);

  1250.   /* If this doesn't call error, we have connected; we don't care if
  1251.      the request itself succeeds or fails.  */

  1252.   mips_request ('r', 0, 0, &err, mips_receive_wait, NULL);
  1253. }

  1254. /* Open a connection to the remote board.  */

  1255. static void
  1256. common_open (struct target_ops *ops, const char *name, int from_tty,
  1257.              enum mips_monitor_type new_monitor,
  1258.              const char *new_monitor_prompt)
  1259. {
  1260.   char *serial_port_name;
  1261.   char *remote_name = 0;
  1262.   char *local_name = 0;
  1263.   char **argv;
  1264.   struct cleanup *cleanup;

  1265.   if (name == 0)
  1266.     error (_("\
  1267. To open a MIPS remote debugging connection, you need to specify what\n\
  1268. serial device is attached to the target board (e.g., /dev/ttya).\n\
  1269. If you want to use TFTP to download to the board, specify the name of a\n\
  1270. temporary file to be used by GDB for downloads as the second argument.\n\
  1271. This filename must be in the form host:filename, where host is the name\n\
  1272. of the host running the TFTP server, and the file must be readable by the\n\
  1273. world.  If the local name of the temporary file differs from the name as\n\
  1274. seen from the board via TFTP, specify that name as the third parameter.\n"));

  1275.   /* Parse the serial port name, the optional TFTP name, and the
  1276.      optional local TFTP name.  */
  1277.   argv = gdb_buildargv (name);
  1278.   cleanup = make_cleanup_freeargv (argv);

  1279.   serial_port_name = xstrdup (argv[0]);
  1280.   if (argv[1])                        /* Remote TFTP name specified?  */
  1281.     {
  1282.       remote_name = argv[1];
  1283.       if (argv[2])                /* Local TFTP filename specified?  */
  1284.         local_name = argv[2];
  1285.     }

  1286.   target_preopen (from_tty);

  1287.   if (mips_is_open)
  1288.     unpush_target (current_ops);

  1289.   /* Open and initialize the serial port.  */
  1290.   mips_desc = serial_open (serial_port_name);
  1291.   if (mips_desc == NULL)
  1292.     perror_with_name (serial_port_name);

  1293.   if (baud_rate != -1)
  1294.     {
  1295.       if (serial_setbaudrate (mips_desc, baud_rate))
  1296.         {
  1297.           serial_close (mips_desc);
  1298.           perror_with_name (serial_port_name);
  1299.         }
  1300.     }

  1301.   serial_raw (mips_desc);

  1302.   /* Open and initialize the optional download port.  If it is in the form
  1303.      hostname#portnumber, it's a UDP socket.  If it is in the form
  1304.      hostname:filename, assume it's the TFTP filename that must be
  1305.      passed to the DDB board to tell it where to get the load file.  */
  1306.   if (remote_name)
  1307.     {
  1308.       if (strchr (remote_name, '#'))
  1309.         {
  1310.           udp_desc = serial_open (remote_name);
  1311.           if (!udp_desc)
  1312.             perror_with_name (_("Unable to open UDP port"));
  1313.           udp_in_use = 1;
  1314.         }
  1315.       else
  1316.         {
  1317.           /* Save the remote and local names of the TFTP temp file.  If
  1318.              the user didn't specify a local name, assume it's the same
  1319.              as the part of the remote name after the "host:".  */
  1320.           if (tftp_name)
  1321.             xfree (tftp_name);
  1322.           if (tftp_localname)
  1323.             xfree (tftp_localname);
  1324.           if (local_name == NULL)
  1325.             if ((local_name = strchr (remote_name, ':')) != NULL)
  1326.               local_name++;        /* Skip over the colon.  */
  1327.           if (local_name == NULL)
  1328.             local_name = remote_name;        /* Local name same as remote name.  */
  1329.           tftp_name = xstrdup (remote_name);
  1330.           tftp_localname = xstrdup (local_name);
  1331.           tftp_in_use = 1;
  1332.         }
  1333.     }

  1334.   current_ops = ops;
  1335.   mips_is_open = 1;

  1336.   /* Reset the expected monitor prompt if it's never been set before.  */
  1337.   if (mips_monitor_prompt == NULL)
  1338.     mips_monitor_prompt = xstrdup (new_monitor_prompt);
  1339.   mips_monitor = new_monitor;

  1340.   mips_initialize ();

  1341.   if (from_tty)
  1342.     printf_unfiltered ("Remote MIPS debugging using %s\n", serial_port_name);

  1343.   /* Switch to using remote target now.  */
  1344.   push_target (ops);

  1345.   inferior_ptid = remote_mips_ptid;
  1346.   inferior_appeared (current_inferior (), ptid_get_pid (inferior_ptid));
  1347.   add_thread_silent (inferior_ptid);

  1348.   /* Try to figure out the processor model if possible.  */
  1349.   deprecated_mips_set_processor_regs_hack ();

  1350.   /* This is really the job of start_remote however, that makes an
  1351.      assumption that the target is about to print out a status message
  1352.      of some sort.  That doesn't happen here (in fact, it may not be
  1353.      possible to get the monitor to send the appropriate packet).  */

  1354.   reinit_frame_cache ();
  1355.   registers_changed ();
  1356.   stop_pc = regcache_read_pc (get_current_regcache ());
  1357.   print_stack_frame (get_selected_frame (NULL), 0, SRC_AND_LOC, 1);
  1358.   xfree (serial_port_name);

  1359.   do_cleanups (cleanup);
  1360. }

  1361. /* Open a connection to an IDT board.  */

  1362. static void
  1363. mips_open (const char *name, int from_tty)
  1364. {
  1365.   const char *monitor_prompt = NULL;
  1366.   if (gdbarch_bfd_arch_info (target_gdbarch ()) != NULL
  1367.       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_mips)
  1368.     {
  1369.     switch (gdbarch_bfd_arch_info (target_gdbarch ())->mach)
  1370.       {
  1371.       case bfd_mach_mips4100:
  1372.       case bfd_mach_mips4300:
  1373.       case bfd_mach_mips4600:
  1374.       case bfd_mach_mips4650:
  1375.       case bfd_mach_mips5000:
  1376.         monitor_prompt = "<RISQ> ";
  1377.         break;
  1378.       }
  1379.     }
  1380.   if (monitor_prompt == NULL)
  1381.     monitor_prompt = "<IDT>";
  1382.   common_open (&mips_ops, name, from_tty, MON_IDT, monitor_prompt);
  1383. }

  1384. /* Open a connection to a PMON board.  */

  1385. static void
  1386. pmon_open (const char *name, int from_tty)
  1387. {
  1388.   common_open (&pmon_ops, name, from_tty, MON_PMON, "PMON> ");
  1389. }

  1390. /* Open a connection to a DDB board.  */

  1391. static void
  1392. ddb_open (const char *name, int from_tty)
  1393. {
  1394.   common_open (&ddb_ops, name, from_tty, MON_DDB, "NEC010>");
  1395. }

  1396. /* Open a connection to a rockhopper board.  */

  1397. static void
  1398. rockhopper_open (const char *name, int from_tty)
  1399. {
  1400.   common_open (&rockhopper_ops, name, from_tty, MON_ROCKHOPPER, "NEC01>");
  1401. }

  1402. /* Open a connection to an LSI board.  */

  1403. static void
  1404. lsi_open (const char *name, int from_tty)
  1405. {
  1406.   int i;

  1407.   /* Clear the LSI breakpoint table.  */
  1408.   for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
  1409.     lsi_breakpoints[i].type = BREAK_UNUSED;

  1410.   common_open (&lsi_ops, name, from_tty, MON_LSI, "PMON> ");
  1411. }

  1412. /* Close a connection to the remote board.  */

  1413. static void
  1414. mips_close (struct target_ops *self)
  1415. {
  1416.   if (mips_is_open)
  1417.     {
  1418.       /* Get the board out of remote debugging mode.  */
  1419.       (void) mips_exit_debug ();

  1420.       close_ports ();
  1421.     }

  1422.   generic_mourn_inferior ();
  1423. }

  1424. /* Detach from the remote board.  */

  1425. static void
  1426. mips_detach (struct target_ops *ops, const char *args, int from_tty)
  1427. {
  1428.   if (args)
  1429.     error (_("Argument given to \"detach\" when remotely debugging."));

  1430.   unpush_target (ops);

  1431.   if (from_tty)
  1432.     printf_unfiltered ("Ending remote MIPS debugging.\n");
  1433. }

  1434. /* Tell the target board to resume.  This does not wait for a reply
  1435.    from the board, except in the case of single-stepping on LSI boards,
  1436.    where PMON does return a reply.  */

  1437. static void
  1438. mips_resume (struct target_ops *ops,
  1439.              ptid_t ptid, int step, enum gdb_signal siggnal)
  1440. {
  1441.   int err;

  1442.   /* LSI PMON requires returns a reply packet "0x1 s 0x0 0x57f" after
  1443.      a single step, so we wait for that.  */
  1444.   mips_request (step ? 's' : 'c', 1, siggnal,
  1445.                 mips_monitor == MON_LSI && step ? &err : (int *) NULL,
  1446.                 mips_receive_wait, NULL);
  1447. }

  1448. /* Return the signal corresponding to SIG, where SIG is the number which
  1449.    the MIPS protocol uses for the signal.  */

  1450. static enum gdb_signal
  1451. mips_signal_from_protocol (int sig)
  1452. {
  1453.   /* We allow a few more signals than the IDT board actually returns, on
  1454.      the theory that there is at least *some* hope that perhaps the numbering
  1455.      for these signals is widely agreed upon.  */
  1456.   if (sig <= 0
  1457.       || sig > 31)
  1458.     return GDB_SIGNAL_UNKNOWN;

  1459.   /* Don't want to use gdb_signal_from_host because we are converting
  1460.      from MIPS signal numbers, not host ones.  Our internal numbers
  1461.      match the MIPS numbers for the signals the board can return, which
  1462.      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
  1463.   return (enum gdb_signal) sig;
  1464. }

  1465. /* Set the register designated by REGNO to the value designated by VALUE.  */

  1466. static void
  1467. mips_set_register (int regno, ULONGEST value)
  1468. {
  1469.   gdb_byte buf[MAX_REGISTER_SIZE];
  1470.   struct regcache *regcache = get_current_regcache ();
  1471.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  1472.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);

  1473.   /* We got the number the register holds, but gdb expects to see a
  1474.      value in the target byte ordering.  */

  1475.   if (mips_monitor != MON_ROCKHOPPER
  1476.       && (regno == mips_regnum (gdbarch)->pc || regno < 32))
  1477.     /* Some 64-bit boards have monitors that only send the bottom 32 bits.
  1478.        In such cases we can only really debug 32-bit code properly so,
  1479.        when reading a GPR or the PC, assume that the full 64-bit
  1480.        value is the sign extension of the lower 32 bits.  */
  1481.     store_signed_integer (buf, register_size (gdbarch, regno), byte_order,
  1482.                           value);
  1483.   else
  1484.     store_unsigned_integer (buf, register_size (gdbarch, regno), byte_order,
  1485.                             value);

  1486.   regcache_raw_supply (regcache, regno, buf);
  1487. }

  1488. /* Wait until the remote stops, and return a wait status.  */

  1489. static ptid_t
  1490. mips_wait (struct target_ops *ops,
  1491.            ptid_t ptid, struct target_waitstatus *status, int options)
  1492. {
  1493.   int rstatus;
  1494.   int err;
  1495.   char buff[DATA_MAXLEN];
  1496.   ULONGEST rpc, rfp, rsp;
  1497.   char pc_string[17], fp_string[17], sp_string[17], flags[20];
  1498.   int nfields;

  1499.   interrupt_count = 0;
  1500.   hit_watchpoint = 0;

  1501.   /* If we have not sent a single step or continue command, then the
  1502.      board is waiting for us to do something.  Return a status
  1503.      indicating that it is stopped.  */
  1504.   if (!mips_need_reply)
  1505.     {
  1506.       status->kind = TARGET_WAITKIND_STOPPED;
  1507.       status->value.sig = GDB_SIGNAL_TRAP;
  1508.       return inferior_ptid;
  1509.     }

  1510.   /* No timeout; we sit here as long as the program continues to execute.  */
  1511.   mips_wait_flag = 1;
  1512.   rstatus = mips_request ('\000', 0, 0, &err, -1, buff);
  1513.   mips_wait_flag = 0;
  1514.   if (err)
  1515.     mips_error (_("Remote failure: %s"), safe_strerror (errno));

  1516.   /* On returning from a continue, the PMON monitor seems to start
  1517.      echoing back the messages we send prior to sending back the
  1518.      ACK.  The code can cope with this, but to try and avoid the
  1519.      unnecessary serial traffic, and "spurious" characters displayed
  1520.      to the user, we cheat and reset the debug protocol.  The problems
  1521.      seems to be caused by a check on the number of arguments, and the
  1522.      command length, within the monitor causing it to echo the command
  1523.      as a bad packet.  */
  1524.   if (mips_monitor == MON_PMON)
  1525.     {
  1526.       mips_exit_debug ();
  1527.       mips_enter_debug ();
  1528.     }

  1529.   /* See if we got back extended status.  If so, pick out the pc, fp,
  1530.      sp, etc...  */

  1531.   nfields = sscanf (buff,
  1532.                     "0x%*x %*c 0x%*x 0x%*x 0x%16s 0x%16s 0x%16s 0x%*x %s",
  1533.                     pc_string, fp_string, sp_string, flags);
  1534.   if (nfields >= 3
  1535.       && read_hex_value (pc_string, &rpc)
  1536.       && read_hex_value (fp_string, &rfp)
  1537.       && read_hex_value (sp_string, &rsp))
  1538.     {
  1539.       struct regcache *regcache = get_current_regcache ();
  1540.       struct gdbarch *gdbarch = get_regcache_arch (regcache);

  1541.       mips_set_register (gdbarch_pc_regnum (gdbarch), rpc);
  1542.       mips_set_register (30, rfp);
  1543.       mips_set_register (gdbarch_sp_regnum (gdbarch), rsp);

  1544.       if (nfields == 9)
  1545.         {
  1546.           int i;

  1547.           for (i = 0; i <= 2; i++)
  1548.             if (flags[i] == 'r' || flags[i] == 'w')
  1549.               hit_watchpoint = 1;
  1550.             else if (flags[i] == '\000')
  1551.               break;
  1552.         }
  1553.     }

  1554.   if (strcmp (target_shortname, "lsi") == 0)
  1555.     {
  1556. #if 0
  1557.       /* If this is an LSI PMON target, see if we just hit a
  1558.          hardrdware watchpoint.  Right now, PMON doesn't give us
  1559.          enough information to determine which breakpoint we hit.  So
  1560.          we have to look up the PC in our own table of breakpoints,
  1561.          and if found, assume it's just a normal instruction fetch
  1562.          breakpoint, not a data watchpoint.  FIXME when PMON provides
  1563.          some way to tell us what type of breakpoint it is.  */
  1564.       int i;
  1565.       CORE_ADDR pc = regcache_read_pc (get_current_regcache ());

  1566.       hit_watchpoint = 1;
  1567.       for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
  1568.         {
  1569.           if (lsi_breakpoints[i].addr == pc
  1570.               && lsi_breakpoints[i].type == BREAK_FETCH)
  1571.             {
  1572.               hit_watchpoint = 0;
  1573.               break;
  1574.             }
  1575.         }
  1576. #else
  1577.       /* If a data breakpoint was hit, PMON returns the following packet:
  1578.          0x1 c 0x0 0x57f 0x1
  1579.          The return packet from an ordinary breakpoint doesn't have the
  1580.          extra 0x01 field tacked onto the end.  */
  1581.       if (nfields == 1 && rpc == 1)
  1582.         hit_watchpoint = 1;
  1583. #endif
  1584.     }

  1585.   /* NOTE: The following (sig) numbers are defined by PMON:
  1586.      SPP_SIGTRAP     5       breakpoint
  1587.      SPP_SIGINT      2
  1588.      SPP_SIGSEGV     11
  1589.      SPP_SIGBUS      10
  1590.      SPP_SIGILL      4
  1591.      SPP_SIGFPE      8
  1592.      SPP_SIGTERM     15 */

  1593.   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
  1594.      and so on, because the constants we want here are determined by the
  1595.      MIPS protocol and have nothing to do with what host we are running on.  */
  1596.   if ((rstatus & 0xff) == 0)
  1597.     {
  1598.       status->kind = TARGET_WAITKIND_EXITED;
  1599.       status->value.integer = (((rstatus) >> 8) & 0xff);
  1600.     }
  1601.   else if ((rstatus & 0xff) == 0x7f)
  1602.     {
  1603.       status->kind = TARGET_WAITKIND_STOPPED;
  1604.       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0xff);

  1605.       /* If the stop PC is in the _exit function, assume
  1606.          we hit the 'break 0x3ff' instruction in _exit, so this
  1607.          is not a normal breakpoint.  */
  1608.       if (strcmp (target_shortname, "lsi") == 0)
  1609.         {
  1610.           const char *func_name;
  1611.           CORE_ADDR func_start;
  1612.           CORE_ADDR pc = regcache_read_pc (get_current_regcache ());

  1613.           find_pc_partial_function (pc, &func_name, &func_start, NULL);
  1614.           if (func_name != NULL && strcmp (func_name, "_exit") == 0
  1615.               && func_start == pc)
  1616.             status->kind = TARGET_WAITKIND_EXITED;
  1617.         }
  1618.     }
  1619.   else
  1620.     {
  1621.       status->kind = TARGET_WAITKIND_SIGNALLED;
  1622.       status->value.sig = mips_signal_from_protocol (rstatus & 0x7f);
  1623.     }

  1624.   return inferior_ptid;
  1625. }

  1626. /* We have to map between the register numbers used by gdb and the
  1627.    register numbers used by the debugging protocol.  */

  1628. #define REGNO_OFFSET 96

  1629. static int
  1630. mips_map_regno (struct gdbarch *gdbarch, int regno)
  1631. {
  1632.   if (regno < 32)
  1633.     return regno;
  1634.   if (regno >= mips_regnum (gdbarch)->fp0
  1635.       && regno < mips_regnum (gdbarch)->fp0 + 32)
  1636.     return regno - mips_regnum (gdbarch)->fp0 + 32;
  1637.   else if (regno == mips_regnum (gdbarch)->pc)
  1638.     return REGNO_OFFSET + 0;
  1639.   else if (regno == mips_regnum (gdbarch)->cause)
  1640.     return REGNO_OFFSET + 1;
  1641.   else if (regno == mips_regnum (gdbarch)->hi)
  1642.     return REGNO_OFFSET + 2;
  1643.   else if (regno == mips_regnum (gdbarch)->lo)
  1644.     return REGNO_OFFSET + 3;
  1645.   else if (regno == mips_regnum (gdbarch)->fp_control_status)
  1646.     return REGNO_OFFSET + 4;
  1647.   else if (regno == mips_regnum (gdbarch)->fp_implementation_revision)
  1648.     return REGNO_OFFSET + 5;
  1649.   else
  1650.     /* FIXME: Is there a way to get the status register?  */
  1651.     return 0;
  1652. }

  1653. /* Fetch the remote registers.  */

  1654. static void
  1655. mips_fetch_registers (struct target_ops *ops,
  1656.                       struct regcache *regcache, int regno)
  1657. {
  1658.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  1659.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  1660.   ULONGEST val;
  1661.   int err;

  1662.   if (regno == -1)
  1663.     {
  1664.       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
  1665.         mips_fetch_registers (ops, regcache, regno);
  1666.       return;
  1667.     }

  1668.   if (regno == gdbarch_deprecated_fp_regnum (gdbarch)
  1669.       || regno == MIPS_ZERO_REGNUM)
  1670.     /* gdbarch_deprecated_fp_regnum on the mips is a hack which is just
  1671.        supposed to read zero (see also mips-nat.c).  */
  1672.     val = 0;
  1673.   else
  1674.     {
  1675.       /* If PMON doesn't support this register, don't waste serial
  1676.          bandwidth trying to read it.  */
  1677.       int pmon_reg = mips_map_regno (gdbarch, regno);

  1678.       if (regno != 0 && pmon_reg == 0)
  1679.         val = 0;
  1680.       else
  1681.         {
  1682.           /* Unfortunately the PMON version in the Vr4300 board has been
  1683.              compiled without the 64bit register access commands.  This
  1684.              means we cannot get hold of the full register width.  */
  1685.           if (mips_monitor == MON_DDB || mips_monitor == MON_ROCKHOPPER)
  1686.             val = mips_request ('t', pmon_reg, 0,
  1687.                                 &err, mips_receive_wait, NULL);
  1688.           else
  1689.             val = mips_request ('r', pmon_reg, 0,
  1690.                                 &err, mips_receive_wait, NULL);
  1691.           if (err)
  1692.             mips_error (_("Can't read register %d: %s"), regno,
  1693.                         safe_strerror (errno));
  1694.         }
  1695.     }

  1696.   mips_set_register (regno, val);
  1697. }

  1698. /* Prepare to store registers.  The MIPS protocol can store individual
  1699.    registers, so this function doesn't have to do anything.  */

  1700. static void
  1701. mips_prepare_to_store (struct target_ops *self, struct regcache *regcache)
  1702. {
  1703. }

  1704. /* Store remote register(s).  */

  1705. static void
  1706. mips_store_registers (struct target_ops *ops,
  1707.                       struct regcache *regcache, int regno)
  1708. {
  1709.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  1710.   ULONGEST val;
  1711.   int err;

  1712.   if (regno == -1)
  1713.     {
  1714.       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
  1715.         mips_store_registers (ops, regcache, regno);
  1716.       return;
  1717.     }

  1718.   regcache_cooked_read_unsigned (regcache, regno, &val);
  1719.   mips_request (mips_monitor == MON_ROCKHOPPER ? 'T' : 'R',
  1720.                   mips_map_regno (gdbarch, regno),
  1721.                 val,
  1722.                 &err, mips_receive_wait, NULL);
  1723.   if (err)
  1724.     mips_error (_("Can't write register %d: %s"), regno,
  1725.                 safe_strerror (errno));
  1726. }

  1727. /* Fetch a word from the target board.  Return word fetched in location
  1728.    addressed by VALP.  Return 0 when successful; return positive error
  1729.    code when not.  */

  1730. static int
  1731. mips_fetch_word (CORE_ADDR addr, unsigned int *valp)
  1732. {
  1733.   int err;

  1734.   *valp = mips_request ('d', addr, 0, &err, mips_receive_wait, NULL);
  1735.   if (err)
  1736.     {
  1737.       /* Data space failed; try instruction space.  */
  1738.       *valp = mips_request ('i', addr, 0, &err,
  1739.                             mips_receive_wait, NULL);
  1740.     }
  1741.   return err;
  1742. }

  1743. /* Store a word to the target board.  Returns errno code or zero for
  1744.    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
  1745.    memory location there.  */

  1746. /* FIXME! make sure only 32-bit quantities get stored!  */
  1747. static int
  1748. mips_store_word (CORE_ADDR addr, unsigned int val, int *old_contents)
  1749. {
  1750.   int err;
  1751.   unsigned int oldcontents;

  1752.   oldcontents = mips_request ('D', addr, val, &err,
  1753.                               mips_receive_wait, NULL);
  1754.   if (err)
  1755.     {
  1756.       /* Data space failed; try instruction space.  */
  1757.       oldcontents = mips_request ('I', addr, val, &err,
  1758.                                   mips_receive_wait, NULL);
  1759.       if (err)
  1760.         return errno;
  1761.     }
  1762.   if (old_contents != NULL)
  1763.     *old_contents = oldcontents;
  1764.   return 0;
  1765. }

  1766. /* Helper for mips_xfer_partial that handles memory transfers.
  1767.    Arguments are like target_xfer_partial.  Note that the protocol
  1768.    gives us the correct value for a longword, since it transfers
  1769.    values in ASCII.  We want the byte values, so we have to swap the
  1770.    longword values.  */

  1771. static int mask_address_p = 1;

  1772. static enum target_xfer_status
  1773. mips_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  1774.                   ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  1775. {
  1776.   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
  1777.   int i;
  1778.   CORE_ADDR addr;
  1779.   int count;
  1780.   gdb_byte *buffer;
  1781.   int status;

  1782.   /* PMON targets do not cope well with 64 bit addresses.  Mask the
  1783.      value down to 32 bits.  */
  1784.   if (mask_address_p)
  1785.     memaddr &= (CORE_ADDR) 0xffffffff;

  1786.   /* Round starting address down to longword boundary.  */
  1787.   addr = memaddr & ~3;
  1788.   /* Round ending address up; get number of longwords that makes.  */
  1789.   count = (((memaddr + len) - addr) + 3) / 4;
  1790.   /* Allocate buffer of that many longwords.  */
  1791.   buffer = alloca (count * 4);

  1792.   if (writebuf != NULL)
  1793.     {
  1794.       /* Fill start and end extra bytes of buffer with existing data.  */
  1795.       if (addr != memaddr || len < 4)
  1796.         {
  1797.           unsigned int val;

  1798.           if (mips_fetch_word (addr, &val))
  1799.             return TARGET_XFER_E_IO;

  1800.           /* Need part of initial word -- fetch it.  */
  1801.           store_unsigned_integer (&buffer[0], 4, byte_order, val);
  1802.         }

  1803.       if (count > 1)
  1804.         {
  1805.           unsigned int val;

  1806.           /* Need part of last word -- fetch it.  FIXME: we do this even
  1807.              if we don't need it.  */
  1808.           if (mips_fetch_word (addr + (count - 1) * 4, &val))
  1809.             return TARGET_XFER_E_IO;

  1810.           store_unsigned_integer (&buffer[(count - 1) * 4],
  1811.                                   4, byte_order, val);
  1812.         }

  1813.       /* Copy data to be written over corresponding part of buffer.  */

  1814.       memcpy ((char *) buffer + (memaddr & 3), writebuf, len);

  1815.       /* Write the entire buffer.  */

  1816.       for (i = 0; i < count; i++, addr += 4)
  1817.         {
  1818.           int word;

  1819.           word = extract_unsigned_integer (&buffer[i * 4], 4, byte_order);
  1820.           status = mips_store_word (addr, word, NULL);
  1821.           /* Report each kilobyte (we download 32-bit words at a time).  */
  1822.           if (i % 256 == 255)
  1823.             {
  1824.               printf_unfiltered ("*");
  1825.               gdb_flush (gdb_stdout);
  1826.             }
  1827.           if (status)
  1828.             return TARGET_XFER_E_IO;
  1829.           /* FIXME: Do we want a QUIT here?  */
  1830.         }
  1831.       if (count >= 256)
  1832.         printf_unfiltered ("\n");
  1833.     }
  1834.   else
  1835.     {
  1836.       /* Read all the longwords.  */
  1837.       for (i = 0; i < count; i++, addr += 4)
  1838.         {
  1839.           unsigned int val;

  1840.           if (mips_fetch_word (addr, &val))
  1841.             return TARGET_XFER_E_IO;

  1842.           store_unsigned_integer (&buffer[i * 4], 4, byte_order, val);
  1843.           QUIT;
  1844.         }

  1845.       /* Copy appropriate bytes out of the buffer.  */
  1846.       memcpy (readbuf, buffer + (memaddr & 3), len);
  1847.     }
  1848.   *xfered_len = len;
  1849.   return TARGET_XFER_OK;
  1850. }

  1851. /* Target to_xfer_partial implementation.  */

  1852. static enum target_xfer_status
  1853. mips_xfer_partial (struct target_ops *ops, enum target_object object,
  1854.                    const char *annex, gdb_byte *readbuf,
  1855.                    const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  1856.                    ULONGEST *xfered_len)
  1857. {
  1858.   switch (object)
  1859.     {
  1860.     case TARGET_OBJECT_MEMORY:
  1861.       return mips_xfer_memory (readbuf, writebuf, offset, len, xfered_len);

  1862.     default:
  1863.       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
  1864.                                             readbuf, writebuf, offset, len,
  1865.                                             xfered_len);
  1866.     }
  1867. }

  1868. /* Print info on this target.  */

  1869. static void
  1870. mips_files_info (struct target_ops *ignore)
  1871. {
  1872.   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
  1873. }

  1874. /* Kill the process running on the board.  This will actually only
  1875.    work if we are doing remote debugging over the console input.  I
  1876.    think that if IDT/sim had the remote debug interrupt enabled on the
  1877.    right port, we could interrupt the process with a break signal.  */

  1878. static void
  1879. mips_kill (struct target_ops *ops)
  1880. {
  1881.   if (!mips_wait_flag)
  1882.     {
  1883.       target_mourn_inferior ();
  1884.       return;
  1885.     }

  1886.   interrupt_count++;

  1887.   if (interrupt_count >= 2)
  1888.     {
  1889.       interrupt_count = 0;

  1890.       target_terminal_ours ();

  1891.       if (query (_("Interrupted while waiting for the program.\n\
  1892. Give up (and stop debugging it)? ")))
  1893.         {
  1894.           /* Clean up in such a way that mips_close won't try to talk
  1895.              to the board (it almost surely won't work since we
  1896.              weren't able to talk to it).  */
  1897.           mips_wait_flag = 0;
  1898.           close_ports ();

  1899.           printf_unfiltered ("Ending remote MIPS debugging.\n");
  1900.           target_mourn_inferior ();
  1901.           quit ();
  1902.         }

  1903.       target_terminal_inferior ();
  1904.     }

  1905.   if (remote_debug > 0)
  1906.     printf_unfiltered ("Sending break\n");

  1907.   serial_send_break (mips_desc);

  1908.   target_mourn_inferior ();

  1909. #if 0
  1910.   if (mips_is_open)
  1911.     {
  1912.       char cc;

  1913.       /* Send a ^C.  */
  1914.       cc = '\003';
  1915.       serial_write (mips_desc, &cc, 1);
  1916.       sleep (1);
  1917.       target_mourn_inferior ();
  1918.     }
  1919. #endif
  1920. }

  1921. /* Start running on the target board.  */

  1922. static void
  1923. mips_create_inferior (struct target_ops *ops, char *execfile,
  1924.                       char *args, char **env, int from_tty)
  1925. {
  1926.   CORE_ADDR entry_pt;

  1927.   if (args && *args)
  1928.     {
  1929.       warning (_("\
  1930. Can't pass arguments to remote MIPS board; arguments ignored."));
  1931.       /* And don't try to use them on the next "run" command.  */
  1932.       execute_command ("set args", 0);
  1933.     }

  1934.   if (execfile == 0 || exec_bfd == 0)
  1935.     error (_("No executable file specified"));

  1936.   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);

  1937.   init_wait_for_inferior ();

  1938.   regcache_write_pc (get_current_regcache (), entry_pt);
  1939. }

  1940. /* Clean up after a process. The bulk of the work is done in mips_close(),
  1941.    which is called when unpushing the target.  */

  1942. static void
  1943. mips_mourn_inferior (struct target_ops *ops)
  1944. {
  1945.   if (current_ops != NULL)
  1946.     unpush_target (current_ops);
  1947. }

  1948. /* We can write a breakpoint and read the shadow contents in one
  1949.    operation.  */

  1950. /* Insert a breakpoint.  On targets that don't have built-in
  1951.    breakpoint support, we read the contents of the target location and
  1952.    stash it, then overwrite it with a breakpoint instruction.  ADDR is
  1953.    the target location in the target machine.  BPT is the breakpoint
  1954.    being inserted or removed, which contains memory for saving the
  1955.    target contents.  */

  1956. static int
  1957. mips_insert_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
  1958.                         struct bp_target_info *bp_tgt)
  1959. {
  1960.   if (monitor_supports_breakpoints)
  1961.     {
  1962.       bp_tgt->placed_address = bp_tgt->reqstd_address;
  1963.       return mips_set_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
  1964.                                   BREAK_FETCH);
  1965.     }
  1966.   else
  1967.     return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
  1968. }

  1969. /* Remove a breakpoint.  */

  1970. static int
  1971. mips_remove_breakpoint (struct target_ops *ops, struct gdbarch *gdbarch,
  1972.                         struct bp_target_info *bp_tgt)
  1973. {
  1974.   if (monitor_supports_breakpoints)
  1975.     return mips_clear_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
  1976.                                   BREAK_FETCH);
  1977.   else
  1978.     return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
  1979. }

  1980. /* Tell whether this target can support a hardware breakpoint.  CNT
  1981.    is the number of hardware breakpoints already installed.  This
  1982.    implements the target_can_use_hardware_watchpoint macro.  */

  1983. static int
  1984. mips_can_use_watchpoint (struct target_ops *self,
  1985.                          int type, int cnt, int othertype)
  1986. {
  1987.   return cnt < MAX_LSI_BREAKPOINTS && strcmp (target_shortname, "lsi") == 0;
  1988. }


  1989. /* Compute a don't care mask for the region bounding ADDR and ADDR + LEN - 1.
  1990.    This is used for memory ref breakpoints.  */

  1991. static unsigned long
  1992. calculate_mask (CORE_ADDR addr, int len)
  1993. {
  1994.   unsigned long mask;
  1995.   int i;

  1996.   mask = addr ^ (addr + len - 1);

  1997.   for (i = 32; i >= 0; i--)
  1998.     if (mask == 0)
  1999.       break;
  2000.     else
  2001.       mask >>= 1;

  2002.   mask = (unsigned long) 0xffffffff >> i;

  2003.   return mask;
  2004. }


  2005. /* Set a data watchpoint.  ADDR and LEN should be obvious.  TYPE is 0
  2006.    for a write watchpoint, 1 for a read watchpoint, or 2 for a read/write
  2007.    watchpoint.  */

  2008. static int
  2009. mips_insert_watchpoint (struct target_ops *self,
  2010.                         CORE_ADDR addr, int len, int type,
  2011.                         struct expression *cond)
  2012. {
  2013.   if (mips_set_breakpoint (addr, len, type))
  2014.     return -1;

  2015.   return 0;
  2016. }

  2017. /* Remove a watchpoint.  */

  2018. static int
  2019. mips_remove_watchpoint (struct target_ops *self,
  2020.                         CORE_ADDR addr, int len, int type,
  2021.                         struct expression *cond)
  2022. {
  2023.   if (mips_clear_breakpoint (addr, len, type))
  2024.     return -1;

  2025.   return 0;
  2026. }

  2027. /* Test to see if a watchpoint has been hit.  Return 1 if so; return 0,
  2028.    if not.  */

  2029. static int
  2030. mips_stopped_by_watchpoint (struct target_ops *ops)
  2031. {
  2032.   return hit_watchpoint;
  2033. }


  2034. /* Insert a breakpoint.  */

  2035. static int
  2036. mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type)
  2037. {
  2038.   return mips_common_breakpoint (1, addr, len, type);
  2039. }


  2040. /* Clear a breakpoint.  */

  2041. static int
  2042. mips_clear_breakpoint (CORE_ADDR addr, int len, enum break_type type)
  2043. {
  2044.   return mips_common_breakpoint (0, addr, len, type);
  2045. }


  2046. /* Check the error code from the return packet for an LSI breakpoint
  2047.    command.  If there's no error, just return 0.  If it's a warning,
  2048.    print the warning text and return 0.  If it's an error, print
  2049.    the error text and return 1.  <ADDR> is the address of the breakpoint
  2050.    that was being set.  <RERRFLG> is the error code returned by PMON.
  2051.    This is a helper function for mips_common_breakpoint.  */

  2052. static int
  2053. mips_check_lsi_error (CORE_ADDR addr, int rerrflg)
  2054. {
  2055.   struct lsi_error *err;
  2056.   const char *saddr = paddress (target_gdbarch (), addr);

  2057.   if (rerrflg == 0)                /* no error */
  2058.     return 0;

  2059.   /* Warnings can be ORed together, so check them all.  */
  2060.   if (rerrflg & W_WARN)
  2061.     {
  2062.       if (monitor_warnings)
  2063.         {
  2064.           int found = 0;

  2065.           for (err = lsi_warning_table; err->code != 0; err++)
  2066.             {
  2067.               if ((err->code & rerrflg) == err->code)
  2068.                 {
  2069.                   found = 1;
  2070.                   fprintf_unfiltered (gdb_stderr, "\
  2071. mips_common_breakpoint (%s): Warning: %s\n",
  2072.                                       saddr,
  2073.                                       err->string);
  2074.                 }
  2075.             }
  2076.           if (!found)
  2077.             fprintf_unfiltered (gdb_stderr, "\
  2078. mips_common_breakpoint (%s): Unknown warning: 0x%x\n",
  2079.                                 saddr,
  2080.                                 rerrflg);
  2081.         }
  2082.       return 0;
  2083.     }

  2084.   /* Errors are unique, i.e. can't be ORed together.  */
  2085.   for (err = lsi_error_table; err->code != 0; err++)
  2086.     {
  2087.       if ((err->code & rerrflg) == err->code)
  2088.         {
  2089.           fprintf_unfiltered (gdb_stderr, "\
  2090. mips_common_breakpoint (%s): Error: %s\n",
  2091.                               saddr,
  2092.                               err->string);
  2093.           return 1;
  2094.         }
  2095.     }
  2096.   fprintf_unfiltered (gdb_stderr, "\
  2097. mips_common_breakpoint (%s): Unknown error: 0x%x\n",
  2098.                       saddr,
  2099.                       rerrflg);
  2100.   return 1;
  2101. }


  2102. /* This routine sends a breakpoint command to the remote target.

  2103.    <SET> is 1 if setting a breakpoint, or 0 if clearing a breakpoint.
  2104.    <ADDR> is the address of the breakpoint.
  2105.    <LEN> the length of the region to break on.
  2106.    <TYPE> is the type of breakpoint:
  2107.    0 = write                    (BREAK_WRITE)
  2108.    1 = read                     (BREAK_READ)
  2109.    2 = read/write               (BREAK_ACCESS)
  2110.    3 = instruction fetch        (BREAK_FETCH)

  2111.    Return 0 if successful; otherwise 1.  */

  2112. static int
  2113. mips_common_breakpoint (int set, CORE_ADDR addr, int len, enum break_type type)
  2114. {
  2115.   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
  2116.   char buf[DATA_MAXLEN + 1];
  2117.   char cmd, rcmd;
  2118.   int rpid, rerrflg, rresponse, rlen;
  2119.   int nfields;

  2120.   addr = gdbarch_addr_bits_remove (target_gdbarch (), addr);

  2121.   if (mips_monitor == MON_LSI)
  2122.     {
  2123.       if (set == 0)                /* clear breakpoint */
  2124.         {
  2125.           /* The LSI PMON "clear breakpoint" has this form:
  2126.              <pid> 'b' <bptn> 0x0
  2127.              reply:
  2128.              <pid> 'b' 0x0 <code>

  2129.              <bptn> is a breakpoint number returned by an earlier 'B' command.
  2130.              Possible return codes: OK, E_BPT.  */

  2131.           int i;

  2132.           /* Search for the breakpoint in the table.  */
  2133.           for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
  2134.             if (lsi_breakpoints[i].type == type
  2135.                 && lsi_breakpoints[i].addr == addr
  2136.                 && lsi_breakpoints[i].len == len)
  2137.               break;

  2138.           /* Clear the table entry and tell PMON to clear the breakpoint.  */
  2139.           if (i == MAX_LSI_BREAKPOINTS)
  2140.             {
  2141.               warning (_("\
  2142. mips_common_breakpoint: Attempt to clear bogus breakpoint at %s"),
  2143.                        paddress (target_gdbarch (), addr));
  2144.               return 1;
  2145.             }

  2146.           lsi_breakpoints[i].type = BREAK_UNUSED;
  2147.           sprintf (buf, "0x0 b 0x%x 0x0", i);
  2148.           mips_send_packet (buf, 1);

  2149.           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
  2150.           buf[rlen] = '\0';

  2151.           nfields = sscanf (buf, "0x%x b 0x0 0x%x", &rpid, &rerrflg);
  2152.           if (nfields != 2)
  2153.             mips_error (_("mips_common_breakpoint: "
  2154.                         "Bad response from remote board: %s"),
  2155.                         buf);

  2156.           return (mips_check_lsi_error (addr, rerrflg));
  2157.         }
  2158.       else
  2159.         /* set a breakpoint */
  2160.         {
  2161.           /* The LSI PMON "set breakpoint" command has this form:
  2162.              <pid> 'B' <addr> 0x0
  2163.              reply:
  2164.              <pid> 'B' <bptn> <code>

  2165.              The "set data breakpoint" command has this form:

  2166.              <pid> 'A' <addr1> <type> [<addr2>  [<value>]]

  2167.              where: type= "0x1" = read
  2168.              "0x2" = write
  2169.              "0x3" = access (read or write)

  2170.              The reply returns two values:
  2171.              bptn - a breakpoint number, which is a small integer with
  2172.              possible values of zero through 255.
  2173.              code - an error return code, a value of zero indicates a
  2174.              succesful completion, other values indicate various
  2175.              errors and warnings.

  2176.              Possible return codes: OK, W_QAL, E_QAL, E_OUT, E_NON.  */

  2177.           if (type == BREAK_FETCH)        /* instruction breakpoint */
  2178.             {
  2179.               cmd = 'B';
  2180.               sprintf (buf, "0x0 B 0x%s 0x0", phex_nz (addr, addr_size));
  2181.             }
  2182.           else
  2183.             /* watchpoint */
  2184.             {
  2185.               cmd = 'A';
  2186.               sprintf (buf, "0x0 A 0x%s 0x%x 0x%s",
  2187.                        phex_nz (addr, addr_size),
  2188.                        type == BREAK_READ ? 1 : (type == BREAK_WRITE ? 2 : 3),
  2189.                        phex_nz (addr + len - 1, addr_size));
  2190.             }
  2191.           mips_send_packet (buf, 1);

  2192.           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
  2193.           buf[rlen] = '\0';

  2194.           nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
  2195.                             &rpid, &rcmd, &rresponse, &rerrflg);
  2196.           if (nfields != 4 || rcmd != cmd || rresponse > 255)
  2197.             mips_error (_("mips_common_breakpoint: "
  2198.                         "Bad response from remote board: %s"),
  2199.                         buf);

  2200.           if (rerrflg != 0)
  2201.             if (mips_check_lsi_error (addr, rerrflg))
  2202.               return 1;

  2203.           /* rresponse contains PMON's breakpoint number.  Record the
  2204.              information for this breakpoint so we can clear it later.  */
  2205.           lsi_breakpoints[rresponse].type = type;
  2206.           lsi_breakpoints[rresponse].addr = addr;
  2207.           lsi_breakpoints[rresponse].len = len;

  2208.           return 0;
  2209.         }
  2210.     }
  2211.   else
  2212.     {
  2213.       /* On non-LSI targets, the breakpoint command has this form:
  2214.          0x0 <CMD> <ADDR> <MASK> <FLAGS>
  2215.          <MASK> is a don't care mask for addresses.
  2216.          <FLAGS> is any combination of `r', `w', or `f' for
  2217.          read/write/fetch.  */

  2218.       unsigned long mask;

  2219.       mask = calculate_mask (addr, len);
  2220.       addr &= ~mask;

  2221.       if (set)                        /* set a breakpoint */
  2222.         {
  2223.           char *flags;

  2224.           switch (type)
  2225.             {
  2226.             case BREAK_WRITE:        /* write */
  2227.               flags = "w";
  2228.               break;
  2229.             case BREAK_READ:        /* read */
  2230.               flags = "r";
  2231.               break;
  2232.             case BREAK_ACCESS:        /* read/write */
  2233.               flags = "rw";
  2234.               break;
  2235.             case BREAK_FETCH:        /* fetch */
  2236.               flags = "f";
  2237.               break;
  2238.             default:
  2239.               internal_error (__FILE__, __LINE__,
  2240.                               _("failed internal consistency check"));
  2241.             }

  2242.           cmd = 'B';
  2243.           sprintf (buf, "0x0 B 0x%s 0x%s %s", phex_nz (addr, addr_size),
  2244.                    phex_nz (mask, addr_size), flags);
  2245.         }
  2246.       else
  2247.         {
  2248.           cmd = 'b';
  2249.           sprintf (buf, "0x0 b 0x%s", phex_nz (addr, addr_size));
  2250.         }

  2251.       mips_send_packet (buf, 1);

  2252.       rlen = mips_receive_packet (buf, 1, mips_receive_wait);
  2253.       buf[rlen] = '\0';

  2254.       nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
  2255.                         &rpid, &rcmd, &rerrflg, &rresponse);

  2256.       if (nfields != 4 || rcmd != cmd)
  2257.         mips_error (_("mips_common_breakpoint: "
  2258.                     "Bad response from remote board: %s"),
  2259.                     buf);

  2260.       if (rerrflg != 0)
  2261.         {
  2262.           /* Ddb returns "0x0 b 0x16 0x0\000", whereas
  2263.              Cogent returns "0x0 b 0xffffffff 0x16\000": */
  2264.           if (mips_monitor == MON_DDB)
  2265.             rresponse = rerrflg;
  2266.           if (rresponse != 22)        /* invalid argument */
  2267.             fprintf_unfiltered (gdb_stderr, "\
  2268. mips_common_breakpoint (%s):  Got error: 0x%x\n",
  2269.                                 paddress (target_gdbarch (), addr), rresponse);
  2270.           return 1;
  2271.         }
  2272.     }
  2273.   return 0;
  2274. }

  2275. /* Send one S record as specified by SREC of length LEN, starting
  2276.    at ADDR.  Note, however, that ADDR is not used except to provide
  2277.    a useful message to the user in the event that a NACK is received
  2278.    from the board.  */

  2279. static void
  2280. send_srec (char *srec, int len, CORE_ADDR addr)
  2281. {
  2282.   while (1)
  2283.     {
  2284.       int ch;

  2285.       serial_write (mips_desc, srec, len);

  2286.       ch = mips_readchar (remote_timeout);

  2287.       switch (ch)
  2288.         {
  2289.         case SERIAL_TIMEOUT:
  2290.           error (_("Timeout during download."));
  2291.           break;
  2292.         case 0x6:                /* ACK */
  2293.           return;
  2294.         case 0x15:                /* NACK */
  2295.           fprintf_unfiltered (gdb_stderr,
  2296.                               "Download got a NACK at byte %s!  Retrying.\n",
  2297.                               paddress (target_gdbarch (), addr));
  2298.           continue;
  2299.         default:
  2300.           error (_("Download got unexpected ack char: 0x%x, retrying."),
  2301.                  ch);
  2302.         }
  2303.     }
  2304. }

  2305. /*  Download a binary file by converting it to S records.  */

  2306. static void
  2307. mips_load_srec (const char *args)
  2308. {
  2309.   bfd *abfd;
  2310.   asection *s;
  2311.   char srec[1024];
  2312.   bfd_byte *buffer;
  2313.   unsigned int i;
  2314.   unsigned int srec_frame = 200;
  2315.   int reclen;
  2316.   struct cleanup *cleanup;
  2317.   static int hashmark = 1;

  2318.   buffer = alloca (srec_frame * 2 + 256);

  2319.   abfd = gdb_bfd_open (args, NULL, -1);
  2320.   if (!abfd)
  2321.     {
  2322.       printf_filtered ("Unable to open file %s\n", args);
  2323.       return;
  2324.     }

  2325.   cleanup = make_cleanup_bfd_unref (abfd);
  2326.   if (bfd_check_format (abfd, bfd_object) == 0)
  2327.     {
  2328.       printf_filtered ("File is not an object file\n");
  2329.       do_cleanups (cleanup);
  2330.       return;
  2331.     }

  2332. /* This actually causes a download in the IDT binary format: */
  2333.   mips_send_command (LOAD_CMD, 0);

  2334.   for (s = abfd->sections; s; s = s->next)
  2335.     {
  2336.       if (s->flags & SEC_LOAD)
  2337.         {
  2338.           unsigned int numbytes;

  2339.           /* FIXME!  vma too small?????  */
  2340.           printf_filtered ("%s\t: 0x%4lx .. 0x%4lx  ", s->name,
  2341.                            (long) s->vma,
  2342.                            (long) (s->vma + bfd_get_section_size (s)));
  2343.           gdb_flush (gdb_stdout);

  2344.           for (i = 0; i < bfd_get_section_size (s); i += numbytes)
  2345.             {
  2346.               numbytes = min (srec_frame, bfd_get_section_size (s) - i);

  2347.               bfd_get_section_contents (abfd, s, buffer, i, numbytes);

  2348.               reclen = mips_make_srec (srec, '3', s->vma + i,
  2349.                                        buffer, numbytes);
  2350.               send_srec (srec, reclen, s->vma + i);

  2351.               if (deprecated_ui_load_progress_hook)
  2352.                 deprecated_ui_load_progress_hook (s->name, i);

  2353.               if (hashmark)
  2354.                 {
  2355.                   putchar_unfiltered ('#');
  2356.                   gdb_flush (gdb_stdout);
  2357.                 }

  2358.             }                        /* Per-packet (or S-record) loop */

  2359.           putchar_unfiltered ('\n');
  2360.         }                        /* Loadable sections */
  2361.     }
  2362.   if (hashmark)
  2363.     putchar_unfiltered ('\n');

  2364.   /* Write a type 7 terminator record. no data for a type 7, and there
  2365.      is no data, so len is 0.  */

  2366.   reclen = mips_make_srec (srec, '7', abfd->start_address, NULL, 0);

  2367.   send_srec (srec, reclen, abfd->start_address);

  2368.   serial_flush_input (mips_desc);
  2369.   do_cleanups (cleanup);
  2370. }

  2371. /*
  2372. * mips_make_srec -- make an srecord.  This writes each line, one at a
  2373. *      time, each with it's own header and trailer line.
  2374. *      An srecord looks like this:
  2375. *
  2376. * byte count-+     address
  2377. * start ---+ |        |       data        +- checksum
  2378. *          | |        |                   |
  2379. *        S01000006F6B692D746573742E73726563E4
  2380. *        S315000448600000000000000000FC00005900000000E9
  2381. *        S31A0004000023C1400037DE00F023604000377B009020825000348D
  2382. *        S30B0004485A0000000000004E
  2383. *        S70500040000F6
  2384. *
  2385. *      S<type><length><address><data><checksum>
  2386. *
  2387. *      Where
  2388. *      - length
  2389. *        is the number of bytes following upto the checksum.  Note that
  2390. *        this is not the number of chars following, since it takes two
  2391. *        chars to represent a byte.
  2392. *      - type
  2393. *        is one of:
  2394. *        0) header record
  2395. *        1) two byte address data record
  2396. *        2) three byte address data record
  2397. *        3) four byte address data record
  2398. *        7) four byte address termination record
  2399. *        8) three byte address termination record
  2400. *        9) two byte address termination record
  2401. *
  2402. *      - address
  2403. *        is the start address of the data following, or in the case of
  2404. *        a termination record, the start address of the image
  2405. *      - data
  2406. *        is the data.
  2407. *      - checksum
  2408. *        is the sum of all the raw byte data in the record, from the length
  2409. *        upwards, modulo 256 and subtracted from 255.
  2410. *
  2411. * This routine returns the length of the S-record.
  2412. *
  2413. */

  2414. static int
  2415. mips_make_srec (char *buf, int type, CORE_ADDR memaddr, unsigned char *myaddr,
  2416.                 int len)
  2417. {
  2418.   unsigned char checksum;
  2419.   int i;

  2420.   /* Create the header for the srec.  addr_size is the number of bytes
  2421.      in the address, and 1 is the number of bytes in the count.  */

  2422.   /* FIXME!! bigger buf required for 64-bit!  */
  2423.   buf[0] = 'S';
  2424.   buf[1] = type;
  2425.   buf[2] = len + 4 + 1;                /* len + 4 byte address + 1 byte checksum */
  2426.   /* This assumes S3 style downloads (4byte addresses).  There should
  2427.      probably be a check, or the code changed to make it more
  2428.      explicit.  */
  2429.   buf[3] = memaddr >> 24;
  2430.   buf[4] = memaddr >> 16;
  2431.   buf[5] = memaddr >> 8;
  2432.   buf[6] = memaddr;
  2433.   memcpy (&buf[7], myaddr, len);

  2434.   /* Note that the checksum is calculated on the raw data, not the
  2435.      hexified data.  It includes the length, address and the data
  2436.      portions of the packet.  */
  2437.   checksum = 0;
  2438.   buf += 2;                        /* Point at length byte.  */
  2439.   for (i = 0; i < len + 4 + 1; i++)
  2440.     checksum += *buf++;

  2441.   *buf = ~checksum;

  2442.   return len + 8;
  2443. }

  2444. /* The following manifest controls whether we enable the simple flow
  2445.    control support provided by the monitor.  If enabled the code will
  2446.    wait for an affirmative ACK between transmitting packets.  */
  2447. #define DOETXACK (1)

  2448. /* The PMON fast-download uses an encoded packet format constructed of
  2449.    3byte data packets (encoded as 4 printable ASCII characters), and
  2450.    escape sequences (preceded by a '/'):

  2451.    'K'     clear checksum
  2452.    'C'     compare checksum (12bit value, not included in checksum calculation)
  2453.    'S'     define symbol name (for addr) terminated with ","
  2454.            and padded to 4char boundary
  2455.    'Z'     zero fill multiple of 3bytes
  2456.    'B'     byte (12bit encoded value, of 8bit data)
  2457.    'A'     address (36bit encoded value)
  2458.    'E'     define entry as original address, and exit load

  2459.    The packets are processed in 4 character chunks, so the escape
  2460.    sequences that do not have any data (or variable length data)
  2461.    should be padded to a 4 character boundary.  The decoder will give
  2462.    an error if the complete message block size is not a multiple of
  2463.    4bytes (size of record).

  2464.    The encoding of numbers is done in 6bit fields.  The 6bit value is
  2465.    used to index into this string to get the specific character
  2466.    encoding for the value: */
  2467. static char encoding[] =
  2468.   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.";

  2469. /* Convert the number of bits required into an encoded number, 6bits
  2470.    at a time (range 0..63).  Keep a checksum if required (passed
  2471.    pointer non-NULL).  The function returns the number of encoded
  2472.    characters written into the buffer.  */

  2473. static int
  2474. pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum)
  2475. {
  2476.   int count = (n / 6);

  2477.   if ((n % 12) != 0)
  2478.     {
  2479.       fprintf_unfiltered (gdb_stderr,
  2480.                           "Fast encoding bitcount must be a "
  2481.                           "multiple of 12bits: %dbit%s\n",
  2482.                           n, (n == 1) ? "" : "s");
  2483.       return (0);
  2484.     }
  2485.   if (n > 36)
  2486.     {
  2487.       fprintf_unfiltered (gdb_stderr,
  2488.                           "Fast encoding cannot process more "
  2489.                           "than 36bits at the moment: %dbits\n", n);
  2490.       return (0);
  2491.     }

  2492.   /* Deal with the checksum: */
  2493.   if (chksum != NULL)
  2494.     {
  2495.       switch (n)
  2496.         {
  2497.         case 36:
  2498.           *chksum += ((v >> 24) & 0xFFF);
  2499.         case 24:
  2500.           *chksum += ((v >> 12) & 0xFFF);
  2501.         case 12:
  2502.           *chksum += ((v >> 0) & 0xFFF);
  2503.         }
  2504.     }

  2505.   do
  2506.     {
  2507.       n -= 6;
  2508.       *p++ = encoding[(v >> n) & 0x3F];
  2509.     }
  2510.   while (n > 0);

  2511.   return (count);
  2512. }

  2513. /* Shorthand function (that could be in-lined) to output the zero-fill
  2514.    escape sequence into the data stream.  */

  2515. static int
  2516. pmon_zeroset (int recsize, char **buff,
  2517.               unsigned int *amount, unsigned int *chksum)
  2518. {
  2519.   int count;

  2520.   sprintf (*buff, "/Z");
  2521.   count = pmon_makeb64 (*amount, (*buff + 2), 12, chksum);
  2522.   *buff += (count + 2);
  2523.   *amount = 0;
  2524.   return (recsize + count + 2);
  2525. }

  2526. /* Add the checksum specified by *VALUE to end of the record under
  2527.    construction.  *BUF specifies the location at which to begin
  2528.    writing characters comprising the checksum information.  RECSIZE
  2529.    specifies the size of the record constructed thus far.  (A trailing
  2530.    NUL character may be present in the buffer holding the record, but
  2531.    the record size does not include this character.)

  2532.    Return the total size of the record after adding the checksum escape,
  2533.    the checksum itself, and the trailing newline.

  2534.    The checksum specified by *VALUE is zeroed out prior to returning.
  2535.    Additionally, *BUF is updated to refer to the location just beyond
  2536.    the record elements added by this call.  */

  2537. static int
  2538. pmon_checkset (int recsize, char **buff, unsigned int *value)
  2539. {
  2540.   int count;

  2541.   /* Add the checksum (without updating the value): */
  2542.   sprintf (*buff, "/C");
  2543.   count = pmon_makeb64 (*value, (*buff + 2), 12, NULL);
  2544.   *buff += (count + 2);
  2545.   sprintf (*buff, "\n");
  2546.   *buff += 2;                        /* Include zero terminator.  */
  2547.   /* Forcing a checksum validation clears the sum: */
  2548.   *value = 0;
  2549.   return (recsize + count + 3);
  2550. }

  2551. /* Amount of padding we leave after at the end of the output buffer,
  2552.    for the checksum and line termination characters: */
  2553. #define CHECKSIZE (4 + 4 + 4 + 2)
  2554. /* zero-fill, checksum, transfer end and line termination space.  */

  2555. /* The amount of binary data loaded from the object file in a single
  2556.    operation: */
  2557. #define BINCHUNK (1024)

  2558. /* Maximum line of data accepted by the monitor: */
  2559. #define MAXRECSIZE (550)
  2560. /* NOTE: This constant depends on the monitor being used.  This value
  2561.    is for PMON 5.x on the Cogent Vr4300 board.  */

  2562. /* Create a FastLoad format record.

  2563.    *OUTBUF is the buffer into which a FastLoad formatted record is
  2564.    written.  On return, the pointer position represented by *OUTBUF
  2565.    is updated to point at the end of the data, i.e. the next position
  2566.    in the buffer that may be written.  No attempt is made to NUL-
  2567.    terminate this portion of the record written to the buffer.

  2568.    INBUF contains the binary input data from which the FastLoad
  2569.    formatted record will be built.  *INPTR is an index into this
  2570.    buffer.  *INPTR is updated as the input is consumed.  Thus, on
  2571.    return, the caller has access to the position of the next input
  2572.    byte yet to be processed.  INAMOUNT is the size, in bytes, of the
  2573.    input data.

  2574.    *RECSIZE will be written with the size of the record written to the
  2575.    output buffer prior to returning.  This size does not include a
  2576.    NUL-termination byte as none is written to the output buffer.

  2577.    *CSUM is the output buffer checksum.  It is updated as data is
  2578.    written to the output buffer.

  2579.    *ZEROFILL is the current number of 3-byte zero sequences that have
  2580.    been encountered.  It is both an input and an output to this
  2581.    function.  */

  2582. static void
  2583. pmon_make_fastrec (char **outbuf, unsigned char *inbuf, int *inptr,
  2584.                    int inamount, int *recsize, unsigned int *csum,
  2585.                    unsigned int *zerofill)
  2586. {
  2587.   int count = 0;
  2588.   char *p = *outbuf;

  2589.   /* This is a simple check to ensure that our data will fit within
  2590.      the maximum allowable record size.  Each record output is 4bytes
  2591.      in length.  We must allow space for a pending zero fill command,
  2592.      the record, and a checksum record.  */
  2593.   while ((*recsize < (MAXRECSIZE - CHECKSIZE)) && ((inamount - *inptr) > 0))
  2594.     {
  2595.       /* Process the binary data: */
  2596.       if ((inamount - *inptr) < 3)
  2597.         {
  2598.           if (*zerofill != 0)
  2599.             *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
  2600.           sprintf (p, "/B");
  2601.           count = pmon_makeb64 (inbuf[*inptr], &p[2], 12, csum);
  2602.           p += (2 + count);
  2603.           *recsize += (2 + count);
  2604.           (*inptr)++;
  2605.         }
  2606.       else
  2607.         {
  2608.           unsigned int value = ((inbuf[*inptr + 0] << 16)
  2609.                                 | (inbuf[*inptr + 1] << 8)
  2610.                                 | (inbuf[*inptr + 2]));

  2611.           /* Simple check for zero dataTODO: A better check would be
  2612.              to check the last, and then the middle byte for being zero
  2613.              (if the first byte is not).  We could then check for
  2614.              following runs of zeros, and if above a certain size it is
  2615.              worth the 4 or 8 character hit of the byte insertions used
  2616.              to pad to the start of the zeroes.  NOTE: This also depends
  2617.              on the alignment at the end of the zero run.  */
  2618.           if (value == 0x00000000)
  2619.             {
  2620.               (*zerofill)++;
  2621.               if (*zerofill == 0xFFF)        /* 12bit counter */
  2622.                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
  2623.             }
  2624.           else
  2625.             {
  2626.               if (*zerofill != 0)
  2627.                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
  2628.               count = pmon_makeb64 (value, p, 24, csum);
  2629.               p += count;
  2630.               *recsize += count;
  2631.             }
  2632.           *inptr += 3;
  2633.         }
  2634.     }

  2635.   *outbuf = p;
  2636.   return;
  2637. }

  2638. /* Attempt to read an ACK.  If an ACK is not read in a timely manner,
  2639.    output the message specified by MESG.  Return -1 for failure, 0
  2640.    for success.  */

  2641. static int
  2642. pmon_check_ack (char *mesg)
  2643. {
  2644. #if defined(DOETXACK)
  2645.   int c;

  2646.   if (!tftp_in_use)
  2647.     {
  2648.       c = serial_readchar (udp_in_use ? udp_desc : mips_desc,
  2649.                            remote_timeout);
  2650.       if ((c == SERIAL_TIMEOUT) || (c != 0x06))
  2651.         {
  2652.           fprintf_unfiltered (gdb_stderr,
  2653.                               "Failed to receive valid ACK for %s\n", mesg);
  2654.           return (-1);                /* Terminate the download.  */
  2655.         }
  2656.     }
  2657. #endif /* DOETXACK */
  2658.   return (0);
  2659. }

  2660. /* pmon_download - Send a sequence of characters to the PMON download port,
  2661.    which is either a serial port or a UDP socket.  */

  2662. static void
  2663. pmon_start_download (void)
  2664. {
  2665.   if (tftp_in_use)
  2666.     {
  2667.       /* Create the temporary download file.  */
  2668.       if ((tftp_file = fopen (tftp_localname, "w")) == NULL)
  2669.         perror_with_name (tftp_localname);
  2670.     }
  2671.   else
  2672.     {
  2673.       mips_send_command (udp_in_use ? LOAD_CMD_UDP : LOAD_CMD, 0);
  2674.       mips_expect ("Downloading from ");
  2675.       mips_expect (udp_in_use ? "udp" : "tty0");
  2676.       mips_expect (", ^C to abort\r\n");
  2677.     }
  2678. }

  2679. /* Look for the string specified by STRING sent from the target board
  2680.    during a download operation.  If the string in question is not
  2681.    seen, output an error message, remove the temporary file, if
  2682.    appropriate, and return 0.  Otherwise, return 1 to indicate
  2683.    success.  */

  2684. static int
  2685. mips_expect_download (char *string)
  2686. {
  2687.   if (!mips_expect (string))
  2688.     {
  2689.       fprintf_unfiltered (gdb_stderr, "Load did not complete successfully.\n");
  2690.       if (tftp_in_use)
  2691.         remove (tftp_localname);        /* Remove temporary file.  */
  2692.       return 0;
  2693.     }
  2694.   else
  2695.     return 1;
  2696. }

  2697. /* Look for messages from the target board associated with the entry
  2698.    address.

  2699.    NOTE: This function doesn't indicate success or failure, so we
  2700.    have no way to determine whether or not the output from the board
  2701.    was correctly seen.  However, given that other items are checked
  2702.    after this, it seems unlikely that those checks will pass if this
  2703.    check doesn't first (silently) pass.  */

  2704. static void
  2705. pmon_check_entry_address (char *entry_address, int final)
  2706. {
  2707.   char hexnumber[9];                /* Includes '\0' space.  */

  2708.   mips_expect_timeout (entry_address, tftp_in_use ? 15 : remote_timeout);
  2709.   sprintf (hexnumber, "%x", final);
  2710.   mips_expect (hexnumber);
  2711.   mips_expect ("\r\n");
  2712. }

  2713. /* Look for messages from the target board showing the total number of
  2714.    bytes downloaded to the board.  Output 1 for success if the tail
  2715.    end of the message was read correctly, 0 otherwise.  */

  2716. static int
  2717. pmon_check_total (int bintotal)
  2718. {
  2719.   char hexnumber[9];                /* Includes '\0' space.  */

  2720.   mips_expect ("\r\ntotal = 0x");
  2721.   sprintf (hexnumber, "%x", bintotal);
  2722.   mips_expect (hexnumber);
  2723.   return mips_expect_download (" bytes\r\n");
  2724. }

  2725. /* Look for the termination messages associated with the end of
  2726.    a download to the board.

  2727.    Also, when `tftp_in_use' is set, issue the load command to the
  2728.    board causing the file to be transferred.  (This is done prior
  2729.    to looking for the above mentioned termination messages.)  */

  2730. static void
  2731. pmon_end_download (int final, int bintotal)
  2732. {
  2733.   char hexnumber[9];                /* Includes '\0' space.  */

  2734.   if (tftp_in_use)
  2735.     {
  2736.       static char *load_cmd_prefix = "load -b -s ";
  2737.       char *cmd;
  2738.       struct stat stbuf;

  2739.       /* Close off the temporary file containing the load data.  */
  2740.       fclose (tftp_file);
  2741.       tftp_file = NULL;

  2742.       /* Make the temporary file readable by the world.  */
  2743.       if (stat (tftp_localname, &stbuf) == 0)
  2744.         chmod (tftp_localname, stbuf.st_mode | S_IROTH);

  2745.       /* Must reinitialize the board to prevent PMON from crashing.  */
  2746.       if (mips_monitor != MON_ROCKHOPPER)
  2747.         mips_send_command ("initEther\r", -1);

  2748.       /* Send the load command.  */
  2749.       cmd = xmalloc (strlen (load_cmd_prefix) + strlen (tftp_name) + 2);
  2750.       strcpy (cmd, load_cmd_prefix);
  2751.       strcat (cmd, tftp_name);
  2752.       strcat (cmd, "\r");
  2753.       mips_send_command (cmd, 0);
  2754.       xfree (cmd);
  2755.       if (!mips_expect_download ("Downloading from "))
  2756.         return;
  2757.       if (!mips_expect_download (tftp_name))
  2758.         return;
  2759.       if (!mips_expect_download (", ^C to abort\r\n"))
  2760.         return;
  2761.     }

  2762.   /* Wait for the stuff that PMON prints after the load has completed.
  2763.      The timeout value for use in the tftp case (15 seconds) was picked
  2764.      arbitrarily but might be too small for really large downloads.  FIXME.  */
  2765.   switch (mips_monitor)
  2766.     {
  2767.     case MON_LSI:
  2768.       pmon_check_ack ("termination");
  2769.       pmon_check_entry_address ("Entry address is ", final);
  2770.       if (!pmon_check_total (bintotal))
  2771.         return;
  2772.       break;
  2773.     case MON_ROCKHOPPER:
  2774.       if (!pmon_check_total (bintotal))
  2775.         return;
  2776.       pmon_check_entry_address ("Entry Address  = ", final);
  2777.       break;
  2778.     default:
  2779.       pmon_check_entry_address ("Entry Address  = ", final);
  2780.       pmon_check_ack ("termination");
  2781.       if (!pmon_check_total (bintotal))
  2782.         return;
  2783.       break;
  2784.     }

  2785.   if (tftp_in_use)
  2786.     remove (tftp_localname);        /* Remove temporary file.  */
  2787. }

  2788. /* Write the buffer specified by BUFFER of length LENGTH to either
  2789.    the board or the temporary file that'll eventually be transferred
  2790.    to the board.  */

  2791. static void
  2792. pmon_download (char *buffer, int length)
  2793. {
  2794.   if (tftp_in_use)
  2795.     {
  2796.       size_t written;

  2797.       written = fwrite (buffer, 1, length, tftp_file);
  2798.       if (written < length)
  2799.         perror_with_name (tftp_localname);
  2800.     }
  2801.   else
  2802.     serial_write (udp_in_use ? udp_desc : mips_desc, buffer, length);
  2803. }

  2804. /* Open object or executable file, FILE, and send it to the board
  2805.    using the FastLoad format.  */

  2806. static void
  2807. pmon_load_fast (const char *file)
  2808. {
  2809.   bfd *abfd;
  2810.   asection *s;
  2811.   unsigned char *binbuf;
  2812.   char *buffer;
  2813.   int reclen;
  2814.   unsigned int csum = 0;
  2815.   int hashmark = !tftp_in_use;
  2816.   int bintotal = 0;
  2817.   int final = 0;
  2818.   int finished = 0;
  2819.   struct cleanup *cleanup;

  2820.   buffer = (char *) xmalloc (MAXRECSIZE + 1);
  2821.   binbuf = (unsigned char *) xmalloc (BINCHUNK);

  2822.   abfd = gdb_bfd_open (file, NULL, -1);
  2823.   if (!abfd)
  2824.     {
  2825.       printf_filtered ("Unable to open file %s\n", file);
  2826.       return;
  2827.     }
  2828.   cleanup = make_cleanup_bfd_unref (abfd);

  2829.   if (bfd_check_format (abfd, bfd_object) == 0)
  2830.     {
  2831.       printf_filtered ("File is not an object file\n");
  2832.       do_cleanups (cleanup);
  2833.       return;
  2834.     }

  2835.   /* Setup the required download state: */
  2836.   mips_send_command ("set dlproto etxack\r", -1);
  2837.   mips_send_command ("set dlecho off\r", -1);
  2838.   /* NOTE: We get a "cannot set variable" message if the variable is
  2839.      already defined to have the argument we give.  The code doesn't
  2840.      care, since it just scans to the next prompt anyway.  */
  2841.   /* Start the download: */
  2842.   pmon_start_download ();

  2843.   /* Zero the checksum.  */
  2844.   sprintf (buffer, "/Kxx\n");
  2845.   reclen = strlen (buffer);
  2846.   pmon_download (buffer, reclen);
  2847.   finished = pmon_check_ack ("/Kxx");

  2848.   for (s = abfd->sections; s && !finished; s = s->next)
  2849.     if (s->flags & SEC_LOAD)        /* Only deal with loadable sections.  */
  2850.       {
  2851.         bintotal += bfd_get_section_size (s);
  2852.         final = (s->vma + bfd_get_section_size (s));

  2853.         printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name,
  2854.                          (unsigned int) s->vma,
  2855.                          (unsigned int) (s->vma + bfd_get_section_size (s)));
  2856.         gdb_flush (gdb_stdout);

  2857.         /* Output the starting address.  */
  2858.         sprintf (buffer, "/A");
  2859.         reclen = pmon_makeb64 (s->vma, &buffer[2], 36, &csum);
  2860.         buffer[2 + reclen] = '\n';
  2861.         buffer[3 + reclen] = '\0';
  2862.         reclen += 3;        /* For the initial escape code and carriage return.  */
  2863.         pmon_download (buffer, reclen);
  2864.         finished = pmon_check_ack ("/A");

  2865.         if (!finished)
  2866.           {
  2867.             unsigned int binamount;
  2868.             unsigned int zerofill = 0;
  2869.             char *bp = buffer;
  2870.             unsigned int i;

  2871.             reclen = 0;

  2872.             for (i = 0;
  2873.                  i < bfd_get_section_size (s) && !finished;
  2874.                  i += binamount)
  2875.               {
  2876.                 int binptr = 0;

  2877.                 binamount = min (BINCHUNK, bfd_get_section_size (s) - i);

  2878.                 bfd_get_section_contents (abfd, s, binbuf, i, binamount);

  2879.                 /* This keeps a rolling checksum, until we decide to output
  2880.                    the line: */
  2881.                 for (; ((binamount - binptr) > 0);)
  2882.                   {
  2883.                     pmon_make_fastrec (&bp, binbuf, &binptr, binamount,
  2884.                                        &reclen, &csum, &zerofill);
  2885.                     if (reclen >= (MAXRECSIZE - CHECKSIZE))
  2886.                       {
  2887.                         reclen = pmon_checkset (reclen, &bp, &csum);
  2888.                         pmon_download (buffer, reclen);
  2889.                         finished = pmon_check_ack ("data record");
  2890.                         if (finished)
  2891.                           {
  2892.                             zerofill = 0;        /* Do not transmit pending
  2893.                                                    zerofills.  */
  2894.                             break;
  2895.                           }

  2896.                         if (deprecated_ui_load_progress_hook)
  2897.                           deprecated_ui_load_progress_hook (s->name, i);

  2898.                         if (hashmark)
  2899.                           {
  2900.                             putchar_unfiltered ('#');
  2901.                             gdb_flush (gdb_stdout);
  2902.                           }

  2903.                         bp = buffer;
  2904.                         reclen = 0;        /* buffer processed */
  2905.                       }
  2906.                   }
  2907.               }

  2908.             /* Ensure no out-standing zerofill requests: */
  2909.             if (zerofill != 0)
  2910.               reclen = pmon_zeroset (reclen, &bp, &zerofill, &csum);

  2911.             /* and then flush the line: */
  2912.             if (reclen > 0)
  2913.               {
  2914.                 reclen = pmon_checkset (reclen, &bp, &csum);
  2915.                 /* Currently pmon_checkset outputs the line terminator by
  2916.                    default, so we write out the buffer so far: */
  2917.                 pmon_download (buffer, reclen);
  2918.                 finished = pmon_check_ack ("record remnant");
  2919.               }
  2920.           }

  2921.         putchar_unfiltered ('\n');
  2922.       }

  2923.   /* Terminate the transfer.  We know that we have an empty output
  2924.      buffer at this point.  */
  2925.   sprintf (buffer, "/E/E\n");        /* Include dummy padding characters.  */
  2926.   reclen = strlen (buffer);
  2927.   pmon_download (buffer, reclen);

  2928.   if (finished)
  2929.     {                                /* Ignore the termination message: */
  2930.       serial_flush_input (udp_in_use ? udp_desc : mips_desc);
  2931.     }
  2932.   else
  2933.     {                                /* Deal with termination message: */
  2934.       pmon_end_download (final, bintotal);
  2935.     }

  2936.   do_cleanups (cleanup);
  2937.   return;
  2938. }

  2939. /* mips_load -- download a file.  */

  2940. static void
  2941. mips_load (struct target_ops *self, const char *file, int from_tty)
  2942. {
  2943.   struct regcache *regcache;

  2944.   /* Get the board out of remote debugging mode.  */
  2945.   if (mips_exit_debug ())
  2946.     error (_("mips_load:  Couldn't get into monitor mode."));

  2947.   if (mips_monitor != MON_IDT)
  2948.     pmon_load_fast (file);
  2949.   else
  2950.     mips_load_srec (file);

  2951.   mips_initialize ();

  2952.   /* Finally, make the PC point at the start address.  */
  2953.   regcache = get_current_regcache ();
  2954.   if (mips_monitor != MON_IDT)
  2955.     {
  2956.       /* Work around problem where PMON monitor updates the PC after a load
  2957.          to a different value than GDB thinks it has.  The following ensures
  2958.          that the regcache_write_pc() WILL update the PC value: */
  2959.       regcache_invalidate (regcache,
  2960.                            mips_regnum (get_regcache_arch (regcache))->pc);
  2961.     }
  2962.   if (exec_bfd)
  2963.     regcache_write_pc (regcache, bfd_get_start_address (exec_bfd));
  2964. }

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

  2966. static int
  2967. mips_thread_alive (struct target_ops *ops, ptid_t ptid)
  2968. {
  2969.   if (ptid_equal (ptid, remote_mips_ptid))
  2970.     /* The monitor's task is always alive.  */
  2971.     return 1;

  2972.   return 0;
  2973. }

  2974. /* Convert a thread ID to a string.  Returns the string in a static
  2975.    buffer.  */

  2976. static char *
  2977. mips_pid_to_str (struct target_ops *ops, ptid_t ptid)
  2978. {
  2979.   static char buf[64];

  2980.   if (ptid_equal (ptid, remote_mips_ptid))
  2981.     {
  2982.       xsnprintf (buf, sizeof buf, "Thread <main>");
  2983.       return buf;
  2984.     }

  2985.   return normal_pid_to_str (ptid);
  2986. }

  2987. /* Pass the command argument as a packet to PMON verbatim.  */

  2988. static void
  2989. pmon_command (char *args, int from_tty)
  2990. {
  2991.   char buf[DATA_MAXLEN + 1];
  2992.   int rlen;

  2993.   sprintf (buf, "0x0 %s", args);
  2994.   mips_send_packet (buf, 1);
  2995.   printf_filtered ("Send packet: %s\n", buf);

  2996.   rlen = mips_receive_packet (buf, 1, mips_receive_wait);
  2997.   buf[rlen] = '\0';
  2998.   printf_filtered ("Received packet: %s\n", buf);
  2999. }

  3000. /* -Wmissing-prototypes */
  3001. extern initialize_file_ftype _initialize_remote_mips;

  3002. /* Initialize mips_ops, lsi_ops, ddb_ops, pmon_ops, and rockhopper_ops.
  3003.    Create target specific commands and perform other initializations
  3004.    specific to this file.  */

  3005. void
  3006. _initialize_remote_mips (void)
  3007. {
  3008.   /* Initialize the fields in mips_ops that are common to all four targets.  */
  3009.   mips_ops.to_longname = "Remote MIPS debugging over serial line";
  3010.   mips_ops.to_close = mips_close;
  3011.   mips_ops.to_detach = mips_detach;
  3012.   mips_ops.to_resume = mips_resume;
  3013.   mips_ops.to_fetch_registers = mips_fetch_registers;
  3014.   mips_ops.to_store_registers = mips_store_registers;
  3015.   mips_ops.to_prepare_to_store = mips_prepare_to_store;
  3016.   mips_ops.to_xfer_partial = mips_xfer_partial;
  3017.   mips_ops.to_files_info = mips_files_info;
  3018.   mips_ops.to_insert_breakpoint = mips_insert_breakpoint;
  3019.   mips_ops.to_remove_breakpoint = mips_remove_breakpoint;
  3020.   mips_ops.to_insert_watchpoint = mips_insert_watchpoint;
  3021.   mips_ops.to_remove_watchpoint = mips_remove_watchpoint;
  3022.   mips_ops.to_stopped_by_watchpoint = mips_stopped_by_watchpoint;
  3023.   mips_ops.to_can_use_hw_breakpoint = mips_can_use_watchpoint;
  3024.   mips_ops.to_kill = mips_kill;
  3025.   mips_ops.to_load = mips_load;
  3026.   mips_ops.to_create_inferior = mips_create_inferior;
  3027.   mips_ops.to_mourn_inferior = mips_mourn_inferior;
  3028.   mips_ops.to_thread_alive = mips_thread_alive;
  3029.   mips_ops.to_pid_to_str = mips_pid_to_str;
  3030.   mips_ops.to_log_command = serial_log_command;
  3031.   mips_ops.to_stratum = process_stratum;
  3032.   mips_ops.to_has_all_memory = default_child_has_all_memory;
  3033.   mips_ops.to_has_memory = default_child_has_memory;
  3034.   mips_ops.to_has_stack = default_child_has_stack;
  3035.   mips_ops.to_has_registers = default_child_has_registers;
  3036.   mips_ops.to_has_execution = default_child_has_execution;
  3037.   mips_ops.to_magic = OPS_MAGIC;

  3038.   /* Copy the common fields to all four target vectors.  */
  3039.   rockhopper_ops = pmon_ops = ddb_ops = lsi_ops = mips_ops;

  3040.   /* Initialize target-specific fields in the target vectors.  */
  3041.   mips_ops.to_shortname = "mips";
  3042.   mips_ops.to_doc = "\
  3043. Debug a board using the MIPS remote debugging protocol over a serial line.\n\
  3044. The argument is the device it is connected to or, if it contains a colon,\n\
  3045. HOST:PORT to access a board over a network";
  3046.   mips_ops.to_open = mips_open;
  3047.   mips_ops.to_wait = mips_wait;

  3048.   pmon_ops.to_shortname = "pmon";
  3049.   pmon_ops.to_doc = "\
  3050. Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
  3051. line. The argument is the device it is connected to or, if it contains a\n\
  3052. colon, HOST:PORT to access a board over a network";
  3053.   pmon_ops.to_open = pmon_open;
  3054.   pmon_ops.to_wait = mips_wait;

  3055.   ddb_ops.to_shortname = "ddb";
  3056.   ddb_ops.to_doc = "\
  3057. Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
  3058. line. The first argument is the device it is connected to or, if it contains\n\
  3059. a colon, HOST:PORT to access a board over a network.  The optional second\n\
  3060. parameter is the temporary file in the form HOST:FILENAME to be used for\n\
  3061. TFTP downloads to the board.  The optional third parameter is the local name\n\
  3062. of the TFTP temporary file, if it differs from the filename seen by the board.";
  3063.   ddb_ops.to_open = ddb_open;
  3064.   ddb_ops.to_wait = mips_wait;

  3065.   rockhopper_ops.to_shortname = "rockhopper";
  3066.   rockhopper_ops.to_doc = ddb_ops.to_doc;
  3067.   rockhopper_ops.to_open = rockhopper_open;
  3068.   rockhopper_ops.to_wait = mips_wait;

  3069.   lsi_ops.to_shortname = "lsi";
  3070.   lsi_ops.to_doc = pmon_ops.to_doc;
  3071.   lsi_ops.to_open = lsi_open;
  3072.   lsi_ops.to_wait = mips_wait;

  3073.   /* Add the targets.  */
  3074.   add_target (&mips_ops);
  3075.   add_target (&pmon_ops);
  3076.   add_target (&ddb_ops);
  3077.   add_target (&lsi_ops);
  3078.   add_target (&rockhopper_ops);

  3079.   add_setshow_zinteger_cmd ("timeout", no_class, &mips_receive_wait, _("\
  3080. Set timeout in seconds for remote MIPS serial I/O."), _("\
  3081. Show timeout in seconds for remote MIPS serial I/O."), NULL,
  3082.                             NULL,
  3083.                             NULL, /* FIXME: i18n: */
  3084.                             &setlist, &showlist);

  3085.   add_setshow_zinteger_cmd ("retransmit-timeout", no_class,
  3086.                             &mips_retransmit_wait, _("\
  3087. Set retransmit timeout in seconds for remote MIPS serial I/O."), _("\
  3088. Show retransmit timeout in seconds for remote MIPS serial I/O."), _("\
  3089. This is the number of seconds to wait for an acknowledgement to a packet\n\
  3090. before resending the packet."),
  3091.                             NULL,
  3092.                             NULL, /* FIXME: i18n: */
  3093.                             &setlist, &showlist);

  3094.   add_setshow_zinteger_cmd ("syn-garbage-limit", no_class,
  3095.                             &mips_syn_garbage_("\
  3096. Set the maximum number of characters to ignore when scanning for a SYN."), _("\
  3097. Show the maximum number of characters to ignore when scanning for a SYN."), _("\
  3098. This is the maximum number of characters GDB will ignore when trying to\n\
  3099. synchronize with the remote system.  A value of -1 means that there is no\n\
  3100. limit. (Note that these characters are printed out even though they are\n\
  3101. ignored.)"),
  3102.                             NULL,
  3103.                             NULL, /* FIXME: i18n: */
  3104.                             &setlist, &showlist);

  3105.   add_setshow_string_cmd ("monitor-prompt", class_obscure,
  3106.                           &mips_monitor_prompt, _("\
  3107. Set the prompt that GDB expects from the monitor."), _("\
  3108. Show the prompt that GDB expects from the monitor."), NULL,
  3109.                           NULL,
  3110.                           NULL, /* FIXME: i18n: */
  3111.                           &setlist, &showlist);

  3112.   add_setshow_zinteger_cmd ("monitor-warnings", class_obscure,
  3113.                             &monitor_warnings, _("\
  3114. Set printing of monitor warnings."), _("\
  3115. Show printing of monitor warnings."), _("\
  3116. When enabled, monitor warnings about hardware breakpoints will be displayed."),
  3117.                             NULL,
  3118.                             NULL, /* FIXME: i18n: */
  3119.                             &setlist, &showlist);

  3120.   add_com ("pmon", class_obscure, pmon_command,
  3121.            _("Send a packet to PMON (must be in debug mode)."));

  3122.   add_setshow_boolean_cmd ("mask-address", no_class, &mask_address_p, _("\
  3123. Set zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
  3124. Show zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
  3125. Use \"on\" to enable the masking and \"off\" to disable it."),
  3126.                            NULL,
  3127.                            NULL, /* FIXME: i18n: */
  3128.                            &setlist, &showlist);
  3129.   remote_mips_ptid = ptid_build (42000, 0, 42000);
  3130. }