GDB (API)
/home/stan/gdb/src/gdb/remote-mips.c
Go to the documentation of this file.
00001 /* Remote debugging interface for MIPS remote debugging protocol.
00002 
00003    Copyright (C) 1993-2013 Free Software Foundation, Inc.
00004 
00005    Contributed by Cygnus Support.  Written by Ian Lance Taylor
00006    <ian@cygnus.com>.
00007 
00008    This file is part of GDB.
00009 
00010    This program is free software; you can redistribute it and/or modify
00011    it under the terms of the GNU General Public License as published by
00012    the Free Software Foundation; either version 3 of the License, or
00013    (at your option) any later version.
00014 
00015    This program is distributed in the hope that it will be useful,
00016    but WITHOUT ANY WARRANTY; without even the implied warranty of
00017    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00018    GNU General Public License for more details.
00019 
00020    You should have received a copy of the GNU General Public License
00021    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00022 
00023 #include "defs.h"
00024 #include "inferior.h"
00025 #include "bfd.h"
00026 #include "symfile.h"
00027 #include "gdbcmd.h"
00028 #include "gdbcore.h"
00029 #include "serial.h"
00030 #include "target.h"
00031 #include "exceptions.h"
00032 #include "gdb_string.h"
00033 #include "gdb_stat.h"
00034 #include "gdb_usleep.h"
00035 #include "regcache.h"
00036 #include <ctype.h>
00037 #include "mips-tdep.h"
00038 #include "gdbthread.h"
00039 #include "gdb_bfd.h"
00040 
00041 
00042 /* Breakpoint types.  Values 0, 1, and 2 must agree with the watch
00043    types passed by breakpoint.c to target_insert_watchpoint.
00044    Value 3 is our own invention, and is used for ordinary instruction
00045    breakpoints.  Value 4 is used to mark an unused watchpoint in tables.  */
00046 enum break_type
00047   {
00048     BREAK_WRITE,                /* 0 */
00049     BREAK_READ,                 /* 1 */
00050     BREAK_ACCESS,               /* 2 */
00051     BREAK_FETCH,                /* 3 */
00052     BREAK_UNUSED                /* 4 */
00053   };
00054 
00055 /* Prototypes for local functions.  */
00056 
00057 static int mips_readchar (int timeout);
00058 
00059 static int mips_receive_header (unsigned char *hdr, int *pgarbage,
00060                                 int ch, int timeout);
00061 
00062 static int mips_receive_trailer (unsigned char *trlr, int *pgarbage,
00063                                  int *pch, int timeout);
00064 
00065 static int mips_cksum (const unsigned char *hdr,
00066                        const char *data, int len);
00067 
00068 static void mips_send_packet (const char *s, int get_ack);
00069 
00070 static void mips_send_command (const char *cmd, int prompt);
00071 
00072 static int mips_receive_packet (char *buff, int throw_error, int timeout);
00073 
00074 static ULONGEST mips_request (int cmd, ULONGEST addr, ULONGEST data,
00075                               int *perr, int timeout, char *buff);
00076 
00077 static void mips_initialize (void);
00078 
00079 static void mips_open (char *name, int from_tty);
00080 
00081 static void pmon_open (char *name, int from_tty);
00082 
00083 static void ddb_open (char *name, int from_tty);
00084 
00085 static void lsi_open (char *name, int from_tty);
00086 
00087 static void mips_close (void);
00088 
00089 static void mips_detach (struct target_ops *ops, char *args, int from_tty);
00090 
00091 static int mips_map_regno (struct gdbarch *, int);
00092 
00093 static void mips_set_register (int regno, ULONGEST value);
00094 
00095 static void mips_prepare_to_store (struct regcache *regcache);
00096 
00097 static int mips_fetch_word (CORE_ADDR addr, unsigned int *valp);
00098 
00099 static int mips_store_word (CORE_ADDR addr, unsigned int value,
00100                             int *old_contents);
00101 
00102 static int mips_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len,
00103                              int write, 
00104                              struct mem_attrib *attrib,
00105                              struct target_ops *target);
00106 
00107 static void mips_files_info (struct target_ops *ignore);
00108 
00109 static void mips_mourn_inferior (struct target_ops *ops);
00110 
00111 static int pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum);
00112 
00113 static int pmon_zeroset (int recsize, char **buff, unsigned int *amount,
00114                          unsigned int *chksum);
00115 
00116 static int pmon_checkset (int recsize, char **buff, unsigned int *value);
00117 
00118 static void pmon_make_fastrec (char **outbuf, unsigned char *inbuf,
00119                                int *inptr, int inamount, int *recsize,
00120                                unsigned int *csum, unsigned int *zerofill);
00121 
00122 static int pmon_check_ack (char *mesg);
00123 
00124 static void pmon_start_download (void);
00125 
00126 static void pmon_end_download (int final, int bintotal);
00127 
00128 static void pmon_download (char *buffer, int length);
00129 
00130 static void pmon_load_fast (char *file);
00131 
00132 static void mips_load (char *file, int from_tty);
00133 
00134 static int mips_make_srec (char *buffer, int type, CORE_ADDR memaddr,
00135                            unsigned char *myaddr, int len);
00136 
00137 static int mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type);
00138 
00139 static int mips_clear_breakpoint (CORE_ADDR addr, int len,
00140                                   enum break_type type);
00141 
00142 static int mips_common_breakpoint (int set, CORE_ADDR addr, int len,
00143                                    enum break_type type);
00144 
00145 /* Forward declarations.  */
00146 extern struct target_ops mips_ops;
00147 extern struct target_ops pmon_ops;
00148 extern struct target_ops ddb_ops;
00149 extern struct target_ops rockhopper_ops;
00150 /* *INDENT-OFF* */
00151 /* The MIPS remote debugging interface is built on top of a simple
00152    packet protocol.  Each packet is organized as follows:
00153 
00154    SYN  The first character is always a SYN (ASCII 026, or ^V).  SYN
00155    may not appear anywhere else in the packet.  Any time a SYN is
00156    seen, a new packet should be assumed to have begun.
00157 
00158    TYPE_LEN
00159    This byte contains the upper five bits of the logical length
00160    of the data section, plus a single bit indicating whether this
00161    is a data packet or an acknowledgement.  The documentation
00162    indicates that this bit is 1 for a data packet, but the actual
00163    board uses 1 for an acknowledgement.  The value of the byte is
00164    0x40 + (ack ? 0x20 : 0) + (len >> 6)
00165    (we always have 0 <= len < 1024).  Acknowledgement packets do
00166    not carry data, and must have a data length of 0.
00167 
00168    LEN1 This byte contains the lower six bits of the logical length of
00169    the data section.  The value is
00170    0x40 + (len & 0x3f)
00171 
00172    SEQ  This byte contains the six bit sequence number of the packet.
00173    The value is
00174    0x40 + seq
00175    An acknowlegment packet contains the sequence number of the
00176    packet being acknowledged plus 1 modulo 64.  Data packets are
00177    transmitted in sequence.  There may only be one outstanding
00178    unacknowledged data packet at a time.  The sequence numbers
00179    are independent in each direction.  If an acknowledgement for
00180    the previous packet is received (i.e., an acknowledgement with
00181    the sequence number of the packet just sent) the packet just
00182    sent should be retransmitted.  If no acknowledgement is
00183    received within a timeout period, the packet should be
00184    retransmitted.  This has an unfortunate failure condition on a
00185    high-latency line, as a delayed acknowledgement may lead to an
00186    endless series of duplicate packets.
00187 
00188    DATA The actual data bytes follow.  The following characters are
00189    escaped inline with DLE (ASCII 020, or ^P):
00190    SYN (026)    DLE S
00191    DLE (020)    DLE D
00192    ^C  (003)    DLE C
00193    ^S  (023)    DLE s
00194    ^Q  (021)    DLE q
00195    The additional DLE characters are not counted in the logical
00196    length stored in the TYPE_LEN and LEN1 bytes.
00197 
00198    CSUM1
00199    CSUM2
00200    CSUM3
00201    These bytes contain an 18 bit checksum of the complete
00202    contents of the packet excluding the SEQ byte and the
00203    CSUM[123] bytes.  The checksum is simply the twos complement
00204    addition of all the bytes treated as unsigned characters.  The
00205    values of the checksum bytes are:
00206    CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
00207    CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
00208    CSUM3: 0x40 + (cksum & 0x3f)
00209 
00210    It happens that the MIPS remote debugging protocol always
00211    communicates with ASCII strings.  Because of this, this
00212    implementation doesn't bother to handle the DLE quoting mechanism,
00213    since it will never be required.  */
00214 /* *INDENT-ON* */
00215 
00216 
00217 /* The SYN character which starts each packet.  */
00218 #define SYN '\026'
00219 
00220 /* The 0x40 used to offset each packet (this value ensures that all of
00221    the header and trailer bytes, other than SYN, are printable ASCII
00222    characters).  */
00223 #define HDR_OFFSET 0x40
00224 
00225 /* The indices of the bytes in the packet header.  */
00226 #define HDR_INDX_SYN 0
00227 #define HDR_INDX_TYPE_LEN 1
00228 #define HDR_INDX_LEN1 2
00229 #define HDR_INDX_SEQ 3
00230 #define HDR_LENGTH 4
00231 
00232 /* The data/ack bit in the TYPE_LEN header byte.  */
00233 #define TYPE_LEN_DA_BIT 0x20
00234 #define TYPE_LEN_DATA 0
00235 #define TYPE_LEN_ACK TYPE_LEN_DA_BIT
00236 
00237 /* How to compute the header bytes.  */
00238 #define HDR_SET_SYN(data, len, seq) (SYN)
00239 #define HDR_SET_TYPE_LEN(data, len, seq) \
00240   (HDR_OFFSET \
00241    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
00242    + (((len) >> 6) & 0x1f))
00243 #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
00244 #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))
00245 
00246 /* Check that a header byte is reasonable.  */
00247 #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)
00248 
00249 /* Get data from the header.  These macros evaluate their argument
00250    multiple times.  */
00251 #define HDR_IS_DATA(hdr) \
00252   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
00253 #define HDR_GET_LEN(hdr) \
00254   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
00255 #define HDR_GET_SEQ(hdr) ((unsigned int)(hdr)[HDR_INDX_SEQ] & 0x3f)
00256 
00257 /* The maximum data length.  */
00258 #define DATA_MAXLEN 1023
00259 
00260 /* The trailer offset.  */
00261 #define TRLR_OFFSET HDR_OFFSET
00262 
00263 /* The indices of the bytes in the packet trailer.  */
00264 #define TRLR_INDX_CSUM1 0
00265 #define TRLR_INDX_CSUM2 1
00266 #define TRLR_INDX_CSUM3 2
00267 #define TRLR_LENGTH 3
00268 
00269 /* How to compute the trailer bytes.  */
00270 #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
00271 #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
00272 #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))
00273 
00274 /* Check that a trailer byte is reasonable.  */
00275 #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)
00276 
00277 /* Get data from the trailer.  This evaluates its argument multiple
00278    times.  */
00279 #define TRLR_GET_CKSUM(trlr) \
00280   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
00281    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
00282    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))
00283 
00284 /* The sequence number modulos.  */
00285 #define SEQ_MODULOS (64)
00286 
00287 /* PMON commands to load from the serial port or UDP socket.  */
00288 #define LOAD_CMD        "load -b -s tty0\r"
00289 #define LOAD_CMD_UDP    "load -b -s udp\r"
00290 
00291 /* The target vectors for the four different remote MIPS targets.
00292    These are initialized with code in _initialize_remote_mips instead
00293    of static initializers, to make it easier to extend the target_ops
00294    vector later.  */
00295 struct target_ops mips_ops, pmon_ops, ddb_ops, rockhopper_ops, lsi_ops;
00296 
00297 enum mips_monitor_type
00298   {
00299     /* IDT/SIM monitor being used: */
00300     MON_IDT,
00301     /* PMON monitor being used: */
00302     MON_PMON,                   /* 3.0.83 [COGENT,EB,FP,NET]
00303                                    Algorithmics Ltd. Nov  9 1995 17:19:50 */
00304     MON_DDB,                    /* 2.7.473 [DDBVR4300,EL,FP,NET]
00305                                    Risq Modular Systems,
00306                                    Thu Jun 6 09:28:40 PDT 1996 */
00307     MON_LSI,                    /* 4.3.12 [EB,FP],
00308                                    LSI LOGIC Corp. Tue Feb 25 13:22:14 1997 */
00309     MON_ROCKHOPPER,
00310     /* Last and unused value, for sizing vectors, etc.  */
00311     MON_LAST
00312   };
00313 static enum mips_monitor_type mips_monitor = MON_LAST;
00314 
00315 /* The monitor prompt text.  If the user sets the PMON prompt
00316    to some new value, the GDB `set monitor-prompt' command must also
00317    be used to inform GDB about the expected prompt.  Otherwise, GDB
00318    will not be able to connect to PMON in mips_initialize().
00319    If the `set monitor-prompt' command is not used, the expected
00320    default prompt will be set according the target:
00321    target               prompt
00322    -----                -----
00323    pmon         PMON> 
00324    ddb          NEC010>
00325    lsi          PMON>
00326  */
00327 static char *mips_monitor_prompt;
00328 
00329 /* Set to 1 if the target is open.  */
00330 static int mips_is_open;
00331 
00332 /* Currently active target description (if mips_is_open == 1).  */
00333 static struct target_ops *current_ops;
00334 
00335 /* Set to 1 while the connection is being initialized.  */
00336 static int mips_initializing;
00337 
00338 /* Set to 1 while the connection is being brought down.  */
00339 static int mips_exiting;
00340 
00341 /* The next sequence number to send.  */
00342 static unsigned int mips_send_seq;
00343 
00344 /* The next sequence number we expect to receive.  */
00345 static unsigned int mips_receive_seq;
00346 
00347 /* The time to wait before retransmitting a packet, in seconds.  */
00348 static int mips_retransmit_wait = 3;
00349 
00350 /* The number of times to try retransmitting a packet before giving up.  */
00351 static int mips_send_retries = 10;
00352 
00353 /* The number of garbage characters to accept when looking for an
00354    SYN for the next packet.  */
00355 static int mips_syn_garbage = 10;
00356 
00357 /* The time to wait for a packet, in seconds.  */
00358 static int mips_receive_wait = 5;
00359 
00360 /* Set if we have sent a packet to the board but have not yet received
00361    a reply.  */
00362 static int mips_need_reply = 0;
00363 
00364 /* Handle used to access serial I/O stream.  */
00365 static struct serial *mips_desc;
00366 
00367 /* UDP handle used to download files to target.  */
00368 static struct serial *udp_desc;
00369 static int udp_in_use;
00370 
00371 /* TFTP filename used to download files to DDB board, in the form
00372    host:filename.  */
00373 static char *tftp_name;         /* host:filename */
00374 static char *tftp_localname;    /* filename portion of above */
00375 static int tftp_in_use;
00376 static FILE *tftp_file;
00377 
00378 /* Counts the number of times the user tried to interrupt the target (usually
00379    via ^C.  */
00380 static int interrupt_count;
00381 
00382 /* If non-zero, means that the target is running.  */
00383 static int mips_wait_flag = 0;
00384 
00385 /* If non-zero, monitor supports breakpoint commands.  */
00386 static int monitor_supports_breakpoints = 0;
00387 
00388 /* Data cache header.  */
00389 
00390 #if 0                           /* not used (yet?)  */
00391 static DCACHE *mips_dcache;
00392 #endif
00393 
00394 /* Non-zero means that we've just hit a read or write watchpoint.  */
00395 static int hit_watchpoint;
00396 
00397 /* Table of breakpoints/watchpoints (used only on LSI PMON target).
00398    The table is indexed by a breakpoint number, which is an integer
00399    from 0 to 255 returned by the LSI PMON when a breakpoint is set.  */
00400 
00401 #define MAX_LSI_BREAKPOINTS 256
00402 struct lsi_breakpoint_info
00403   {
00404     enum break_type type;       /* type of breakpoint */
00405     CORE_ADDR addr;             /* address of breakpoint */
00406     int len;                    /* length of region being watched */
00407     unsigned long value;        /* value to watch */
00408   }
00409 lsi_breakpoints[MAX_LSI_BREAKPOINTS];
00410 
00411 /* Error/warning codes returned by LSI PMON for breakpoint commands.
00412    Warning values may be ORed together; error values may not.  */
00413 #define W_WARN  0x100           /* This bit is set if the error code
00414                                    is a warning */
00415 #define W_MSK   0x101           /* warning: Range feature is supported
00416                                    via mask */
00417 #define W_VAL   0x102           /* warning: Value check is not
00418                                    supported in hardware */
00419 #define W_QAL   0x104           /* warning: Requested qualifiers are
00420                                    not supported in hardware */
00421 
00422 #define E_ERR   0x200           /* This bit is set if the error code
00423                                    is an error */
00424 #define E_BPT   0x200           /* error: No such breakpoint number */
00425 #define E_RGE   0x201           /* error: Range is not supported */
00426 #define E_QAL   0x202           /* error: The requested qualifiers can
00427                                    not be used */
00428 #define E_OUT   0x203           /* error: Out of hardware resources */
00429 #define E_NON   0x204           /* error: Hardware breakpoint not supported */
00430 
00431 struct lsi_error
00432   {
00433     int code;                   /* error code */
00434     char *string;               /* string associated with this code */
00435   };
00436 
00437 struct lsi_error lsi_warning_table[] =
00438 {
00439   {W_MSK, "Range feature is supported via mask"},
00440   {W_VAL, "Value check is not supported in hardware"},
00441   {W_QAL, "Requested qualifiers are not supported in hardware"},
00442   {0, NULL}
00443 };
00444 
00445 struct lsi_error lsi_error_table[] =
00446 {
00447   {E_BPT, "No such breakpoint number"},
00448   {E_RGE, "Range is not supported"},
00449   {E_QAL, "The requested qualifiers can not be used"},
00450   {E_OUT, "Out of hardware resources"},
00451   {E_NON, "Hardware breakpoint not supported"},
00452   {0, NULL}
00453 };
00454 
00455 /* Set to 1 with the 'set monitor-warnings' command to enable printing
00456    of warnings returned by PMON when hardware breakpoints are used.  */
00457 static int monitor_warnings;
00458 
00459 /* This is the ptid we use while we're connected to the remote.  Its
00460    value is arbitrary, as the remote-mips target doesn't have a notion of
00461    processes or threads, but we need something non-null to place in
00462    inferior_ptid.  */
00463 static ptid_t remote_mips_ptid;
00464 
00465 /* Close any ports which might be open.  Reset certain globals indicating
00466    the state of those ports.  */
00467 
00468 static void
00469 close_ports (void)
00470 {
00471   mips_is_open = 0;
00472   serial_close (mips_desc);
00473 
00474   if (udp_in_use)
00475     {
00476       serial_close (udp_desc);
00477       udp_in_use = 0;
00478     }
00479   tftp_in_use = 0;
00480 }
00481 
00482 /* Handle low-level error that we can't recover from.  Note that just
00483    error()ing out from target_wait or some such low-level place will cause
00484    all hell to break loose--the rest of GDB will tend to get left in an
00485    inconsistent state.  */
00486 
00487 static void ATTRIBUTE_NORETURN
00488 mips_error (char *string,...)
00489 {
00490   va_list args;
00491   char *fmt;
00492 
00493   target_terminal_ours ();
00494   wrap_here ("");               /* Force out any buffered output.  */
00495   gdb_flush (gdb_stdout);
00496   gdb_flush (gdb_stderr);
00497 
00498   /* Clean up in such a way that mips_close won't try to talk to the
00499      board (it almost surely won't work since we weren't able to talk to
00500      it).  */
00501   close_ports ();
00502 
00503   if (!ptid_equal (inferior_ptid, null_ptid))
00504     target_mourn_inferior ();
00505 
00506   fmt = concat (_("Ending remote MIPS debugging: "),
00507                 string, (char *) NULL);
00508   make_cleanup (xfree, fmt);
00509 
00510   va_start (args, string);
00511   throw_verror (TARGET_CLOSE_ERROR, fmt, args);
00512   va_end (args);
00513 }
00514 
00515 /* putc_readable - print a character, displaying non-printable chars in
00516    ^x notation or in hex.  */
00517 
00518 static void
00519 fputc_readable (int ch, struct ui_file *file)
00520 {
00521   if (ch == '\n')
00522     fputc_unfiltered ('\n', file);
00523   else if (ch == '\r')
00524     fprintf_unfiltered (file, "\\r");
00525   else if (ch < 0x20)           /* ASCII control character */
00526     fprintf_unfiltered (file, "^%c", ch + '@');
00527   else if (ch >= 0x7f)          /* non-ASCII characters (rubout or greater) */
00528     fprintf_unfiltered (file, "[%02x]", ch & 0xff);
00529   else
00530     fputc_unfiltered (ch, file);
00531 }
00532 
00533 
00534 /* puts_readable - print a string, displaying non-printable chars in
00535    ^x notation or in hex.  */
00536 
00537 static void
00538 fputs_readable (const char *string, struct ui_file *file)
00539 {
00540   int c;
00541 
00542   while ((c = *string++) != '\0')
00543     fputc_readable (c, file);
00544 }
00545 
00546 
00547 /* Read P as a hex value.  Return true if every character made sense,
00548    storing the result in *RESULT.  Leave *RESULT unchanged otherwise.  */
00549 
00550 static int
00551 read_hex_value (const char *p, ULONGEST *result)
00552 {
00553   ULONGEST retval;
00554 
00555   retval = 0;
00556   while (*p != 0)
00557     {
00558       retval <<= 4;
00559       if (*p >= '0' && *p <= '9')
00560         retval |= *p - '0';
00561       else if (*p >= 'A' && *p <= 'F')
00562         retval |= *p - 'A' + 10;
00563       else if (*p >= 'a' && *p <= 'f')
00564         retval |= *p - 'a' + 10;
00565       else
00566         return 0;
00567       p++;
00568     }
00569   *result = retval;
00570   return 1;
00571 }
00572 
00573 
00574 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
00575    timed out.  TIMEOUT specifies timeout value in seconds.  */
00576 
00577 static int
00578 mips_expect_timeout (const char *string, int timeout)
00579 {
00580   const char *p = string;
00581 
00582   if (remote_debug)
00583     {
00584       fprintf_unfiltered (gdb_stdlog, "Expected \"");
00585       fputs_readable (string, gdb_stdlog);
00586       fprintf_unfiltered (gdb_stdlog, "\", got \"");
00587     }
00588 
00589   immediate_quit++;
00590   QUIT;
00591   while (1)
00592     {
00593       int c;
00594 
00595       /* Must use serial_readchar() here cuz mips_readchar would get
00596          confused if we were waiting for the mips_monitor_prompt...  */
00597 
00598       c = serial_readchar (mips_desc, timeout);
00599 
00600       if (c == SERIAL_TIMEOUT)
00601         {
00602           if (remote_debug)
00603             fprintf_unfiltered (gdb_stdlog, "\": FAIL\n");
00604           return 0;
00605         }
00606 
00607       if (remote_debug)
00608         fputc_readable (c, gdb_stdlog);
00609 
00610       if (c == *p++)
00611         {
00612           if (*p == '\0')
00613             {
00614               immediate_quit--;
00615               if (remote_debug)
00616                 fprintf_unfiltered (gdb_stdlog, "\": OK\n");
00617               return 1;
00618             }
00619         }
00620       else
00621         {
00622           p = string;
00623           if (c == *p)
00624             p++;
00625         }
00626     }
00627 }
00628 
00629 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
00630    timed out.  The timeout value is hard-coded to 2 seconds.  Use
00631    mips_expect_timeout if a different timeout value is needed.  */
00632 
00633 static int
00634 mips_expect (const char *string)
00635 {
00636   return mips_expect_timeout (string, remote_timeout);
00637 }
00638 
00639 /* Read a character from the remote, aborting on error.  Returns
00640    SERIAL_TIMEOUT on timeout (since that's what serial_readchar()
00641    returns).  FIXME: If we see the string mips_monitor_prompt from the
00642    board, then we are debugging on the main console port, and we have
00643    somehow dropped out of remote debugging mode.  In this case, we
00644    automatically go back in to remote debugging mode.  This is a hack,
00645    put in because I can't find any way for a program running on the
00646    remote board to terminate without also ending remote debugging
00647    mode.  I assume users won't have any trouble with this; for one
00648    thing, the IDT documentation generally assumes that the remote
00649    debugging port is not the console port.  This is, however, very
00650    convenient for DejaGnu when you only have one connected serial
00651    port.  */
00652 
00653 static int
00654 mips_readchar (int timeout)
00655 {
00656   int ch;
00657   static int state = 0;
00658   int mips_monitor_prompt_len = strlen (mips_monitor_prompt);
00659 
00660   { /* FIXME this whole block is dead code!  */
00661     int i;
00662 
00663     i = timeout;
00664     if (i == -1 && watchdog > 0)
00665       i = watchdog;
00666   }
00667 
00668   if (state == mips_monitor_prompt_len)
00669     timeout = 1;
00670   ch = serial_readchar (mips_desc, timeout);
00671 
00672   if (ch == SERIAL_TIMEOUT && timeout == -1)    /* Watchdog went off.  */
00673     {
00674       target_mourn_inferior ();
00675       error (_("Watchdog has expired.  Target detached."));
00676     }
00677 
00678   if (ch == SERIAL_EOF)
00679     mips_error (_("End of file from remote"));
00680   if (ch == SERIAL_ERROR)
00681     mips_error (_("Error reading from remote: %s"), safe_strerror (errno));
00682   if (remote_debug > 1)
00683     {
00684       /* Don't use _filtered; we can't deal with a QUIT out of
00685          target_wait, and I think this might be called from there.  */
00686       if (ch != SERIAL_TIMEOUT)
00687         fprintf_unfiltered (gdb_stdlog, "Read '%c' %d 0x%x\n", ch, ch, ch);
00688       else
00689         fprintf_unfiltered (gdb_stdlog, "Timed out in read\n");
00690     }
00691 
00692   /* If we have seen mips_monitor_prompt and we either time out, or
00693      we see a @ (which was echoed from a packet we sent), reset the
00694      board as described above.  The first character in a packet after
00695      the SYN (which is not echoed) is always an @ unless the packet is
00696      more than 64 characters long, which ours never are.  */
00697   if ((ch == SERIAL_TIMEOUT || ch == '@')
00698       && state == mips_monitor_prompt_len
00699       && !mips_initializing
00700       && !mips_exiting)
00701     {
00702       if (remote_debug > 0)
00703         /* Don't use _filtered; we can't deal with a QUIT out of
00704            target_wait, and I think this might be called from there.  */
00705         fprintf_unfiltered (gdb_stdlog,
00706                             "Reinitializing MIPS debugging mode\n");
00707 
00708       mips_need_reply = 0;
00709       mips_initialize ();
00710 
00711       state = 0;
00712 
00713       /* At this point, about the only thing we can do is abort the command
00714          in progress and get back to command level as quickly as possible.  */
00715 
00716       error (_("Remote board reset, debug protocol re-initialized."));
00717     }
00718 
00719   if (ch == mips_monitor_prompt[state])
00720     ++state;
00721   else
00722     state = 0;
00723 
00724   return ch;
00725 }
00726 
00727 /* Get a packet header, putting the data in the supplied buffer.
00728    PGARBAGE is a pointer to the number of garbage characters received
00729    so far.  CH is the last character received.  Returns 0 for success,
00730    or -1 for timeout.  */
00731 
00732 static int
00733 mips_receive_header (unsigned char *hdr, int *pgarbage, int ch, int timeout)
00734 {
00735   int i;
00736 
00737   while (1)
00738     {
00739       /* Wait for a SYN.  mips_syn_garbage is intended to prevent
00740          sitting here indefinitely if the board sends us one garbage
00741          character per second.  ch may already have a value from the
00742          last time through the loop.  */
00743       while (ch != SYN)
00744         {
00745           ch = mips_readchar (timeout);
00746           if (ch == SERIAL_TIMEOUT)
00747             return -1;
00748           if (ch != SYN)
00749             {
00750               /* Printing the character here lets the user of gdb see
00751                  what the program is outputting, if the debugging is
00752                  being done on the console port.  Don't use _filtered:
00753                  we can't deal with a QUIT out of target_wait and
00754                  buffered target output confuses the user.  */
00755               if (!mips_initializing || remote_debug > 0)
00756                 {
00757                   if (isprint (ch) || isspace (ch))
00758                     {
00759                       fputc_unfiltered (ch, gdb_stdtarg);
00760                     }
00761                   else
00762                     {
00763                       fputc_readable (ch, gdb_stdtarg);
00764                     }
00765                   gdb_flush (gdb_stdtarg);
00766                 }
00767               
00768               /* Only count unprintable characters.  */
00769               if (! (isprint (ch) || isspace (ch)))
00770                 (*pgarbage) += 1;
00771 
00772               if (mips_syn_garbage > 0
00773                   && *pgarbage > mips_syn_garbage)
00774                 mips_error (_("Debug protocol failure:  more "
00775                             "than %d characters before a sync."),
00776                             mips_syn_garbage);
00777             }
00778         }
00779 
00780       /* Get the packet header following the SYN.  */
00781       for (i = 1; i < HDR_LENGTH; i++)
00782         {
00783           ch = mips_readchar (timeout);
00784           if (ch == SERIAL_TIMEOUT)
00785             return -1;
00786           /* Make sure this is a header byte.  */
00787           if (ch == SYN || !HDR_CHECK (ch))
00788             break;
00789 
00790           hdr[i] = ch;
00791         }
00792 
00793       /* If we got the complete header, we can return.  Otherwise we
00794          loop around and keep looking for SYN.  */
00795       if (i >= HDR_LENGTH)
00796         return 0;
00797     }
00798 }
00799 
00800 /* Get a packet header, putting the data in the supplied buffer.
00801    PGARBAGE is a pointer to the number of garbage characters received
00802    so far.  The last character read is returned in *PCH.  Returns 0
00803    for success, -1 for timeout, -2 for error.  */
00804 
00805 static int
00806 mips_receive_trailer (unsigned char *trlr, int *pgarbage,
00807                       int *pch, int timeout)
00808 {
00809   int i;
00810   int ch;
00811 
00812   for (i = 0; i < TRLR_LENGTH; i++)
00813     {
00814       ch = mips_readchar (timeout);
00815       *pch = ch;
00816       if (ch == SERIAL_TIMEOUT)
00817         return -1;
00818       if (!TRLR_CHECK (ch))
00819         return -2;
00820       trlr[i] = ch;
00821     }
00822   return 0;
00823 }
00824 
00825 /* Get the checksum of a packet.  HDR points to the packet header.
00826    DATASTR points to the packet data.  LEN is the length of DATASTR.  */
00827 
00828 static int
00829 mips_cksum (const unsigned char *hdr, const char *datastr, int len)
00830 {
00831   const unsigned char *p;
00832   const unsigned char *data = (const unsigned char *) datastr;
00833   int c;
00834   int cksum;
00835 
00836   cksum = 0;
00837 
00838   /* The initial SYN is not included in the checksum.  */
00839   c = HDR_LENGTH - 1;
00840   p = hdr + 1;
00841   while (c-- != 0)
00842     cksum += *p++;
00843 
00844   c = len;
00845   p = data;
00846   while (c-- != 0)
00847     cksum += *p++;
00848 
00849   return cksum;
00850 }
00851 
00852 /* Send a packet containing the given ASCII string.  */
00853 
00854 static void
00855 mips_send_packet (const char *s, int get_ack)
00856 {
00857   /* unsigned */ int len;
00858   unsigned char *packet;
00859   int cksum;
00860   int try;
00861 
00862   len = strlen (s);
00863   if (len > DATA_MAXLEN)
00864     mips_error (_("MIPS protocol data packet too long: %s"), s);
00865 
00866   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);
00867 
00868   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
00869   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
00870   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
00871   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);
00872 
00873   memcpy (packet + HDR_LENGTH, s, len);
00874 
00875   cksum = mips_cksum (packet, (char *) packet + HDR_LENGTH, len);
00876   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
00877   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
00878   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
00879 
00880   /* Increment the sequence number.  This will set mips_send_seq to
00881      the sequence number we expect in the acknowledgement.  */
00882   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;
00883 
00884   /* We can only have one outstanding data packet, so we just wait for
00885      the acknowledgement here.  Keep retransmitting the packet until
00886      we get one, or until we've tried too many times.  */
00887   for (try = 0; try < mips_send_retries; try++)
00888     {
00889       int garbage;
00890       int ch;
00891 
00892       if (remote_debug > 0)
00893         {
00894           /* Don't use _filtered; we can't deal with a QUIT out of
00895              target_wait, and I think this might be called from there.  */
00896           packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
00897           fprintf_unfiltered (gdb_stdlog, "Writing \"%s\"\n", packet + 1);
00898         }
00899 
00900       if (serial_write (mips_desc, packet,
00901                         HDR_LENGTH + len + TRLR_LENGTH) != 0)
00902         mips_error (_("write to target failed: %s"), safe_strerror (errno));
00903 
00904       if (!get_ack)
00905         return;
00906 
00907       garbage = 0;
00908       ch = 0;
00909       while (1)
00910         {
00911           unsigned char hdr[HDR_LENGTH + 1];
00912           unsigned char trlr[TRLR_LENGTH + 1];
00913           int err;
00914           unsigned int seq;
00915 
00916           /* Get the packet header.  If we time out, resend the data
00917              packet.  */
00918           err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
00919           if (err != 0)
00920             break;
00921 
00922           ch = 0;
00923 
00924           /* If we get a data packet, assume it is a duplicate and
00925              ignore it.  FIXME: If the acknowledgement is lost, this
00926              data packet may be the packet the remote sends after the
00927              acknowledgement.  */
00928           if (HDR_IS_DATA (hdr))
00929             {
00930               int i;
00931 
00932               /* Ignore any errors raised whilst attempting to ignore
00933                  packet.  */
00934 
00935               len = HDR_GET_LEN (hdr);
00936 
00937               for (i = 0; i < len; i++)
00938                 {
00939                   int rch;
00940 
00941                   rch = mips_readchar (remote_timeout);
00942                   if (rch == SYN)
00943                     {
00944                       ch = SYN;
00945                       break;
00946                     }
00947                   if (rch == SERIAL_TIMEOUT)
00948                     break;
00949                   /* Ignore the character.  */
00950                 }
00951 
00952               if (i == len)
00953                 (void) mips_receive_trailer (trlr, &garbage, &ch,
00954                                              remote_timeout);
00955 
00956               /* We don't bother checking the checksum, or providing an
00957                  ACK to the packet.  */
00958               continue;
00959             }
00960 
00961           /* If the length is not 0, this is a garbled packet.  */
00962           if (HDR_GET_LEN (hdr) != 0)
00963             continue;
00964 
00965           /* Get the packet trailer.  */
00966           err = mips_receive_trailer (trlr, &garbage, &ch,
00967                                       mips_retransmit_wait);
00968 
00969           /* If we timed out, resend the data packet.  */
00970           if (err == -1)
00971             break;
00972 
00973           /* If we got a bad character, reread the header.  */
00974           if (err != 0)
00975             continue;
00976 
00977           /* If the checksum does not match the trailer checksum, this
00978              is a bad packet; ignore it.  */
00979           if (mips_cksum (hdr, NULL, 0) != TRLR_GET_CKSUM (trlr))
00980             continue;
00981 
00982           if (remote_debug > 0)
00983             {
00984               hdr[HDR_LENGTH] = '\0';
00985               trlr[TRLR_LENGTH] = '\0';
00986               /* Don't use _filtered; we can't deal with a QUIT out of
00987                  target_wait, and I think this might be called from there.  */
00988               fprintf_unfiltered (gdb_stdlog, "Got ack %d \"%s%s\"\n",
00989                                   HDR_GET_SEQ (hdr), hdr + 1, trlr);
00990             }
00991 
00992           /* If this ack is for the current packet, we're done.  */
00993           seq = HDR_GET_SEQ (hdr);
00994           if (seq == mips_send_seq)
00995             return;
00996 
00997           /* If this ack is for the last packet, resend the current
00998              packet.  */
00999           if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
01000             break;
01001 
01002           /* Otherwise this is a bad ack; ignore it.  Increment the
01003              garbage count to ensure that we do not stay in this loop
01004              forever.  */
01005           ++garbage;
01006         }
01007     }
01008 
01009   mips_error (_("Remote did not acknowledge packet"));
01010 }
01011 
01012 /* Receive and acknowledge a packet, returning the data in BUFF (which
01013    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
01014    implies that only the sender retransmits packets, so this code just
01015    waits silently for a packet.  It returns the length of the received
01016    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
01017    don't print an error message and return -1.  */
01018 
01019 static int
01020 mips_receive_packet (char *buff, int throw_error, int timeout)
01021 {
01022   int ch;
01023   int garbage;
01024   int len;
01025   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
01026   int cksum;
01027 
01028   ch = 0;
01029   garbage = 0;
01030   while (1)
01031     {
01032       unsigned char hdr[HDR_LENGTH];
01033       unsigned char trlr[TRLR_LENGTH];
01034       int i;
01035       int err;
01036 
01037       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
01038         {
01039           if (throw_error)
01040             mips_error (_("Timed out waiting for remote packet"));
01041           else
01042             return -1;
01043         }
01044 
01045       ch = 0;
01046 
01047       /* An acknowledgement is probably a duplicate; ignore it.  */
01048       if (!HDR_IS_DATA (hdr))
01049         {
01050           len = HDR_GET_LEN (hdr);
01051           /* Check if the length is valid for an ACK, we may aswell
01052              try and read the remainder of the packet: */
01053           if (len == 0)
01054             {
01055               /* Ignore the error condition, since we are going to
01056                  ignore the packet anyway.  */
01057               (void) mips_receive_trailer (trlr, &garbage, &ch, timeout);
01058             }
01059           /* Don't use _filtered; we can't deal with a QUIT out of
01060              target_wait, and I think this might be called from there.  */
01061           if (remote_debug > 0)
01062             fprintf_unfiltered (gdb_stdlog, "Ignoring unexpected ACK\n");
01063           continue;
01064         }
01065 
01066       len = HDR_GET_LEN (hdr);
01067       for (i = 0; i < len; i++)
01068         {
01069           int rch;
01070 
01071           rch = mips_readchar (timeout);
01072           if (rch == SYN)
01073             {
01074               ch = SYN;
01075               break;
01076             }
01077           if (rch == SERIAL_TIMEOUT)
01078             {
01079               if (throw_error)
01080                 mips_error (_("Timed out waiting for remote packet"));
01081               else
01082                 return -1;
01083             }
01084           buff[i] = rch;
01085         }
01086 
01087       if (i < len)
01088         {
01089           /* Don't use _filtered; we can't deal with a QUIT out of
01090              target_wait, and I think this might be called from there.  */
01091           if (remote_debug > 0)
01092             fprintf_unfiltered (gdb_stdlog,
01093                                 "Got new SYN after %d chars (wanted %d)\n",
01094                                 i, len);
01095           continue;
01096         }
01097 
01098       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
01099       if (err == -1)
01100         {
01101           if (throw_error)
01102             mips_error (_("Timed out waiting for packet"));
01103           else
01104             return -1;
01105         }
01106       if (err == -2)
01107         {
01108           /* Don't use _filtered; we can't deal with a QUIT out of
01109              target_wait, and I think this might be called from there.  */
01110           if (remote_debug > 0)
01111             fprintf_unfiltered (gdb_stdlog, "Got SYN when wanted trailer\n");
01112           continue;
01113         }
01114 
01115       /* If this is the wrong sequence number, ignore it.  */
01116       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
01117         {
01118           /* Don't use _filtered; we can't deal with a QUIT out of
01119              target_wait, and I think this might be called from there.  */
01120           if (remote_debug > 0)
01121             fprintf_unfiltered (gdb_stdlog,
01122                                 "Ignoring sequence number %d (want %d)\n",
01123                                 HDR_GET_SEQ (hdr), mips_receive_seq);
01124           continue;
01125         }
01126 
01127       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
01128         break;
01129 
01130       if (remote_debug > 0)
01131         /* Don't use _filtered; we can't deal with a QUIT out of
01132            target_wait, and I think this might be called from there.  */
01133         printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
01134                            mips_cksum (hdr, buff, len),
01135                            TRLR_GET_CKSUM (trlr));
01136 
01137       /* The checksum failed.  Send an acknowledgement for the
01138          previous packet to tell the remote to resend the packet.  */
01139       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
01140       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
01141       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
01142       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
01143 
01144       cksum = mips_cksum (ack, NULL, 0);
01145 
01146       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
01147       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
01148       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
01149 
01150       if (remote_debug > 0)
01151         {
01152           ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
01153           /* Don't use _filtered; we can't deal with a QUIT out of
01154              target_wait, and I think this might be called from there.  */
01155           printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
01156                              ack + 1);
01157         }
01158 
01159       if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
01160         {
01161           if (throw_error)
01162             mips_error (_("write to target failed: %s"),
01163                         safe_strerror (errno));
01164           else
01165             return -1;
01166         }
01167     }
01168 
01169   if (remote_debug > 0)
01170     {
01171       buff[len] = '\0';
01172       /* Don't use _filtered; we can't deal with a QUIT out of
01173          target_wait, and I think this might be called from there.  */
01174       printf_unfiltered ("Got packet \"%s\"\n", buff);
01175     }
01176 
01177   /* We got the packet.  Send an acknowledgement.  */
01178   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;
01179 
01180   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
01181   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
01182   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
01183   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
01184 
01185   cksum = mips_cksum (ack, NULL, 0);
01186 
01187   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
01188   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
01189   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
01190 
01191   if (remote_debug > 0)
01192     {
01193       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
01194       /* Don't use _filtered; we can't deal with a QUIT out of
01195          target_wait, and I think this might be called from there.  */
01196       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
01197                          ack + 1);
01198     }
01199 
01200   if (serial_write (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
01201     {
01202       if (throw_error)
01203         mips_error (_("write to target failed: %s"), safe_strerror (errno));
01204       else
01205         return -1;
01206     }
01207 
01208   return len;
01209 }
01210 
01211 /* Optionally send a request to the remote system and optionally wait
01212    for the reply.  This implements the remote debugging protocol,
01213    which is built on top of the packet protocol defined above.  Each
01214    request has an ADDR argument and a DATA argument.  The following
01215    requests are defined:
01216 
01217    \0   don't send a request; just wait for a reply
01218    i    read word from instruction space at ADDR
01219    d    read word from data space at ADDR
01220    I    write DATA to instruction space at ADDR
01221    D    write DATA to data space at ADDR
01222    r    read register number ADDR
01223    R    set register number ADDR to value DATA
01224    c    continue execution (if ADDR != 1, set pc to ADDR)
01225    s    single step (if ADDR != 1, set pc to ADDR)
01226 
01227    The read requests return the value requested.  The write requests
01228    return the previous value in the changed location.  The execution
01229    requests return a UNIX wait value (the approximate signal which
01230    caused execution to stop is in the upper eight bits).
01231 
01232    If PERR is not NULL, this function waits for a reply.  If an error
01233    occurs, it sets *PERR to 1 and sets errno according to what the
01234    target board reports.  */
01235 
01236 static ULONGEST
01237 mips_request (int cmd,
01238               ULONGEST addr,
01239               ULONGEST data,
01240               int *perr,
01241               int timeout,
01242               char *buff)
01243 {
01244   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
01245   char myBuff[DATA_MAXLEN + 1];
01246   char response_string[17];
01247   int len;
01248   int rpid;
01249   char rcmd;
01250   int rerrflg;
01251   ULONGEST rresponse;
01252 
01253   if (buff == (char *) NULL)
01254     buff = myBuff;
01255 
01256   if (cmd != '\0')
01257     {
01258       if (mips_need_reply)
01259         internal_error (__FILE__, __LINE__,
01260                         _("mips_request: Trying to send "
01261                           "command before reply"));
01262       /* 'T' sets a register to a 64-bit value, so make sure we use
01263          the right conversion function.  */
01264       if (cmd == 'T')
01265         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
01266                  phex_nz (addr, addr_size), phex_nz (data, 8));
01267       else
01268         sprintf (buff, "0x0 %c 0x%s 0x%s", cmd,
01269                  phex_nz (addr, addr_size), phex_nz (data, addr_size));
01270 
01271       mips_send_packet (buff, 1);
01272       mips_need_reply = 1;
01273     }
01274 
01275   if (perr == (int *) NULL)
01276     return 0;
01277 
01278   if (!mips_need_reply)
01279     internal_error (__FILE__, __LINE__,
01280                     _("mips_request: Trying to get reply before command"));
01281 
01282   mips_need_reply = 0;
01283 
01284   len = mips_receive_packet (buff, 1, timeout);
01285   buff[len] = '\0';
01286 
01287   if (sscanf (buff, "0x%x %c 0x%x 0x%16s",
01288               &rpid, &rcmd, &rerrflg, response_string) != 4
01289       || !read_hex_value (response_string, &rresponse)
01290       || (cmd != '\0' && rcmd != cmd))
01291     mips_error (_("Bad response from remote board"));
01292 
01293   if (rerrflg != 0)
01294     {
01295       *perr = 1;
01296 
01297       /* FIXME: This will returns MIPS errno numbers, which may or may
01298          not be the same as errno values used on other systems.  If
01299          they stick to common errno values, they will be the same, but
01300          if they don't, they must be translated.  */
01301       errno = rresponse;
01302 
01303       return 0;
01304     }
01305 
01306   *perr = 0;
01307   return rresponse;
01308 }
01309 
01310 /* Cleanup associated with mips_initialize().  */
01311 
01312 static void
01313 mips_initialize_cleanups (void *arg)
01314 {
01315   mips_initializing = 0;
01316 }
01317 
01318 /* Cleanup associated with mips_exit_debug().  */
01319 
01320 static void
01321 mips_exit_cleanups (void *arg)
01322 {
01323   mips_exiting = 0;
01324 }
01325 
01326 /* Send a command and wait for that command to be echoed back.  Wait,
01327    too, for the following prompt.  */
01328 
01329 static void
01330 mips_send_command (const char *cmd, int prompt)
01331 {
01332   serial_write (mips_desc, cmd, strlen (cmd));
01333   mips_expect (cmd);
01334   mips_expect ("\n");
01335   if (prompt)
01336     mips_expect (mips_monitor_prompt);
01337 }
01338 
01339 /* Enter remote (dbx) debug mode: */
01340 
01341 static void
01342 mips_enter_debug (void)
01343 {
01344   /* Reset the sequence numbers, ready for the new debug sequence: */
01345   mips_send_seq = 0;
01346   mips_receive_seq = 0;
01347 
01348   if (mips_monitor != MON_IDT)
01349     mips_send_command ("debug\r", 0);
01350   else                          /* Assume IDT monitor by default.  */
01351     mips_send_command ("db tty0\r", 0);
01352 
01353   gdb_usleep (1000000);
01354   serial_write (mips_desc, "\r", sizeof "\r" - 1);
01355 
01356   /* We don't need to absorb any spurious characters here, since the
01357      mips_receive_header will eat up a reasonable number of characters
01358      whilst looking for the SYN, however this avoids the "garbage"
01359      being displayed to the user.  */
01360   if (mips_monitor != MON_IDT)
01361     mips_expect ("\r");
01362 
01363   {
01364     char buff[DATA_MAXLEN + 1];
01365 
01366     if (mips_receive_packet (buff, 1, 3) < 0)
01367       mips_error (_("Failed to initialize (didn't receive packet)."));
01368   }
01369 }
01370 
01371 /* Exit remote (dbx) debug mode, returning to the monitor prompt: */
01372 
01373 static int
01374 mips_exit_debug (void)
01375 {
01376   int err;
01377   struct cleanup *old_cleanups = make_cleanup (mips_exit_cleanups, NULL);
01378 
01379   mips_exiting = 1;
01380 
01381   if (mips_monitor != MON_IDT && mips_monitor != MON_ROCKHOPPER)
01382     {
01383       /* The DDB (NEC) and MiniRISC (LSI) versions of PMON exit immediately,
01384          so we do not get a reply to this command: */
01385       mips_request ('x', 0, 0, NULL, mips_receive_wait, NULL);
01386       mips_need_reply = 0;
01387       if (!mips_expect (" break!"))
01388         {
01389           do_cleanups (old_cleanups);
01390           return -1;
01391         }
01392     }
01393   else
01394     mips_request ('x', 0, 0, &err, mips_receive_wait, NULL);
01395 
01396   if (!mips_expect (mips_monitor_prompt))
01397     {
01398       do_cleanups (old_cleanups);
01399       return -1;
01400     }
01401 
01402   do_cleanups (old_cleanups);
01403 
01404   return 0;
01405 }
01406 
01407 /* Initialize a new connection to the MIPS board, and make sure we are
01408    really connected.  */
01409 
01410 static void
01411 mips_initialize (void)
01412 {
01413   int err;
01414   struct cleanup *old_cleanups;
01415   int j;
01416 
01417   /* What is this code doing here?  I don't see any way it can happen, and
01418      it might mean mips_initializing didn't get cleared properly.
01419      So I'll make it a warning.  */
01420 
01421   if (mips_initializing)
01422     {
01423       warning (_("internal error: mips_initialize called twice"));
01424       return;
01425     }
01426 
01427   old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);
01428 
01429   mips_wait_flag = 0;
01430   mips_initializing = 1;
01431 
01432   /* At this point, the packit protocol isn't responding.  We'll try getting
01433      into the monitor, and restarting the protocol.  */
01434 
01435   /* Force the system into the monitor.  After this we *should* be at
01436      the mips_monitor_prompt.  */
01437   if (mips_monitor != MON_IDT)
01438     j = 0;                      /* Start by checking if we are already
01439                                    at the prompt.  */
01440   else
01441     j = 1;                      /* Start by sending a break.  */
01442   for (; j <= 4; j++)
01443     {
01444       switch (j)
01445         {
01446         case 0:         /* First, try sending a CR.  */
01447           serial_flush_input (mips_desc);
01448           serial_write (mips_desc, "\r", 1);
01449           break;
01450         case 1:         /* First, try sending a break.  */
01451           serial_send_break (mips_desc);
01452           break;
01453         case 2:         /* Then, try a ^C.  */
01454           serial_write (mips_desc, "\003", 1);
01455           break;
01456         case 3:         /* Then, try escaping from download.  */
01457           {
01458             if (mips_monitor != MON_IDT)
01459               {
01460                 char tbuff[7];
01461 
01462                 /* We shouldn't need to send multiple termination
01463                    sequences, since the target performs line (or
01464                    block) reads, and then processes those
01465                    packets.  In-case we were downloading a large packet
01466                    we flush the output buffer before inserting a
01467                    termination sequence.  */
01468                 serial_flush_output (mips_desc);
01469                 sprintf (tbuff, "\r/E/E\r");
01470                 serial_write (mips_desc, tbuff, 6);
01471               }
01472             else
01473               {
01474                 char srec[10];
01475                 int i;
01476 
01477                 /* We are possibly in binary download mode, having
01478                    aborted in the middle of an S-record.  ^C won't
01479                    work because of binary mode.  The only reliable way
01480                    out is to send enough termination packets (8 bytes)
01481                    to fill up and then overflow the largest size
01482                    S-record (255 bytes in this case).  This amounts to
01483                    256/8 + 1 packets.  */
01484 
01485                 mips_make_srec (srec, '7', 0, NULL, 0);
01486 
01487                 for (i = 1; i <= 33; i++)
01488                   {
01489                     serial_write (mips_desc, srec, 8);
01490 
01491                     if (serial_readchar (mips_desc, 0) >= 0)
01492                       break;    /* Break immediatly if we get something from
01493                                    the board.  */
01494                   }
01495               }
01496           }
01497           break;
01498         case 4:
01499           mips_error (_("Failed to initialize."));
01500         }
01501 
01502       if (mips_expect (mips_monitor_prompt))
01503         break;
01504     }
01505 
01506   if (mips_monitor != MON_IDT)
01507     {
01508       /* Sometimes PMON ignores the first few characters in the first
01509          command sent after a load.  Sending a blank command gets
01510          around that.  */
01511       mips_send_command ("\r", -1);
01512 
01513       /* Ensure the correct target state: */
01514       if (mips_monitor != MON_LSI)
01515         mips_send_command ("set regsize 64\r", -1);
01516       mips_send_command ("set hostport tty0\r", -1);
01517       mips_send_command ("set brkcmd \"\"\r", -1);
01518       /* Delete all the current breakpoints: */
01519       mips_send_command ("db *\r", -1);
01520       /* NOTE: PMON does not have breakpoint support through the
01521          "debug" mode, only at the monitor command-line.  */
01522     }
01523 
01524   mips_enter_debug ();
01525 
01526   /* Clear all breakpoints: */
01527   if ((mips_monitor == MON_IDT
01528        && mips_clear_breakpoint (-1, 0, BREAK_UNUSED) == 0)
01529       || mips_monitor == MON_LSI)
01530     monitor_supports_breakpoints = 1;
01531   else
01532     monitor_supports_breakpoints = 0;
01533 
01534   do_cleanups (old_cleanups);
01535 
01536   /* If this doesn't call error, we have connected; we don't care if
01537      the request itself succeeds or fails.  */
01538 
01539   mips_request ('r', 0, 0, &err, mips_receive_wait, NULL);
01540 }
01541 
01542 /* Open a connection to the remote board.  */
01543 
01544 static void
01545 common_open (struct target_ops *ops, char *name, int from_tty,
01546              enum mips_monitor_type new_monitor,
01547              const char *new_monitor_prompt)
01548 {
01549   char *serial_port_name;
01550   char *remote_name = 0;
01551   char *local_name = 0;
01552   char **argv;
01553   struct cleanup *cleanup;
01554 
01555   if (name == 0)
01556     error (_("\
01557 To open a MIPS remote debugging connection, you need to specify what\n\
01558 serial device is attached to the target board (e.g., /dev/ttya).\n\
01559 If you want to use TFTP to download to the board, specify the name of a\n\
01560 temporary file to be used by GDB for downloads as the second argument.\n\
01561 This filename must be in the form host:filename, where host is the name\n\
01562 of the host running the TFTP server, and the file must be readable by the\n\
01563 world.  If the local name of the temporary file differs from the name as\n\
01564 seen from the board via TFTP, specify that name as the third parameter.\n"));
01565 
01566   /* Parse the serial port name, the optional TFTP name, and the
01567      optional local TFTP name.  */
01568   argv = gdb_buildargv (name);
01569   cleanup = make_cleanup_freeargv (argv);
01570 
01571   serial_port_name = xstrdup (argv[0]);
01572   if (argv[1])                  /* Remote TFTP name specified?  */
01573     {
01574       remote_name = argv[1];
01575       if (argv[2])              /* Local TFTP filename specified?  */
01576         local_name = argv[2];
01577     }
01578 
01579   target_preopen (from_tty);
01580 
01581   if (mips_is_open)
01582     unpush_target (current_ops);
01583 
01584   /* Open and initialize the serial port.  */
01585   mips_desc = serial_open (serial_port_name);
01586   if (mips_desc == NULL)
01587     perror_with_name (serial_port_name);
01588 
01589   if (baud_rate != -1)
01590     {
01591       if (serial_setbaudrate (mips_desc, baud_rate))
01592         {
01593           serial_close (mips_desc);
01594           perror_with_name (serial_port_name);
01595         }
01596     }
01597 
01598   serial_raw (mips_desc);
01599 
01600   /* Open and initialize the optional download port.  If it is in the form
01601      hostname#portnumber, it's a UDP socket.  If it is in the form
01602      hostname:filename, assume it's the TFTP filename that must be
01603      passed to the DDB board to tell it where to get the load file.  */
01604   if (remote_name)
01605     {
01606       if (strchr (remote_name, '#'))
01607         {
01608           udp_desc = serial_open (remote_name);
01609           if (!udp_desc)
01610             perror_with_name (_("Unable to open UDP port"));
01611           udp_in_use = 1;
01612         }
01613       else
01614         {
01615           /* Save the remote and local names of the TFTP temp file.  If
01616              the user didn't specify a local name, assume it's the same
01617              as the part of the remote name after the "host:".  */
01618           if (tftp_name)
01619             xfree (tftp_name);
01620           if (tftp_localname)
01621             xfree (tftp_localname);
01622           if (local_name == NULL)
01623             if ((local_name = strchr (remote_name, ':')) != NULL)
01624               local_name++;     /* Skip over the colon.  */
01625           if (local_name == NULL)
01626             local_name = remote_name;   /* Local name same as remote name.  */
01627           tftp_name = xstrdup (remote_name);
01628           tftp_localname = xstrdup (local_name);
01629           tftp_in_use = 1;
01630         }
01631     }
01632 
01633   current_ops = ops;
01634   mips_is_open = 1;
01635 
01636   /* Reset the expected monitor prompt if it's never been set before.  */
01637   if (mips_monitor_prompt == NULL)
01638     mips_monitor_prompt = xstrdup (new_monitor_prompt);
01639   mips_monitor = new_monitor;
01640 
01641   mips_initialize ();
01642 
01643   if (from_tty)
01644     printf_unfiltered ("Remote MIPS debugging using %s\n", serial_port_name);
01645 
01646   /* Switch to using remote target now.  */
01647   push_target (ops);
01648 
01649   inferior_ptid = remote_mips_ptid;
01650   inferior_appeared (current_inferior (), ptid_get_pid (inferior_ptid));
01651   add_thread_silent (inferior_ptid);
01652 
01653   /* Try to figure out the processor model if possible.  */
01654   deprecated_mips_set_processor_regs_hack ();
01655 
01656   /* This is really the job of start_remote however, that makes an
01657      assumption that the target is about to print out a status message
01658      of some sort.  That doesn't happen here (in fact, it may not be
01659      possible to get the monitor to send the appropriate packet).  */
01660 
01661   reinit_frame_cache ();
01662   registers_changed ();
01663   stop_pc = regcache_read_pc (get_current_regcache ());
01664   print_stack_frame (get_selected_frame (NULL), 0, SRC_AND_LOC, 1);
01665   xfree (serial_port_name);
01666 
01667   do_cleanups (cleanup);
01668 }
01669 
01670 /* Open a connection to an IDT board.  */
01671 
01672 static void
01673 mips_open (char *name, int from_tty)
01674 {
01675   const char *monitor_prompt = NULL;
01676   if (gdbarch_bfd_arch_info (target_gdbarch ()) != NULL
01677       && gdbarch_bfd_arch_info (target_gdbarch ())->arch == bfd_arch_mips)
01678     {
01679     switch (gdbarch_bfd_arch_info (target_gdbarch ())->mach)
01680       {
01681       case bfd_mach_mips4100:
01682       case bfd_mach_mips4300:
01683       case bfd_mach_mips4600:
01684       case bfd_mach_mips4650:
01685       case bfd_mach_mips5000:
01686         monitor_prompt = "<RISQ> ";
01687         break;
01688       }
01689     }
01690   if (monitor_prompt == NULL)
01691     monitor_prompt = "<IDT>";
01692   common_open (&mips_ops, name, from_tty, MON_IDT, monitor_prompt);
01693 }
01694 
01695 /* Open a connection to a PMON board.  */
01696 
01697 static void
01698 pmon_open (char *name, int from_tty)
01699 {
01700   common_open (&pmon_ops, name, from_tty, MON_PMON, "PMON> ");
01701 }
01702 
01703 /* Open a connection to a DDB board.  */
01704 
01705 static void
01706 ddb_open (char *name, int from_tty)
01707 {
01708   common_open (&ddb_ops, name, from_tty, MON_DDB, "NEC010>");
01709 }
01710 
01711 /* Open a connection to a rockhopper board.  */
01712 
01713 static void
01714 rockhopper_open (char *name, int from_tty)
01715 {
01716   common_open (&rockhopper_ops, name, from_tty, MON_ROCKHOPPER, "NEC01>");
01717 }
01718 
01719 /* Open a connection to an LSI board.  */
01720 
01721 static void
01722 lsi_open (char *name, int from_tty)
01723 {
01724   int i;
01725 
01726   /* Clear the LSI breakpoint table.  */
01727   for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
01728     lsi_breakpoints[i].type = BREAK_UNUSED;
01729 
01730   common_open (&lsi_ops, name, from_tty, MON_LSI, "PMON> ");
01731 }
01732 
01733 /* Close a connection to the remote board.  */
01734 
01735 static void
01736 mips_close (void)
01737 {
01738   if (mips_is_open)
01739     {
01740       /* Get the board out of remote debugging mode.  */
01741       (void) mips_exit_debug ();
01742 
01743       close_ports ();
01744     }
01745 
01746   generic_mourn_inferior ();
01747 }
01748 
01749 /* Detach from the remote board.  */
01750 
01751 static void
01752 mips_detach (struct target_ops *ops, char *args, int from_tty)
01753 {
01754   if (args)
01755     error (_("Argument given to \"detach\" when remotely debugging."));
01756 
01757   unpush_target (ops);
01758 
01759   if (from_tty)
01760     printf_unfiltered ("Ending remote MIPS debugging.\n");
01761 }
01762 
01763 /* Tell the target board to resume.  This does not wait for a reply
01764    from the board, except in the case of single-stepping on LSI boards,
01765    where PMON does return a reply.  */
01766 
01767 static void
01768 mips_resume (struct target_ops *ops,
01769              ptid_t ptid, int step, enum gdb_signal siggnal)
01770 {
01771   int err;
01772 
01773   /* LSI PMON requires returns a reply packet "0x1 s 0x0 0x57f" after
01774      a single step, so we wait for that.  */
01775   mips_request (step ? 's' : 'c', 1, siggnal,
01776                 mips_monitor == MON_LSI && step ? &err : (int *) NULL,
01777                 mips_receive_wait, NULL);
01778 }
01779 
01780 /* Return the signal corresponding to SIG, where SIG is the number which
01781    the MIPS protocol uses for the signal.  */
01782 
01783 static enum gdb_signal
01784 mips_signal_from_protocol (int sig)
01785 {
01786   /* We allow a few more signals than the IDT board actually returns, on
01787      the theory that there is at least *some* hope that perhaps the numbering
01788      for these signals is widely agreed upon.  */
01789   if (sig <= 0
01790       || sig > 31)
01791     return GDB_SIGNAL_UNKNOWN;
01792 
01793   /* Don't want to use gdb_signal_from_host because we are converting
01794      from MIPS signal numbers, not host ones.  Our internal numbers
01795      match the MIPS numbers for the signals the board can return, which
01796      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
01797   return (enum gdb_signal) sig;
01798 }
01799 
01800 /* Set the register designated by REGNO to the value designated by VALUE.  */
01801 
01802 static void
01803 mips_set_register (int regno, ULONGEST value)
01804 {
01805   gdb_byte buf[MAX_REGISTER_SIZE];
01806   struct regcache *regcache = get_current_regcache ();
01807   struct gdbarch *gdbarch = get_regcache_arch (regcache);
01808   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
01809 
01810   /* We got the number the register holds, but gdb expects to see a
01811      value in the target byte ordering.  */
01812 
01813   if (mips_monitor != MON_ROCKHOPPER
01814       && (regno == mips_regnum (gdbarch)->pc || regno < 32))
01815     /* Some 64-bit boards have monitors that only send the bottom 32 bits.
01816        In such cases we can only really debug 32-bit code properly so,
01817        when reading a GPR or the PC, assume that the full 64-bit
01818        value is the sign extension of the lower 32 bits.  */
01819     store_signed_integer (buf, register_size (gdbarch, regno), byte_order,
01820                           value);
01821   else
01822     store_unsigned_integer (buf, register_size (gdbarch, regno), byte_order,
01823                             value);
01824 
01825   regcache_raw_supply (regcache, regno, buf);
01826 }
01827 
01828 /* Wait until the remote stops, and return a wait status.  */
01829 
01830 static ptid_t
01831 mips_wait (struct target_ops *ops,
01832            ptid_t ptid, struct target_waitstatus *status, int options)
01833 {
01834   int rstatus;
01835   int err;
01836   char buff[DATA_MAXLEN];
01837   ULONGEST rpc, rfp, rsp;
01838   char pc_string[17], fp_string[17], sp_string[17], flags[20];
01839   int nfields;
01840 
01841   interrupt_count = 0;
01842   hit_watchpoint = 0;
01843 
01844   /* If we have not sent a single step or continue command, then the
01845      board is waiting for us to do something.  Return a status
01846      indicating that it is stopped.  */
01847   if (!mips_need_reply)
01848     {
01849       status->kind = TARGET_WAITKIND_STOPPED;
01850       status->value.sig = GDB_SIGNAL_TRAP;
01851       return inferior_ptid;
01852     }
01853 
01854   /* No timeout; we sit here as long as the program continues to execute.  */
01855   mips_wait_flag = 1;
01856   rstatus = mips_request ('\000', 0, 0, &err, -1, buff);
01857   mips_wait_flag = 0;
01858   if (err)
01859     mips_error (_("Remote failure: %s"), safe_strerror (errno));
01860 
01861   /* On returning from a continue, the PMON monitor seems to start
01862      echoing back the messages we send prior to sending back the
01863      ACK.  The code can cope with this, but to try and avoid the
01864      unnecessary serial traffic, and "spurious" characters displayed
01865      to the user, we cheat and reset the debug protocol.  The problems
01866      seems to be caused by a check on the number of arguments, and the
01867      command length, within the monitor causing it to echo the command
01868      as a bad packet.  */
01869   if (mips_monitor == MON_PMON)
01870     {
01871       mips_exit_debug ();
01872       mips_enter_debug ();
01873     }
01874 
01875   /* See if we got back extended status.  If so, pick out the pc, fp,
01876      sp, etc...  */
01877 
01878   nfields = sscanf (buff,
01879                     "0x%*x %*c 0x%*x 0x%*x 0x%16s 0x%16s 0x%16s 0x%*x %s",
01880                     pc_string, fp_string, sp_string, flags);
01881   if (nfields >= 3
01882       && read_hex_value (pc_string, &rpc)
01883       && read_hex_value (fp_string, &rfp)
01884       && read_hex_value (sp_string, &rsp))
01885     {
01886       struct regcache *regcache = get_current_regcache ();
01887       struct gdbarch *gdbarch = get_regcache_arch (regcache);
01888 
01889       mips_set_register (gdbarch_pc_regnum (gdbarch), rpc);
01890       mips_set_register (30, rfp);
01891       mips_set_register (gdbarch_sp_regnum (gdbarch), rsp);
01892 
01893       if (nfields == 9)
01894         {
01895           int i;
01896 
01897           for (i = 0; i <= 2; i++)
01898             if (flags[i] == 'r' || flags[i] == 'w')
01899               hit_watchpoint = 1;
01900             else if (flags[i] == '\000')
01901               break;
01902         }
01903     }
01904 
01905   if (strcmp (target_shortname, "lsi") == 0)
01906     {
01907 #if 0
01908       /* If this is an LSI PMON target, see if we just hit a
01909          hardrdware watchpoint.  Right now, PMON doesn't give us
01910          enough information to determine which breakpoint we hit.  So
01911          we have to look up the PC in our own table of breakpoints,
01912          and if found, assume it's just a normal instruction fetch
01913          breakpoint, not a data watchpoint.  FIXME when PMON provides
01914          some way to tell us what type of breakpoint it is.  */
01915       int i;
01916       CORE_ADDR pc = regcache_read_pc (get_current_regcache ());
01917 
01918       hit_watchpoint = 1;
01919       for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
01920         {
01921           if (lsi_breakpoints[i].addr == pc
01922               && lsi_breakpoints[i].type == BREAK_FETCH)
01923             {
01924               hit_watchpoint = 0;
01925               break;
01926             }
01927         }
01928 #else
01929       /* If a data breakpoint was hit, PMON returns the following packet:
01930          0x1 c 0x0 0x57f 0x1
01931          The return packet from an ordinary breakpoint doesn't have the
01932          extra 0x01 field tacked onto the end.  */
01933       if (nfields == 1 && rpc == 1)
01934         hit_watchpoint = 1;
01935 #endif
01936     }
01937 
01938   /* NOTE: The following (sig) numbers are defined by PMON:
01939      SPP_SIGTRAP     5       breakpoint
01940      SPP_SIGINT      2
01941      SPP_SIGSEGV     11
01942      SPP_SIGBUS      10
01943      SPP_SIGILL      4
01944      SPP_SIGFPE      8
01945      SPP_SIGTERM     15 */
01946 
01947   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
01948      and so on, because the constants we want here are determined by the
01949      MIPS protocol and have nothing to do with what host we are running on.  */
01950   if ((rstatus & 0xff) == 0)
01951     {
01952       status->kind = TARGET_WAITKIND_EXITED;
01953       status->value.integer = (((rstatus) >> 8) & 0xff);
01954     }
01955   else if ((rstatus & 0xff) == 0x7f)
01956     {
01957       status->kind = TARGET_WAITKIND_STOPPED;
01958       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0xff);
01959 
01960       /* If the stop PC is in the _exit function, assume
01961          we hit the 'break 0x3ff' instruction in _exit, so this
01962          is not a normal breakpoint.  */
01963       if (strcmp (target_shortname, "lsi") == 0)
01964         {
01965           const char *func_name;
01966           CORE_ADDR func_start;
01967           CORE_ADDR pc = regcache_read_pc (get_current_regcache ());
01968 
01969           find_pc_partial_function (pc, &func_name, &func_start, NULL);
01970           if (func_name != NULL && strcmp (func_name, "_exit") == 0
01971               && func_start == pc)
01972             status->kind = TARGET_WAITKIND_EXITED;
01973         }
01974     }
01975   else
01976     {
01977       status->kind = TARGET_WAITKIND_SIGNALLED;
01978       status->value.sig = mips_signal_from_protocol (rstatus & 0x7f);
01979     }
01980 
01981   return inferior_ptid;
01982 }
01983 
01984 /* We have to map between the register numbers used by gdb and the
01985    register numbers used by the debugging protocol.  */
01986 
01987 #define REGNO_OFFSET 96
01988 
01989 static int
01990 mips_map_regno (struct gdbarch *gdbarch, int regno)
01991 {
01992   if (regno < 32)
01993     return regno;
01994   if (regno >= mips_regnum (gdbarch)->fp0
01995       && regno < mips_regnum (gdbarch)->fp0 + 32)
01996     return regno - mips_regnum (gdbarch)->fp0 + 32;
01997   else if (regno == mips_regnum (gdbarch)->pc)
01998     return REGNO_OFFSET + 0;
01999   else if (regno == mips_regnum (gdbarch)->cause)
02000     return REGNO_OFFSET + 1;
02001   else if (regno == mips_regnum (gdbarch)->hi)
02002     return REGNO_OFFSET + 2;
02003   else if (regno == mips_regnum (gdbarch)->lo)
02004     return REGNO_OFFSET + 3;
02005   else if (regno == mips_regnum (gdbarch)->fp_control_status)
02006     return REGNO_OFFSET + 4;
02007   else if (regno == mips_regnum (gdbarch)->fp_implementation_revision)
02008     return REGNO_OFFSET + 5;
02009   else
02010     /* FIXME: Is there a way to get the status register?  */
02011     return 0;
02012 }
02013 
02014 /* Fetch the remote registers.  */
02015 
02016 static void
02017 mips_fetch_registers (struct target_ops *ops,
02018                       struct regcache *regcache, int regno)
02019 {
02020   struct gdbarch *gdbarch = get_regcache_arch (regcache);
02021   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
02022   ULONGEST val;
02023   int err;
02024 
02025   if (regno == -1)
02026     {
02027       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
02028         mips_fetch_registers (ops, regcache, regno);
02029       return;
02030     }
02031 
02032   if (regno == gdbarch_deprecated_fp_regnum (gdbarch)
02033       || regno == MIPS_ZERO_REGNUM)
02034     /* gdbarch_deprecated_fp_regnum on the mips is a hack which is just
02035        supposed to read zero (see also mips-nat.c).  */
02036     val = 0;
02037   else
02038     {
02039       /* If PMON doesn't support this register, don't waste serial
02040          bandwidth trying to read it.  */
02041       int pmon_reg = mips_map_regno (gdbarch, regno);
02042 
02043       if (regno != 0 && pmon_reg == 0)
02044         val = 0;
02045       else
02046         {
02047           /* Unfortunately the PMON version in the Vr4300 board has been
02048              compiled without the 64bit register access commands.  This
02049              means we cannot get hold of the full register width.  */
02050           if (mips_monitor == MON_DDB || mips_monitor == MON_ROCKHOPPER)
02051             val = mips_request ('t', pmon_reg, 0,
02052                                 &err, mips_receive_wait, NULL);
02053           else
02054             val = mips_request ('r', pmon_reg, 0,
02055                                 &err, mips_receive_wait, NULL);
02056           if (err)
02057             mips_error (_("Can't read register %d: %s"), regno,
02058                         safe_strerror (errno));
02059         }
02060     }
02061 
02062   mips_set_register (regno, val);
02063 }
02064 
02065 /* Prepare to store registers.  The MIPS protocol can store individual
02066    registers, so this function doesn't have to do anything.  */
02067 
02068 static void
02069 mips_prepare_to_store (struct regcache *regcache)
02070 {
02071 }
02072 
02073 /* Store remote register(s).  */
02074 
02075 static void
02076 mips_store_registers (struct target_ops *ops,
02077                       struct regcache *regcache, int regno)
02078 {
02079   struct gdbarch *gdbarch = get_regcache_arch (regcache);
02080   ULONGEST val;
02081   int err;
02082 
02083   if (regno == -1)
02084     {
02085       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
02086         mips_store_registers (ops, regcache, regno);
02087       return;
02088     }
02089 
02090   regcache_cooked_read_unsigned (regcache, regno, &val);
02091   mips_request (mips_monitor == MON_ROCKHOPPER ? 'T' : 'R',
02092                 mips_map_regno (gdbarch, regno),
02093                 val,
02094                 &err, mips_receive_wait, NULL);
02095   if (err)
02096     mips_error (_("Can't write register %d: %s"), regno,
02097                 safe_strerror (errno));
02098 }
02099 
02100 /* Fetch a word from the target board.  Return word fetched in location
02101    addressed by VALP.  Return 0 when successful; return positive error
02102    code when not.  */
02103 
02104 static int
02105 mips_fetch_word (CORE_ADDR addr, unsigned int *valp)
02106 {
02107   int err;
02108 
02109   *valp = mips_request ('d', addr, 0, &err, mips_receive_wait, NULL);
02110   if (err)
02111     {
02112       /* Data space failed; try instruction space.  */
02113       *valp = mips_request ('i', addr, 0, &err,
02114                             mips_receive_wait, NULL);
02115     }
02116   return err;
02117 }
02118 
02119 /* Store a word to the target board.  Returns errno code or zero for
02120    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
02121    memory location there.  */
02122 
02123 /* FIXME! make sure only 32-bit quantities get stored!  */
02124 static int
02125 mips_store_word (CORE_ADDR addr, unsigned int val, int *old_contents)
02126 {
02127   int err;
02128   unsigned int oldcontents;
02129 
02130   oldcontents = mips_request ('D', addr, val, &err,
02131                               mips_receive_wait, NULL);
02132   if (err)
02133     {
02134       /* Data space failed; try instruction space.  */
02135       oldcontents = mips_request ('I', addr, val, &err,
02136                                   mips_receive_wait, NULL);
02137       if (err)
02138         return errno;
02139     }
02140   if (old_contents != NULL)
02141     *old_contents = oldcontents;
02142   return 0;
02143 }
02144 
02145 /* Read or write LEN bytes from inferior memory at MEMADDR,
02146    transferring to or from debugger address MYADDR.  Write to inferior
02147    if SHOULD_WRITE is nonzero.  Returns length of data written or
02148    read; 0 for error.  Note that protocol gives us the correct value
02149    for a longword, since it transfers values in ASCII.  We want the
02150    byte values, so we have to swap the longword values.  */
02151 
02152 static int mask_address_p = 1;
02153 
02154 static int
02155 mips_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int write,
02156                   struct mem_attrib *attrib, struct target_ops *target)
02157 {
02158   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
02159   int i;
02160   CORE_ADDR addr;
02161   int count;
02162   gdb_byte *buffer;
02163   int status;
02164 
02165   /* PMON targets do not cope well with 64 bit addresses.  Mask the
02166      value down to 32 bits.  */
02167   if (mask_address_p)
02168     memaddr &= (CORE_ADDR) 0xffffffff;
02169 
02170   /* Round starting address down to longword boundary.  */
02171   addr = memaddr & ~3;
02172   /* Round ending address up; get number of longwords that makes.  */
02173   count = (((memaddr + len) - addr) + 3) / 4;
02174   /* Allocate buffer of that many longwords.  */
02175   buffer = alloca (count * 4);
02176 
02177   if (write)
02178     {
02179       /* Fill start and end extra bytes of buffer with existing data.  */
02180       if (addr != memaddr || len < 4)
02181         {
02182           unsigned int val;
02183 
02184           if (mips_fetch_word (addr, &val))
02185             return 0;
02186 
02187           /* Need part of initial word -- fetch it.  */
02188           store_unsigned_integer (&buffer[0], 4, byte_order, val);
02189         }
02190 
02191       if (count > 1)
02192         {
02193           unsigned int val;
02194 
02195           /* Need part of last word -- fetch it.  FIXME: we do this even
02196              if we don't need it.  */
02197           if (mips_fetch_word (addr + (count - 1) * 4, &val))
02198             return 0;
02199 
02200           store_unsigned_integer (&buffer[(count - 1) * 4],
02201                                   4, byte_order, val);
02202         }
02203 
02204       /* Copy data to be written over corresponding part of buffer.  */
02205 
02206       memcpy ((char *) buffer + (memaddr & 3), myaddr, len);
02207 
02208       /* Write the entire buffer.  */
02209 
02210       for (i = 0; i < count; i++, addr += 4)
02211         {
02212           int word;
02213 
02214           word = extract_unsigned_integer (&buffer[i * 4], 4, byte_order);
02215           status = mips_store_word (addr, word, NULL);
02216           /* Report each kilobyte (we download 32-bit words at a time).  */
02217           if (i % 256 == 255)
02218             {
02219               printf_unfiltered ("*");
02220               gdb_flush (gdb_stdout);
02221             }
02222           if (status)
02223             {
02224               errno = status;
02225               return 0;
02226             }
02227           /* FIXME: Do we want a QUIT here?  */
02228         }
02229       if (count >= 256)
02230         printf_unfiltered ("\n");
02231     }
02232   else
02233     {
02234       /* Read all the longwords.  */
02235       for (i = 0; i < count; i++, addr += 4)
02236         {
02237           unsigned int val;
02238 
02239           if (mips_fetch_word (addr, &val))
02240             return 0;
02241 
02242           store_unsigned_integer (&buffer[i * 4], 4, byte_order, val);
02243           QUIT;
02244         }
02245 
02246       /* Copy appropriate bytes out of the buffer.  */
02247       memcpy (myaddr, buffer + (memaddr & 3), len);
02248     }
02249   return len;
02250 }
02251 
02252 /* Print info on this target.  */
02253 
02254 static void
02255 mips_files_info (struct target_ops *ignore)
02256 {
02257   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
02258 }
02259 
02260 /* Kill the process running on the board.  This will actually only
02261    work if we are doing remote debugging over the console input.  I
02262    think that if IDT/sim had the remote debug interrupt enabled on the
02263    right port, we could interrupt the process with a break signal.  */
02264 
02265 static void
02266 mips_kill (struct target_ops *ops)
02267 {
02268   if (!mips_wait_flag)
02269     {
02270       target_mourn_inferior ();
02271       return;
02272     }
02273 
02274   interrupt_count++;
02275 
02276   if (interrupt_count >= 2)
02277     {
02278       interrupt_count = 0;
02279 
02280       target_terminal_ours ();
02281 
02282       if (query (_("Interrupted while waiting for the program.\n\
02283 Give up (and stop debugging it)? ")))
02284         {
02285           /* Clean up in such a way that mips_close won't try to talk
02286              to the board (it almost surely won't work since we
02287              weren't able to talk to it).  */
02288           mips_wait_flag = 0;
02289           close_ports ();
02290 
02291           printf_unfiltered ("Ending remote MIPS debugging.\n");
02292           target_mourn_inferior ();
02293           quit ();
02294         }
02295 
02296       target_terminal_inferior ();
02297     }
02298 
02299   if (remote_debug > 0)
02300     printf_unfiltered ("Sending break\n");
02301 
02302   serial_send_break (mips_desc);
02303 
02304   target_mourn_inferior ();
02305 
02306 #if 0
02307   if (mips_is_open)
02308     {
02309       char cc;
02310 
02311       /* Send a ^C.  */
02312       cc = '\003';
02313       serial_write (mips_desc, &cc, 1);
02314       sleep (1);
02315       target_mourn_inferior ();
02316     }
02317 #endif
02318 }
02319 
02320 /* Start running on the target board.  */
02321 
02322 static void
02323 mips_create_inferior (struct target_ops *ops, char *execfile,
02324                       char *args, char **env, int from_tty)
02325 {
02326   CORE_ADDR entry_pt;
02327 
02328   if (args && *args)
02329     {
02330       warning (_("\
02331 Can't pass arguments to remote MIPS board; arguments ignored."));
02332       /* And don't try to use them on the next "run" command.  */
02333       execute_command ("set args", 0);
02334     }
02335 
02336   if (execfile == 0 || exec_bfd == 0)
02337     error (_("No executable file specified"));
02338 
02339   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
02340 
02341   init_wait_for_inferior ();
02342 
02343   regcache_write_pc (get_current_regcache (), entry_pt);
02344 }
02345 
02346 /* Clean up after a process. The bulk of the work is done in mips_close(),
02347    which is called when unpushing the target.  */
02348 
02349 static void
02350 mips_mourn_inferior (struct target_ops *ops)
02351 {
02352   if (current_ops != NULL)
02353     unpush_target (current_ops);
02354 }
02355 
02356 /* We can write a breakpoint and read the shadow contents in one
02357    operation.  */
02358 
02359 /* Insert a breakpoint.  On targets that don't have built-in
02360    breakpoint support, we read the contents of the target location and
02361    stash it, then overwrite it with a breakpoint instruction.  ADDR is
02362    the target location in the target machine.  BPT is the breakpoint
02363    being inserted or removed, which contains memory for saving the
02364    target contents.  */
02365 
02366 static int
02367 mips_insert_breakpoint (struct gdbarch *gdbarch,
02368                         struct bp_target_info *bp_tgt)
02369 {
02370   if (monitor_supports_breakpoints)
02371     return mips_set_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
02372                                 BREAK_FETCH);
02373   else
02374     return memory_insert_breakpoint (gdbarch, bp_tgt);
02375 }
02376 
02377 /* Remove a breakpoint.  */
02378 
02379 static int
02380 mips_remove_breakpoint (struct gdbarch *gdbarch,
02381                         struct bp_target_info *bp_tgt)
02382 {
02383   if (monitor_supports_breakpoints)
02384     return mips_clear_breakpoint (bp_tgt->placed_address, MIPS_INSN32_SIZE,
02385                                   BREAK_FETCH);
02386   else
02387     return memory_remove_breakpoint (gdbarch, bp_tgt);
02388 }
02389 
02390 /* Tell whether this target can support a hardware breakpoint.  CNT
02391    is the number of hardware breakpoints already installed.  This
02392    implements the target_can_use_hardware_watchpoint macro.  */
02393 
02394 static int
02395 mips_can_use_watchpoint (int type, int cnt, int othertype)
02396 {
02397   return cnt < MAX_LSI_BREAKPOINTS && strcmp (target_shortname, "lsi") == 0;
02398 }
02399 
02400 
02401 /* Compute a don't care mask for the region bounding ADDR and ADDR + LEN - 1.
02402    This is used for memory ref breakpoints.  */
02403 
02404 static unsigned long
02405 calculate_mask (CORE_ADDR addr, int len)
02406 {
02407   unsigned long mask;
02408   int i;
02409 
02410   mask = addr ^ (addr + len - 1);
02411 
02412   for (i = 32; i >= 0; i--)
02413     if (mask == 0)
02414       break;
02415     else
02416       mask >>= 1;
02417 
02418   mask = (unsigned long) 0xffffffff >> i;
02419 
02420   return mask;
02421 }
02422 
02423 
02424 /* Set a data watchpoint.  ADDR and LEN should be obvious.  TYPE is 0
02425    for a write watchpoint, 1 for a read watchpoint, or 2 for a read/write
02426    watchpoint.  */
02427 
02428 static int
02429 mips_insert_watchpoint (CORE_ADDR addr, int len, int type,
02430                         struct expression *cond)
02431 {
02432   if (mips_set_breakpoint (addr, len, type))
02433     return -1;
02434 
02435   return 0;
02436 }
02437 
02438 /* Remove a watchpoint.  */
02439 
02440 static int
02441 mips_remove_watchpoint (CORE_ADDR addr, int len, int type,
02442                         struct expression *cond)
02443 {
02444   if (mips_clear_breakpoint (addr, len, type))
02445     return -1;
02446 
02447   return 0;
02448 }
02449 
02450 /* Test to see if a watchpoint has been hit.  Return 1 if so; return 0,
02451    if not.  */
02452 
02453 static int
02454 mips_stopped_by_watchpoint (void)
02455 {
02456   return hit_watchpoint;
02457 }
02458 
02459 
02460 /* Insert a breakpoint.  */
02461 
02462 static int
02463 mips_set_breakpoint (CORE_ADDR addr, int len, enum break_type type)
02464 {
02465   return mips_common_breakpoint (1, addr, len, type);
02466 }
02467 
02468 
02469 /* Clear a breakpoint.  */
02470 
02471 static int
02472 mips_clear_breakpoint (CORE_ADDR addr, int len, enum break_type type)
02473 {
02474   return mips_common_breakpoint (0, addr, len, type);
02475 }
02476 
02477 
02478 /* Check the error code from the return packet for an LSI breakpoint
02479    command.  If there's no error, just return 0.  If it's a warning,
02480    print the warning text and return 0.  If it's an error, print
02481    the error text and return 1.  <ADDR> is the address of the breakpoint
02482    that was being set.  <RERRFLG> is the error code returned by PMON.
02483    This is a helper function for mips_common_breakpoint.  */
02484 
02485 static int
02486 mips_check_lsi_error (CORE_ADDR addr, int rerrflg)
02487 {
02488   struct lsi_error *err;
02489   const char *saddr = paddress (target_gdbarch (), addr);
02490 
02491   if (rerrflg == 0)             /* no error */
02492     return 0;
02493 
02494   /* Warnings can be ORed together, so check them all.  */
02495   if (rerrflg & W_WARN)
02496     {
02497       if (monitor_warnings)
02498         {
02499           int found = 0;
02500 
02501           for (err = lsi_warning_table; err->code != 0; err++)
02502             {
02503               if ((err->code & rerrflg) == err->code)
02504                 {
02505                   found = 1;
02506                   fprintf_unfiltered (gdb_stderr, "\
02507 mips_common_breakpoint (%s): Warning: %s\n",
02508                                       saddr,
02509                                       err->string);
02510                 }
02511             }
02512           if (!found)
02513             fprintf_unfiltered (gdb_stderr, "\
02514 mips_common_breakpoint (%s): Unknown warning: 0x%x\n",
02515                                 saddr,
02516                                 rerrflg);
02517         }
02518       return 0;
02519     }
02520 
02521   /* Errors are unique, i.e. can't be ORed together.  */
02522   for (err = lsi_error_table; err->code != 0; err++)
02523     {
02524       if ((err->code & rerrflg) == err->code)
02525         {
02526           fprintf_unfiltered (gdb_stderr, "\
02527 mips_common_breakpoint (%s): Error: %s\n",
02528                               saddr,
02529                               err->string);
02530           return 1;
02531         }
02532     }
02533   fprintf_unfiltered (gdb_stderr, "\
02534 mips_common_breakpoint (%s): Unknown error: 0x%x\n",
02535                       saddr,
02536                       rerrflg);
02537   return 1;
02538 }
02539 
02540 
02541 /* This routine sends a breakpoint command to the remote target.
02542 
02543    <SET> is 1 if setting a breakpoint, or 0 if clearing a breakpoint.
02544    <ADDR> is the address of the breakpoint.
02545    <LEN> the length of the region to break on.
02546    <TYPE> is the type of breakpoint:
02547    0 = write                    (BREAK_WRITE)
02548    1 = read                     (BREAK_READ)
02549    2 = read/write               (BREAK_ACCESS)
02550    3 = instruction fetch        (BREAK_FETCH)
02551 
02552    Return 0 if successful; otherwise 1.  */
02553 
02554 static int
02555 mips_common_breakpoint (int set, CORE_ADDR addr, int len, enum break_type type)
02556 {
02557   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
02558   char buf[DATA_MAXLEN + 1];
02559   char cmd, rcmd;
02560   int rpid, rerrflg, rresponse, rlen;
02561   int nfields;
02562 
02563   addr = gdbarch_addr_bits_remove (target_gdbarch (), addr);
02564 
02565   if (mips_monitor == MON_LSI)
02566     {
02567       if (set == 0)             /* clear breakpoint */
02568         {
02569           /* The LSI PMON "clear breakpoint" has this form:
02570              <pid> 'b' <bptn> 0x0
02571              reply:
02572              <pid> 'b' 0x0 <code>
02573 
02574              <bptn> is a breakpoint number returned by an earlier 'B' command.
02575              Possible return codes: OK, E_BPT.  */
02576 
02577           int i;
02578 
02579           /* Search for the breakpoint in the table.  */
02580           for (i = 0; i < MAX_LSI_BREAKPOINTS; i++)
02581             if (lsi_breakpoints[i].type == type
02582                 && lsi_breakpoints[i].addr == addr
02583                 && lsi_breakpoints[i].len == len)
02584               break;
02585 
02586           /* Clear the table entry and tell PMON to clear the breakpoint.  */
02587           if (i == MAX_LSI_BREAKPOINTS)
02588             {
02589               warning (_("\
02590 mips_common_breakpoint: Attempt to clear bogus breakpoint at %s"),
02591                        paddress (target_gdbarch (), addr));
02592               return 1;
02593             }
02594 
02595           lsi_breakpoints[i].type = BREAK_UNUSED;
02596           sprintf (buf, "0x0 b 0x%x 0x0", i);
02597           mips_send_packet (buf, 1);
02598 
02599           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
02600           buf[rlen] = '\0';
02601 
02602           nfields = sscanf (buf, "0x%x b 0x0 0x%x", &rpid, &rerrflg);
02603           if (nfields != 2)
02604             mips_error (_("mips_common_breakpoint: "
02605                         "Bad response from remote board: %s"),
02606                         buf);
02607 
02608           return (mips_check_lsi_error (addr, rerrflg));
02609         }
02610       else
02611         /* set a breakpoint */
02612         {
02613           /* The LSI PMON "set breakpoint" command has this form:
02614              <pid> 'B' <addr> 0x0
02615              reply:
02616              <pid> 'B' <bptn> <code>
02617 
02618              The "set data breakpoint" command has this form:
02619 
02620              <pid> 'A' <addr1> <type> [<addr2>  [<value>]]
02621 
02622              where: type= "0x1" = read
02623              "0x2" = write
02624              "0x3" = access (read or write)
02625 
02626              The reply returns two values:
02627              bptn - a breakpoint number, which is a small integer with
02628              possible values of zero through 255.
02629              code - an error return code, a value of zero indicates a
02630              succesful completion, other values indicate various
02631              errors and warnings.
02632 
02633              Possible return codes: OK, W_QAL, E_QAL, E_OUT, E_NON.  */
02634 
02635           if (type == BREAK_FETCH)      /* instruction breakpoint */
02636             {
02637               cmd = 'B';
02638               sprintf (buf, "0x0 B 0x%s 0x0", phex_nz (addr, addr_size));
02639             }
02640           else
02641             /* watchpoint */
02642             {
02643               cmd = 'A';
02644               sprintf (buf, "0x0 A 0x%s 0x%x 0x%s",
02645                        phex_nz (addr, addr_size),
02646                        type == BREAK_READ ? 1 : (type == BREAK_WRITE ? 2 : 3),
02647                        phex_nz (addr + len - 1, addr_size));
02648             }
02649           mips_send_packet (buf, 1);
02650 
02651           rlen = mips_receive_packet (buf, 1, mips_receive_wait);
02652           buf[rlen] = '\0';
02653 
02654           nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
02655                             &rpid, &rcmd, &rresponse, &rerrflg);
02656           if (nfields != 4 || rcmd != cmd || rresponse > 255)
02657             mips_error (_("mips_common_breakpoint: "
02658                         "Bad response from remote board: %s"),
02659                         buf);
02660 
02661           if (rerrflg != 0)
02662             if (mips_check_lsi_error (addr, rerrflg))
02663               return 1;
02664 
02665           /* rresponse contains PMON's breakpoint number.  Record the
02666              information for this breakpoint so we can clear it later.  */
02667           lsi_breakpoints[rresponse].type = type;
02668           lsi_breakpoints[rresponse].addr = addr;
02669           lsi_breakpoints[rresponse].len = len;
02670 
02671           return 0;
02672         }
02673     }
02674   else
02675     {
02676       /* On non-LSI targets, the breakpoint command has this form:
02677          0x0 <CMD> <ADDR> <MASK> <FLAGS>
02678          <MASK> is a don't care mask for addresses.
02679          <FLAGS> is any combination of `r', `w', or `f' for 
02680          read/write/fetch.  */
02681 
02682       unsigned long mask;
02683 
02684       mask = calculate_mask (addr, len);
02685       addr &= ~mask;
02686 
02687       if (set)                  /* set a breakpoint */
02688         {
02689           char *flags;
02690 
02691           switch (type)
02692             {
02693             case BREAK_WRITE:   /* write */
02694               flags = "w";
02695               break;
02696             case BREAK_READ:    /* read */
02697               flags = "r";
02698               break;
02699             case BREAK_ACCESS:  /* read/write */
02700               flags = "rw";
02701               break;
02702             case BREAK_FETCH:   /* fetch */
02703               flags = "f";
02704               break;
02705             default:
02706               internal_error (__FILE__, __LINE__,
02707                               _("failed internal consistency check"));
02708             }
02709 
02710           cmd = 'B';
02711           sprintf (buf, "0x0 B 0x%s 0x%s %s", phex_nz (addr, addr_size),
02712                    phex_nz (mask, addr_size), flags);
02713         }
02714       else
02715         {
02716           cmd = 'b';
02717           sprintf (buf, "0x0 b 0x%s", phex_nz (addr, addr_size));
02718         }
02719 
02720       mips_send_packet (buf, 1);
02721 
02722       rlen = mips_receive_packet (buf, 1, mips_receive_wait);
02723       buf[rlen] = '\0';
02724 
02725       nfields = sscanf (buf, "0x%x %c 0x%x 0x%x",
02726                         &rpid, &rcmd, &rerrflg, &rresponse);
02727 
02728       if (nfields != 4 || rcmd != cmd)
02729         mips_error (_("mips_common_breakpoint: "
02730                     "Bad response from remote board: %s"),
02731                     buf);
02732 
02733       if (rerrflg != 0)
02734         {
02735           /* Ddb returns "0x0 b 0x16 0x0\000", whereas
02736              Cogent returns "0x0 b 0xffffffff 0x16\000": */
02737           if (mips_monitor == MON_DDB)
02738             rresponse = rerrflg;
02739           if (rresponse != 22)  /* invalid argument */
02740             fprintf_unfiltered (gdb_stderr, "\
02741 mips_common_breakpoint (%s):  Got error: 0x%x\n",
02742                                 paddress (target_gdbarch (), addr), rresponse);
02743           return 1;
02744         }
02745     }
02746   return 0;
02747 }
02748 
02749 /* Send one S record as specified by SREC of length LEN, starting
02750    at ADDR.  Note, however, that ADDR is not used except to provide
02751    a useful message to the user in the event that a NACK is received
02752    from the board.  */
02753 
02754 static void
02755 send_srec (char *srec, int len, CORE_ADDR addr)
02756 {
02757   while (1)
02758     {
02759       int ch;
02760 
02761       serial_write (mips_desc, srec, len);
02762 
02763       ch = mips_readchar (remote_timeout);
02764 
02765       switch (ch)
02766         {
02767         case SERIAL_TIMEOUT:
02768           error (_("Timeout during download."));
02769           break;
02770         case 0x6:               /* ACK */
02771           return;
02772         case 0x15:              /* NACK */
02773           fprintf_unfiltered (gdb_stderr,
02774                               "Download got a NACK at byte %s!  Retrying.\n",
02775                               paddress (target_gdbarch (), addr));
02776           continue;
02777         default:
02778           error (_("Download got unexpected ack char: 0x%x, retrying."),
02779                  ch);
02780         }
02781     }
02782 }
02783 
02784 /*  Download a binary file by converting it to S records.  */
02785 
02786 static void
02787 mips_load_srec (char *args)
02788 {
02789   bfd *abfd;
02790   asection *s;
02791   char srec[1024];
02792   bfd_byte *buffer;
02793   unsigned int i;
02794   unsigned int srec_frame = 200;
02795   int reclen;
02796   struct cleanup *cleanup;
02797   static int hashmark = 1;
02798 
02799   buffer = alloca (srec_frame * 2 + 256);
02800 
02801   abfd = gdb_bfd_open (args, NULL, -1);
02802   if (!abfd)
02803     {
02804       printf_filtered ("Unable to open file %s\n", args);
02805       return;
02806     }
02807 
02808   cleanup = make_cleanup_bfd_unref (abfd);
02809   if (bfd_check_format (abfd, bfd_object) == 0)
02810     {
02811       printf_filtered ("File is not an object file\n");
02812       do_cleanups (cleanup);
02813       return;
02814     }
02815 
02816 /* This actually causes a download in the IDT binary format: */
02817   mips_send_command (LOAD_CMD, 0);
02818 
02819   for (s = abfd->sections; s; s = s->next)
02820     {
02821       if (s->flags & SEC_LOAD)
02822         {
02823           unsigned int numbytes;
02824 
02825           /* FIXME!  vma too small?????  */
02826           printf_filtered ("%s\t: 0x%4lx .. 0x%4lx  ", s->name,
02827                            (long) s->vma,
02828                            (long) (s->vma + bfd_get_section_size (s)));
02829           gdb_flush (gdb_stdout);
02830 
02831           for (i = 0; i < bfd_get_section_size (s); i += numbytes)
02832             {
02833               numbytes = min (srec_frame, bfd_get_section_size (s) - i);
02834 
02835               bfd_get_section_contents (abfd, s, buffer, i, numbytes);
02836 
02837               reclen = mips_make_srec (srec, '3', s->vma + i, 
02838                                        buffer, numbytes);
02839               send_srec (srec, reclen, s->vma + i);
02840 
02841               if (deprecated_ui_load_progress_hook)
02842                 deprecated_ui_load_progress_hook (s->name, i);
02843 
02844               if (hashmark)
02845                 {
02846                   putchar_unfiltered ('#');
02847                   gdb_flush (gdb_stdout);
02848                 }
02849 
02850             }                   /* Per-packet (or S-record) loop */
02851 
02852           putchar_unfiltered ('\n');
02853         }                       /* Loadable sections */
02854     }
02855   if (hashmark)
02856     putchar_unfiltered ('\n');
02857 
02858   /* Write a type 7 terminator record. no data for a type 7, and there
02859      is no data, so len is 0.  */
02860 
02861   reclen = mips_make_srec (srec, '7', abfd->start_address, NULL, 0);
02862 
02863   send_srec (srec, reclen, abfd->start_address);
02864 
02865   serial_flush_input (mips_desc);
02866   do_cleanups (cleanup);
02867 }
02868 
02869 /*
02870  * mips_make_srec -- make an srecord.  This writes each line, one at a
02871  *      time, each with it's own header and trailer line.
02872  *      An srecord looks like this:
02873  *
02874  * byte count-+     address
02875  * start ---+ |        |       data        +- checksum
02876  *          | |        |                   |
02877  *        S01000006F6B692D746573742E73726563E4
02878  *        S315000448600000000000000000FC00005900000000E9
02879  *        S31A0004000023C1400037DE00F023604000377B009020825000348D
02880  *        S30B0004485A0000000000004E
02881  *        S70500040000F6
02882  *
02883  *      S<type><length><address><data><checksum>
02884  *
02885  *      Where
02886  *      - length
02887  *        is the number of bytes following upto the checksum.  Note that
02888  *        this is not the number of chars following, since it takes two
02889  *        chars to represent a byte.
02890  *      - type
02891  *        is one of:
02892  *        0) header record
02893  *        1) two byte address data record
02894  *        2) three byte address data record
02895  *        3) four byte address data record
02896  *        7) four byte address termination record
02897  *        8) three byte address termination record
02898  *        9) two byte address termination record
02899  *       
02900  *      - address
02901  *        is the start address of the data following, or in the case of
02902  *        a termination record, the start address of the image
02903  *      - data
02904  *        is the data.
02905  *      - checksum
02906  *        is the sum of all the raw byte data in the record, from the length
02907  *        upwards, modulo 256 and subtracted from 255.
02908  *
02909  * This routine returns the length of the S-record.
02910  *
02911  */
02912 
02913 static int
02914 mips_make_srec (char *buf, int type, CORE_ADDR memaddr, unsigned char *myaddr,
02915                 int len)
02916 {
02917   unsigned char checksum;
02918   int i;
02919 
02920   /* Create the header for the srec.  addr_size is the number of bytes
02921      in the address, and 1 is the number of bytes in the count.  */
02922 
02923   /* FIXME!! bigger buf required for 64-bit!  */
02924   buf[0] = 'S';
02925   buf[1] = type;
02926   buf[2] = len + 4 + 1;         /* len + 4 byte address + 1 byte checksum */
02927   /* This assumes S3 style downloads (4byte addresses).  There should
02928      probably be a check, or the code changed to make it more
02929      explicit.  */
02930   buf[3] = memaddr >> 24;
02931   buf[4] = memaddr >> 16;
02932   buf[5] = memaddr >> 8;
02933   buf[6] = memaddr;
02934   memcpy (&buf[7], myaddr, len);
02935 
02936   /* Note that the checksum is calculated on the raw data, not the
02937      hexified data.  It includes the length, address and the data
02938      portions of the packet.  */
02939   checksum = 0;
02940   buf += 2;                     /* Point at length byte.  */
02941   for (i = 0; i < len + 4 + 1; i++)
02942     checksum += *buf++;
02943 
02944   *buf = ~checksum;
02945 
02946   return len + 8;
02947 }
02948 
02949 /* The following manifest controls whether we enable the simple flow
02950    control support provided by the monitor.  If enabled the code will
02951    wait for an affirmative ACK between transmitting packets.  */
02952 #define DOETXACK (1)
02953 
02954 /* The PMON fast-download uses an encoded packet format constructed of
02955    3byte data packets (encoded as 4 printable ASCII characters), and
02956    escape sequences (preceded by a '/'):
02957 
02958    'K'     clear checksum
02959    'C'     compare checksum (12bit value, not included in checksum calculation)
02960    'S'     define symbol name (for addr) terminated with ","
02961            and padded to 4char boundary
02962    'Z'     zero fill multiple of 3bytes
02963    'B'     byte (12bit encoded value, of 8bit data)
02964    'A'     address (36bit encoded value)
02965    'E'     define entry as original address, and exit load
02966 
02967    The packets are processed in 4 character chunks, so the escape
02968    sequences that do not have any data (or variable length data)
02969    should be padded to a 4 character boundary.  The decoder will give
02970    an error if the complete message block size is not a multiple of
02971    4bytes (size of record).
02972 
02973    The encoding of numbers is done in 6bit fields.  The 6bit value is
02974    used to index into this string to get the specific character
02975    encoding for the value: */
02976 static char encoding[] =
02977   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.";
02978 
02979 /* Convert the number of bits required into an encoded number, 6bits
02980    at a time (range 0..63).  Keep a checksum if required (passed
02981    pointer non-NULL).  The function returns the number of encoded
02982    characters written into the buffer.  */
02983 
02984 static int
02985 pmon_makeb64 (unsigned long v, char *p, int n, unsigned int *chksum)
02986 {
02987   int count = (n / 6);
02988 
02989   if ((n % 12) != 0)
02990     {
02991       fprintf_unfiltered (gdb_stderr,
02992                           "Fast encoding bitcount must be a "
02993                           "multiple of 12bits: %dbit%s\n",
02994                           n, (n == 1) ? "" : "s");
02995       return (0);
02996     }
02997   if (n > 36)
02998     {
02999       fprintf_unfiltered (gdb_stderr,
03000                           "Fast encoding cannot process more "
03001                           "than 36bits at the moment: %dbits\n", n);
03002       return (0);
03003     }
03004 
03005   /* Deal with the checksum: */
03006   if (chksum != NULL)
03007     {
03008       switch (n)
03009         {
03010         case 36:
03011           *chksum += ((v >> 24) & 0xFFF);
03012         case 24:
03013           *chksum += ((v >> 12) & 0xFFF);
03014         case 12:
03015           *chksum += ((v >> 0) & 0xFFF);
03016         }
03017     }
03018 
03019   do
03020     {
03021       n -= 6;
03022       *p++ = encoding[(v >> n) & 0x3F];
03023     }
03024   while (n > 0);
03025 
03026   return (count);
03027 }
03028 
03029 /* Shorthand function (that could be in-lined) to output the zero-fill
03030    escape sequence into the data stream.  */
03031 
03032 static int
03033 pmon_zeroset (int recsize, char **buff,
03034               unsigned int *amount, unsigned int *chksum)
03035 {
03036   int count;
03037 
03038   sprintf (*buff, "/Z");
03039   count = pmon_makeb64 (*amount, (*buff + 2), 12, chksum);
03040   *buff += (count + 2);
03041   *amount = 0;
03042   return (recsize + count + 2);
03043 }
03044 
03045 /* Add the checksum specified by *VALUE to end of the record under
03046    construction.  *BUF specifies the location at which to begin
03047    writing characters comprising the checksum information.  RECSIZE
03048    specifies the size of the record constructed thus far.  (A trailing
03049    NUL character may be present in the buffer holding the record, but
03050    the record size does not include this character.)
03051 
03052    Return the total size of the record after adding the checksum escape,
03053    the checksum itself, and the trailing newline.
03054    
03055    The checksum specified by *VALUE is zeroed out prior to returning.
03056    Additionally, *BUF is updated to refer to the location just beyond
03057    the record elements added by this call.  */
03058 
03059 static int
03060 pmon_checkset (int recsize, char **buff, unsigned int *value)
03061 {
03062   int count;
03063 
03064   /* Add the checksum (without updating the value): */
03065   sprintf (*buff, "/C");
03066   count = pmon_makeb64 (*value, (*buff + 2), 12, NULL);
03067   *buff += (count + 2);
03068   sprintf (*buff, "\n");
03069   *buff += 2;                   /* Include zero terminator.  */
03070   /* Forcing a checksum validation clears the sum: */
03071   *value = 0;
03072   return (recsize + count + 3);
03073 }
03074 
03075 /* Amount of padding we leave after at the end of the output buffer,
03076    for the checksum and line termination characters: */
03077 #define CHECKSIZE (4 + 4 + 4 + 2)
03078 /* zero-fill, checksum, transfer end and line termination space.  */
03079 
03080 /* The amount of binary data loaded from the object file in a single
03081    operation: */
03082 #define BINCHUNK (1024)
03083 
03084 /* Maximum line of data accepted by the monitor: */
03085 #define MAXRECSIZE (550)
03086 /* NOTE: This constant depends on the monitor being used.  This value
03087    is for PMON 5.x on the Cogent Vr4300 board.  */
03088 
03089 /* Create a FastLoad format record.
03090 
03091    *OUTBUF is the buffer into which a FastLoad formatted record is
03092    written.  On return, the pointer position represented by *OUTBUF
03093    is updated to point at the end of the data, i.e. the next position
03094    in the buffer that may be written.  No attempt is made to NUL-
03095    terminate this portion of the record written to the buffer.
03096    
03097    INBUF contains the binary input data from which the FastLoad
03098    formatted record will be built.  *INPTR is an index into this
03099    buffer.  *INPTR is updated as the input is consumed.  Thus, on
03100    return, the caller has access to the position of the next input
03101    byte yet to be processed.  INAMOUNT is the size, in bytes, of the
03102    input data.
03103 
03104    *RECSIZE will be written with the size of the record written to the
03105    output buffer prior to returning.  This size does not include a
03106    NUL-termination byte as none is written to the output buffer.
03107 
03108    *CSUM is the output buffer checksum.  It is updated as data is
03109    written to the output buffer.
03110    
03111    *ZEROFILL is the current number of 3-byte zero sequences that have
03112    been encountered.  It is both an input and an output to this
03113    function.  */
03114 
03115 static void
03116 pmon_make_fastrec (char **outbuf, unsigned char *inbuf, int *inptr,
03117                    int inamount, int *recsize, unsigned int *csum,
03118                    unsigned int *zerofill)
03119 {
03120   int count = 0;
03121   char *p = *outbuf;
03122 
03123   /* This is a simple check to ensure that our data will fit within
03124      the maximum allowable record size.  Each record output is 4bytes
03125      in length.  We must allow space for a pending zero fill command,
03126      the record, and a checksum record.  */
03127   while ((*recsize < (MAXRECSIZE - CHECKSIZE)) && ((inamount - *inptr) > 0))
03128     {
03129       /* Process the binary data: */
03130       if ((inamount - *inptr) < 3)
03131         {
03132           if (*zerofill != 0)
03133             *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
03134           sprintf (p, "/B");
03135           count = pmon_makeb64 (inbuf[*inptr], &p[2], 12, csum);
03136           p += (2 + count);
03137           *recsize += (2 + count);
03138           (*inptr)++;
03139         }
03140       else
03141         {
03142           unsigned int value = ((inbuf[*inptr + 0] << 16)
03143                                 | (inbuf[*inptr + 1] << 8)
03144                                 | (inbuf[*inptr + 2]));
03145 
03146           /* Simple check for zero data.  TODO: A better check would be
03147              to check the last, and then the middle byte for being zero
03148              (if the first byte is not).  We could then check for
03149              following runs of zeros, and if above a certain size it is
03150              worth the 4 or 8 character hit of the byte insertions used
03151              to pad to the start of the zeroes.  NOTE: This also depends
03152              on the alignment at the end of the zero run.  */
03153           if (value == 0x00000000)
03154             {
03155               (*zerofill)++;
03156               if (*zerofill == 0xFFF)   /* 12bit counter */
03157                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
03158             }
03159           else
03160             {
03161               if (*zerofill != 0)
03162                 *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
03163               count = pmon_makeb64 (value, p, 24, csum);
03164               p += count;
03165               *recsize += count;
03166             }
03167           *inptr += 3;
03168         }
03169     }
03170 
03171   *outbuf = p;
03172   return;
03173 }
03174 
03175 /* Attempt to read an ACK.  If an ACK is not read in a timely manner,
03176    output the message specified by MESG.  Return -1 for failure, 0
03177    for success.  */
03178 
03179 static int
03180 pmon_check_ack (char *mesg)
03181 {
03182 #if defined(DOETXACK)
03183   int c;
03184 
03185   if (!tftp_in_use)
03186     {
03187       c = serial_readchar (udp_in_use ? udp_desc : mips_desc,
03188                            remote_timeout);
03189       if ((c == SERIAL_TIMEOUT) || (c != 0x06))
03190         {
03191           fprintf_unfiltered (gdb_stderr,
03192                               "Failed to receive valid ACK for %s\n", mesg);
03193           return (-1);          /* Terminate the download.  */
03194         }
03195     }
03196 #endif /* DOETXACK */
03197   return (0);
03198 }
03199 
03200 /* pmon_download - Send a sequence of characters to the PMON download port,
03201    which is either a serial port or a UDP socket.  */
03202 
03203 static void
03204 pmon_start_download (void)
03205 {
03206   if (tftp_in_use)
03207     {
03208       /* Create the temporary download file.  */
03209       if ((tftp_file = fopen (tftp_localname, "w")) == NULL)
03210         perror_with_name (tftp_localname);
03211     }
03212   else
03213     {
03214       mips_send_command (udp_in_use ? LOAD_CMD_UDP : LOAD_CMD, 0);
03215       mips_expect ("Downloading from ");
03216       mips_expect (udp_in_use ? "udp" : "tty0");
03217       mips_expect (", ^C to abort\r\n");
03218     }
03219 }
03220 
03221 /* Look for the string specified by STRING sent from the target board
03222    during a download operation.  If the string in question is not
03223    seen, output an error message, remove the temporary file, if
03224    appropriate, and return 0.  Otherwise, return 1 to indicate
03225    success.  */
03226 
03227 static int
03228 mips_expect_download (char *string)
03229 {
03230   if (!mips_expect (string))
03231     {
03232       fprintf_unfiltered (gdb_stderr, "Load did not complete successfully.\n");
03233       if (tftp_in_use)
03234         remove (tftp_localname);        /* Remove temporary file.  */
03235       return 0;
03236     }
03237   else
03238     return 1;
03239 }
03240 
03241 /* Look for messages from the target board associated with the entry
03242    address.
03243 
03244    NOTE: This function doesn't indicate success or failure, so we
03245    have no way to determine whether or not the output from the board
03246    was correctly seen.  However, given that other items are checked
03247    after this, it seems unlikely that those checks will pass if this
03248    check doesn't first (silently) pass.  */
03249 
03250 static void
03251 pmon_check_entry_address (char *entry_address, int final)
03252 {
03253   char hexnumber[9];            /* Includes '\0' space.  */
03254 
03255   mips_expect_timeout (entry_address, tftp_in_use ? 15 : remote_timeout);
03256   sprintf (hexnumber, "%x", final);
03257   mips_expect (hexnumber);
03258   mips_expect ("\r\n");
03259 }
03260 
03261 /* Look for messages from the target board showing the total number of
03262    bytes downloaded to the board.  Output 1 for success if the tail
03263    end of the message was read correctly, 0 otherwise.  */
03264 
03265 static int
03266 pmon_check_total (int bintotal)
03267 {
03268   char hexnumber[9];            /* Includes '\0' space.  */
03269 
03270   mips_expect ("\r\ntotal = 0x");
03271   sprintf (hexnumber, "%x", bintotal);
03272   mips_expect (hexnumber);
03273   return mips_expect_download (" bytes\r\n");
03274 }
03275 
03276 /* Look for the termination messages associated with the end of
03277    a download to the board.
03278 
03279    Also, when `tftp_in_use' is set, issue the load command to the
03280    board causing the file to be transferred.  (This is done prior
03281    to looking for the above mentioned termination messages.)  */
03282    
03283 static void
03284 pmon_end_download (int final, int bintotal)
03285 {
03286   char hexnumber[9];            /* Includes '\0' space.  */
03287 
03288   if (tftp_in_use)
03289     {
03290       static char *load_cmd_prefix = "load -b -s ";
03291       char *cmd;
03292       struct stat stbuf;
03293 
03294       /* Close off the temporary file containing the load data.  */
03295       fclose (tftp_file);
03296       tftp_file = NULL;
03297 
03298       /* Make the temporary file readable by the world.  */
03299       if (stat (tftp_localname, &stbuf) == 0)
03300         chmod (tftp_localname, stbuf.st_mode | S_IROTH);
03301 
03302       /* Must reinitialize the board to prevent PMON from crashing.  */
03303       if (mips_monitor != MON_ROCKHOPPER)
03304         mips_send_command ("initEther\r", -1);
03305 
03306       /* Send the load command.  */
03307       cmd = xmalloc (strlen (load_cmd_prefix) + strlen (tftp_name) + 2);
03308       strcpy (cmd, load_cmd_prefix);
03309       strcat (cmd, tftp_name);
03310       strcat (cmd, "\r");
03311       mips_send_command (cmd, 0);
03312       xfree (cmd);
03313       if (!mips_expect_download ("Downloading from "))
03314         return;
03315       if (!mips_expect_download (tftp_name))
03316         return;
03317       if (!mips_expect_download (", ^C to abort\r\n"))
03318         return;
03319     }
03320 
03321   /* Wait for the stuff that PMON prints after the load has completed.
03322      The timeout value for use in the tftp case (15 seconds) was picked
03323      arbitrarily but might be too small for really large downloads.  FIXME.  */
03324   switch (mips_monitor)
03325     {
03326     case MON_LSI:
03327       pmon_check_ack ("termination");
03328       pmon_check_entry_address ("Entry address is ", final);
03329       if (!pmon_check_total (bintotal))
03330         return;
03331       break;
03332     case MON_ROCKHOPPER:
03333       if (!pmon_check_total (bintotal))
03334         return;
03335       pmon_check_entry_address ("Entry Address  = ", final);
03336       break;
03337     default:
03338       pmon_check_entry_address ("Entry Address  = ", final);
03339       pmon_check_ack ("termination");
03340       if (!pmon_check_total (bintotal))
03341         return;
03342       break;
03343     }
03344 
03345   if (tftp_in_use)
03346     remove (tftp_localname);    /* Remove temporary file.  */
03347 }
03348 
03349 /* Write the buffer specified by BUFFER of length LENGTH to either
03350    the board or the temporary file that'll eventually be transferred
03351    to the board.  */
03352 
03353 static void
03354 pmon_download (char *buffer, int length)
03355 {
03356   if (tftp_in_use)
03357     {
03358       size_t written;
03359 
03360       written = fwrite (buffer, 1, length, tftp_file);
03361       if (written < length)
03362         perror_with_name (tftp_localname);
03363     }
03364   else
03365     serial_write (udp_in_use ? udp_desc : mips_desc, buffer, length);
03366 }
03367 
03368 /* Open object or executable file, FILE, and send it to the board
03369    using the FastLoad format.  */
03370 
03371 static void
03372 pmon_load_fast (char *file)
03373 {
03374   bfd *abfd;
03375   asection *s;
03376   unsigned char *binbuf;
03377   char *buffer;
03378   int reclen;
03379   unsigned int csum = 0;
03380   int hashmark = !tftp_in_use;
03381   int bintotal = 0;
03382   int final = 0;
03383   int finished = 0;
03384   struct cleanup *cleanup;
03385 
03386   buffer = (char *) xmalloc (MAXRECSIZE + 1);
03387   binbuf = (unsigned char *) xmalloc (BINCHUNK);
03388 
03389   abfd = gdb_bfd_open (file, NULL, -1);
03390   if (!abfd)
03391     {
03392       printf_filtered ("Unable to open file %s\n", file);
03393       return;
03394     }
03395   cleanup = make_cleanup_bfd_unref (abfd);
03396 
03397   if (bfd_check_format (abfd, bfd_object) == 0)
03398     {
03399       printf_filtered ("File is not an object file\n");
03400       do_cleanups (cleanup);
03401       return;
03402     }
03403 
03404   /* Setup the required download state: */
03405   mips_send_command ("set dlproto etxack\r", -1);
03406   mips_send_command ("set dlecho off\r", -1);
03407   /* NOTE: We get a "cannot set variable" message if the variable is
03408      already defined to have the argument we give.  The code doesn't
03409      care, since it just scans to the next prompt anyway.  */
03410   /* Start the download: */
03411   pmon_start_download ();
03412 
03413   /* Zero the checksum.  */
03414   sprintf (buffer, "/Kxx\n");
03415   reclen = strlen (buffer);
03416   pmon_download (buffer, reclen);
03417   finished = pmon_check_ack ("/Kxx");
03418 
03419   for (s = abfd->sections; s && !finished; s = s->next)
03420     if (s->flags & SEC_LOAD)    /* Only deal with loadable sections.  */
03421       {
03422         bintotal += bfd_get_section_size (s);
03423         final = (s->vma + bfd_get_section_size (s));
03424 
03425         printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name,
03426                          (unsigned int) s->vma,
03427                          (unsigned int) (s->vma + bfd_get_section_size (s)));
03428         gdb_flush (gdb_stdout);
03429 
03430         /* Output the starting address.  */
03431         sprintf (buffer, "/A");
03432         reclen = pmon_makeb64 (s->vma, &buffer[2], 36, &csum);
03433         buffer[2 + reclen] = '\n';
03434         buffer[3 + reclen] = '\0';
03435         reclen += 3;    /* For the initial escape code and carriage return.  */
03436         pmon_download (buffer, reclen);
03437         finished = pmon_check_ack ("/A");
03438 
03439         if (!finished)
03440           {
03441             unsigned int binamount;
03442             unsigned int zerofill = 0;
03443             char *bp = buffer;
03444             unsigned int i;
03445 
03446             reclen = 0;
03447 
03448             for (i = 0;
03449                  i < bfd_get_section_size (s) && !finished;
03450                  i += binamount)
03451               {
03452                 int binptr = 0;
03453 
03454                 binamount = min (BINCHUNK, bfd_get_section_size (s) - i);
03455 
03456                 bfd_get_section_contents (abfd, s, binbuf, i, binamount);
03457 
03458                 /* This keeps a rolling checksum, until we decide to output
03459                    the line: */
03460                 for (; ((binamount - binptr) > 0);)
03461                   {
03462                     pmon_make_fastrec (&bp, binbuf, &binptr, binamount, 
03463                                        &reclen, &csum, &zerofill);
03464                     if (reclen >= (MAXRECSIZE - CHECKSIZE))
03465                       {
03466                         reclen = pmon_checkset (reclen, &bp, &csum);
03467                         pmon_download (buffer, reclen);
03468                         finished = pmon_check_ack ("data record");
03469                         if (finished)
03470                           {
03471                             zerofill = 0;       /* Do not transmit pending
03472                                                    zerofills.  */
03473                             break;
03474                           }
03475 
03476                         if (deprecated_ui_load_progress_hook)
03477                           deprecated_ui_load_progress_hook (s->name, i);
03478 
03479                         if (hashmark)
03480                           {
03481                             putchar_unfiltered ('#');
03482                             gdb_flush (gdb_stdout);
03483                           }
03484 
03485                         bp = buffer;
03486                         reclen = 0;     /* buffer processed */
03487                       }
03488                   }
03489               }
03490 
03491             /* Ensure no out-standing zerofill requests: */
03492             if (zerofill != 0)
03493               reclen = pmon_zeroset (reclen, &bp, &zerofill, &csum);
03494 
03495             /* and then flush the line: */
03496             if (reclen > 0)
03497               {
03498                 reclen = pmon_checkset (reclen, &bp, &csum);
03499                 /* Currently pmon_checkset outputs the line terminator by
03500                    default, so we write out the buffer so far: */
03501                 pmon_download (buffer, reclen);
03502                 finished = pmon_check_ack ("record remnant");
03503               }
03504           }
03505 
03506         putchar_unfiltered ('\n');
03507       }
03508 
03509   /* Terminate the transfer.  We know that we have an empty output
03510      buffer at this point.  */
03511   sprintf (buffer, "/E/E\n");   /* Include dummy padding characters.  */
03512   reclen = strlen (buffer);
03513   pmon_download (buffer, reclen);
03514 
03515   if (finished)
03516     {                           /* Ignore the termination message: */
03517       serial_flush_input (udp_in_use ? udp_desc : mips_desc);
03518     }
03519   else
03520     {                           /* Deal with termination message: */
03521       pmon_end_download (final, bintotal);
03522     }
03523 
03524   do_cleanups (cleanup);
03525   return;
03526 }
03527 
03528 /* mips_load -- download a file.  */
03529 
03530 static void
03531 mips_load (char *file, int from_tty)
03532 {
03533   struct regcache *regcache;
03534 
03535   /* Get the board out of remote debugging mode.  */
03536   if (mips_exit_debug ())
03537     error (_("mips_load:  Couldn't get into monitor mode."));
03538 
03539   if (mips_monitor != MON_IDT)
03540     pmon_load_fast (file);
03541   else
03542     mips_load_srec (file);
03543 
03544   mips_initialize ();
03545 
03546   /* Finally, make the PC point at the start address.  */
03547   regcache = get_current_regcache ();
03548   if (mips_monitor != MON_IDT)
03549     {
03550       /* Work around problem where PMON monitor updates the PC after a load
03551          to a different value than GDB thinks it has.  The following ensures
03552          that the regcache_write_pc() WILL update the PC value: */
03553       regcache_invalidate (regcache,
03554                            mips_regnum (get_regcache_arch (regcache))->pc);
03555     }
03556   if (exec_bfd)
03557     regcache_write_pc (regcache, bfd_get_start_address (exec_bfd));
03558 }
03559 
03560 /* Check to see if a thread is still alive.  */
03561  
03562 static int
03563 mips_thread_alive (struct target_ops *ops, ptid_t ptid)
03564 {
03565   if (ptid_equal (ptid, remote_mips_ptid))
03566     /* The monitor's task is always alive.  */
03567     return 1;
03568 
03569   return 0;
03570 }
03571 
03572 /* Convert a thread ID to a string.  Returns the string in a static
03573    buffer.  */
03574 
03575 static char *
03576 mips_pid_to_str (struct target_ops *ops, ptid_t ptid)
03577 {
03578   static char buf[64];
03579 
03580   if (ptid_equal (ptid, remote_mips_ptid))
03581     {
03582       xsnprintf (buf, sizeof buf, "Thread <main>");
03583       return buf;
03584     }
03585 
03586   return normal_pid_to_str (ptid);
03587 }
03588 
03589 /* Pass the command argument as a packet to PMON verbatim.  */
03590 
03591 static void
03592 pmon_command (char *args, int from_tty)
03593 {
03594   char buf[DATA_MAXLEN + 1];
03595   int rlen;
03596 
03597   sprintf (buf, "0x0 %s", args);
03598   mips_send_packet (buf, 1);
03599   printf_filtered ("Send packet: %s\n", buf);
03600 
03601   rlen = mips_receive_packet (buf, 1, mips_receive_wait);
03602   buf[rlen] = '\0';
03603   printf_filtered ("Received packet: %s\n", buf);
03604 }
03605 
03606 /* -Wmissing-prototypes */
03607 extern initialize_file_ftype _initialize_remote_mips;
03608 
03609 /* Initialize mips_ops, lsi_ops, ddb_ops, pmon_ops, and rockhopper_ops.
03610    Create target specific commands and perform other initializations
03611    specific to this file.  */
03612 
03613 void
03614 _initialize_remote_mips (void)
03615 {
03616   /* Initialize the fields in mips_ops that are common to all four targets.  */
03617   mips_ops.to_longname = "Remote MIPS debugging over serial line";
03618   mips_ops.to_close = mips_close;
03619   mips_ops.to_detach = mips_detach;
03620   mips_ops.to_resume = mips_resume;
03621   mips_ops.to_fetch_registers = mips_fetch_registers;
03622   mips_ops.to_store_registers = mips_store_registers;
03623   mips_ops.to_prepare_to_store = mips_prepare_to_store;
03624   mips_ops.deprecated_xfer_memory = mips_xfer_memory;
03625   mips_ops.to_files_info = mips_files_info;
03626   mips_ops.to_insert_breakpoint = mips_insert_breakpoint;
03627   mips_ops.to_remove_breakpoint = mips_remove_breakpoint;
03628   mips_ops.to_insert_watchpoint = mips_insert_watchpoint;
03629   mips_ops.to_remove_watchpoint = mips_remove_watchpoint;
03630   mips_ops.to_stopped_by_watchpoint = mips_stopped_by_watchpoint;
03631   mips_ops.to_can_use_hw_breakpoint = mips_can_use_watchpoint;
03632   mips_ops.to_kill = mips_kill;
03633   mips_ops.to_load = mips_load;
03634   mips_ops.to_create_inferior = mips_create_inferior;
03635   mips_ops.to_mourn_inferior = mips_mourn_inferior;
03636   mips_ops.to_thread_alive = mips_thread_alive;
03637   mips_ops.to_pid_to_str = mips_pid_to_str;
03638   mips_ops.to_log_command = serial_log_command;
03639   mips_ops.to_stratum = process_stratum;
03640   mips_ops.to_has_all_memory = default_child_has_all_memory;
03641   mips_ops.to_has_memory = default_child_has_memory;
03642   mips_ops.to_has_stack = default_child_has_stack;
03643   mips_ops.to_has_registers = default_child_has_registers;
03644   mips_ops.to_has_execution = default_child_has_execution;
03645   mips_ops.to_magic = OPS_MAGIC;
03646 
03647   /* Copy the common fields to all four target vectors.  */
03648   rockhopper_ops = pmon_ops = ddb_ops = lsi_ops = mips_ops;
03649 
03650   /* Initialize target-specific fields in the target vectors.  */
03651   mips_ops.to_shortname = "mips";
03652   mips_ops.to_doc = "\
03653 Debug a board using the MIPS remote debugging protocol over a serial line.\n\
03654 The argument is the device it is connected to or, if it contains a colon,\n\
03655 HOST:PORT to access a board over a network";
03656   mips_ops.to_open = mips_open;
03657   mips_ops.to_wait = mips_wait;
03658 
03659   pmon_ops.to_shortname = "pmon";
03660   pmon_ops.to_doc = "\
03661 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
03662 line. The argument is the device it is connected to or, if it contains a\n\
03663 colon, HOST:PORT to access a board over a network";
03664   pmon_ops.to_open = pmon_open;
03665   pmon_ops.to_wait = mips_wait;
03666 
03667   ddb_ops.to_shortname = "ddb";
03668   ddb_ops.to_doc = "\
03669 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
03670 line. The first argument is the device it is connected to or, if it contains\n\
03671 a colon, HOST:PORT to access a board over a network.  The optional second\n\
03672 parameter is the temporary file in the form HOST:FILENAME to be used for\n\
03673 TFTP downloads to the board.  The optional third parameter is the local name\n\
03674 of the TFTP temporary file, if it differs from the filename seen by the board.";
03675   ddb_ops.to_open = ddb_open;
03676   ddb_ops.to_wait = mips_wait;
03677 
03678   rockhopper_ops.to_shortname = "rockhopper";
03679   rockhopper_ops.to_doc = ddb_ops.to_doc;
03680   rockhopper_ops.to_open = rockhopper_open;
03681   rockhopper_ops.to_wait = mips_wait;
03682 
03683   lsi_ops.to_shortname = "lsi";
03684   lsi_ops.to_doc = pmon_ops.to_doc;
03685   lsi_ops.to_open = lsi_open;
03686   lsi_ops.to_wait = mips_wait;
03687 
03688   /* Add the targets.  */
03689   add_target (&mips_ops);
03690   add_target (&pmon_ops);
03691   add_target (&ddb_ops);
03692   add_target (&lsi_ops);
03693   add_target (&rockhopper_ops);
03694 
03695   add_setshow_zinteger_cmd ("timeout", no_class, &mips_receive_wait, _("\
03696 Set timeout in seconds for remote MIPS serial I/O."), _("\
03697 Show timeout in seconds for remote MIPS serial I/O."), NULL,
03698                             NULL,
03699                             NULL, /* FIXME: i18n: */
03700                             &setlist, &showlist);
03701 
03702   add_setshow_zinteger_cmd ("retransmit-timeout", no_class,
03703                             &mips_retransmit_wait, _("\
03704 Set retransmit timeout in seconds for remote MIPS serial I/O."), _("\
03705 Show retransmit timeout in seconds for remote MIPS serial I/O."), _("\
03706 This is the number of seconds to wait for an acknowledgement to a packet\n\
03707 before resending the packet."),
03708                             NULL,
03709                             NULL, /* FIXME: i18n: */
03710                             &setlist, &showlist);
03711 
03712   add_setshow_zinteger_cmd ("syn-garbage-limit", no_class,
03713                             &mips_syn_garbage,  _("\
03714 Set the maximum number of characters to ignore when scanning for a SYN."), _("\
03715 Show the maximum number of characters to ignore when scanning for a SYN."), _("\
03716 This is the maximum number of characters GDB will ignore when trying to\n\
03717 synchronize with the remote system.  A value of -1 means that there is no\n\
03718 limit. (Note that these characters are printed out even though they are\n\
03719 ignored.)"),
03720                             NULL,
03721                             NULL, /* FIXME: i18n: */
03722                             &setlist, &showlist);
03723 
03724   add_setshow_string_cmd ("monitor-prompt", class_obscure,
03725                           &mips_monitor_prompt, _("\
03726 Set the prompt that GDB expects from the monitor."), _("\
03727 Show the prompt that GDB expects from the monitor."), NULL,
03728                           NULL,
03729                           NULL, /* FIXME: i18n: */
03730                           &setlist, &showlist);
03731 
03732   add_setshow_zinteger_cmd ("monitor-warnings", class_obscure,
03733                             &monitor_warnings, _("\
03734 Set printing of monitor warnings."), _("\
03735 Show printing of monitor warnings."), _("\
03736 When enabled, monitor warnings about hardware breakpoints will be displayed."),
03737                             NULL,
03738                             NULL, /* FIXME: i18n: */
03739                             &setlist, &showlist);
03740 
03741   add_com ("pmon", class_obscure, pmon_command,
03742            _("Send a packet to PMON (must be in debug mode)."));
03743 
03744   add_setshow_boolean_cmd ("mask-address", no_class, &mask_address_p, _("\
03745 Set zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
03746 Show zeroing of upper 32 bits of 64-bit addresses when talking to PMON targets."), _("\
03747 Use \"on\" to enable the masking and \"off\" to disable it."),
03748                            NULL,
03749                            NULL, /* FIXME: i18n: */
03750                            &setlist, &showlist);
03751   remote_mips_ptid = ptid_build (42000, 0, 42000);
03752 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines