home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / gdb-4.14-src.lha / gdb-4.14 / gdb / remote-mips.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-19  |  43.5 KB  |  1,557 lines

  1. /* Remote debugging interface for MIPS remote debugging protocol.
  2.    Copyright 1993, 1994 Free Software Foundation, Inc.
  3.    Contributed by Cygnus Support.  Written by Ian Lance Taylor
  4.    <ian@cygnus.com>.
  5.  
  6. This file is part of GDB.
  7.  
  8. This program is free software; you can redistribute it and/or modify
  9. it under the terms of the GNU General Public License as published by
  10. the Free Software Foundation; either version 2 of the License, or
  11. (at your option) any later version.
  12.  
  13. This program is distributed in the hope that it will be useful,
  14. but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. GNU General Public License for more details.
  17.  
  18. You should have received a copy of the GNU General Public License
  19. along with this program; if not, write to the Free Software
  20. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. #include "defs.h"
  23. #include "inferior.h"
  24. #include "bfd.h"
  25. #include "symfile.h"
  26. #include "wait.h"
  27. #include "gdbcmd.h"
  28. #include "gdbcore.h"
  29. #include "serial.h"
  30. #include "target.h"
  31. #include "remote-utils.h"
  32.  
  33. #include <signal.h>
  34. #include <varargs.h>
  35.  
  36. extern char *mips_read_processor_type PARAMS ((void));
  37.  
  38. extern void mips_set_processor_type_command PARAMS ((char *, int));
  39.  
  40.  
  41. /* Prototypes for local functions.  */
  42.  
  43. static int mips_readchar PARAMS ((int timeout));
  44.  
  45. static int mips_receive_header PARAMS ((unsigned char *hdr, int *pgarbage,
  46.                     int ch, int timeout));
  47.  
  48. static int mips_receive_trailer PARAMS ((unsigned char *trlr, int *pgarbage,
  49.                      int *pch, int timeout));
  50.  
  51. static int mips_cksum PARAMS ((const unsigned char *hdr,
  52.                    const unsigned char *data,
  53.                    int len));
  54.  
  55. static void mips_send_packet PARAMS ((const char *s, int get_ack));
  56.  
  57. static int mips_receive_packet PARAMS ((char *buff, int throw_error,
  58.                     int timeout));
  59.  
  60. static int mips_request PARAMS ((char cmd, unsigned int addr,
  61.                  unsigned int data, int *perr, int timeout));
  62.  
  63. static void mips_initialize PARAMS ((void));
  64.  
  65. static void mips_open PARAMS ((char *name, int from_tty));
  66.  
  67. static void mips_close PARAMS ((int quitting));
  68.  
  69. static void mips_detach PARAMS ((char *args, int from_tty));
  70.  
  71. static void mips_resume PARAMS ((int pid, int step,
  72.                  enum target_signal siggnal));
  73.  
  74. static int mips_wait PARAMS ((int pid, struct target_waitstatus *status));
  75.  
  76. static int mips_map_regno PARAMS ((int regno));
  77.  
  78. static void mips_fetch_registers PARAMS ((int regno));
  79.  
  80. static void mips_prepare_to_store PARAMS ((void));
  81.  
  82. static void mips_store_registers PARAMS ((int regno));
  83.  
  84. static int mips_fetch_word PARAMS ((CORE_ADDR addr));
  85.  
  86. static int mips_store_word PARAMS ((CORE_ADDR addr, int value,
  87.                     char *old_contents));
  88.  
  89. static int mips_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len,
  90.                      int write, struct target_ops *ignore));
  91.  
  92. static void mips_files_info PARAMS ((struct target_ops *ignore));
  93.  
  94. static void mips_create_inferior PARAMS ((char *execfile, char *args,
  95.                       char **env));
  96.  
  97. static void mips_mourn_inferior PARAMS ((void));
  98.  
  99. /* A forward declaration.  */
  100. extern struct target_ops mips_ops;
  101.  
  102. /* The MIPS remote debugging interface is built on top of a simple
  103.    packet protocol.  Each packet is organized as follows:
  104.  
  105.    SYN    The first character is always a SYN (ASCII 026, or ^V).  SYN
  106.     may not appear anywhere else in the packet.  Any time a SYN is
  107.     seen, a new packet should be assumed to have begun.
  108.  
  109.    TYPE_LEN
  110.     This byte contains the upper five bits of the logical length
  111.     of the data section, plus a single bit indicating whether this
  112.     is a data packet or an acknowledgement.  The documentation
  113.     indicates that this bit is 1 for a data packet, but the actual
  114.     board uses 1 for an acknowledgement.  The value of the byte is
  115.         0x40 + (ack ? 0x20 : 0) + (len >> 6)
  116.     (we always have 0 <= len < 1024).  Acknowledgement packets do
  117.     not carry data, and must have a data length of 0.
  118.  
  119.    LEN1 This byte contains the lower six bits of the logical length of
  120.     the data section.  The value is
  121.          0x40 + (len & 0x3f)
  122.  
  123.    SEQ    This byte contains the six bit sequence number of the packet.
  124.     The value is
  125.         0x40 + seq
  126.     An acknowlegment packet contains the sequence number of the
  127.     packet being acknowledged plus 1 module 64.  Data packets are
  128.     transmitted in sequence.  There may only be one outstanding
  129.     unacknowledged data packet at a time.  The sequence numbers
  130.     are independent in each direction.  If an acknowledgement for
  131.     the previous packet is received (i.e., an acknowledgement with
  132.     the sequence number of the packet just sent) the packet just
  133.     sent should be retransmitted.  If no acknowledgement is
  134.     received within a timeout period, the packet should be
  135.     retransmitted.  This has an unfortunate failure condition on a
  136.     high-latency line, as a delayed acknowledgement may lead to an
  137.     endless series of duplicate packets.
  138.  
  139.    DATA    The actual data bytes follow.  The following characters are
  140.     escaped inline with DLE (ASCII 020, or ^P):
  141.         SYN (026)    DLE S
  142.         DLE (020)    DLE D
  143.         ^C  (003)    DLE C
  144.         ^S  (023)    DLE s
  145.         ^Q  (021)    DLE q
  146.     The additional DLE characters are not counted in the logical
  147.     length stored in the TYPE_LEN and LEN1 bytes.
  148.  
  149.    CSUM1
  150.    CSUM2
  151.    CSUM3
  152.     These bytes contain an 18 bit checksum of the complete
  153.     contents of the packet excluding the SEQ byte and the
  154.     CSUM[123] bytes.  The checksum is simply the twos complement
  155.     addition of all the bytes treated as unsigned characters.  The
  156.     values of the checksum bytes are:
  157.         CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
  158.         CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
  159.         CSUM3: 0x40 + (cksum & 0x3f)
  160.  
  161.    It happens that the MIPS remote debugging protocol always
  162.    communicates with ASCII strings.  Because of this, this
  163.    implementation doesn't bother to handle the DLE quoting mechanism,
  164.    since it will never be required.  */
  165.  
  166. /* The SYN character which starts each packet.  */
  167. #define SYN '\026'
  168.  
  169. /* The 0x40 used to offset each packet (this value ensures that all of
  170.    the header and trailer bytes, other than SYN, are printable ASCII
  171.    characters).  */
  172. #define HDR_OFFSET 0x40
  173.  
  174. /* The indices of the bytes in the packet header.  */
  175. #define HDR_INDX_SYN 0
  176. #define HDR_INDX_TYPE_LEN 1
  177. #define HDR_INDX_LEN1 2
  178. #define HDR_INDX_SEQ 3
  179. #define HDR_LENGTH 4
  180.  
  181. /* The data/ack bit in the TYPE_LEN header byte.  */
  182. #define TYPE_LEN_DA_BIT 0x20
  183. #define TYPE_LEN_DATA 0
  184. #define TYPE_LEN_ACK TYPE_LEN_DA_BIT
  185.  
  186. /* How to compute the header bytes.  */
  187. #define HDR_SET_SYN(data, len, seq) (SYN)
  188. #define HDR_SET_TYPE_LEN(data, len, seq) \
  189.   (HDR_OFFSET \
  190.    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
  191.    + (((len) >> 6) & 0x1f))
  192. #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
  193. #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))
  194.  
  195. /* Check that a header byte is reasonable.  */
  196. #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)
  197.  
  198. /* Get data from the header.  These macros evaluate their argument
  199.    multiple times.  */
  200. #define HDR_IS_DATA(hdr) \
  201.   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
  202. #define HDR_GET_LEN(hdr) \
  203.   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
  204. #define HDR_GET_SEQ(hdr) ((hdr)[HDR_INDX_SEQ] & 0x3f)
  205.  
  206. /* The maximum data length.  */
  207. #define DATA_MAXLEN 1023
  208.  
  209. /* The trailer offset.  */
  210. #define TRLR_OFFSET HDR_OFFSET
  211.  
  212. /* The indices of the bytes in the packet trailer.  */
  213. #define TRLR_INDX_CSUM1 0
  214. #define TRLR_INDX_CSUM2 1
  215. #define TRLR_INDX_CSUM3 2
  216. #define TRLR_LENGTH 3
  217.  
  218. /* How to compute the trailer bytes.  */
  219. #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
  220. #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
  221. #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))
  222.  
  223. /* Check that a trailer byte is reasonable.  */
  224. #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)
  225.  
  226. /* Get data from the trailer.  This evaluates its argument multiple
  227.    times.  */
  228. #define TRLR_GET_CKSUM(trlr) \
  229.   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
  230.    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
  231.    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))
  232.  
  233. /* The sequence number modulos.  */
  234. #define SEQ_MODULOS (64)
  235.  
  236. /* Set to 1 if the target is open.  */
  237. static int mips_is_open;
  238.  
  239. /* Set to 1 while the connection is being initialized.  */
  240. static int mips_initializing;
  241.  
  242. /* The next sequence number to send.  */
  243. static int mips_send_seq;
  244.  
  245. /* The next sequence number we expect to receive.  */
  246. static int mips_receive_seq;
  247.  
  248. /* The time to wait before retransmitting a packet, in seconds.  */
  249. static int mips_retransmit_wait = 3;
  250.  
  251. /* The number of times to try retransmitting a packet before giving up.  */
  252. static int mips_send_retries = 10;
  253.  
  254. /* The number of garbage characters to accept when looking for an
  255.    SYN for the next packet.  */
  256. static int mips_syn_garbage = 1050;
  257.  
  258. /* The time to wait for a packet, in seconds.  */
  259. static int mips_receive_wait = 5;
  260.  
  261. /* Set if we have sent a packet to the board but have not yet received
  262.    a reply.  */
  263. static int mips_need_reply = 0;
  264.  
  265. /* Handle used to access serial I/O stream.  */
  266. static serial_t mips_desc;
  267.  
  268. /* Handle low-level error that we can't recover from.  Note that just
  269.    error()ing out from target_wait or some such low-level place will cause
  270.    all hell to break loose--the rest of GDB will tend to get left in an
  271.    inconsistent state.  */
  272.  
  273. static NORETURN void
  274. mips_error (va_alist)
  275.      va_dcl
  276. {
  277.   va_list args;
  278.   char *string;
  279.  
  280.   va_start (args);
  281.   target_terminal_ours ();
  282.   wrap_here("");            /* Force out any buffered output */
  283.   gdb_flush (gdb_stdout);
  284.   if (error_pre_print)
  285.     fprintf_filtered (gdb_stderr, error_pre_print);
  286.   string = va_arg (args, char *);
  287.   vfprintf_filtered (gdb_stderr, string, args);
  288.   fprintf_filtered (gdb_stderr, "\n");
  289.   va_end (args);
  290.  
  291.   /* Clean up in such a way that mips_close won't try to talk to the
  292.      board (it almost surely won't work since we weren't able to talk to
  293.      it).  */
  294.   mips_is_open = 0;
  295.   SERIAL_CLOSE (mips_desc);
  296.  
  297.   printf_unfiltered ("Ending remote MIPS debugging.\n");
  298.   target_mourn_inferior ();
  299.  
  300.   return_to_top_level (RETURN_ERROR);
  301. }
  302.  
  303. /* Read a character from the remote, aborting on error.  Returns
  304.    SERIAL_TIMEOUT on timeout (since that's what SERIAL_READCHAR
  305.    returns).  FIXME: If we see the string "<IDT>" from the board, then
  306.    we are debugging on the main console port, and we have somehow
  307.    dropped out of remote debugging mode.  In this case, we
  308.    automatically go back in to remote debugging mode.  This is a hack,
  309.    put in because I can't find any way for a program running on the
  310.    remote board to terminate without also ending remote debugging
  311.    mode.  I assume users won't have any trouble with this; for one
  312.    thing, the IDT documentation generally assumes that the remote
  313.    debugging port is not the console port.  This is, however, very
  314.    convenient for DejaGnu when you only have one connected serial
  315.    port.  */
  316.  
  317. static int
  318. mips_readchar (timeout)
  319.      int timeout;
  320. {
  321.   int ch;
  322.   static int state = 0;
  323.   static char nextstate[5] = { '<', 'I', 'D', 'T', '>' };
  324.  
  325.   if (state == 5) 
  326.     timeout = 1;
  327.   ch = SERIAL_READCHAR (mips_desc, timeout);
  328.   if (ch == SERIAL_EOF)
  329.     mips_error ("End of file from remote");
  330.   if (ch == SERIAL_ERROR)
  331.     mips_error ("Error reading from remote: %s", safe_strerror (errno));
  332.   if (sr_get_debug () > 1)
  333.     {
  334.       /* Don't use _filtered; we can't deal with a QUIT out of
  335.      target_wait, and I think this might be called from there.  */
  336.       if (ch != SERIAL_TIMEOUT)
  337.     printf_unfiltered ("Read '%c' %d 0x%x\n", ch, ch, ch);
  338.       else
  339.     printf_unfiltered ("Timed out in read\n");
  340.     }
  341.  
  342.   /* If we have seen <IDT> and we either time out, or we see a @
  343.      (which was echoed from a packet we sent), reset the board as
  344.      described above.  The first character in a packet after the SYN
  345.      (which is not echoed) is always an @ unless the packet is more
  346.      than 64 characters long, which ours never are.  */
  347.   if ((ch == SERIAL_TIMEOUT || ch == '@')
  348.       && state == 5
  349.       && ! mips_initializing)
  350.     {
  351.       if (sr_get_debug () > 0)
  352.     /* Don't use _filtered; we can't deal with a QUIT out of
  353.        target_wait, and I think this might be called from there.  */
  354.     printf_unfiltered ("Reinitializing MIPS debugging mode\n");
  355.       SERIAL_WRITE (mips_desc, "\015db tty0\015", sizeof "\015db tty0\015" - 1);
  356.       sleep (1);
  357.  
  358.       mips_need_reply = 0;
  359.       mips_initialize ();
  360.  
  361.       state = 0;
  362.  
  363.       mips_error ("Remote board reset");
  364.     }
  365.  
  366.   if (ch == nextstate[state])
  367.     ++state;
  368.   else
  369.     state = 0;
  370.  
  371.   return ch;
  372. }
  373.  
  374. /* Get a packet header, putting the data in the supplied buffer.
  375.    PGARBAGE is a pointer to the number of garbage characters received
  376.    so far.  CH is the last character received.  Returns 0 for success,
  377.    or -1 for timeout.  */
  378.  
  379. static int
  380. mips_receive_header (hdr, pgarbage, ch, timeout)
  381.      unsigned char *hdr;
  382.      int *pgarbage;
  383.      int ch;
  384.      int timeout;
  385. {
  386.   int i;
  387.  
  388.   while (1)
  389.     {
  390.       /* Wait for a SYN.  mips_syn_garbage is intended to prevent
  391.      sitting here indefinitely if the board sends us one garbage
  392.      character per second.  ch may already have a value from the
  393.      last time through the loop.  */
  394.       while (ch != SYN)
  395.     {
  396.       ch = mips_readchar (timeout);
  397.       if (ch == SERIAL_TIMEOUT)
  398.         return -1;
  399.       if (ch != SYN)
  400.         {
  401.           /* Printing the character here lets the user of gdb see
  402.          what the program is outputting, if the debugging is
  403.          being done on the console port.  Don't use _filtered;
  404.          we can't deal with a QUIT out of target_wait.  */
  405.           if (! mips_initializing || sr_get_debug () > 0)
  406.         {
  407.           if (ch < 0x20 && ch != '\n')
  408.             {
  409.               putchar_unfiltered ('^');
  410.               putchar_unfiltered (ch + 0x40);
  411.             }
  412.           else
  413.             putchar_unfiltered (ch);
  414.           gdb_flush (gdb_stdout);
  415.         }
  416.  
  417.           ++*pgarbage;
  418.           if (*pgarbage > mips_syn_garbage)
  419.         mips_error ("Remote debugging protocol failure");
  420.         }
  421.     }
  422.  
  423.       /* Get the packet header following the SYN.  */
  424.       for (i = 1; i < HDR_LENGTH; i++)
  425.     {
  426.       ch = mips_readchar (timeout);
  427.       if (ch == SERIAL_TIMEOUT)
  428.         return -1;
  429.  
  430.       /* Make sure this is a header byte.  */
  431.       if (ch == SYN || ! HDR_CHECK (ch))
  432.         break;
  433.  
  434.       hdr[i] = ch;
  435.     }
  436.  
  437.       /* If we got the complete header, we can return.  Otherwise we
  438.      loop around and keep looking for SYN.  */
  439.       if (i >= HDR_LENGTH)
  440.     return 0;
  441.     }
  442. }
  443.  
  444. /* Get a packet header, putting the data in the supplied buffer.
  445.    PGARBAGE is a pointer to the number of garbage characters received
  446.    so far.  The last character read is returned in *PCH.  Returns 0
  447.    for success, -1 for timeout, -2 for error.  */
  448.  
  449. static int
  450. mips_receive_trailer (trlr, pgarbage, pch, timeout)
  451.      unsigned char *trlr;
  452.      int *pgarbage;
  453.      int *pch;
  454.      int timeout;
  455. {
  456.   int i;
  457.   int ch;
  458.  
  459.   for (i = 0; i < TRLR_LENGTH; i++)
  460.     {
  461.       ch = mips_readchar (timeout);
  462.       *pch = ch;
  463.       if (ch == SERIAL_TIMEOUT)
  464.     return -1;
  465.       if (! TRLR_CHECK (ch))
  466.     return -2;
  467.       trlr[i] = ch;
  468.     }
  469.   return 0;
  470. }
  471.  
  472. /* Get the checksum of a packet.  HDR points to the packet header.
  473.    DATA points to the packet data.  LEN is the length of DATA.  */
  474.  
  475. static int
  476. mips_cksum (hdr, data, len)
  477.      const unsigned char *hdr;
  478.      const unsigned char *data;
  479.      int len;
  480. {
  481.   register const unsigned char *p;
  482.   register int c;
  483.   register int cksum;
  484.  
  485.   cksum = 0;
  486.  
  487.   /* The initial SYN is not included in the checksum.  */
  488.   c = HDR_LENGTH - 1;
  489.   p = hdr + 1;
  490.   while (c-- != 0)
  491.     cksum += *p++;
  492.   
  493.   c = len;
  494.   p = data;
  495.   while (c-- != 0)
  496.     cksum += *p++;
  497.  
  498.   return cksum;
  499. }
  500.  
  501. /* Send a packet containing the given ASCII string.  */
  502.  
  503. static void
  504. mips_send_packet (s, get_ack)
  505.      const char *s;
  506.      int get_ack;
  507. {
  508.   unsigned int len;
  509.   unsigned char *packet;
  510.   register int cksum;
  511.   int try;
  512.  
  513.   len = strlen (s);
  514.   if (len > DATA_MAXLEN)
  515.     mips_error ("MIPS protocol data packet too long: %s", s);
  516.  
  517.   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);
  518.  
  519.   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
  520.   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
  521.   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
  522.   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);
  523.  
  524.   memcpy (packet + HDR_LENGTH, s, len);
  525.  
  526.   cksum = mips_cksum (packet, packet + HDR_LENGTH, len);
  527.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  528.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  529.   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
  530.  
  531.   /* Increment the sequence number.  This will set mips_send_seq to
  532.      the sequence number we expect in the acknowledgement.  */
  533.   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;
  534.  
  535.   if (! get_ack)
  536.     return;
  537.  
  538.   /* We can only have one outstanding data packet, so we just wait for
  539.      the acknowledgement here.  Keep retransmitting the packet until
  540.      we get one, or until we've tried too many times.  */
  541.   for (try = 0; try < mips_send_retries; try++)
  542.     {
  543.       int garbage;
  544.       int ch;
  545.  
  546.       if (sr_get_debug () > 0)
  547.     {
  548.       /* Don't use _filtered; we can't deal with a QUIT out of
  549.          target_wait, and I think this might be called from there.  */
  550.       packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
  551.       printf_unfiltered ("Writing \"%s\"\n", packet + 1);
  552.     }
  553.  
  554.       if (SERIAL_WRITE (mips_desc, packet,
  555.             HDR_LENGTH + len + TRLR_LENGTH) != 0)
  556.     mips_error ("write to target failed: %s", safe_strerror (errno));
  557.  
  558.       garbage = 0;
  559.       ch = 0;
  560.       while (1)
  561.     {
  562.       unsigned char hdr[HDR_LENGTH + 1];
  563.       unsigned char trlr[TRLR_LENGTH + 1];
  564.       int err;
  565.       int seq;
  566.  
  567.       /* Get the packet header.  If we time out, resend the data
  568.          packet.  */
  569.       err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
  570.       if (err != 0)
  571.         break;
  572.  
  573.       ch = 0;
  574.  
  575.       /* If we get a data packet, assume it is a duplicate and
  576.          ignore it.  FIXME: If the acknowledgement is lost, this
  577.          data packet may be the packet the remote sends after the
  578.          acknowledgement.  */
  579.       if (HDR_IS_DATA (hdr))
  580.         continue;
  581.  
  582.       /* If the length is not 0, this is a garbled packet.  */
  583.       if (HDR_GET_LEN (hdr) != 0)
  584.         continue;
  585.  
  586.       /* Get the packet trailer.  */
  587.       err = mips_receive_trailer (trlr, &garbage, &ch,
  588.                       mips_retransmit_wait);
  589.  
  590.       /* If we timed out, resend the data packet.  */
  591.       if (err == -1)
  592.         break;
  593.  
  594.       /* If we got a bad character, reread the header.  */
  595.       if (err != 0)
  596.         continue;
  597.  
  598.       /* If the checksum does not match the trailer checksum, this
  599.          is a bad packet; ignore it.  */
  600.       if (mips_cksum (hdr, (unsigned char *) NULL, 0)
  601.           != TRLR_GET_CKSUM (trlr))
  602.         continue;
  603.  
  604.       if (sr_get_debug () > 0)
  605.         {
  606.           hdr[HDR_LENGTH] = '\0';
  607.           trlr[TRLR_LENGTH] = '\0';
  608.           /* Don't use _filtered; we can't deal with a QUIT out of
  609.          target_wait, and I think this might be called from there.  */
  610.           printf_unfiltered ("Got ack %d \"%s%s\"\n",
  611.                    HDR_GET_SEQ (hdr), hdr + 1, trlr);
  612.         }
  613.  
  614.       /* If this ack is for the current packet, we're done.  */
  615.       seq = HDR_GET_SEQ (hdr);
  616.       if (seq == mips_send_seq)
  617.         return;
  618.  
  619.       /* If this ack is for the last packet, resend the current
  620.          packet.  */
  621.       if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
  622.         break;
  623.  
  624.       /* Otherwise this is a bad ack; ignore it.  Increment the
  625.          garbage count to ensure that we do not stay in this loop
  626.          forever.  */
  627.       ++garbage;
  628.     }
  629.     }
  630.  
  631.   mips_error ("Remote did not acknowledge packet");
  632. }
  633.  
  634. /* Receive and acknowledge a packet, returning the data in BUFF (which
  635.    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
  636.    implies that only the sender retransmits packets, so this code just
  637.    waits silently for a packet.  It returns the length of the received
  638.    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
  639.    don't print an error message and return -1.  */
  640.  
  641. static int
  642. mips_receive_packet (buff, throw_error, timeout)
  643.      char *buff;
  644.      int throw_error;
  645.      int timeout;
  646. {
  647.   int ch;
  648.   int garbage;
  649.   int len;
  650.   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
  651.   int cksum;
  652.  
  653.   ch = 0;
  654.   garbage = 0;
  655.   while (1)
  656.     {
  657.       unsigned char hdr[HDR_LENGTH];
  658.       unsigned char trlr[TRLR_LENGTH];
  659.       int i;
  660.       int err;
  661.  
  662.       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
  663.     {
  664.       if (throw_error)
  665.         mips_error ("Timed out waiting for remote packet");
  666.       else
  667.         return -1;
  668.     }
  669.  
  670.       ch = 0;
  671.  
  672.       /* An acknowledgement is probably a duplicate; ignore it.  */
  673.       if (! HDR_IS_DATA (hdr))
  674.     {
  675.       /* Don't use _filtered; we can't deal with a QUIT out of
  676.          target_wait, and I think this might be called from there.  */
  677.       if (sr_get_debug () > 0)
  678.         printf_unfiltered ("Ignoring unexpected ACK\n");
  679.       continue;
  680.     }
  681.  
  682.       /* If this is the wrong sequence number, ignore it.  */
  683.       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
  684.     {
  685.       /* Don't use _filtered; we can't deal with a QUIT out of
  686.          target_wait, and I think this might be called from there.  */
  687.       if (sr_get_debug () > 0)
  688.         printf_unfiltered ("Ignoring sequence number %d (want %d)\n",
  689.                  HDR_GET_SEQ (hdr), mips_receive_seq);
  690.       continue;
  691.     }
  692.  
  693.       len = HDR_GET_LEN (hdr);
  694.  
  695.       for (i = 0; i < len; i++)
  696.     {
  697.       int rch;
  698.  
  699.       rch = mips_readchar (timeout);
  700.       if (rch == SYN)
  701.         {
  702.           ch = SYN;
  703.           break;
  704.         }
  705.       if (rch == SERIAL_TIMEOUT)
  706.         {
  707.           if (throw_error)
  708.         mips_error ("Timed out waiting for remote packet");
  709.           else
  710.         return -1;
  711.         }
  712.       buff[i] = rch;
  713.     }
  714.  
  715.       if (i < len)
  716.     {
  717.       /* Don't use _filtered; we can't deal with a QUIT out of
  718.          target_wait, and I think this might be called from there.  */
  719.       if (sr_get_debug () > 0)
  720.         printf_unfiltered ("Got new SYN after %d chars (wanted %d)\n",
  721.                  i, len);
  722.       continue;
  723.     }
  724.  
  725.       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
  726.       if (err == -1)
  727.     {
  728.       if (throw_error)
  729.         mips_error ("Timed out waiting for packet");
  730.       else
  731.         return -1;
  732.     }
  733.       if (err == -2)
  734.     {
  735.       /* Don't use _filtered; we can't deal with a QUIT out of
  736.          target_wait, and I think this might be called from there.  */
  737.       if (sr_get_debug () > 0)
  738.         printf_unfiltered ("Got SYN when wanted trailer\n");
  739.       continue;
  740.     }
  741.  
  742.       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
  743.     break;
  744.  
  745.       if (sr_get_debug () > 0)
  746.     /* Don't use _filtered; we can't deal with a QUIT out of
  747.        target_wait, and I think this might be called from there.  */
  748.     printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
  749.              mips_cksum (hdr, buff, len),
  750.              TRLR_GET_CKSUM (trlr));
  751.  
  752.       /* The checksum failed.  Send an acknowledgement for the
  753.      previous packet to tell the remote to resend the packet.  */
  754.       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
  755.       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
  756.       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
  757.       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
  758.  
  759.       cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
  760.  
  761.       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  762.       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  763.       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
  764.  
  765.       if (sr_get_debug () > 0)
  766.     {
  767.       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
  768.       /* Don't use _filtered; we can't deal with a QUIT out of
  769.          target_wait, and I think this might be called from there.  */
  770.       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
  771.                ack + 1);
  772.     }
  773.  
  774.       if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
  775.     {
  776.       if (throw_error)
  777.         mips_error ("write to target failed: %s", safe_strerror (errno));
  778.       else
  779.         return -1;
  780.     }
  781.     }
  782.  
  783.   if (sr_get_debug () > 0)
  784.     {
  785.       buff[len] = '\0';
  786.       /* Don't use _filtered; we can't deal with a QUIT out of
  787.      target_wait, and I think this might be called from there.  */
  788.       printf_unfiltered ("Got packet \"%s\"\n", buff);
  789.     }
  790.  
  791.   /* We got the packet.  Send an acknowledgement.  */
  792.   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;
  793.  
  794.   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
  795.   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
  796.   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
  797.   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
  798.  
  799.   cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
  800.  
  801.   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
  802.   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
  803.   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
  804.  
  805.   if (sr_get_debug () > 0)
  806.     {
  807.       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
  808.       /* Don't use _filtered; we can't deal with a QUIT out of
  809.      target_wait, and I think this might be called from there.  */
  810.       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
  811.                ack + 1);
  812.     }
  813.  
  814.   if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
  815.     {
  816.       if (throw_error)
  817.     mips_error ("write to target failed: %s", safe_strerror (errno));
  818.       else
  819.     return -1;
  820.     }
  821.  
  822.   return len;
  823. }
  824.  
  825. /* Optionally send a request to the remote system and optionally wait
  826.    for the reply.  This implements the remote debugging protocol,
  827.    which is built on top of the packet protocol defined above.  Each
  828.    request has an ADDR argument and a DATA argument.  The following
  829.    requests are defined:
  830.  
  831.    \0    don't send a request; just wait for a reply
  832.    i    read word from instruction space at ADDR
  833.    d    read word from data space at ADDR
  834.    I    write DATA to instruction space at ADDR
  835.    D    write DATA to data space at ADDR
  836.    r    read register number ADDR
  837.    R    set register number ADDR to value DATA
  838.    c    continue execution (if ADDR != 1, set pc to ADDR)
  839.    s    single step (if ADDR != 1, set pc to ADDR)
  840.  
  841.    The read requests return the value requested.  The write requests
  842.    return the previous value in the changed location.  The execution
  843.    requests return a UNIX wait value (the approximate signal which
  844.    caused execution to stop is in the upper eight bits).
  845.  
  846.    If PERR is not NULL, this function waits for a reply.  If an error
  847.    occurs, it sets *PERR to 1 and sets errno according to what the
  848.    target board reports.  */
  849.  
  850. static int
  851. mips_request (cmd, addr, data, perr, timeout)
  852.      char cmd;
  853.      unsigned int addr;
  854.      unsigned int data;
  855.      int *perr;
  856.      int timeout;
  857. {
  858.   char buff[DATA_MAXLEN + 1];
  859.   int len;
  860.   int rpid;
  861.   char rcmd;
  862.   int rerrflg;
  863.   int rresponse;
  864.   
  865.   if (cmd != '\0')
  866.     {
  867.       if (mips_need_reply)
  868.     fatal ("mips_request: Trying to send command before reply");
  869.       sprintf (buff, "0x0 %c 0x%x 0x%x", cmd, addr, data);
  870.       mips_send_packet (buff, 1);
  871.       mips_need_reply = 1;
  872.     }
  873.  
  874.   if (perr == (int *) NULL)
  875.     return 0;
  876.  
  877.   if (! mips_need_reply)
  878.     fatal ("mips_request: Trying to get reply before command");
  879.  
  880.   mips_need_reply = 0;
  881.  
  882.   len = mips_receive_packet (buff, 1, timeout);
  883.   buff[len] = '\0';
  884.  
  885.   if (sscanf (buff, "0x%x %c 0x%x 0x%x",
  886.           &rpid, &rcmd, &rerrflg, &rresponse) != 4
  887.       || (cmd != '\0' && rcmd != cmd))
  888.     mips_error ("Bad response from remote board");
  889.  
  890.   if (rerrflg != 0)
  891.     {
  892.       *perr = 1;
  893.  
  894.       /* FIXME: This will returns MIPS errno numbers, which may or may
  895.      not be the same as errno values used on other systems.  If
  896.      they stick to common errno values, they will be the same, but
  897.      if they don't, they must be translated.  */
  898.       errno = rresponse;
  899.  
  900.       return 0;
  901.     }
  902.  
  903.   *perr = 0;
  904.   return rresponse;
  905. }
  906.  
  907. static void
  908. mips_initialize_cleanups (arg)
  909.      PTR arg;
  910. {
  911.   mips_initializing = 0;
  912. }
  913.  
  914. /* Initialize a new connection to the MIPS board, and make sure we are
  915.    really connected.  */
  916.  
  917. static void
  918. mips_initialize ()
  919. {
  920.   char cr;
  921.   char buff[DATA_MAXLEN + 1];
  922.   int err;
  923.   struct cleanup *old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);
  924.  
  925.   /* What is this code doing here?  I don't see any way it can happen, and
  926.      it might mean mips_initializing didn't get cleared properly.
  927.      So I'll make it a warning.  */
  928.   if (mips_initializing)
  929.     {
  930.       warning ("internal error: mips_initialize called twice");
  931.       return;
  932.     }
  933.  
  934.   mips_initializing = 1;
  935.  
  936.   mips_send_seq = 0;
  937.   mips_receive_seq = 0;
  938.  
  939.   /* The board seems to want to send us a packet.  I don't know what
  940.      it means.  The packet seems to be triggered by a carriage return
  941.      character, although perhaps any character would do.  */
  942.   cr = '\015';
  943.   /* FIXME check the result from this */
  944.   SERIAL_WRITE (mips_desc, &cr, 1);
  945.  
  946.   if (mips_receive_packet (buff, 0, 3) < 0)
  947.     {
  948.       char cc;
  949.  
  950.       /* We did not receive the packet we expected; try resetting the
  951.      board and trying again.  */
  952.       printf_filtered ("Failed to initialize; trying to reset board\n");
  953.       cc = '\003';
  954.       SERIAL_WRITE (mips_desc, &cc, 1);
  955.       sleep (2);
  956.       SERIAL_WRITE (mips_desc, "\015db tty0\015", sizeof "\015db tty0\015" - 1);
  957.       sleep (1);
  958.       cr = '\015';
  959.       SERIAL_WRITE (mips_desc, &cr, 1);
  960.     }
  961.   mips_receive_packet (buff, 1, 3);
  962.  
  963.   do_cleanups (old_cleanups);
  964.  
  965.   /* If this doesn't call error, we have connected; we don't care if
  966.      the request itself succeeds or fails.  */
  967.   mips_request ('r', (unsigned int) 0, (unsigned int) 0, &err,
  968.         mips_receive_wait);
  969. }
  970.  
  971. /* Open a connection to the remote board.  */
  972.  
  973. static void
  974. mips_open (name, from_tty)
  975.      char *name;
  976.      int from_tty;
  977. {
  978.   char *ptype;
  979.  
  980.   if (name == 0)
  981.     error (
  982. "To open a MIPS remote debugging connection, you need to specify what serial\n\
  983. device is attached to the target board (e.g., /dev/ttya).");
  984.  
  985.   target_preopen (from_tty);
  986.  
  987.   if (mips_is_open)
  988.     unpush_target (&mips_ops);
  989.  
  990.   mips_desc = SERIAL_OPEN (name);
  991.   if (mips_desc == (serial_t) NULL)
  992.     perror_with_name (name);
  993.  
  994.   if (baud_rate != -1)
  995.     {
  996.       if (SERIAL_SETBAUDRATE (mips_desc, baud_rate))
  997.         {
  998.           SERIAL_CLOSE (mips_desc);
  999.           perror_with_name (name);
  1000.         }
  1001.     }
  1002.  
  1003.   SERIAL_RAW (mips_desc);
  1004.  
  1005.   mips_is_open = 1;
  1006.  
  1007.   mips_initialize ();
  1008.  
  1009.   if (from_tty)
  1010.     printf_unfiltered ("Remote MIPS debugging using %s\n", name);
  1011.  
  1012.   /* Switch to using remote target now.  */
  1013.   push_target (&mips_ops);
  1014.  
  1015.   /* FIXME: Should we call start_remote here?  */
  1016.  
  1017.   /* Try to figure out the processor model if possible.  */
  1018.   ptype = mips_read_processor_type ();
  1019.   if (ptype)
  1020.     mips_set_processor_type_command (strsave (ptype), 0);
  1021. }
  1022.  
  1023. /* Close a connection to the remote board.  */
  1024.  
  1025. static void
  1026. mips_close (quitting)
  1027.      int quitting;
  1028. {
  1029.   if (mips_is_open)
  1030.     {
  1031.       int err;
  1032.  
  1033.       mips_is_open = 0;
  1034.  
  1035.       /* Get the board out of remote debugging mode.  */
  1036.       mips_request ('x', (unsigned int) 0, (unsigned int) 0, &err,
  1037.             mips_receive_wait);
  1038.  
  1039.       SERIAL_CLOSE (mips_desc);
  1040.     }
  1041. }
  1042.  
  1043. /* Detach from the remote board.  */
  1044.  
  1045. static void
  1046. mips_detach (args, from_tty)
  1047.      char *args;
  1048.      int from_tty;
  1049. {
  1050.   if (args)
  1051.     error ("Argument given to \"detach\" when remotely debugging.");
  1052.  
  1053.   pop_target ();
  1054.   if (from_tty)
  1055.     printf_unfiltered ("Ending remote MIPS debugging.\n");
  1056. }
  1057.  
  1058. /* Tell the target board to resume.  This does not wait for a reply
  1059.    from the board.  */
  1060.  
  1061. static void
  1062. mips_resume (pid, step, siggnal)
  1063.      int pid, step;
  1064.      enum target_signal siggnal;
  1065. {
  1066.   if (siggnal != TARGET_SIGNAL_0)
  1067.     warning
  1068.       ("Can't send signals to a remote system.  Try `handle %s ignore'.",
  1069.        target_signal_to_name (siggnal));
  1070.  
  1071.   mips_request (step ? 's' : 'c',
  1072.         (unsigned int) 1,
  1073.         (unsigned int) 0,
  1074.         (int *) NULL,
  1075.         mips_receive_wait);
  1076. }
  1077.  
  1078. /* Return the signal corresponding to SIG, where SIG is the number which
  1079.    the MIPS protocol uses for the signal.  */
  1080. enum target_signal
  1081. mips_signal_from_protocol (sig)
  1082.      int sig;
  1083. {
  1084.   /* We allow a few more signals than the IDT board actually returns, on
  1085.      the theory that there is at least *some* hope that perhaps the numbering
  1086.      for these signals is widely agreed upon.  */
  1087.   if (sig <= 0
  1088.       || sig > 31)
  1089.     return TARGET_SIGNAL_UNKNOWN;
  1090.  
  1091.   /* Don't want to use target_signal_from_host because we are converting
  1092.      from MIPS signal numbers, not host ones.  Our internal numbers
  1093.      match the MIPS numbers for the signals the board can return, which
  1094.      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
  1095.   return (enum target_signal) sig;
  1096. }
  1097.  
  1098. /* Wait until the remote stops, and return a wait status.  */
  1099.  
  1100. static int
  1101. mips_wait (pid, status)
  1102.      int pid;
  1103.      struct target_waitstatus *status;
  1104. {
  1105.   int rstatus;
  1106.   int err;
  1107.  
  1108.   /* If we have not sent a single step or continue command, then the
  1109.      board is waiting for us to do something.  Return a status
  1110.      indicating that it is stopped.  */
  1111.   if (! mips_need_reply)
  1112.     {
  1113.       status->kind = TARGET_WAITKIND_STOPPED;
  1114.       status->value.sig = TARGET_SIGNAL_TRAP;
  1115.       return 0;
  1116.     }
  1117.  
  1118.   /* No timeout; we sit here as long as the program continues to execute.  */
  1119.   rstatus = mips_request ('\0', (unsigned int) 0, (unsigned int) 0, &err, -1);
  1120.   if (err)
  1121.     mips_error ("Remote failure: %s", safe_strerror (errno));
  1122.  
  1123.   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
  1124.      and so on, because the constants we want here are determined by the
  1125.      MIPS protocol and have nothing to do with what host we are running on.  */
  1126.   if ((rstatus & 0377) == 0)
  1127.     {
  1128.       status->kind = TARGET_WAITKIND_EXITED;
  1129.       status->value.integer = (((rstatus) >> 8) & 0377);
  1130.     }
  1131.   else if ((rstatus & 0377) == 0177)
  1132.     {
  1133.       status->kind = TARGET_WAITKIND_STOPPED;
  1134.       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0377);
  1135.     }
  1136.   else
  1137.     {
  1138.       status->kind = TARGET_WAITKIND_SIGNALLED;
  1139.       status->value.sig = mips_signal_from_protocol (rstatus & 0177);
  1140.     }
  1141.  
  1142.   return 0;
  1143. }
  1144.  
  1145. /* We have to map between the register numbers used by gdb and the
  1146.    register numbers used by the debugging protocol.  This function
  1147.    assumes that we are using tm-mips.h.  */
  1148.  
  1149. #define REGNO_OFFSET 96
  1150.  
  1151. static int
  1152. mips_map_regno (regno)
  1153.      int regno;
  1154. {
  1155.   if (regno < 32)
  1156.     return regno;
  1157.   if (regno >= FP0_REGNUM && regno < FP0_REGNUM + 32)
  1158.     return regno - FP0_REGNUM + 32;
  1159.   switch (regno)
  1160.     {
  1161.     case PC_REGNUM:
  1162.       return REGNO_OFFSET + 0;
  1163.     case CAUSE_REGNUM:
  1164.       return REGNO_OFFSET + 1;
  1165.     case HI_REGNUM:
  1166.       return REGNO_OFFSET + 2;
  1167.     case LO_REGNUM:
  1168.       return REGNO_OFFSET + 3;
  1169.     case FCRCS_REGNUM:
  1170.       return REGNO_OFFSET + 4;
  1171.     case FCRIR_REGNUM:
  1172.       return REGNO_OFFSET + 5;
  1173.     default:
  1174.       /* FIXME: Is there a way to get the status register?  */
  1175.       return 0;
  1176.     }
  1177. }
  1178.  
  1179. /* Fetch the remote registers.  */
  1180.  
  1181. static void
  1182. mips_fetch_registers (regno)
  1183.      int regno;
  1184. {
  1185.   unsigned LONGEST val;
  1186.   int err;
  1187.  
  1188.   if (regno == -1)
  1189.     {
  1190.       for (regno = 0; regno < NUM_REGS; regno++)
  1191.     mips_fetch_registers (regno);
  1192.       return;
  1193.     }
  1194.  
  1195.   if (regno == FP_REGNUM || regno == ZERO_REGNUM)
  1196.     /* FP_REGNUM on the mips is a hack which is just supposed to read
  1197.        zero (see also mips-nat.c).  */
  1198.     val = 0;
  1199.   else
  1200.     {
  1201.       val = mips_request ('r', (unsigned int) mips_map_regno (regno),
  1202.               (unsigned int) 0, &err, mips_receive_wait);
  1203.       if (err)
  1204.     mips_error ("Can't read register %d: %s", regno,
  1205.             safe_strerror (errno));
  1206.     }
  1207.  
  1208.   {
  1209.     char buf[MAX_REGISTER_RAW_SIZE];
  1210.  
  1211.     /* We got the number the register holds, but gdb expects to see a
  1212.        value in the target byte ordering.  */
  1213.     store_unsigned_integer (buf, REGISTER_RAW_SIZE (regno), val);
  1214.     supply_register (regno, buf);
  1215.   }
  1216. }
  1217.  
  1218. /* Prepare to store registers.  The MIPS protocol can store individual
  1219.    registers, so this function doesn't have to do anything.  */
  1220.  
  1221. static void
  1222. mips_prepare_to_store ()
  1223. {
  1224. }
  1225.  
  1226. /* Store remote register(s).  */
  1227.  
  1228. static void
  1229. mips_store_registers (regno)
  1230.      int regno;
  1231. {
  1232.   int err;
  1233.  
  1234.   if (regno == -1)
  1235.     {
  1236.       for (regno = 0; regno < NUM_REGS; regno++)
  1237.     mips_store_registers (regno);
  1238.       return;
  1239.     }
  1240.  
  1241.   mips_request ('R', (unsigned int) mips_map_regno (regno),
  1242.         (unsigned int) read_register (regno),
  1243.         &err, mips_receive_wait);
  1244.   if (err)
  1245.     mips_error ("Can't write register %d: %s", regno, safe_strerror (errno));
  1246. }
  1247.  
  1248. /* Fetch a word from the target board.  */
  1249.  
  1250. static int 
  1251. mips_fetch_word (addr)
  1252.      CORE_ADDR addr;
  1253. {
  1254.   int val;
  1255.   int err;
  1256.  
  1257.   val = mips_request ('d', (unsigned int) addr, (unsigned int) 0, &err,
  1258.               mips_receive_wait);
  1259.   if (err)
  1260.     {
  1261.       /* Data space failed; try instruction space.  */
  1262.       val = mips_request ('i', (unsigned int) addr, (unsigned int) 0, &err,
  1263.               mips_receive_wait);
  1264.       if (err)
  1265.     mips_error ("Can't read address 0x%x: %s", addr, safe_strerror (errno));
  1266.     }
  1267.   return val;
  1268. }
  1269.  
  1270. /* Store a word to the target board.  Returns errno code or zero for
  1271.    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
  1272.    memory location there.  */
  1273.  
  1274. static int
  1275. mips_store_word (addr, val, old_contents)
  1276.      CORE_ADDR addr;
  1277.      int val;
  1278.      char *old_contents;
  1279. {
  1280.   int err;
  1281.   unsigned int oldcontents;
  1282.  
  1283.   oldcontents = mips_request ('D', (unsigned int) addr, (unsigned int) val,
  1284.                   &err,
  1285.                   mips_receive_wait);
  1286.   if (err)
  1287.     {
  1288.       /* Data space failed; try instruction space.  */
  1289.       oldcontents = mips_request ('I', (unsigned int) addr,
  1290.                   (unsigned int) val, &err,
  1291.                   mips_receive_wait);
  1292.       if (err)
  1293.     return errno;
  1294.     }
  1295.   if (old_contents != NULL)
  1296.     store_unsigned_integer (old_contents, 4, oldcontents);
  1297.   return 0;
  1298. }
  1299.  
  1300. /* Read or write LEN bytes from inferior memory at MEMADDR,
  1301.    transferring to or from debugger address MYADDR.  Write to inferior
  1302.    if SHOULD_WRITE is nonzero.  Returns length of data written or
  1303.    read; 0 for error.  Note that protocol gives us the correct value
  1304.    for a longword, since it transfers values in ASCII.  We want the
  1305.    byte values, so we have to swap the longword values.  */
  1306.  
  1307. static int
  1308. mips_xfer_memory (memaddr, myaddr, len, write, ignore)
  1309.      CORE_ADDR memaddr;
  1310.      char *myaddr;
  1311.      int len;
  1312.      int write;
  1313.      struct target_ops *ignore;
  1314. {
  1315.   register int i;
  1316.   /* Round starting address down to longword boundary.  */
  1317.   register CORE_ADDR addr = memaddr &~ 3;
  1318.   /* Round ending address up; get number of longwords that makes.  */
  1319.   register int count = (((memaddr + len) - addr) + 3) / 4;
  1320.   /* Allocate buffer of that many longwords.  */
  1321.   register char *buffer = alloca (count * 4);
  1322.  
  1323.   int status;
  1324.  
  1325.   if (write)
  1326.     {
  1327.       /* Fill start and end extra bytes of buffer with existing data.  */
  1328.       if (addr != memaddr || len < 4)
  1329.     {
  1330.       /* Need part of initial word -- fetch it.  */
  1331.       store_unsigned_integer (&buffer[0], 4, mips_fetch_word (addr));
  1332.     }
  1333.  
  1334.       if (count > 1)
  1335.     {
  1336.       /* Need part of last word -- fetch it.  FIXME: we do this even
  1337.          if we don't need it.  */
  1338.       store_unsigned_integer (&buffer[(count - 1) * 4], 4,
  1339.                   mips_fetch_word (addr + (count - 1) * 4));
  1340.     }
  1341.  
  1342.       /* Copy data to be written over corresponding part of buffer */
  1343.  
  1344.       memcpy ((char *) buffer + (memaddr & 3), myaddr, len);
  1345.  
  1346.       /* Write the entire buffer.  */
  1347.  
  1348.       for (i = 0; i < count; i++, addr += 4)
  1349.     {
  1350.       status = mips_store_word (addr,
  1351.                     extract_unsigned_integer (&buffer[i*4], 4),
  1352.                     NULL);
  1353.       /* Report each kilobyte (we download 32-bit words at a time) */
  1354.       if (i % 256 == 255) 
  1355.         {
  1356.           printf_unfiltered ("*");
  1357.           fflush (stdout);
  1358.         }
  1359.       if (status)
  1360.         {
  1361.           errno = status;
  1362.           return 0;
  1363.         }
  1364.       /* FIXME: Do we want a QUIT here?  */
  1365.     }
  1366.       if (count >= 256)
  1367.     printf_unfiltered ("\n");
  1368.     }
  1369.   else
  1370.     {
  1371.       /* Read all the longwords */
  1372.       for (i = 0; i < count; i++, addr += 4)
  1373.     {
  1374.       store_unsigned_integer (&buffer[i*4], 4, mips_fetch_word (addr));
  1375.       QUIT;
  1376.     }
  1377.  
  1378.       /* Copy appropriate bytes out of the buffer.  */
  1379.       memcpy (myaddr, buffer + (memaddr & 3), len);
  1380.     }
  1381.   return len;
  1382. }
  1383.  
  1384. /* Print info on this target.  */
  1385.  
  1386. static void
  1387. mips_files_info (ignore)
  1388.      struct target_ops *ignore;
  1389. {
  1390.   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
  1391. }
  1392.  
  1393. /* Kill the process running on the board.  This will actually only
  1394.    work if we are doing remote debugging over the console input.  I
  1395.    think that if IDT/sim had the remote debug interrupt enabled on the
  1396.    right port, we could interrupt the process with a break signal.  */
  1397.  
  1398. static void
  1399. mips_kill ()
  1400. {
  1401. #if 0
  1402.   if (mips_is_open)
  1403.     {
  1404.       char cc;
  1405.  
  1406.       /* Send a ^C.  */
  1407.       cc = '\003';
  1408.       SERIAL_WRITE (mips_desc, &cc, 1);
  1409.       sleep (1);
  1410.       target_mourn_inferior ();
  1411.     }
  1412. #endif
  1413. }
  1414.  
  1415. /* Start running on the target board.  */
  1416.  
  1417. static void
  1418. mips_create_inferior (execfile, args, env)
  1419.      char *execfile;
  1420.      char *args;
  1421.      char **env;
  1422. {
  1423.   CORE_ADDR entry_pt;
  1424.  
  1425.   if (args && *args)
  1426.     {
  1427.       warning ("\
  1428. Can't pass arguments to remote MIPS board; arguments ignored.");
  1429.       /* And don't try to use them on the next "run" command.  */
  1430.       execute_command ("set args", 0);
  1431.     }
  1432.  
  1433.   if (execfile == 0 || exec_bfd == 0)
  1434.     error ("No executable file specified");
  1435.  
  1436.   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
  1437.  
  1438.   init_wait_for_inferior ();
  1439.  
  1440.   /* FIXME: Should we set inferior_pid here?  */
  1441.  
  1442.   proceed (entry_pt, TARGET_SIGNAL_DEFAULT, 0);
  1443. }
  1444.  
  1445. /* Clean up after a process.  Actually nothing to do.  */
  1446.  
  1447. static void
  1448. mips_mourn_inferior ()
  1449. {
  1450.   unpush_target (&mips_ops);
  1451.   generic_mourn_inferior ();
  1452. }
  1453.  
  1454. /* We can write a breakpoint and read the shadow contents in one
  1455.    operation.  */
  1456.  
  1457. /* The IDT board uses an unusual breakpoint value, and sometimes gets
  1458.    confused when it sees the usual MIPS breakpoint instruction.  */
  1459.  
  1460. #define BREAK_INSN (0x00000a0d)
  1461. #define BREAK_INSN_SIZE (4)
  1462.  
  1463. /* Insert a breakpoint on targets that don't have any better breakpoint
  1464.    support.  We read the contents of the target location and stash it,
  1465.    then overwrite it with a breakpoint instruction.  ADDR is the target
  1466.    location in the target machine.  CONTENTS_CACHE is a pointer to 
  1467.    memory allocated for saving the target contents.  It is guaranteed
  1468.    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
  1469.    is accomplished via BREAKPOINT_MAX).  */
  1470.  
  1471. static int
  1472. mips_insert_breakpoint (addr, contents_cache)
  1473.      CORE_ADDR addr;
  1474.      char *contents_cache;
  1475. {
  1476.   int status;
  1477.  
  1478.   return mips_store_word (addr, BREAK_INSN, contents_cache);
  1479. }
  1480.  
  1481. static int
  1482. mips_remove_breakpoint (addr, contents_cache)
  1483.      CORE_ADDR addr;
  1484.      char *contents_cache;
  1485. {
  1486.   return target_write_memory (addr, contents_cache, BREAK_INSN_SIZE);
  1487. }
  1488.  
  1489. /* The target vector.  */
  1490.  
  1491. struct target_ops mips_ops =
  1492. {
  1493.   "mips",            /* to_shortname */
  1494.   "Remote MIPS debugging over serial line",    /* to_longname */
  1495.   "\
  1496. Debug a board using the MIPS remote debugging protocol over a serial line.\n\
  1497. The argument is the device it is connected to or, if it contains a colon,\n\
  1498. HOST:PORT to access a board over a network",  /* to_doc */
  1499.   mips_open,            /* to_open */
  1500.   mips_close,            /* to_close */
  1501.   NULL,                /* to_attach */
  1502.   mips_detach,            /* to_detach */
  1503.   mips_resume,            /* to_resume */
  1504.   mips_wait,            /* to_wait */
  1505.   mips_fetch_registers,        /* to_fetch_registers */
  1506.   mips_store_registers,        /* to_store_registers */
  1507.   mips_prepare_to_store,    /* to_prepare_to_store */
  1508.   mips_xfer_memory,        /* to_xfer_memory */
  1509.   mips_files_info,        /* to_files_info */
  1510.   mips_insert_breakpoint,    /* to_insert_breakpoint */
  1511.   mips_remove_breakpoint,    /* to_remove_breakpoint */
  1512.   NULL,                /* to_terminal_init */
  1513.   NULL,                /* to_terminal_inferior */
  1514.   NULL,                /* to_terminal_ours_for_output */
  1515.   NULL,                /* to_terminal_ours */
  1516.   NULL,                /* to_terminal_info */
  1517.   mips_kill,            /* to_kill */
  1518.   generic_load,            /* to_load */
  1519.   NULL,                /* to_lookup_symbol */
  1520.   mips_create_inferior,        /* to_create_inferior */
  1521.   mips_mourn_inferior,        /* to_mourn_inferior */
  1522.   NULL,                /* to_can_run */
  1523.   NULL,                /* to_notice_signals */
  1524.   0,                /* to_stop */
  1525.   process_stratum,        /* to_stratum */
  1526.   NULL,                /* to_next */
  1527.   1,                /* to_has_all_memory */
  1528.   1,                /* to_has_memory */
  1529.   1,                /* to_has_stack */
  1530.   1,                /* to_has_registers */
  1531.   1,                /* to_has_execution */
  1532.   NULL,                /* sections */
  1533.   NULL,                /* sections_end */
  1534.   OPS_MAGIC            /* to_magic */
  1535. };
  1536.  
  1537. void
  1538. _initialize_remote_mips ()
  1539. {
  1540.   add_target (&mips_ops);
  1541.  
  1542.   add_show_from_set (
  1543.     add_set_cmd ("timeout", no_class, var_zinteger,
  1544.          (char *) &mips_receive_wait,
  1545.          "Set timeout in seconds for remote MIPS serial I/O.",
  1546.          &setlist),
  1547.     &showlist);
  1548.  
  1549.   add_show_from_set (
  1550.     add_set_cmd ("retransmit-timeout", no_class, var_zinteger,
  1551.          (char *) &mips_retransmit_wait,
  1552.      "Set retransmit timeout in seconds for remote MIPS serial I/O.\n\
  1553. This is the number of seconds to wait for an acknowledgement to a packet\n\
  1554. before resending the packet.", &setlist),
  1555.     &showlist);
  1556. }
  1557.