* values.c (unpack_double): Make it compile with MSVC++ 2.x.
[platform/upstream/binutils.git] / gdb / remote-mips.c
1 /* Remote debugging interface for MIPS remote debugging protocol.
2    Copyright 1993, 1994, 1995 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.  Written by Ian Lance Taylor
4    <ian@cygnus.com>.
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "bfd.h"
25 #include "symfile.h"
26 #include "wait.h"
27 #include "gdbcmd.h"
28 #include "gdbcore.h"
29 #include "serial.h"
30 #include "target.h"
31 #include "remote-utils.h"
32 #include "gdb_string.h"
33
34 #include <signal.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #ifdef ANSI_PROTOTYPES
38 #include <stdarg.h>
39 #else
40 #include <varargs.h>
41 #endif
42
43 /* Microsoft C's stat.h doesn't define all the POSIX file modes.  */
44 #ifndef S_IROTH
45 #define S_IROTH S_IREAD
46 #endif
47
48 extern void mips_set_processor_type_command PARAMS ((char *, int));
49
50 \f
51 /* Prototypes for local functions.  */
52
53 static int mips_readchar PARAMS ((int timeout));
54
55 static int mips_receive_header PARAMS ((unsigned char *hdr, int *pgarbage,
56                                         int ch, int timeout));
57
58 static int mips_receive_trailer PARAMS ((unsigned char *trlr, int *pgarbage,
59                                          int *pch, int timeout));
60
61 static int mips_cksum PARAMS ((const unsigned char *hdr,
62                                const unsigned char *data,
63                                int len));
64
65 static void mips_send_packet PARAMS ((const char *s, int get_ack));
66
67 static void mips_send_command PARAMS ((const char *cmd, int prompt));
68
69 static int mips_receive_packet PARAMS ((char *buff, int throw_error,
70                                         int timeout));
71
72 static CORE_ADDR mips_request PARAMS ((int cmd, CORE_ADDR addr,
73                                  CORE_ADDR data, int *perr, int timeout,
74                                  char *buff));
75
76 static void mips_initialize PARAMS ((void));
77
78 static void mips_open PARAMS ((char *name, int from_tty));
79
80 static void pmon_open PARAMS ((char *name, int from_tty));
81
82 static void ddb_open PARAMS ((char *name, int from_tty));
83
84 static void mips_close PARAMS ((int quitting));
85
86 static void mips_detach PARAMS ((char *args, int from_tty));
87
88 static void mips_resume PARAMS ((int pid, int step,
89                                  enum target_signal siggnal));
90
91 static int mips_wait PARAMS ((int pid, struct target_waitstatus *status));
92
93 static int pmon_wait PARAMS ((int pid, struct target_waitstatus *status));
94
95 static int mips_map_regno PARAMS ((int regno));
96
97 static void mips_fetch_registers PARAMS ((int regno));
98
99 static void mips_prepare_to_store PARAMS ((void));
100
101 static void mips_store_registers PARAMS ((int regno));
102
103 static unsigned int mips_fetch_word PARAMS ((CORE_ADDR addr));
104
105 static int mips_store_word PARAMS ((CORE_ADDR addr, unsigned int value,
106                                     char *old_contents));
107
108 static int mips_xfer_memory PARAMS ((CORE_ADDR memaddr, char *myaddr, int len,
109                                      int write, struct target_ops *ignore));
110
111 static void mips_files_info PARAMS ((struct target_ops *ignore));
112
113 static void mips_create_inferior PARAMS ((char *execfile, char *args,
114                                           char **env));
115
116 static void mips_mourn_inferior PARAMS ((void));
117
118 static int pmon_makeb64 PARAMS ((unsigned long v, char *p, int n, int *chksum));
119
120 static int pmon_zeroset PARAMS ((int recsize, char **buff, int *amount,
121                                  unsigned int *chksum));
122
123 static int pmon_checkset PARAMS ((int recsize, char **buff, int *value));
124
125 static void pmon_make_fastrec PARAMS ((char **outbuf, unsigned char *inbuf,
126                                        int *inptr, int inamount, int *recsize,
127                                        unsigned int *csum, unsigned int *zerofill));
128
129 static int pmon_check_ack PARAMS ((char *mesg));
130
131 static void pmon_start_download PARAMS ((void));
132
133 static void pmon_end_download PARAMS ((int final, int bintotal));
134
135 static void pmon_download PARAMS ((char *buffer, int length));
136
137 static void pmon_load_fast PARAMS ((char *file));
138
139 static void mips_load PARAMS ((char *file, int from_tty));
140
141 static int mips_make_srec PARAMS ((char *buffer, int type, CORE_ADDR memaddr,
142                                    unsigned char *myaddr, int len));
143
144 static int common_breakpoint PARAMS ((int cmd, CORE_ADDR addr, CORE_ADDR mask,
145                                       char *flags));
146
147 static void common_open PARAMS ((struct target_ops *ops, char *name,
148                                  int from_tty));
149 /* Forward declarations.  */
150 extern struct target_ops mips_ops;
151 extern struct target_ops pmon_ops;
152 extern struct target_ops ddb_ops;
153 \f
154 /* The MIPS remote debugging interface is built on top of a simple
155    packet protocol.  Each packet is organized as follows:
156
157    SYN  The first character is always a SYN (ASCII 026, or ^V).  SYN
158         may not appear anywhere else in the packet.  Any time a SYN is
159         seen, a new packet should be assumed to have begun.
160
161    TYPE_LEN
162         This byte contains the upper five bits of the logical length
163         of the data section, plus a single bit indicating whether this
164         is a data packet or an acknowledgement.  The documentation
165         indicates that this bit is 1 for a data packet, but the actual
166         board uses 1 for an acknowledgement.  The value of the byte is
167                 0x40 + (ack ? 0x20 : 0) + (len >> 6)
168         (we always have 0 <= len < 1024).  Acknowledgement packets do
169         not carry data, and must have a data length of 0.
170
171    LEN1 This byte contains the lower six bits of the logical length of
172         the data section.  The value is
173                 0x40 + (len & 0x3f)
174
175    SEQ  This byte contains the six bit sequence number of the packet.
176         The value is
177                 0x40 + seq
178         An acknowlegment packet contains the sequence number of the
179         packet being acknowledged plus 1 modulo 64.  Data packets are
180         transmitted in sequence.  There may only be one outstanding
181         unacknowledged data packet at a time.  The sequence numbers
182         are independent in each direction.  If an acknowledgement for
183         the previous packet is received (i.e., an acknowledgement with
184         the sequence number of the packet just sent) the packet just
185         sent should be retransmitted.  If no acknowledgement is
186         received within a timeout period, the packet should be
187         retransmitted.  This has an unfortunate failure condition on a
188         high-latency line, as a delayed acknowledgement may lead to an
189         endless series of duplicate packets.
190
191    DATA The actual data bytes follow.  The following characters are
192         escaped inline with DLE (ASCII 020, or ^P):
193                 SYN (026)       DLE S
194                 DLE (020)       DLE D
195                 ^C  (003)       DLE C
196                 ^S  (023)       DLE s
197                 ^Q  (021)       DLE q
198         The additional DLE characters are not counted in the logical
199         length stored in the TYPE_LEN and LEN1 bytes.
200
201    CSUM1
202    CSUM2
203    CSUM3
204         These bytes contain an 18 bit checksum of the complete
205         contents of the packet excluding the SEQ byte and the
206         CSUM[123] bytes.  The checksum is simply the twos complement
207         addition of all the bytes treated as unsigned characters.  The
208         values of the checksum bytes are:
209                 CSUM1: 0x40 + ((cksum >> 12) & 0x3f)
210                 CSUM2: 0x40 + ((cksum >> 6) & 0x3f)
211                 CSUM3: 0x40 + (cksum & 0x3f)
212
213    It happens that the MIPS remote debugging protocol always
214    communicates with ASCII strings.  Because of this, this
215    implementation doesn't bother to handle the DLE quoting mechanism,
216    since it will never be required.  */
217
218 /* The SYN character which starts each packet.  */
219 #define SYN '\026'
220
221 /* The 0x40 used to offset each packet (this value ensures that all of
222    the header and trailer bytes, other than SYN, are printable ASCII
223    characters).  */
224 #define HDR_OFFSET 0x40
225
226 /* The indices of the bytes in the packet header.  */
227 #define HDR_INDX_SYN 0
228 #define HDR_INDX_TYPE_LEN 1
229 #define HDR_INDX_LEN1 2
230 #define HDR_INDX_SEQ 3
231 #define HDR_LENGTH 4
232
233 /* The data/ack bit in the TYPE_LEN header byte.  */
234 #define TYPE_LEN_DA_BIT 0x20
235 #define TYPE_LEN_DATA 0
236 #define TYPE_LEN_ACK TYPE_LEN_DA_BIT
237
238 /* How to compute the header bytes.  */
239 #define HDR_SET_SYN(data, len, seq) (SYN)
240 #define HDR_SET_TYPE_LEN(data, len, seq) \
241   (HDR_OFFSET \
242    + ((data) ? TYPE_LEN_DATA : TYPE_LEN_ACK) \
243    + (((len) >> 6) & 0x1f))
244 #define HDR_SET_LEN1(data, len, seq) (HDR_OFFSET + ((len) & 0x3f))
245 #define HDR_SET_SEQ(data, len, seq) (HDR_OFFSET + (seq))
246
247 /* Check that a header byte is reasonable.  */
248 #define HDR_CHECK(ch) (((ch) & HDR_OFFSET) == HDR_OFFSET)
249
250 /* Get data from the header.  These macros evaluate their argument
251    multiple times.  */
252 #define HDR_IS_DATA(hdr) \
253   (((hdr)[HDR_INDX_TYPE_LEN] & TYPE_LEN_DA_BIT) == TYPE_LEN_DATA)
254 #define HDR_GET_LEN(hdr) \
255   ((((hdr)[HDR_INDX_TYPE_LEN] & 0x1f) << 6) + (((hdr)[HDR_INDX_LEN1] & 0x3f)))
256 #define HDR_GET_SEQ(hdr) ((unsigned int)(hdr)[HDR_INDX_SEQ] & 0x3f)
257
258 /* The maximum data length.  */
259 #define DATA_MAXLEN 1023
260
261 /* The trailer offset.  */
262 #define TRLR_OFFSET HDR_OFFSET
263
264 /* The indices of the bytes in the packet trailer.  */
265 #define TRLR_INDX_CSUM1 0
266 #define TRLR_INDX_CSUM2 1
267 #define TRLR_INDX_CSUM3 2
268 #define TRLR_LENGTH 3
269
270 /* How to compute the trailer bytes.  */
271 #define TRLR_SET_CSUM1(cksum) (TRLR_OFFSET + (((cksum) >> 12) & 0x3f))
272 #define TRLR_SET_CSUM2(cksum) (TRLR_OFFSET + (((cksum) >>  6) & 0x3f))
273 #define TRLR_SET_CSUM3(cksum) (TRLR_OFFSET + (((cksum)      ) & 0x3f))
274
275 /* Check that a trailer byte is reasonable.  */
276 #define TRLR_CHECK(ch) (((ch) & TRLR_OFFSET) == TRLR_OFFSET)
277
278 /* Get data from the trailer.  This evaluates its argument multiple
279    times.  */
280 #define TRLR_GET_CKSUM(trlr) \
281   ((((trlr)[TRLR_INDX_CSUM1] & 0x3f) << 12) \
282    + (((trlr)[TRLR_INDX_CSUM2] & 0x3f) <<  6) \
283    + ((trlr)[TRLR_INDX_CSUM3] & 0x3f))
284
285 /* The sequence number modulos.  */
286 #define SEQ_MODULOS (64)
287
288 /* PMON commands to load from the serial port or UDP socket.  */
289 #define LOAD_CMD        "load -b -s tty0\r"
290 #define LOAD_CMD_UDP    "load -b -s udp\r"
291
292 enum mips_monitor_type {
293   /* IDT/SIM monitor being used: */
294   MON_IDT,
295   /* PMON monitor being used: */
296   MON_PMON,   /* 3.0.83 [COGENT,EB,FP,NET] Algorithmics Ltd. Nov  9 1995 17:19:50 */
297   MON_DDB,  /* 2.7.473 [DDBVR4300,EL,FP,NET] Risq Modular Systems,  Thu Jun 6 09:28:40 PDT 1996 */
298   /* Last and unused value, for sizing vectors, etc. */
299   MON_LAST
300 };
301 static enum mips_monitor_type mips_monitor = MON_LAST;
302
303 /* The default monitor prompt text: */
304 static char *mips_monitor_prompt = TARGET_MONITOR_PROMPT;
305 /* For the Cogent PMON world this is still not ideal. The default
306    prompt is "PMON> ", unfortunately the user can change the prompt
307    and the new prompt will survive over a power-cycle (EEPROM). This
308    means that the code should really force the monitor prompt to a
309    known value as the very first action, and that the
310    "mips_monitor_prompt" support is not needed... since the prompt
311    could be explicitly set to TARGET_MONITOR_PROMPT (even though it
312    may be the prompt for a different monitor). However, this will
313    require changing the mips_initialize reset sequence. (TODO) */
314
315 /* Set to 1 if the target is open.  */
316 static int mips_is_open;
317
318 /* Currently active target description (if mips_is_open == 1) */
319 static struct target_ops *current_ops;
320
321 /* Set to 1 while the connection is being initialized.  */
322 static int mips_initializing;
323
324 /* The next sequence number to send.  */
325 static unsigned int mips_send_seq;
326
327 /* The next sequence number we expect to receive.  */
328 static unsigned int mips_receive_seq;
329
330 /* The time to wait before retransmitting a packet, in seconds.  */
331 static int mips_retransmit_wait = 3;
332
333 /* The number of times to try retransmitting a packet before giving up.  */
334 static int mips_send_retries = 10;
335
336 /* The number of garbage characters to accept when looking for an
337    SYN for the next packet.  */
338 static int mips_syn_garbage = 1050;
339
340 /* The time to wait for a packet, in seconds.  */
341 static int mips_receive_wait = 5;
342
343 /* Set if we have sent a packet to the board but have not yet received
344    a reply.  */
345 static int mips_need_reply = 0;
346
347 /* Handle used to access serial I/O stream.  */
348 static serial_t mips_desc;
349
350 /* UDP handle used to download files to target.  */
351 static serial_t udp_desc;
352 static int udp_in_use;
353
354 /* TFTP filename used to download files to DDB board, in the form
355    host:filename.  */
356 static char *tftp_name;         /* host:filename */
357 static char *tftp_localname;    /* filename portion of above */
358 static int tftp_in_use;
359 static FILE *tftp_file;
360
361 /* Counts the number of times the user tried to interrupt the target (usually
362    via ^C.  */
363 static int interrupt_count;
364
365 /* If non-zero, means that the target is running. */
366 static int mips_wait_flag = 0;
367
368 /* If non-zero, monitor supports breakpoint commands. */
369 static monitor_supports_breakpoints = 0;
370
371 /* Data cache header.  */
372
373 #if 0   /* not used (yet?) */
374 static DCACHE *mips_dcache;
375 #endif
376
377 /* Non-zero means that we've just hit a read or write watchpoint */
378 static int hit_watchpoint;
379
380 static void
381 close_ports()
382 {
383   mips_is_open = 0;
384   SERIAL_CLOSE (mips_desc);
385
386   if (udp_in_use)
387     {
388       SERIAL_CLOSE (udp_desc);
389       udp_in_use = 0;
390     }
391   tftp_in_use = 0;
392 }
393     
394 /* Handle low-level error that we can't recover from.  Note that just
395    error()ing out from target_wait or some such low-level place will cause
396    all hell to break loose--the rest of GDB will tend to get left in an
397    inconsistent state.  */
398
399 static NORETURN void
400 #ifdef ANSI_PROTOTYPES
401 mips_error (char *string, ...)
402 #else
403 mips_error (va_alist)
404      va_dcl
405 #endif
406 {
407   va_list args;
408
409 #ifdef ANSI_PROTOTYPES
410   va_start (args, string);
411 #else
412   char *string;
413   va_start (args);
414   string = va_arg (args, char *);
415 #endif
416  
417   target_terminal_ours ();
418   wrap_here("");                        /* Force out any buffered output */
419   gdb_flush (gdb_stdout);
420   if (error_pre_print)
421     fprintf_filtered (gdb_stderr, error_pre_print);
422   vfprintf_filtered (gdb_stderr, string, args);
423   fprintf_filtered (gdb_stderr, "\n");
424   va_end (args);
425   gdb_flush (gdb_stderr);
426
427   /* Clean up in such a way that mips_close won't try to talk to the
428      board (it almost surely won't work since we weren't able to talk to
429      it).  */
430   close_ports ();
431
432   printf_unfiltered ("Ending remote MIPS debugging.\n");
433   target_mourn_inferior ();
434
435   return_to_top_level (RETURN_ERROR);
436 }
437
438 /* putc_readable - print a character, displaying non-printable chars in
439    ^x notation or in hex.  */
440
441 static void
442 putc_readable (ch)
443      int ch;
444 {
445   if (ch == '\n')
446     putchar_unfiltered ('\n');
447   else if (ch == '\r')
448     printf_unfiltered ("\\r");
449   else if (ch < 0x20)   /* ASCII control character */
450     printf_unfiltered ("^%c", ch + '@');
451   else if (ch >= 0x7f)  /* non-ASCII characters (rubout or greater) */
452     printf_unfiltered ("[%02x]", ch & 0xff);
453   else
454     putchar_unfiltered (ch);
455 }
456
457
458 /* puts_readable - print a string, displaying non-printable chars in
459    ^x notation or in hex.  */
460
461 static void
462 puts_readable (string)
463      char *string;
464 {
465   int c;
466
467   while ((c = *string++) != '\0')
468     putc_readable (c);
469 }
470
471
472 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
473    timed out.  TIMEOUT specifies timeout value in seconds.
474 */
475
476 int
477 mips_expect_timeout (string, timeout)
478      char *string;
479      int timeout;
480 {
481   char *p = string;
482
483   if (remote_debug)
484     {
485       printf_unfiltered ("Expected \"");
486       puts_readable (string);
487       printf_unfiltered ("\", got \"");
488     }
489
490   immediate_quit = 1;
491   while (1)
492     {
493       int c;
494
495 /* Must use SERIAL_READCHAR here cuz mips_readchar would get confused if we
496    were waiting for the mips_monitor_prompt... */
497
498       c = SERIAL_READCHAR (mips_desc, timeout);
499
500       if (c == SERIAL_TIMEOUT)
501         {
502           if (remote_debug)
503             printf_unfiltered ("\": FAIL\n");
504           return 0;
505         }
506
507       if (remote_debug)
508         putc_readable (c);
509
510       if (c == *p++)
511         {       
512           if (*p == '\0')
513             {
514               immediate_quit = 0;
515               if (remote_debug)
516               printf_unfiltered ("\": OK\n");
517               return 1;
518             }
519         }
520       else
521         {
522           p = string;
523           if (c == *p)
524             p++;
525         }
526     }
527 }
528
529 /* Wait until STRING shows up in mips_desc.  Returns 1 if successful, else 0 if
530    timed out.  The timeout value is hard-coded to 2 seconds.  Use
531    mips_expect_timeout if a different timeout value is needed.
532 */
533
534 int
535 mips_expect (string)
536      char *string;
537 {
538     return mips_expect_timeout (string, 2);
539 }
540
541 /* Read the required number of characters into the given buffer (which
542    is assumed to be large enough). The only failure is a timeout. */
543 int
544 mips_getstring (string, n)
545      char *string;
546      int n;
547 {
548   char *p = string;
549   int c;
550
551   immediate_quit = 1;
552   while (n > 0)
553     {
554       c = SERIAL_READCHAR (mips_desc, 2);
555
556       if (c == SERIAL_TIMEOUT) {
557         fprintf_unfiltered (stderr, "Failed to read %d characters from target (TIMEOUT)\n", n);
558         return 0;
559       }
560
561       *p++ = c;
562       n--;
563     }
564
565   return 1;
566 }
567
568 /* Read a character from the remote, aborting on error.  Returns
569    SERIAL_TIMEOUT on timeout (since that's what SERIAL_READCHAR
570    returns).  FIXME: If we see the string mips_monitor_prompt from
571    the board, then we are debugging on the main console port, and we
572    have somehow dropped out of remote debugging mode.  In this case,
573    we automatically go back in to remote debugging mode.  This is a
574    hack, put in because I can't find any way for a program running on
575    the remote board to terminate without also ending remote debugging
576    mode.  I assume users won't have any trouble with this; for one
577    thing, the IDT documentation generally assumes that the remote
578    debugging port is not the console port.  This is, however, very
579    convenient for DejaGnu when you only have one connected serial
580    port.  */
581
582 static int
583 mips_readchar (timeout)
584      int timeout;
585 {
586   int ch;
587   static int state = 0;
588   static int mips_monitor_prompt_len = -1;
589
590   /* NASTY, since we assume that the prompt does not change after the
591      first mips_readchar call: */
592   if (mips_monitor_prompt_len == -1)
593    mips_monitor_prompt_len = strlen(mips_monitor_prompt);
594
595 #ifdef MAINTENANCE_CMDS
596   {
597     int i;
598
599     i = timeout;
600     if (i == -1 && watchdog > 0)
601      i = watchdog;
602   }
603 #endif
604
605   if (state == mips_monitor_prompt_len)
606     timeout = 1;
607   ch = SERIAL_READCHAR (mips_desc, timeout);
608 #ifdef MAINTENANCE_CMDS
609   if (ch == SERIAL_TIMEOUT && timeout == -1) /* Watchdog went off */
610     {
611       target_mourn_inferior ();
612       error ("Watchdog has expired.  Target detached.\n");
613     }
614 #endif
615   if (ch == SERIAL_EOF)
616     mips_error ("End of file from remote");
617   if (ch == SERIAL_ERROR)
618     mips_error ("Error reading from remote: %s", safe_strerror (errno));
619   if (remote_debug > 1)
620     {
621       /* Don't use _filtered; we can't deal with a QUIT out of
622          target_wait, and I think this might be called from there.  */
623       if (ch != SERIAL_TIMEOUT)
624         printf_unfiltered ("Read '%c' %d 0x%x\n", ch, ch, ch);
625       else
626         printf_unfiltered ("Timed out in read\n");
627     }
628
629   /* If we have seen mips_monitor_prompt and we either time out, or
630      we see a @ (which was echoed from a packet we sent), reset the
631      board as described above.  The first character in a packet after
632      the SYN (which is not echoed) is always an @ unless the packet is
633      more than 64 characters long, which ours never are.  */
634   if ((ch == SERIAL_TIMEOUT || ch == '@')
635       && state == mips_monitor_prompt_len
636       && ! mips_initializing)
637     {
638       if (remote_debug > 0)
639         /* Don't use _filtered; we can't deal with a QUIT out of
640            target_wait, and I think this might be called from there.  */
641         printf_unfiltered ("Reinitializing MIPS debugging mode\n");
642
643       mips_need_reply = 0;
644       mips_initialize ();
645
646       state = 0;
647
648       /* At this point, about the only thing we can do is abort the command
649          in progress and get back to command level as quickly as possible. */
650
651       error ("Remote board reset, debug protocol re-initialized.");
652     }
653
654   if (ch == mips_monitor_prompt[state])
655     ++state;
656   else
657     state = 0;
658
659   return ch;
660 }
661
662 /* Get a packet header, putting the data in the supplied buffer.
663    PGARBAGE is a pointer to the number of garbage characters received
664    so far.  CH is the last character received.  Returns 0 for success,
665    or -1 for timeout.  */
666
667 static int
668 mips_receive_header (hdr, pgarbage, ch, timeout)
669      unsigned char *hdr;
670      int *pgarbage;
671      int ch;
672      int timeout;
673 {
674   int i;
675
676   while (1)
677     {
678       /* Wait for a SYN.  mips_syn_garbage is intended to prevent
679          sitting here indefinitely if the board sends us one garbage
680          character per second.  ch may already have a value from the
681          last time through the loop.  */
682       while (ch != SYN)
683         {
684           ch = mips_readchar (timeout);
685           if (ch == SERIAL_TIMEOUT)
686            return -1;
687           if (ch != SYN)
688             {
689               /* Printing the character here lets the user of gdb see
690                  what the program is outputting, if the debugging is
691                  being done on the console port.  Don't use _filtered;
692                  we can't deal with a QUIT out of target_wait.  */
693               if (! mips_initializing || remote_debug > 0)
694                 {
695                   putc_readable (ch);
696                   gdb_flush (gdb_stdout);
697                 }
698
699               ++*pgarbage;
700               if (mips_syn_garbage > 0
701                   && *pgarbage > mips_syn_garbage)
702                 mips_error ("Debug protocol failure:  more than %d characters before a sync.", 
703                             mips_syn_garbage);
704             }
705         }
706
707       /* Get the packet header following the SYN.  */
708       for (i = 1; i < HDR_LENGTH; i++)
709         {
710           ch = mips_readchar (timeout);
711           if (ch == SERIAL_TIMEOUT)
712             return -1;
713           /* Make sure this is a header byte.  */
714           if (ch == SYN || ! HDR_CHECK (ch))
715             break;
716
717           hdr[i] = ch;
718         }
719
720       /* If we got the complete header, we can return.  Otherwise we
721          loop around and keep looking for SYN.  */
722       if (i >= HDR_LENGTH)
723         return 0;
724     }
725 }
726
727 /* Get a packet header, putting the data in the supplied buffer.
728    PGARBAGE is a pointer to the number of garbage characters received
729    so far.  The last character read is returned in *PCH.  Returns 0
730    for success, -1 for timeout, -2 for error.  */
731
732 static int
733 mips_receive_trailer (trlr, pgarbage, pch, timeout)
734      unsigned char *trlr;
735      int *pgarbage;
736      int *pch;
737      int timeout;
738 {
739   int i;
740   int ch;
741
742   for (i = 0; i < TRLR_LENGTH; i++)
743     {
744       ch = mips_readchar (timeout);
745       *pch = ch;
746       if (ch == SERIAL_TIMEOUT)
747         return -1;
748       if (! TRLR_CHECK (ch))
749         return -2;
750       trlr[i] = ch;
751     }
752   return 0;
753 }
754
755 /* Get the checksum of a packet.  HDR points to the packet header.
756    DATA points to the packet data.  LEN is the length of DATA.  */
757
758 static int
759 mips_cksum (hdr, data, len)
760      const unsigned char *hdr;
761      const unsigned char *data;
762      int len;
763 {
764   register const unsigned char *p;
765   register int c;
766   register int cksum;
767
768   cksum = 0;
769
770   /* The initial SYN is not included in the checksum.  */
771   c = HDR_LENGTH - 1;
772   p = hdr + 1;
773   while (c-- != 0)
774     cksum += *p++;
775   
776   c = len;
777   p = data;
778   while (c-- != 0)
779     cksum += *p++;
780
781   return cksum;
782 }
783
784 /* Send a packet containing the given ASCII string.  */
785
786 static void
787 mips_send_packet (s, get_ack)
788      const char *s;
789      int get_ack;
790 {
791   /* unsigned */ int len;
792   unsigned char *packet;
793   register int cksum;
794   int try;
795
796   len = strlen (s);
797   if (len > DATA_MAXLEN)
798     mips_error ("MIPS protocol data packet too long: %s", s);
799
800   packet = (unsigned char *) alloca (HDR_LENGTH + len + TRLR_LENGTH + 1);
801
802   packet[HDR_INDX_SYN] = HDR_SET_SYN (1, len, mips_send_seq);
803   packet[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (1, len, mips_send_seq);
804   packet[HDR_INDX_LEN1] = HDR_SET_LEN1 (1, len, mips_send_seq);
805   packet[HDR_INDX_SEQ] = HDR_SET_SEQ (1, len, mips_send_seq);
806
807   memcpy (packet + HDR_LENGTH, s, len);
808
809   cksum = mips_cksum (packet, packet + HDR_LENGTH, len);
810   packet[HDR_LENGTH + len + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
811   packet[HDR_LENGTH + len + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
812   packet[HDR_LENGTH + len + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
813
814   /* Increment the sequence number.  This will set mips_send_seq to
815      the sequence number we expect in the acknowledgement.  */
816   mips_send_seq = (mips_send_seq + 1) % SEQ_MODULOS;
817
818   /* We can only have one outstanding data packet, so we just wait for
819      the acknowledgement here.  Keep retransmitting the packet until
820      we get one, or until we've tried too many times.  */
821   for (try = 0; try < mips_send_retries; try++)
822     {
823       int garbage;
824       int ch;
825
826       if (remote_debug > 0)
827         {
828           /* Don't use _filtered; we can't deal with a QUIT out of
829              target_wait, and I think this might be called from there.  */
830           packet[HDR_LENGTH + len + TRLR_LENGTH] = '\0';
831           printf_unfiltered ("Writing \"%s\"\n", packet + 1);
832         }
833
834       if (SERIAL_WRITE (mips_desc, packet,
835                         HDR_LENGTH + len + TRLR_LENGTH) != 0)
836         mips_error ("write to target failed: %s", safe_strerror (errno));
837
838       if (! get_ack)
839         return;
840
841       garbage = 0;
842       ch = 0;
843       while (1)
844         {
845           unsigned char hdr[HDR_LENGTH + 1];
846           unsigned char trlr[TRLR_LENGTH + 1];
847           int err;
848           unsigned int seq;
849
850           /* Get the packet header.  If we time out, resend the data
851              packet.  */
852           err = mips_receive_header (hdr, &garbage, ch, mips_retransmit_wait);
853           if (err != 0)
854             break;
855
856           ch = 0;
857
858           /* If we get a data packet, assume it is a duplicate and
859              ignore it.  FIXME: If the acknowledgement is lost, this
860              data packet may be the packet the remote sends after the
861              acknowledgement.  */
862           if (HDR_IS_DATA (hdr)) {
863             int i;
864
865             /* Ignore any errors raised whilst attempting to ignore
866                packet. */
867
868             len = HDR_GET_LEN (hdr);
869
870             for (i = 0; i < len; i++)
871               {
872                 int rch;
873
874                 rch = mips_readchar (2);
875                 if (rch == SYN)
876                   {
877                     ch = SYN;
878                     break;
879                   }
880                 if (rch == SERIAL_TIMEOUT)
881                   break;
882                 /* ignore the character */
883               }
884
885             if (i == len)
886               (void) mips_receive_trailer (trlr, &garbage, &ch, 2);
887
888             /* We don't bother checking the checksum, or providing an
889                ACK to the packet. */
890             continue;
891           }
892
893           /* If the length is not 0, this is a garbled packet.  */
894           if (HDR_GET_LEN (hdr) != 0)
895             continue;
896
897           /* Get the packet trailer.  */
898           err = mips_receive_trailer (trlr, &garbage, &ch,
899                                       mips_retransmit_wait);
900
901           /* If we timed out, resend the data packet.  */
902           if (err == -1)
903             break;
904
905           /* If we got a bad character, reread the header.  */
906           if (err != 0)
907             continue;
908
909           /* If the checksum does not match the trailer checksum, this
910              is a bad packet; ignore it.  */
911           if (mips_cksum (hdr, (unsigned char *) NULL, 0)
912               != TRLR_GET_CKSUM (trlr))
913             continue;
914
915           if (remote_debug > 0)
916             {
917               hdr[HDR_LENGTH] = '\0';
918               trlr[TRLR_LENGTH] = '\0';
919               /* Don't use _filtered; we can't deal with a QUIT out of
920                  target_wait, and I think this might be called from there.  */
921               printf_unfiltered ("Got ack %d \"%s%s\"\n",
922                                HDR_GET_SEQ (hdr), hdr + 1, trlr);
923             }
924
925           /* If this ack is for the current packet, we're done.  */
926           seq = HDR_GET_SEQ (hdr);
927           if (seq == mips_send_seq)
928             return;
929
930           /* If this ack is for the last packet, resend the current
931              packet.  */
932           if ((seq + 1) % SEQ_MODULOS == mips_send_seq)
933             break;
934
935           /* Otherwise this is a bad ack; ignore it.  Increment the
936              garbage count to ensure that we do not stay in this loop
937              forever.  */
938           ++garbage;
939         }
940     }
941
942   mips_error ("Remote did not acknowledge packet");
943 }
944
945 /* Receive and acknowledge a packet, returning the data in BUFF (which
946    should be DATA_MAXLEN + 1 bytes).  The protocol documentation
947    implies that only the sender retransmits packets, so this code just
948    waits silently for a packet.  It returns the length of the received
949    packet.  If THROW_ERROR is nonzero, call error() on errors.  If not,
950    don't print an error message and return -1.  */
951
952 static int
953 mips_receive_packet (buff, throw_error, timeout)
954      char *buff;
955      int throw_error;
956      int timeout;
957 {
958   int ch;
959   int garbage;
960   int len;
961   unsigned char ack[HDR_LENGTH + TRLR_LENGTH + 1];
962   int cksum;
963
964   ch = 0;
965   garbage = 0;
966   while (1)
967     {
968       unsigned char hdr[HDR_LENGTH];
969       unsigned char trlr[TRLR_LENGTH];
970       int i;
971       int err;
972
973       if (mips_receive_header (hdr, &garbage, ch, timeout) != 0)
974         {
975           if (throw_error)
976             mips_error ("Timed out waiting for remote packet");
977           else
978             return -1;
979         }
980
981       ch = 0;
982
983       /* An acknowledgement is probably a duplicate; ignore it.  */
984       if (! HDR_IS_DATA (hdr))
985         {
986           len = HDR_GET_LEN (hdr);
987           /* Check if the length is valid for an ACK, we may aswell
988              try and read the remainder of the packet: */
989           if (len == 0)
990             {
991               /* Ignore the error condition, since we are going to
992                  ignore the packet anyway. */
993               (void) mips_receive_trailer (trlr, &garbage, &ch, timeout);
994             }
995           /* Don't use _filtered; we can't deal with a QUIT out of
996              target_wait, and I think this might be called from there.  */
997           if (remote_debug > 0)
998             printf_unfiltered ("Ignoring unexpected ACK\n");
999           continue;
1000         }
1001
1002       len = HDR_GET_LEN (hdr);
1003       for (i = 0; i < len; i++)
1004         {
1005           int rch;
1006
1007           rch = mips_readchar (timeout);
1008           if (rch == SYN)
1009             {
1010               ch = SYN;
1011               break;
1012             }
1013           if (rch == SERIAL_TIMEOUT)
1014             {
1015               if (throw_error)
1016                 mips_error ("Timed out waiting for remote packet");
1017               else
1018                 return -1;
1019             }
1020           buff[i] = rch;
1021         }
1022
1023       if (i < len)
1024         {
1025           /* Don't use _filtered; we can't deal with a QUIT out of
1026              target_wait, and I think this might be called from there.  */
1027           if (remote_debug > 0)
1028             printf_unfiltered ("Got new SYN after %d chars (wanted %d)\n",
1029                              i, len);
1030           continue;
1031         }
1032
1033       err = mips_receive_trailer (trlr, &garbage, &ch, timeout);
1034       if (err == -1)
1035         {
1036           if (throw_error)
1037             mips_error ("Timed out waiting for packet");
1038           else
1039             return -1;
1040         }
1041       if (err == -2)
1042         {
1043           /* Don't use _filtered; we can't deal with a QUIT out of
1044              target_wait, and I think this might be called from there.  */
1045           if (remote_debug > 0)
1046             printf_unfiltered ("Got SYN when wanted trailer\n");
1047           continue;
1048         }
1049
1050       /* If this is the wrong sequence number, ignore it.  */
1051       if (HDR_GET_SEQ (hdr) != mips_receive_seq)
1052         {
1053           /* Don't use _filtered; we can't deal with a QUIT out of
1054              target_wait, and I think this might be called from there.  */
1055           if (remote_debug > 0)
1056             printf_unfiltered ("Ignoring sequence number %d (want %d)\n",
1057                              HDR_GET_SEQ (hdr), mips_receive_seq);
1058           continue;
1059         }
1060
1061       if (mips_cksum (hdr, buff, len) == TRLR_GET_CKSUM (trlr))
1062         break;
1063
1064       if (remote_debug > 0)
1065         /* Don't use _filtered; we can't deal with a QUIT out of
1066            target_wait, and I think this might be called from there.  */
1067         printf_unfiltered ("Bad checksum; data %d, trailer %d\n",
1068                          mips_cksum (hdr, buff, len),
1069                          TRLR_GET_CKSUM (trlr));
1070
1071       /* The checksum failed.  Send an acknowledgement for the
1072          previous packet to tell the remote to resend the packet.  */
1073       ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1074       ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1075       ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1076       ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1077
1078       cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
1079
1080       ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1081       ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1082       ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1083
1084       if (remote_debug > 0)
1085         {
1086           ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1087           /* Don't use _filtered; we can't deal with a QUIT out of
1088              target_wait, and I think this might be called from there.  */
1089           printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1090                            ack + 1);
1091         }
1092
1093       if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1094         {
1095           if (throw_error)
1096             mips_error ("write to target failed: %s", safe_strerror (errno));
1097           else
1098             return -1;
1099         }
1100     }
1101
1102   if (remote_debug > 0)
1103     {
1104       buff[len] = '\0';
1105       /* Don't use _filtered; we can't deal with a QUIT out of
1106          target_wait, and I think this might be called from there.  */
1107       printf_unfiltered ("Got packet \"%s\"\n", buff);
1108     }
1109
1110   /* We got the packet.  Send an acknowledgement.  */
1111   mips_receive_seq = (mips_receive_seq + 1) % SEQ_MODULOS;
1112
1113   ack[HDR_INDX_SYN] = HDR_SET_SYN (0, 0, mips_receive_seq);
1114   ack[HDR_INDX_TYPE_LEN] = HDR_SET_TYPE_LEN (0, 0, mips_receive_seq);
1115   ack[HDR_INDX_LEN1] = HDR_SET_LEN1 (0, 0, mips_receive_seq);
1116   ack[HDR_INDX_SEQ] = HDR_SET_SEQ (0, 0, mips_receive_seq);
1117
1118   cksum = mips_cksum (ack, (unsigned char *) NULL, 0);
1119
1120   ack[HDR_LENGTH + TRLR_INDX_CSUM1] = TRLR_SET_CSUM1 (cksum);
1121   ack[HDR_LENGTH + TRLR_INDX_CSUM2] = TRLR_SET_CSUM2 (cksum);
1122   ack[HDR_LENGTH + TRLR_INDX_CSUM3] = TRLR_SET_CSUM3 (cksum);
1123
1124   if (remote_debug > 0)
1125     {
1126       ack[HDR_LENGTH + TRLR_LENGTH] = '\0';
1127       /* Don't use _filtered; we can't deal with a QUIT out of
1128          target_wait, and I think this might be called from there.  */
1129       printf_unfiltered ("Writing ack %d \"%s\"\n", mips_receive_seq,
1130                        ack + 1);
1131     }
1132
1133   if (SERIAL_WRITE (mips_desc, ack, HDR_LENGTH + TRLR_LENGTH) != 0)
1134     {
1135       if (throw_error)
1136         mips_error ("write to target failed: %s", safe_strerror (errno));
1137       else
1138         return -1;
1139     }
1140
1141   return len;
1142 }
1143 \f
1144 /* Optionally send a request to the remote system and optionally wait
1145    for the reply.  This implements the remote debugging protocol,
1146    which is built on top of the packet protocol defined above.  Each
1147    request has an ADDR argument and a DATA argument.  The following
1148    requests are defined:
1149
1150    \0   don't send a request; just wait for a reply
1151    i    read word from instruction space at ADDR
1152    d    read word from data space at ADDR
1153    I    write DATA to instruction space at ADDR
1154    D    write DATA to data space at ADDR
1155    r    read register number ADDR
1156    R    set register number ADDR to value DATA
1157    c    continue execution (if ADDR != 1, set pc to ADDR)
1158    s    single step (if ADDR != 1, set pc to ADDR)
1159
1160    The read requests return the value requested.  The write requests
1161    return the previous value in the changed location.  The execution
1162    requests return a UNIX wait value (the approximate signal which
1163    caused execution to stop is in the upper eight bits).
1164
1165    If PERR is not NULL, this function waits for a reply.  If an error
1166    occurs, it sets *PERR to 1 and sets errno according to what the
1167    target board reports.  */
1168
1169 static CORE_ADDR 
1170 mips_request (cmd, addr, data, perr, timeout, buff)
1171      int cmd;
1172      CORE_ADDR addr;
1173      CORE_ADDR data;
1174      int *perr;
1175      int timeout;
1176      char *buff;
1177 {
1178   char myBuff[DATA_MAXLEN + 1];
1179   int len;
1180   int rpid;
1181   char rcmd;
1182   int rerrflg;
1183   int rresponse;
1184
1185   if (buff == (char *) NULL)
1186     buff = myBuff;
1187
1188   if (cmd != '\0')
1189     {
1190       if (mips_need_reply)
1191         fatal ("mips_request: Trying to send command before reply");
1192       sprintf (buff, "0x0 %c 0x%s 0x%s", cmd, paddr_nz (addr), paddr_nz (data));
1193       mips_send_packet (buff, 1);
1194       mips_need_reply = 1;
1195     }
1196
1197   if (perr == (int *) NULL)
1198     return 0;
1199
1200   if (! mips_need_reply)
1201     fatal ("mips_request: Trying to get reply before command");
1202
1203   mips_need_reply = 0;
1204
1205   len = mips_receive_packet (buff, 1, timeout);
1206   buff[len] = '\0';
1207
1208   if (sscanf (buff, "0x%x %c 0x%x 0x%x",
1209               &rpid, &rcmd, &rerrflg, &rresponse) != 4
1210       || (cmd != '\0' && rcmd != cmd))
1211     mips_error ("Bad response from remote board");
1212
1213   if (rerrflg != 0)
1214     {
1215       *perr = 1;
1216
1217       /* FIXME: This will returns MIPS errno numbers, which may or may
1218          not be the same as errno values used on other systems.  If
1219          they stick to common errno values, they will be the same, but
1220          if they don't, they must be translated.  */
1221       errno = rresponse;
1222
1223       return 0;
1224     }
1225
1226   *perr = 0;
1227   return rresponse;
1228 }
1229
1230 static void
1231 mips_initialize_cleanups (arg)
1232      PTR arg;
1233 {
1234   mips_initializing = 0;
1235 }
1236
1237 static void
1238 mips_send_command (cmd, prompt)
1239      const char *cmd;
1240      int prompt;
1241 {
1242   SERIAL_WRITE (mips_desc, cmd, strlen(cmd));
1243   mips_expect (cmd);
1244   mips_expect ("\n");
1245   if (prompt)
1246     mips_expect (mips_monitor_prompt);
1247 }
1248
1249 /* Enter remote (dbx) debug mode: */
1250 static void
1251 mips_enter_debug ()
1252 {
1253   /* Reset the sequence numbers, ready for the new debug sequence: */
1254   mips_send_seq = 0;
1255   mips_receive_seq = 0;
1256
1257   if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
1258     mips_send_command ("debug\r", 0);
1259   else /* assume IDT monitor by default */
1260     mips_send_command ("db tty0\r", 0);
1261
1262   SERIAL_WRITE (mips_desc, "\r", sizeof "\r" - 1);
1263
1264   /* We don't need to absorb any spurious characters here, since the
1265      mips_receive_header will eat up a reasonable number of characters
1266      whilst looking for the SYN, however this avoids the "garbage"
1267      being displayed to the user. */
1268   if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
1269     mips_expect ("\r");
1270   
1271   {
1272     char buff[DATA_MAXLEN + 1];
1273     if (mips_receive_packet (buff, 1, 3) < 0)
1274       mips_error ("Failed to initialize (didn't receive packet).");
1275   }
1276 }
1277
1278 /* Exit remote (dbx) debug mode, returning to the monitor prompt: */
1279 static int
1280 mips_exit_debug ()
1281 {
1282   int err;
1283
1284   if (mips_monitor == MON_DDB)
1285     {
1286       /* The Ddb version of PMON exits immediately, so we do not get
1287          a reply to this command: */
1288       mips_request ('x', (unsigned int) 0, (unsigned int) 0, NULL,
1289                 mips_receive_wait, NULL);
1290       mips_need_reply = 0;
1291       if (!mips_expect (" break!"))
1292         return -1;
1293     }
1294   else
1295     mips_request ('x', (unsigned int) 0, (unsigned int) 0, &err,
1296                   mips_receive_wait, NULL);
1297
1298   if (mips_monitor == MON_PMON && !mips_expect ("Exiting remote debug mode"))
1299     return -1;
1300     
1301   if (mips_monitor == MON_DDB)
1302     {
1303       if (!mips_expect ("\n"))
1304         return -1;
1305     }
1306   else
1307     if (!mips_expect ("\r\n"))
1308       return -1;
1309
1310   if (!mips_expect (mips_monitor_prompt))
1311     return -1;
1312
1313   return 0;
1314 }
1315
1316 /* Initialize a new connection to the MIPS board, and make sure we are
1317    really connected.  */
1318
1319 static void
1320 mips_initialize ()
1321 {
1322   int err;
1323   struct cleanup *old_cleanups = make_cleanup (mips_initialize_cleanups, NULL);
1324   int j;
1325
1326   /* What is this code doing here?  I don't see any way it can happen, and
1327      it might mean mips_initializing didn't get cleared properly.
1328      So I'll make it a warning.  */
1329
1330   if (mips_initializing)
1331     {
1332       warning ("internal error: mips_initialize called twice");
1333       return;
1334     }
1335
1336   mips_wait_flag = 0;
1337   mips_initializing = 1;
1338
1339   /* At this point, the packit protocol isn't responding.  We'll try getting
1340      into the monitor, and restarting the protocol.  */
1341
1342   /* Force the system into the monitor.  After this we *should* be at
1343      the mips_monitor_prompt.  */
1344   if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
1345     j = 0; /* start by checking if we are already at the prompt */
1346   else
1347     j = 1; /* start by sending a break */
1348   for (; j <= 4; j++)
1349     {
1350       switch (j)
1351         {
1352         case 0:                 /* First, try sending a CR */
1353           SERIAL_FLUSH_INPUT (mips_desc);
1354           SERIAL_WRITE (mips_desc, "\r", 1);
1355           break;
1356         case 1:                 /* First, try sending a break */
1357           SERIAL_SEND_BREAK (mips_desc);
1358           break;
1359         case 2:                 /* Then, try a ^C */
1360           SERIAL_WRITE (mips_desc, "\003", 1);
1361           break;
1362         case 3:                 /* Then, try escaping from download */
1363           {
1364             if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
1365               {
1366                 char tbuff[7];
1367
1368                 /* We shouldn't need to send multiple termination
1369                    sequences, since the target performs line (or
1370                    block) reads, and then processes those
1371                    packets. In-case we were downloading a large packet
1372                    we flush the output buffer before inserting a
1373                    termination sequence. */
1374                 SERIAL_FLUSH_OUTPUT (mips_desc);
1375                 sprintf (tbuff, "\r/E/E\r");
1376                 SERIAL_WRITE (mips_desc, tbuff, 6);
1377               }
1378             else
1379               {
1380                 char srec[10];
1381                 int i;
1382
1383                 /* We are possibly in binary download mode, having
1384                    aborted in the middle of an S-record.  ^C won't
1385                    work because of binary mode.  The only reliable way
1386                    out is to send enough termination packets (8 bytes)
1387                    to fill up and then overflow the largest size
1388                    S-record (255 bytes in this case).  This amounts to
1389                    256/8 + 1 packets.
1390                    */
1391
1392                 mips_make_srec (srec, '7', 0, NULL, 0);
1393
1394                 for (i = 1; i <= 33; i++)
1395                   {
1396                     SERIAL_WRITE (mips_desc, srec, 8);
1397
1398                     if (SERIAL_READCHAR (mips_desc, 0) >= 0)
1399                       break;    /* Break immediatly if we get something from
1400                                    the board. */
1401                   }
1402               }
1403           }
1404           break;
1405         case 4:
1406           mips_error ("Failed to initialize.");
1407         }
1408
1409       if (mips_expect (mips_monitor_prompt))
1410         break;
1411     }
1412
1413   if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
1414     {
1415       /* Ensure the correct target state: */
1416       mips_send_command ("set regsize 64\r", -1);
1417       mips_send_command ("set hostport tty0\r", -1);
1418       mips_send_command ("set brkcmd \"\"\r", -1);
1419       /* Delete all the current breakpoints: */
1420       mips_send_command ("db *\r", -1);
1421       /* NOTE: PMON does not have breakpoint support through the
1422          "debug" mode, only at the monitor command-line. */
1423     }
1424
1425   mips_enter_debug ();
1426
1427   /* Clear all breakpoints: */
1428   if (common_breakpoint ('b', -1, 0, NULL))
1429    monitor_supports_breakpoints = 0;
1430   else
1431    monitor_supports_breakpoints = 1;
1432
1433   do_cleanups (old_cleanups);
1434
1435   /* If this doesn't call error, we have connected; we don't care if
1436      the request itself succeeds or fails.  */
1437
1438   mips_request ('r', (unsigned int) 0, (unsigned int) 0, &err,
1439                 mips_receive_wait, NULL);
1440   set_current_frame (create_new_frame (read_fp (), read_pc ()));
1441   select_frame (get_current_frame (), 0);
1442 }
1443
1444 /* Open a connection to the remote board.  */
1445 static void
1446 common_open (ops, name, from_tty)
1447      struct target_ops *ops;
1448      char *name;
1449      int from_tty;
1450 {
1451   char *ptype;
1452   char *serial_port_name;
1453   char *remote_name = 0;
1454   char *local_name = 0;
1455   char **argv;
1456
1457   if (name == 0)
1458     error (
1459 "To open a MIPS remote debugging connection, you need to specify what serial\n\
1460 device is attached to the target board (e.g., /dev/ttya).\n"
1461 "If you want to use TFTP to download to the board, specify the name of a\n"
1462 "temporary file to be used by GDB for downloads as the second argument.\n"
1463 "This filename must be in the form host:filename, where host is the name\n"
1464 "of the host running the TFTP server, and the file must be readable by the\n"
1465 "world.  If the local name of the temporary file differs from the name as\n"
1466 "seen from the board via TFTP, specify that name as the third parameter.\n");
1467
1468   /* Parse the serial port name, the optional TFTP name, and the
1469      optional local TFTP name.  */
1470   if ((argv = buildargv (name)) == NULL)
1471     nomem(0);
1472   make_cleanup (freeargv, (char *) argv);
1473
1474   serial_port_name = strsave (argv[0]);
1475   if (argv[1])                          /* remote TFTP name specified? */
1476     {
1477       remote_name = argv[1];
1478       if (argv[2])                      /* local TFTP filename specified? */
1479         local_name = argv[2];
1480     }
1481
1482   target_preopen (from_tty);
1483
1484   if (mips_is_open)
1485     unpush_target (current_ops);
1486
1487   /* Open and initialize the serial port.  */
1488   mips_desc = SERIAL_OPEN (serial_port_name);
1489   if (mips_desc == (serial_t) NULL)
1490     perror_with_name (serial_port_name);
1491
1492   if (baud_rate != -1)
1493     {
1494       if (SERIAL_SETBAUDRATE (mips_desc, baud_rate))
1495         {
1496           SERIAL_CLOSE (mips_desc);
1497           perror_with_name (serial_port_name);
1498         }
1499     }
1500
1501   SERIAL_RAW (mips_desc);
1502
1503   /* Open and initialize the optional download port.  If it is in the form
1504      hostname#portnumber, it's a UDP socket.  If it is in the form
1505      hostname:filename, assume it's the TFTP filename that must be
1506      passed to the DDB board to tell it where to get the load file.  */
1507   if (remote_name)
1508     {
1509       if (strchr (remote_name, '#'))
1510         {
1511           udp_desc = SERIAL_OPEN (remote_name);
1512           if (!udp_desc)
1513             perror_with_name ("Unable to open UDP port");
1514           udp_in_use = 1;
1515         }
1516       else
1517         {
1518           /* Save the remote and local names of the TFTP temp file.  If
1519              the user didn't specify a local name, assume it's the same
1520              as the part of the remote name after the "host:".  */
1521           if (tftp_name)
1522             free (tftp_name);
1523           if (tftp_localname)
1524             free (tftp_localname);
1525           if (local_name == NULL)
1526               if ((local_name = strchr (remote_name, ':')) != NULL)
1527                 local_name++;           /* skip over the colon */
1528           if (local_name == NULL)
1529             local_name = remote_name;   /* local name same as remote name */
1530           tftp_name = strsave (remote_name);
1531           tftp_localname = strsave (local_name);
1532           tftp_in_use = 1;
1533         }
1534     }
1535
1536   current_ops = ops;
1537   mips_is_open = 1;
1538
1539   mips_initialize ();
1540
1541   if (from_tty)
1542     printf_unfiltered ("Remote MIPS debugging using %s\n", serial_port_name);
1543
1544   /* Switch to using remote target now.  */
1545   push_target (ops);
1546
1547   /* FIXME: Should we call start_remote here?  */
1548
1549   /* Try to figure out the processor model if possible.  */
1550   ptype = mips_read_processor_type ();
1551   if (ptype)
1552     mips_set_processor_type_command (strsave (ptype), 0);
1553
1554 /* This is really the job of start_remote however, that makes an assumption
1555    that the target is about to print out a status message of some sort.  That
1556    doesn't happen here (in fact, it may not be possible to get the monitor to
1557    send the appropriate packet).  */
1558
1559   flush_cached_frames ();
1560   registers_changed ();
1561   stop_pc = read_pc ();
1562   set_current_frame (create_new_frame (read_fp (), stop_pc));
1563   select_frame (get_current_frame (), 0);
1564   print_stack_frame (selected_frame, -1, 1);
1565   free (serial_port_name);
1566 }
1567
1568 static void
1569 mips_open (name, from_tty)
1570      char *name;
1571      int from_tty;
1572 {
1573   mips_monitor = MON_IDT;
1574   common_open (&mips_ops, name, from_tty);
1575 }
1576
1577 static void
1578 pmon_open (name, from_tty)
1579      char *name;
1580      int from_tty;
1581 {
1582   /* The PMON monitor has a prompt different from the default
1583      "TARGET_MONITOR_PROMPT": */
1584   mips_monitor_prompt = "PMON> ";
1585   mips_monitor = MON_PMON;
1586   common_open (&pmon_ops, name, from_tty);
1587 }
1588
1589 static void
1590 ddb_open (name, from_tty)
1591      char *name;
1592      int from_tty;
1593 {
1594   /* The PMON monitor has a prompt different from the default
1595      "TARGET_MONITOR_PROMPT": */
1596   mips_monitor_prompt = "NEC010>";
1597   mips_monitor = MON_DDB;
1598   common_open (&ddb_ops, name, from_tty);
1599 }
1600
1601 /* Close a connection to the remote board.  */
1602
1603 static void
1604 mips_close (quitting)
1605      int quitting;
1606 {
1607   if (mips_is_open)
1608     {
1609       /* Get the board out of remote debugging mode.  */
1610       (void) mips_exit_debug ();
1611
1612       close_ports ();
1613     }
1614 }
1615
1616 /* Detach from the remote board.  */
1617
1618 static void
1619 mips_detach (args, from_tty)
1620      char *args;
1621      int from_tty;
1622 {
1623   if (args)
1624     error ("Argument given to \"detach\" when remotely debugging.");
1625
1626   pop_target ();
1627
1628   mips_close (1);
1629
1630   if (from_tty)
1631     printf_unfiltered ("Ending remote MIPS debugging.\n");
1632 }
1633
1634 /* Tell the target board to resume.  This does not wait for a reply
1635    from the board.  */
1636
1637 static void
1638 mips_resume (pid, step, siggnal)
1639      int pid, step;
1640      enum target_signal siggnal;
1641 {
1642
1643 /* start-sanitize-gm */
1644 #ifndef GENERAL_MAGIC
1645   if (siggnal != TARGET_SIGNAL_0)
1646     warning
1647       ("Can't send signals to a remote system.  Try `handle %s ignore'.",
1648        target_signal_to_name (siggnal));
1649 #endif /* GENERAL_MAGIC */
1650 /* end-sanitize-gm */
1651
1652   mips_request (step ? 's' : 'c',
1653                 (unsigned int) 1,
1654                 (unsigned int) siggnal,
1655                 (int *) NULL,
1656                 mips_receive_wait, NULL);
1657 }
1658
1659 /* Return the signal corresponding to SIG, where SIG is the number which
1660    the MIPS protocol uses for the signal.  */
1661 enum target_signal
1662 mips_signal_from_protocol (sig)
1663      int sig;
1664 {
1665   /* We allow a few more signals than the IDT board actually returns, on
1666      the theory that there is at least *some* hope that perhaps the numbering
1667      for these signals is widely agreed upon.  */
1668   if (sig <= 0
1669       || sig > 31)
1670     return TARGET_SIGNAL_UNKNOWN;
1671
1672   /* Don't want to use target_signal_from_host because we are converting
1673      from MIPS signal numbers, not host ones.  Our internal numbers
1674      match the MIPS numbers for the signals the board can return, which
1675      are: SIGINT, SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGTRAP.  */
1676   return (enum target_signal) sig;
1677 }
1678
1679 /* Wait until the remote stops, and return a wait status.  */
1680
1681 static int
1682 mips_wait (pid, status)
1683      int pid;
1684      struct target_waitstatus *status;
1685 {
1686   int rstatus;
1687   int err;
1688   char buff[DATA_MAXLEN];
1689   int rpc, rfp, rsp;
1690   char flags[20];
1691   int nfields;
1692
1693   interrupt_count = 0;
1694   hit_watchpoint = 0;
1695
1696   /* If we have not sent a single step or continue command, then the
1697      board is waiting for us to do something.  Return a status
1698      indicating that it is stopped.  */
1699   if (! mips_need_reply)
1700     {
1701       status->kind = TARGET_WAITKIND_STOPPED;
1702       status->value.sig = TARGET_SIGNAL_TRAP;
1703       return 0;
1704     }
1705
1706   /* No timeout; we sit here as long as the program continues to execute.  */
1707   mips_wait_flag = 1;
1708   rstatus = mips_request ('\000', (unsigned int) 0, (unsigned int) 0, &err, -1,
1709                           buff);
1710   mips_wait_flag = 0;
1711   if (err)
1712     mips_error ("Remote failure: %s", safe_strerror (errno));
1713
1714   nfields = sscanf (buff, "0x%*x %*c 0x%*x 0x%*x 0x%x 0x%x 0x%x 0x%*x %s",
1715                     &rpc, &rfp, &rsp, flags);
1716
1717   /* See if we got back extended status.  If so, pick out the pc, fp, sp, etc... */
1718
1719   if (nfields == 7 || nfields == 9) 
1720     {
1721       char buf[MAX_REGISTER_RAW_SIZE];
1722
1723       store_unsigned_integer (buf, REGISTER_RAW_SIZE (PC_REGNUM), rpc);
1724       supply_register (PC_REGNUM, buf);
1725
1726       store_unsigned_integer (buf, REGISTER_RAW_SIZE (PC_REGNUM), rfp);
1727       supply_register (30, buf); /* This register they are avoiding and so it is unnamed */
1728
1729       store_unsigned_integer (buf, REGISTER_RAW_SIZE (SP_REGNUM), rsp);
1730       supply_register (SP_REGNUM, buf);
1731
1732       store_unsigned_integer (buf, REGISTER_RAW_SIZE (FP_REGNUM), 0);
1733       supply_register (FP_REGNUM, buf);
1734
1735       if (nfields == 9)
1736         {
1737           int i;
1738
1739           for (i = 0; i <= 2; i++)
1740             if (flags[i] == 'r' || flags[i] == 'w')
1741               hit_watchpoint = 1;
1742             else if (flags[i] == '\000')
1743               break;
1744         }
1745     }
1746
1747   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
1748      and so on, because the constants we want here are determined by the
1749      MIPS protocol and have nothing to do with what host we are running on.  */
1750   if ((rstatus & 0377) == 0)
1751     {
1752       status->kind = TARGET_WAITKIND_EXITED;
1753       status->value.integer = (((rstatus) >> 8) & 0377);
1754     }
1755   else if ((rstatus & 0377) == 0177)
1756     {
1757       status->kind = TARGET_WAITKIND_STOPPED;
1758       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0377);
1759     }
1760   else
1761     {
1762       status->kind = TARGET_WAITKIND_SIGNALLED;
1763       status->value.sig = mips_signal_from_protocol (rstatus & 0177);
1764     }
1765
1766   return 0;
1767 }
1768
1769 static int
1770 pmon_wait (pid, status)
1771      int pid;
1772      struct target_waitstatus *status;
1773 {
1774   int rstatus;
1775   int err;
1776   char buff[DATA_MAXLEN];
1777
1778   interrupt_count = 0;
1779   hit_watchpoint = 0;
1780
1781   /* If we have not sent a single step or continue command, then the
1782      board is waiting for us to do something.  Return a status
1783      indicating that it is stopped.  */
1784   if (! mips_need_reply)
1785     {
1786       status->kind = TARGET_WAITKIND_STOPPED;
1787       status->value.sig = TARGET_SIGNAL_TRAP;
1788       return 0;
1789     }
1790
1791   /* Sit, polling the serial until the target decides to talk to
1792      us. NOTE: the timeout value we use is used not just for the
1793      first character, but for all the characters. */
1794   mips_wait_flag = 1;
1795   rstatus = mips_request ('\000', (unsigned int) 0, (unsigned int) 0, &err, -1,
1796                           buff);
1797   mips_wait_flag = 0;
1798   if (err)
1799     mips_error ("Remote failure: %s", safe_strerror (errno));
1800
1801   /* NOTE: The following (sig) numbers are defined by PMON:
1802         SPP_SIGTRAP     5       breakpoint
1803         SPP_SIGINT      2
1804         SPP_SIGSEGV     11
1805         SPP_SIGBUS      10
1806         SPP_SIGILL      4
1807         SPP_SIGFPE      8
1808         SPP_SIGTERM     15 */
1809
1810   /* On returning from a continue, the PMON monitor seems to start
1811      echoing back the messages we send prior to sending back the
1812      ACK. The code can cope with this, but to try and avoid the
1813      unnecessary serial traffic, and "spurious" characters displayed
1814      to the user, we cheat and reset the debug protocol. The problems
1815      seems to be caused by a check on the number of arguments, and the
1816      command length, within the monitor causing it to echo the command
1817      as a bad packet. */
1818   if (mips_monitor != MON_DDB)
1819     {
1820       mips_exit_debug ();
1821       mips_enter_debug ();
1822     }
1823
1824   /* Translate a MIPS waitstatus.  We use constants here rather than WTERMSIG
1825      and so on, because the constants we want here are determined by the
1826      MIPS protocol and have nothing to do with what host we are running on.  */
1827   if ((rstatus & 0377) == 0)
1828     {
1829       status->kind = TARGET_WAITKIND_EXITED;
1830       status->value.integer = (((rstatus) >> 8) & 0377);
1831     }
1832   else if ((rstatus & 0377) == 0177)
1833     {
1834       status->kind = TARGET_WAITKIND_STOPPED;
1835       status->value.sig = mips_signal_from_protocol (((rstatus) >> 8) & 0377);
1836     }
1837   else
1838     {
1839       status->kind = TARGET_WAITKIND_SIGNALLED;
1840       status->value.sig = mips_signal_from_protocol (rstatus & 0177);
1841     }
1842
1843   return 0;
1844 }
1845
1846 /* We have to map between the register numbers used by gdb and the
1847    register numbers used by the debugging protocol.  This function
1848    assumes that we are using tm-mips.h.  */
1849
1850 #define REGNO_OFFSET 96
1851
1852 static int
1853 mips_map_regno (regno)
1854      int regno;
1855 {
1856   if (regno < 32)
1857     return regno;
1858   if (regno >= FP0_REGNUM && regno < FP0_REGNUM + 32)
1859     return regno - FP0_REGNUM + 32;
1860   switch (regno)
1861     {
1862     case PC_REGNUM:
1863       return REGNO_OFFSET + 0;
1864     case CAUSE_REGNUM:
1865       return REGNO_OFFSET + 1;
1866     case HI_REGNUM:
1867       return REGNO_OFFSET + 2;
1868     case LO_REGNUM:
1869       return REGNO_OFFSET + 3;
1870     case FCRCS_REGNUM:
1871       return REGNO_OFFSET + 4;
1872     case FCRIR_REGNUM:
1873       return REGNO_OFFSET + 5;
1874     default:
1875       /* FIXME: Is there a way to get the status register?  */
1876       return 0;
1877     }
1878 }
1879
1880 /* Fetch the remote registers.  */
1881
1882 static void
1883 mips_fetch_registers (regno)
1884      int regno;
1885 {
1886   unsigned LONGEST val;
1887   int err;
1888
1889   if (regno == -1)
1890     {
1891       for (regno = 0; regno < NUM_REGS; regno++)
1892         mips_fetch_registers (regno);
1893       return;
1894     }
1895
1896   if (regno == FP_REGNUM || regno == ZERO_REGNUM)
1897     /* FP_REGNUM on the mips is a hack which is just supposed to read
1898        zero (see also mips-nat.c).  */
1899     val = 0;
1900   else
1901     {
1902       /* Unfortunately the PMON version in the Vr4300 board has been
1903          compiled without the 64bit register access commands. This
1904          means we cannot get hold of the full register width. */
1905       if (mips_monitor == MON_DDB)
1906         val = (unsigned)mips_request ('t', (unsigned int) mips_map_regno (regno),
1907                             (unsigned int) 0, &err, mips_receive_wait, NULL);
1908       else
1909         val = mips_request ('r', (unsigned int) mips_map_regno (regno),
1910                             (unsigned int) 0, &err, mips_receive_wait, NULL);
1911       if (err)
1912         mips_error ("Can't read register %d: %s", regno,
1913                     safe_strerror (errno));
1914     }
1915
1916   {
1917     char buf[MAX_REGISTER_RAW_SIZE];
1918
1919     /* We got the number the register holds, but gdb expects to see a
1920        value in the target byte ordering.  */
1921     store_unsigned_integer (buf, REGISTER_RAW_SIZE (regno), val);
1922     supply_register (regno, buf);
1923   }
1924 }
1925
1926 /* Prepare to store registers.  The MIPS protocol can store individual
1927    registers, so this function doesn't have to do anything.  */
1928
1929 static void
1930 mips_prepare_to_store ()
1931 {
1932 }
1933
1934 /* Store remote register(s).  */
1935
1936 static void
1937 mips_store_registers (regno)
1938      int regno;
1939 {
1940   int err;
1941
1942   if (regno == -1)
1943     {
1944       for (regno = 0; regno < NUM_REGS; regno++)
1945         mips_store_registers (regno);
1946       return;
1947     }
1948
1949   mips_request ('R', (unsigned int) mips_map_regno (regno),
1950                 read_register (regno),
1951                 &err, mips_receive_wait, NULL);
1952   if (err)
1953     mips_error ("Can't write register %d: %s", regno, safe_strerror (errno));
1954 }
1955
1956 /* Fetch a word from the target board.  */
1957
1958 static unsigned int 
1959 mips_fetch_word (addr)
1960      CORE_ADDR addr;
1961 {
1962   unsigned int val;
1963   int err;
1964
1965   /* FIXME! addr was cast to uint! */
1966   val = mips_request ('d', addr, (unsigned int) 0, &err,
1967                       mips_receive_wait, NULL);
1968   if (err)
1969     {
1970       /* Data space failed; try instruction space.  */
1971       /* FIXME! addr was cast to uint! */
1972       val = mips_request ('i', addr, (unsigned int) 0, &err,
1973                           mips_receive_wait, NULL);
1974       if (err)
1975         mips_error ("Can't read address 0x%s: %s",
1976               paddr_nz (addr), safe_strerror (errno));
1977     }
1978   return val;
1979 }
1980
1981 /* Store a word to the target board.  Returns errno code or zero for
1982    success.  If OLD_CONTENTS is non-NULL, put the old contents of that
1983    memory location there.  */
1984
1985 /* FIXME! make sure only 32-bit quantities get stored! */
1986 static int
1987 mips_store_word (addr, val, old_contents)
1988      CORE_ADDR addr;
1989      unsigned int val;
1990      char *old_contents;
1991 {
1992   int err;
1993   unsigned int oldcontents;
1994
1995   oldcontents = mips_request ('D', addr, (unsigned int) val,
1996                               &err,
1997                               mips_receive_wait, NULL);
1998   if (err)
1999     {
2000       /* Data space failed; try instruction space.  */
2001       oldcontents = mips_request ('I', addr,
2002                                   (unsigned int) val, &err,
2003                                   mips_receive_wait, NULL);
2004       if (err)
2005         return errno;
2006     }
2007   if (old_contents != NULL)
2008     store_unsigned_integer (old_contents, 4, oldcontents);
2009   return 0;
2010 }
2011
2012 /* Read or write LEN bytes from inferior memory at MEMADDR,
2013    transferring to or from debugger address MYADDR.  Write to inferior
2014    if SHOULD_WRITE is nonzero.  Returns length of data written or
2015    read; 0 for error.  Note that protocol gives us the correct value
2016    for a longword, since it transfers values in ASCII.  We want the
2017    byte values, so we have to swap the longword values.  */
2018
2019 static int
2020 mips_xfer_memory (memaddr, myaddr, len, write, ignore)
2021      CORE_ADDR memaddr;
2022      char *myaddr;
2023      int len;
2024      int write;
2025      struct target_ops *ignore;
2026 {
2027   register int i;
2028   /* Round starting address down to longword boundary.  */
2029   register CORE_ADDR addr = memaddr &~ 3;
2030   /* Round ending address up; get number of longwords that makes.  */
2031   register int count = (((memaddr + len) - addr) + 3) / 4;
2032   /* Allocate buffer of that many longwords.  */
2033   register char *buffer = alloca (count * 4);
2034
2035   int status;
2036
2037   if (write)
2038     {
2039       /* Fill start and end extra bytes of buffer with existing data.  */
2040       if (addr != memaddr || len < 4)
2041         {
2042           /* Need part of initial word -- fetch it.  */
2043           store_unsigned_integer (&buffer[0], 4, mips_fetch_word (addr));
2044         }
2045
2046       if (count > 1)
2047         {
2048           /* Need part of last word -- fetch it.  FIXME: we do this even
2049              if we don't need it.  */
2050           store_unsigned_integer (&buffer[(count - 1) * 4], 4,
2051                                   mips_fetch_word (addr + (count - 1) * 4));
2052         }
2053
2054       /* Copy data to be written over corresponding part of buffer */
2055
2056       memcpy ((char *) buffer + (memaddr & 3), myaddr, len);
2057
2058       /* Write the entire buffer.  */
2059
2060       for (i = 0; i < count; i++, addr += 4)
2061         {
2062           status = mips_store_word (addr,
2063                                     extract_unsigned_integer (&buffer[i*4], 4),
2064                                     NULL);
2065           /* Report each kilobyte (we download 32-bit words at a time) */
2066           if (i % 256 == 255) 
2067             {
2068               printf_unfiltered ("*");
2069               fflush (stdout);
2070             }
2071           if (status)
2072             {
2073               errno = status;
2074               return 0;
2075             }
2076           /* FIXME: Do we want a QUIT here?  */
2077         }
2078       if (count >= 256)
2079         printf_unfiltered ("\n");
2080     }
2081   else
2082     {
2083       /* Read all the longwords */
2084       for (i = 0; i < count; i++, addr += 4)
2085         {
2086           store_unsigned_integer (&buffer[i*4], 4, mips_fetch_word (addr));
2087           QUIT;
2088         }
2089
2090       /* Copy appropriate bytes out of the buffer.  */
2091       memcpy (myaddr, buffer + (memaddr & 3), len);
2092     }
2093   return len;
2094 }
2095
2096 /* Print info on this target.  */
2097
2098 static void
2099 mips_files_info (ignore)
2100      struct target_ops *ignore;
2101 {
2102   printf_unfiltered ("Debugging a MIPS board over a serial line.\n");
2103 }
2104
2105 /* Kill the process running on the board.  This will actually only
2106    work if we are doing remote debugging over the console input.  I
2107    think that if IDT/sim had the remote debug interrupt enabled on the
2108    right port, we could interrupt the process with a break signal.  */
2109
2110 static void
2111 mips_kill ()
2112 {
2113   if (!mips_wait_flag)
2114     return;
2115
2116   interrupt_count++;
2117
2118   if (interrupt_count >= 2)
2119     {
2120       interrupt_count = 0;
2121
2122       target_terminal_ours ();
2123
2124       if (query ("Interrupted while waiting for the program.\n\
2125 Give up (and stop debugging it)? "))
2126         {
2127           /* Clean up in such a way that mips_close won't try to talk to the
2128              board (it almost surely won't work since we weren't able to talk to
2129              it).  */
2130           mips_wait_flag = 0;
2131           close_ports();
2132
2133           printf_unfiltered ("Ending remote MIPS debugging.\n");
2134           target_mourn_inferior ();
2135
2136           return_to_top_level (RETURN_QUIT);
2137         }
2138
2139       target_terminal_inferior ();
2140     }
2141
2142   if (remote_debug > 0)
2143     printf_unfiltered ("Sending break\n");
2144
2145   SERIAL_SEND_BREAK (mips_desc);
2146
2147 #if 0
2148   if (mips_is_open)
2149     {
2150       char cc;
2151
2152       /* Send a ^C.  */
2153       cc = '\003';
2154       SERIAL_WRITE (mips_desc, &cc, 1);
2155       sleep (1);
2156       target_mourn_inferior ();
2157     }
2158 #endif
2159 }
2160
2161 /* Start running on the target board.  */
2162
2163 static void
2164 mips_create_inferior (execfile, args, env)
2165      char *execfile;
2166      char *args;
2167      char **env;
2168 {
2169   CORE_ADDR entry_pt;
2170
2171   if (args && *args)
2172     {
2173       warning ("\
2174 Can't pass arguments to remote MIPS board; arguments ignored.");
2175       /* And don't try to use them on the next "run" command.  */
2176       execute_command ("set args", 0);
2177     }
2178
2179   if (execfile == 0 || exec_bfd == 0)
2180     error ("No executable file specified");
2181
2182   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
2183
2184   init_wait_for_inferior ();
2185
2186   /* FIXME: Should we set inferior_pid here?  */
2187
2188 /* start-sanitize-gm */
2189 #ifdef GENERAL_MAGIC
2190   magic_create_inferior_hook ();
2191   proceed (entry_pt, TARGET_SIGNAL_PWR, 0);
2192 #else
2193 /* end-sanitize-gm */
2194   proceed (entry_pt, TARGET_SIGNAL_DEFAULT, 0);
2195 /* start-sanitize-gm */
2196 #endif /* GENERAL_MAGIC */
2197 /* end-sanitize-gm */
2198 }
2199
2200 /* Clean up after a process.  Actually nothing to do.  */
2201
2202 static void
2203 mips_mourn_inferior ()
2204 {
2205   if (current_ops != NULL)
2206     unpush_target (current_ops);
2207   generic_mourn_inferior ();
2208 }
2209 \f
2210 /* We can write a breakpoint and read the shadow contents in one
2211    operation.  */
2212
2213 /* The IDT board uses an unusual breakpoint value, and sometimes gets
2214    confused when it sees the usual MIPS breakpoint instruction.  */
2215
2216 #define BREAK_INSN (0x00000a0d)
2217 #define BREAK_INSN_SIZE (4)
2218
2219 /* Insert a breakpoint on targets that don't have any better breakpoint
2220    support.  We read the contents of the target location and stash it,
2221    then overwrite it with a breakpoint instruction.  ADDR is the target
2222    location in the target machine.  CONTENTS_CACHE is a pointer to 
2223    memory allocated for saving the target contents.  It is guaranteed
2224    by the caller to be long enough to save sizeof BREAKPOINT bytes (this
2225    is accomplished via BREAKPOINT_MAX).  */
2226
2227 static int
2228 mips_insert_breakpoint (addr, contents_cache)
2229      CORE_ADDR addr;
2230      char *contents_cache;
2231 {
2232   if (monitor_supports_breakpoints)
2233     return common_breakpoint ('B', addr, 0x3, "f");
2234
2235   return mips_store_word (addr, BREAK_INSN, contents_cache);
2236 }
2237
2238 static int
2239 mips_remove_breakpoint (addr, contents_cache)
2240      CORE_ADDR addr;
2241      char *contents_cache;
2242 {
2243   if (monitor_supports_breakpoints)
2244     return common_breakpoint ('b', addr, 0, NULL);
2245
2246   return target_write_memory (addr, contents_cache, BREAK_INSN_SIZE);
2247 }
2248
2249 #if 0 /* currently not used */
2250 /* PMON does not currently provide support for the debug mode 'b'
2251    commands to manipulate breakpoints. However, if we wanted to use
2252    the monitor breakpoints (rather than the GDB BREAK_INSN version)
2253    then this code performs the work needed to leave debug mode,
2254    set/clear the breakpoint, and then return to debug mode. */
2255
2256 #define PMON_MAX_BP (33) /* 32 SW, 1 HW */
2257 static CORE_ADDR mips_pmon_bp_info[PMON_MAX_BP];
2258 /* NOTE: The code relies on this vector being zero-initialised by the system */
2259
2260 static int
2261 pmon_insert_breakpoint (addr, contents_cache)
2262      CORE_ADDR addr;
2263      char *contents_cache;
2264 {
2265   int status;
2266
2267   if (monitor_supports_breakpoints)
2268     {
2269       char tbuff[12]; /* space for breakpoint command */
2270       int bpnum;
2271       CORE_ADDR bpaddr;
2272
2273       /* PMON does not support debug level breakpoint set/remove: */
2274       if (mips_exit_debug ())
2275         mips_error ("Failed to exit debug mode");
2276
2277       sprintf (tbuff, "b %08x\r", addr);
2278       mips_send_command (tbuff, 0);
2279
2280       mips_expect ("Bpt ");
2281
2282       if (!mips_getstring (tbuff, 2))
2283         return 1;
2284       tbuff[2] = '\0'; /* terminate the string */
2285       if (sscanf (tbuff, "%d", &bpnum) != 1)
2286         {
2287           fprintf_unfiltered (stderr, "Invalid decimal breakpoint number from target: %s\n", tbuff);
2288           return 1;
2289         }
2290
2291       mips_expect (" = ");
2292
2293       /* Lead in the hex number we are expecting: */
2294       tbuff[0] = '0';
2295       tbuff[1] = 'x';
2296
2297       /* FIXME!! only 8 bytes!  need to expand for Bfd64; 
2298          which targets return 64-bit addresses?  PMON returns only 32! */
2299       if (!mips_getstring (&tbuff[2], 8))
2300         return 1;
2301       tbuff[10] = '\0'; /* terminate the string */
2302
2303       if (sscanf (tbuff, "0x%08x", &bpaddr) != 1)
2304         {
2305           fprintf_unfiltered (stderr, "Invalid hex address from target: %s\n", tbuff);
2306           return 1;
2307         }
2308
2309       if (bpnum >= PMON_MAX_BP)
2310         {
2311           fprintf_unfiltered (stderr, "Error: Returned breakpoint number %d outside acceptable range (0..%d)\n",
2312                               bpnum, PMON_MAX_BP - 1);
2313           return 1;
2314         }
2315
2316       if (bpaddr != addr)
2317         fprintf_unfiltered (stderr, "Warning: Breakpoint addresses do not match: 0x%x != 0x%x\n", addr, bpaddr);
2318
2319       mips_pmon_bp_info[bpnum] = bpaddr;
2320
2321       mips_expect ("\r\n");
2322       mips_expect (mips_monitor_prompt);
2323
2324       mips_enter_debug ();
2325
2326       return 0;
2327     }
2328
2329   return mips_store_word (addr, BREAK_INSN, contents_cache);
2330 }
2331
2332 static int
2333 pmon_remove_breakpoint (addr, contents_cache)
2334      CORE_ADDR addr;
2335      char *contents_cache;
2336 {
2337   if (monitor_supports_breakpoints)
2338     {
2339       int bpnum;
2340       char tbuff[7]; /* enough for delete breakpoint command */
2341
2342       for (bpnum = 0; bpnum < PMON_MAX_BP; bpnum++)
2343         if (mips_pmon_bp_info[bpnum] == addr)
2344           break;
2345
2346       if (bpnum >= PMON_MAX_BP)
2347         {
2348           fprintf_unfiltered (stderr,
2349             "pmon_remove_breakpoint: Failed to find breakpoint at address 0x%s\n",
2350             paddr_nz (addr));
2351           return 1;
2352         }
2353
2354       if (mips_exit_debug ())
2355         mips_error ("Failed to exit debug mode");
2356
2357       sprintf (tbuff, "db %02d\r", bpnum);
2358
2359       mips_send_command (tbuff, -1);
2360       /* NOTE: If the breakpoint does not exist then a "Bpt <dd> not
2361          set" message will be returned. */
2362
2363       mips_enter_debug ();
2364
2365       return 0;
2366     }
2367
2368   return target_write_memory (addr, contents_cache, BREAK_INSN_SIZE);
2369 }
2370 #endif
2371
2372 /* Compute a don't care mask for the region bounding ADDR and ADDR + LEN - 1.
2373    This is used for memory ref breakpoints.  */
2374
2375 static unsigned long
2376 calculate_mask (addr, len)
2377      CORE_ADDR addr;
2378      int len;
2379 {
2380   unsigned long mask;
2381   int i;
2382
2383   mask = addr ^ (addr + len - 1);
2384
2385   for (i = 32; i >= 0; i--)
2386     if (mask == 0)
2387       break;
2388     else
2389       mask >>= 1;
2390
2391   mask = (unsigned long) 0xffffffff >> i;
2392
2393   return mask;
2394 }
2395
2396 /* Set a data watchpoint.  ADDR and LEN should be obvious.  TYPE is either 1
2397    for a read watchpoint, or 2 for a read/write watchpoint. */
2398
2399 int
2400 remote_mips_set_watchpoint (addr, len, type)
2401      CORE_ADDR addr;
2402      int len;
2403      int type;
2404 {
2405   CORE_ADDR first_addr;
2406   unsigned long mask;
2407   char *flags;
2408
2409   mask = calculate_mask (addr, len);
2410
2411   first_addr = addr & ~mask;
2412
2413   switch (type)
2414     {
2415     case 0:                     /* write */
2416       flags = "w";
2417       break;
2418     case 1:                     /* read */
2419       flags = "r";
2420       break;
2421     case 2:                     /* read/write */
2422       flags = "rw";
2423       break;
2424     default:
2425       abort ();
2426     }
2427
2428   if (common_breakpoint ('B', first_addr, mask, flags))
2429     return -1;
2430
2431   return 0;
2432 }
2433
2434 int
2435 remote_mips_remove_watchpoint (addr, len, type)
2436      CORE_ADDR addr;
2437      int len;
2438      int type;
2439 {
2440   CORE_ADDR first_addr;
2441   unsigned long mask;
2442
2443   mask = calculate_mask (addr, len);
2444
2445   first_addr = addr & ~mask;
2446
2447   if (common_breakpoint ('b', first_addr, 0, NULL))
2448     return -1;
2449
2450   return 0;
2451 }
2452
2453 int
2454 remote_mips_stopped_by_watchpoint ()
2455 {
2456   return hit_watchpoint;
2457 }
2458
2459 /* This routine generates the a breakpoint command of the form:
2460
2461    0x0 <CMD> <ADDR> <MASK> <FLAGS>
2462
2463    Where <CMD> is one of: `B' to set, or `b' to clear a breakpoint.  <ADDR> is
2464    the address of the breakpoint.  <MASK> is a don't care mask for addresses.
2465    <FLAGS> is any combination of `r', `w', or `f' for read/write/or fetch.  */
2466
2467 static int
2468 common_breakpoint (cmd, addr, mask, flags)
2469      int cmd;
2470      CORE_ADDR addr;
2471      CORE_ADDR mask;
2472      char *flags;
2473 {
2474   int len;
2475   char buf[DATA_MAXLEN + 1];
2476   char rcmd;
2477   int rpid, rerrflg, rresponse;
2478   int nfields;
2479
2480   if (flags)
2481     sprintf (buf, "0x0 %c 0x%s 0x%s %s", cmd, paddr_nz (addr), paddr_nz (mask),
2482              flags);
2483   else
2484     sprintf (buf, "0x0 %c 0x%s", cmd, paddr_nz (addr));
2485
2486   mips_send_packet (buf, 1);
2487
2488   len = mips_receive_packet (buf, 1, mips_receive_wait);
2489   buf[len] = '\0';
2490
2491   nfields = sscanf (buf, "0x%x %c 0x%x 0x%x", &rpid, &rcmd, &rerrflg, &rresponse);
2492
2493   if (nfields != 4
2494       || rcmd != cmd)
2495     mips_error ("common_breakpoint: Bad response from remote board: %s", buf);
2496
2497   if (rerrflg != 0)
2498     {
2499       /* Ddb returns "0x0 b 0x16 0x0\000", whereas
2500          Cogent returns "0x0 b 0xffffffff 0x16\000": */
2501       if (mips_monitor == MON_DDB)
2502         rresponse = rerrflg;
2503       if (rresponse != 22) /* invalid argument */
2504         fprintf_unfiltered (stderr, "common_breakpoint (0x%s):  Got error: 0x%x\n",
2505                             paddr_nz (addr), rresponse);
2506       return 1;
2507     }
2508
2509   return 0;
2510 }
2511 \f
2512 static void
2513 send_srec (srec, len, addr)
2514      char *srec;
2515      int len;
2516      CORE_ADDR addr;
2517 {
2518   while (1)
2519     {
2520       int ch;
2521
2522       SERIAL_WRITE (mips_desc, srec, len);
2523
2524       ch = mips_readchar (2);
2525
2526       switch (ch)
2527         {
2528         case SERIAL_TIMEOUT:
2529           error ("Timeout during download.");
2530           break;
2531         case 0x6:               /* ACK */
2532           return;
2533         case 0x15:              /* NACK */
2534           fprintf_unfiltered (gdb_stderr, "Download got a NACK at byte %d!  Retrying.\n", addr);
2535           continue;
2536         default:
2537           error ("Download got unexpected ack char: 0x%x, retrying.\n", ch);
2538         }
2539     }
2540 }
2541
2542 /*  Download a binary file by converting it to S records. */
2543
2544 static void
2545 mips_load_srec (args)
2546      char *args;
2547 {
2548   bfd *abfd;
2549   asection *s;
2550   char *buffer, srec[1024];
2551   unsigned int i;
2552   unsigned int srec_frame = 200;
2553   int reclen;
2554   static int hashmark = 1;
2555
2556   buffer = alloca (srec_frame * 2 + 256);
2557
2558   abfd = bfd_openr (args, 0);
2559   if (!abfd)
2560     {
2561       printf_filtered ("Unable to open file %s\n", args);
2562       return;
2563     }
2564
2565   if (bfd_check_format (abfd, bfd_object) == 0)
2566     {
2567       printf_filtered ("File is not an object file\n");
2568       return;
2569     }
2570
2571 /* This actually causes a download in the IDT binary format: */
2572   mips_send_command (LOAD_CMD, 0);
2573
2574   for (s = abfd->sections; s; s = s->next)
2575     {
2576       if (s->flags & SEC_LOAD)
2577         {
2578           unsigned int numbytes;
2579
2580           /* FIXME!  vma too small?? */
2581           printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, s->vma,
2582                            s->vma + s->_raw_size);
2583           gdb_flush (gdb_stdout);
2584
2585           for (i = 0; i < s->_raw_size; i += numbytes)
2586             {
2587               numbytes = min (srec_frame, s->_raw_size - i);
2588
2589               bfd_get_section_contents (abfd, s, buffer, i, numbytes);
2590
2591               reclen = mips_make_srec (srec, '3', s->vma + i, buffer, numbytes);
2592               send_srec (srec, reclen, s->vma + i);
2593
2594               if (hashmark)
2595                 {
2596                   putchar_unfiltered ('#');
2597                   gdb_flush (gdb_stdout);
2598                 }
2599
2600             } /* Per-packet (or S-record) loop */
2601           
2602           putchar_unfiltered ('\n');
2603         } /* Loadable sections */
2604     }
2605   if (hashmark) 
2606     putchar_unfiltered ('\n');
2607   
2608   /* Write a type 7 terminator record. no data for a type 7, and there
2609      is no data, so len is 0.  */
2610
2611   reclen = mips_make_srec (srec, '7', abfd->start_address, NULL, 0);
2612
2613   send_srec (srec, reclen, abfd->start_address);
2614
2615   SERIAL_FLUSH_INPUT (mips_desc);
2616 }
2617
2618 /*
2619  * mips_make_srec -- make an srecord. This writes each line, one at a
2620  *      time, each with it's own header and trailer line.
2621  *      An srecord looks like this:
2622  *
2623  * byte count-+     address
2624  * start ---+ |        |       data        +- checksum
2625  *          | |        |                   |
2626  *        S01000006F6B692D746573742E73726563E4
2627  *        S315000448600000000000000000FC00005900000000E9
2628  *        S31A0004000023C1400037DE00F023604000377B009020825000348D
2629  *        S30B0004485A0000000000004E
2630  *        S70500040000F6
2631  *
2632  *      S<type><length><address><data><checksum>
2633  *
2634  *      Where
2635  *      - length
2636  *        is the number of bytes following upto the checksum. Note that
2637  *        this is not the number of chars following, since it takes two
2638  *        chars to represent a byte.
2639  *      - type
2640  *        is one of:
2641  *        0) header record
2642  *        1) two byte address data record
2643  *        2) three byte address data record
2644  *        3) four byte address data record
2645  *        7) four byte address termination record
2646  *        8) three byte address termination record
2647  *        9) two byte address termination record
2648  *       
2649  *      - address
2650  *        is the start address of the data following, or in the case of
2651  *        a termination record, the start address of the image
2652  *      - data
2653  *        is the data.
2654  *      - checksum
2655  *        is the sum of all the raw byte data in the record, from the length
2656  *        upwards, modulo 256 and subtracted from 255.
2657  *
2658  * This routine returns the length of the S-record.
2659  *
2660  */
2661
2662 static int
2663 mips_make_srec (buf, type, memaddr, myaddr, len)
2664      char *buf;
2665      int type;
2666      CORE_ADDR memaddr;
2667      unsigned char *myaddr;
2668      int len;
2669 {
2670   unsigned char checksum;
2671   int i;
2672
2673   /* Create the header for the srec. addr_size is the number of bytes in the address,
2674      and 1 is the number of bytes in the count.  */
2675
2676   /* FIXME!! bigger buf required for 64-bit! */
2677   buf[0] = 'S';
2678   buf[1] = type;
2679   buf[2] = len + 4 + 1;         /* len + 4 byte address + 1 byte checksum */
2680   /* This assumes S3 style downloads (4byte addresses). There should
2681      probably be a check, or the code changed to make it more
2682      explicit. */
2683   buf[3] = memaddr >> 24;
2684   buf[4] = memaddr >> 16;
2685   buf[5] = memaddr >> 8;
2686   buf[6] = memaddr;
2687   memcpy (&buf[7], myaddr, len);
2688
2689   /* Note that the checksum is calculated on the raw data, not the
2690      hexified data.  It includes the length, address and the data
2691      portions of the packet.  */
2692   checksum = 0;
2693   buf += 2;                     /* Point at length byte */
2694   for (i = 0; i < len + 4 + 1; i++)
2695     checksum += *buf++;
2696
2697   *buf = ~checksum;
2698
2699   return len + 8;
2700 }
2701
2702 /* The following manifest controls whether we enable the simple flow
2703    control support provided by the monitor. If enabled the code will
2704    wait for an affirmative ACK between transmitting packets. */
2705 #define DOETXACK (1)
2706
2707 /* The PMON fast-download uses an encoded packet format constructed of
2708    3byte data packets (encoded as 4 printable ASCII characters), and
2709    escape sequences (preceded by a '/'):
2710
2711         'K'     clear checksum
2712         'C'     compare checksum (12bit value, not included in checksum calculation)
2713         'S'     define symbol name (for addr) terminated with "," and padded to 4char boundary
2714         'Z'     zero fill multiple of 3bytes
2715         'B'     byte (12bit encoded value, of 8bit data)
2716         'A'     address (36bit encoded value)
2717         'E'     define entry as original address, and exit load
2718
2719    The packets are processed in 4 character chunks, so the escape
2720    sequences that do not have any data (or variable length data)
2721    should be padded to a 4 character boundary.  The decoder will give
2722    an error if the complete message block size is not a multiple of
2723    4bytes (size of record).
2724
2725    The encoding of numbers is done in 6bit fields.  The 6bit value is
2726    used to index into this string to get the specific character
2727    encoding for the value: */
2728 static char encoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,.";
2729
2730 /* Convert the number of bits required into an encoded number, 6bits
2731    at a time (range 0..63).  Keep a checksum if required (passed
2732    pointer non-NULL). The function returns the number of encoded
2733    characters written into the buffer. */
2734 static int
2735 pmon_makeb64 (v, p, n, chksum)
2736      unsigned long v;
2737      char *p;
2738      int n;
2739      int *chksum;
2740 {
2741   int count = (n / 6);
2742
2743   if ((n % 12) != 0) {
2744     fprintf_unfiltered(stderr,"Fast encoding bitcount must be a multiple of 12bits: %dbit%s\n",n,(n == 1)?"":"s");
2745     return(0);
2746   }
2747   if (n > 36) {
2748     fprintf_unfiltered(stderr,"Fast encoding cannot process more than 36bits at the moment: %dbits\n",n);
2749     return(0);
2750   }
2751
2752   /* Deal with the checksum: */
2753   if (chksum != NULL) {
2754     switch (n) {
2755      case 36: *chksum += ((v >> 24) & 0xFFF);
2756      case 24: *chksum += ((v >> 12) & 0xFFF);
2757      case 12: *chksum += ((v >>  0) & 0xFFF);
2758     }
2759   }
2760
2761   do {
2762     n -= 6;
2763     *p++ = encoding[(v >> n) & 0x3F];
2764   } while (n > 0);
2765
2766   return(count);
2767 }
2768
2769 /* Shorthand function (that could be in-lined) to output the zero-fill
2770    escape sequence into the data stream. */
2771 static int
2772 pmon_zeroset (recsize, buff, amount, chksum)
2773      int recsize;
2774      char **buff;
2775      int *amount;
2776      unsigned int *chksum;
2777 {
2778   int count;
2779
2780   sprintf(*buff,"/Z");
2781   count = pmon_makeb64 (*amount, (*buff + 2), 12, chksum);
2782   *buff += (count + 2);
2783   *amount = 0;
2784   return(recsize + count + 2);
2785 }
2786
2787 static int
2788 pmon_checkset (recsize, buff, value)
2789      int recsize;
2790      char **buff;
2791      int *value;
2792 {
2793   int count;
2794
2795   /* Add the checksum (without updating the value): */
2796   sprintf (*buff, "/C");
2797   count = pmon_makeb64 (*value, (*buff + 2), 12, NULL);
2798   *buff += (count + 2);
2799   sprintf (*buff, "\n");
2800   *buff += 2; /* include zero terminator */
2801   /* Forcing a checksum validation clears the sum: */
2802   *value = 0;
2803   return(recsize + count + 3);
2804 }
2805
2806 /* Amount of padding we leave after at the end of the output buffer,
2807    for the checksum and line termination characters: */
2808 #define CHECKSIZE (4 + 4 + 4 + 2)
2809 /* zero-fill, checksum, transfer end and line termination space. */
2810
2811 /* The amount of binary data loaded from the object file in a single
2812    operation: */
2813 #define BINCHUNK (1024)
2814
2815 /* Maximum line of data accepted by the monitor: */
2816 #define MAXRECSIZE (550)
2817 /* NOTE: This constant depends on the monitor being used. This value
2818    is for PMON 5.x on the Cogent Vr4300 board. */
2819
2820 static void
2821 pmon_make_fastrec (outbuf, inbuf, inptr, inamount, recsize, csum, zerofill)
2822      char **outbuf;
2823      unsigned char *inbuf;
2824      int *inptr;
2825      int inamount;
2826      int *recsize;
2827      unsigned int *csum;
2828      unsigned int *zerofill;
2829 {
2830   int count = 0;
2831   char *p = *outbuf;
2832
2833   /* This is a simple check to ensure that our data will fit within
2834      the maximum allowable record size. Each record output is 4bytes
2835      in length. We must allow space for a pending zero fill command,
2836      the record, and a checksum record. */
2837   while ((*recsize < (MAXRECSIZE - CHECKSIZE)) && ((inamount - *inptr) > 0)) {
2838     /* Process the binary data: */
2839     if ((inamount - *inptr) < 3) {
2840       if (*zerofill != 0)
2841        *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2842       sprintf (p, "/B");
2843       count = pmon_makeb64 (inbuf[*inptr], &p[2], 12, csum);
2844       p += (2 + count);
2845       *recsize += (2 + count);
2846       (*inptr)++;
2847     } else {
2848       unsigned int value = ((inbuf[*inptr + 0] << 16) | (inbuf[*inptr + 1] << 8) | inbuf[*inptr + 2]);
2849       /* Simple check for zero data. TODO: A better check would be
2850          to check the last, and then the middle byte for being zero
2851          (if the first byte is not). We could then check for
2852          following runs of zeros, and if above a certain size it is
2853          worth the 4 or 8 character hit of the byte insertions used
2854          to pad to the start of the zeroes. NOTE: This also depends
2855          on the alignment at the end of the zero run. */
2856       if (value == 0x00000000) {
2857         (*zerofill)++;
2858         if (*zerofill == 0xFFF) /* 12bit counter */
2859          *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2860       }else {
2861         if (*zerofill != 0)
2862          *recsize = pmon_zeroset (*recsize, &p, zerofill, csum);
2863         count = pmon_makeb64 (value, p, 24, csum);
2864         p += count;
2865         *recsize += count;
2866       }
2867       *inptr += 3;
2868     }
2869   }
2870
2871   *outbuf = p;
2872   return;
2873 }
2874
2875 static int
2876 pmon_check_ack(mesg)
2877      char *mesg;
2878 {
2879 #if defined(DOETXACK)
2880   int c;
2881
2882   if (!tftp_in_use)
2883     {
2884       c = SERIAL_READCHAR (udp_in_use ? udp_desc : mips_desc, 2);
2885       if ((c == SERIAL_TIMEOUT) || (c != 0x06))
2886         {
2887           fprintf_unfiltered (gdb_stderr,
2888                               "Failed to receive valid ACK for %s\n", mesg);
2889           return(-1); /* terminate the download */
2890         }
2891     }
2892 #endif /* DOETXACK */
2893   return(0);
2894 }
2895
2896 /* pmon_download - Send a sequence of characters to the PMON download port,
2897    which is either a serial port or a UDP socket.  */
2898
2899 static void
2900 pmon_start_download ()
2901 {
2902   if (tftp_in_use)
2903     {
2904       /* Create the temporary download file.  */
2905       if ((tftp_file = fopen (tftp_localname, "w")) == NULL)
2906         perror_with_name (tftp_localname);
2907     }
2908   else
2909     {
2910       mips_send_command (udp_in_use ? LOAD_CMD_UDP : LOAD_CMD, 0);
2911       mips_expect ("Downloading from ");
2912       mips_expect (udp_in_use ? "udp" : "tty0");
2913       mips_expect (", ^C to abort\r\n");
2914     }
2915 }
2916
2917 static int
2918 mips_expect_download (char *string)
2919 {
2920   if (!mips_expect (string))
2921     {
2922       fprintf_unfiltered (gdb_stderr, "Load did not complete successfully.\n");
2923       if (tftp_in_use)
2924         remove (tftp_localname);        /* Remove temporary file */
2925       return 0;
2926     }
2927   else
2928     return 1;
2929 }
2930
2931 static void
2932 pmon_end_download (final, bintotal)
2933      int final;
2934      int bintotal;
2935 {
2936   char hexnumber[9]; /* includes '\0' space */
2937
2938   if (tftp_in_use)
2939     {
2940       static char *load_cmd_prefix = "load -b -s ";
2941       char *cmd;
2942       struct stat stbuf;
2943
2944       /* Close off the temporary file containing the load data.  */
2945       fclose (tftp_file);
2946       tftp_file = NULL;
2947
2948       /* Make the temporary file readable by the world.  */
2949       if (stat (tftp_localname, &stbuf) == 0)
2950         chmod (tftp_localname, stbuf.st_mode | S_IROTH);
2951
2952       /* Must reinitialize the board to prevent PMON from crashing.  */
2953       mips_send_command ("initEther\r", -1);
2954
2955       /* Send the load command.  */
2956       cmd = xmalloc (strlen (load_cmd_prefix) + strlen (tftp_name) + 2);
2957       strcpy (cmd, load_cmd_prefix);
2958       strcat (cmd, tftp_name);
2959       strcat (cmd, "\r");
2960       mips_send_command (cmd, 0);
2961       free (cmd);
2962       if (!mips_expect_download ("Downloading from "))
2963         return;
2964       if (!mips_expect_download (tftp_name))
2965         return;
2966       if (!mips_expect_download (", ^C to abort\r\n"))
2967         return;
2968     }
2969
2970   /* Wait for the stuff that PMON prints after the load has completed.
2971      The timeout value for use in the tftp case (15 seconds) was picked
2972      arbitrarily but might be too small for really large downloads. FIXME. */
2973   mips_expect_timeout ("Entry Address  = ", tftp_in_use ? 15 : 2);
2974   sprintf (hexnumber,"%x",final);
2975   mips_expect (hexnumber);
2976   mips_expect ("\r\n");
2977   pmon_check_ack ("termination");
2978   mips_expect ("\r\ntotal = 0x");
2979   sprintf (hexnumber,"%x",bintotal);
2980   mips_expect (hexnumber);
2981   if (!mips_expect_download (" bytes\r\n"))
2982     return;
2983
2984   if (tftp_in_use)
2985     remove (tftp_localname);    /* Remove temporary file */
2986 }
2987
2988 static void
2989 pmon_download (buffer, length)
2990      char *buffer;
2991      int length;
2992 {
2993   if (tftp_in_use)
2994     fwrite (buffer, 1, length, tftp_file);
2995   else
2996     SERIAL_WRITE (udp_in_use ? udp_desc : mips_desc, buffer, length);
2997 }
2998
2999 static void
3000 pmon_load_fast (file)
3001      char *file;
3002 {
3003   bfd *abfd;
3004   asection *s;
3005   unsigned char *binbuf;
3006   char *buffer;
3007   int reclen;
3008   unsigned int csum = 0;
3009   int hashmark = !tftp_in_use;
3010   int bintotal = 0;
3011   int final = 0;
3012   int finished = 0;
3013
3014   buffer = (char *)xmalloc(MAXRECSIZE + 1);
3015   binbuf = (unsigned char *)xmalloc(BINCHUNK);
3016
3017   abfd = bfd_openr(file,0);
3018   if (!abfd)
3019    {
3020      printf_filtered ("Unable to open file %s\n",file);
3021      return;
3022    }
3023
3024   if (bfd_check_format(abfd,bfd_object) == 0)
3025    {
3026      printf_filtered("File is not an object file\n");
3027      return;
3028    }
3029
3030   /* Setup the required download state: */
3031   mips_send_command ("set dlproto etxack\r", -1);
3032   mips_send_command ("set dlecho off\r", -1);
3033   /* NOTE: We get a "cannot set variable" message if the variable is
3034      already defined to have the argument we give. The code doesn't
3035      care, since it just scans to the next prompt anyway. */
3036   /* Start the download: */
3037   pmon_start_download();
3038   
3039   /* Zero the checksum */
3040   sprintf(buffer,"/Kxx\n");
3041   reclen = strlen(buffer);
3042   pmon_download (buffer, reclen);
3043   finished = pmon_check_ack("/Kxx");
3044
3045   for (s = abfd->sections; s && !finished; s = s->next)
3046    if (s->flags & SEC_LOAD) /* only deal with loadable sections */
3047     {
3048       bintotal += s->_raw_size;
3049       final = (s->vma + s->_raw_size);
3050
3051       printf_filtered ("%s\t: 0x%4x .. 0x%4x  ", s->name, (unsigned int)s->vma,
3052                        (unsigned int)(s->vma + s->_raw_size));
3053       gdb_flush (gdb_stdout);
3054
3055       /* Output the starting address */
3056       sprintf(buffer,"/A");
3057       reclen = pmon_makeb64(s->vma,&buffer[2],36,&csum);
3058       buffer[2 + reclen] = '\n';
3059       buffer[3 + reclen] = '\0';
3060       reclen += 3; /* for the initial escape code and carriage return */
3061       pmon_download (buffer, reclen);
3062       finished = pmon_check_ack("/A");
3063
3064       if (!finished)
3065        {
3066          unsigned int binamount;
3067          unsigned int zerofill = 0;
3068          char *bp = buffer;
3069          unsigned int i;
3070
3071          reclen = 0;
3072
3073          for (i = 0; ((i < s->_raw_size) && !finished); i += binamount) {
3074            int binptr = 0;
3075
3076            binamount = min (BINCHUNK, s->_raw_size - i);
3077
3078            bfd_get_section_contents (abfd, s, binbuf, i, binamount);
3079
3080            /* This keeps a rolling checksum, until we decide to output
3081               the line: */
3082            for (; ((binamount - binptr) > 0);) {
3083              pmon_make_fastrec (&bp, binbuf, &binptr, binamount, &reclen, &csum, &zerofill);
3084              if (reclen >= (MAXRECSIZE - CHECKSIZE)) {
3085                reclen = pmon_checkset (reclen, &bp, &csum);
3086                pmon_download (buffer, reclen);
3087                finished = pmon_check_ack("data record");
3088                if (finished) {
3089                  zerofill = 0; /* do not transmit pending zerofills */
3090                  break;
3091                }
3092
3093                if (hashmark) {
3094                  putchar_unfiltered ('#');
3095                  gdb_flush (gdb_stdout);
3096                }
3097
3098                bp = buffer;
3099                reclen = 0; /* buffer processed */
3100              }
3101            }
3102          }
3103
3104          /* Ensure no out-standing zerofill requests: */
3105          if (zerofill != 0)
3106           reclen = pmon_zeroset (reclen, &bp, &zerofill, &csum);
3107
3108          /* and then flush the line: */
3109          if (reclen > 0) {
3110            reclen = pmon_checkset (reclen, &bp, &csum);
3111            /* Currently pmon_checkset outputs the line terminator by
3112               default, so we write out the buffer so far: */
3113            pmon_download (buffer, reclen);
3114            finished = pmon_check_ack("record remnant");
3115          }
3116        }
3117
3118       putchar_unfiltered ('\n');
3119     }
3120
3121   /* Terminate the transfer. We know that we have an empty output
3122      buffer at this point. */
3123   sprintf (buffer, "/E/E\n"); /* include dummy padding characters */
3124   reclen = strlen (buffer);
3125   pmon_download (buffer, reclen);
3126
3127   if (finished) { /* Ignore the termination message: */
3128     SERIAL_FLUSH_INPUT (udp_in_use ? udp_desc : mips_desc);
3129   } else { /* Deal with termination message: */
3130     pmon_end_download (final, bintotal);
3131   }
3132
3133   return;
3134 }
3135
3136 /* mips_load -- download a file. */
3137
3138 static void
3139 mips_load (file, from_tty)
3140     char *file;
3141     int  from_tty;
3142 {
3143   /* Get the board out of remote debugging mode.  */
3144   if (mips_exit_debug ())
3145     error ("mips_load:  Couldn't get into monitor mode.");
3146
3147   if (mips_monitor == MON_PMON || mips_monitor == MON_DDB)
3148    pmon_load_fast (file);
3149   else
3150    mips_load_srec (file);
3151
3152   mips_initialize ();
3153
3154   /* Finally, make the PC point at the start address */
3155   if (mips_monitor == MON_DDB)
3156     {
3157       /* Work around problem where DDB monitor does not update the
3158          PC after a load. The following ensures that the write_pc()
3159          WILL update the PC value: */
3160       register_valid[PC_REGNUM] = 0;
3161     }
3162   if (exec_bfd)
3163     write_pc (bfd_get_start_address (exec_bfd));
3164
3165   inferior_pid = 0;             /* No process now */
3166
3167 /* This is necessary because many things were based on the PC at the time that
3168    we attached to the monitor, which is no longer valid now that we have loaded
3169    new code (and just changed the PC).  Another way to do this might be to call
3170    normal_stop, except that the stack may not be valid, and things would get
3171    horribly confused... */
3172
3173   clear_symtab_users ();
3174 }
3175 \f
3176 /* The target vector.  */
3177
3178 struct target_ops mips_ops =
3179 {
3180   "mips",                       /* to_shortname */
3181   "Remote MIPS debugging over serial line",     /* to_longname */
3182   "\
3183 Debug a board using the MIPS remote debugging protocol over a serial line.\n\
3184 The argument is the device it is connected to or, if it contains a colon,\n\
3185 HOST:PORT to access a board over a network",  /* to_doc */
3186   mips_open,                    /* to_open */
3187   mips_close,                   /* to_close */
3188   NULL,                         /* to_attach */
3189   mips_detach,                  /* to_detach */
3190   mips_resume,                  /* to_resume */
3191   mips_wait,                    /* to_wait */
3192   mips_fetch_registers,         /* to_fetch_registers */
3193   mips_store_registers,         /* to_store_registers */
3194   mips_prepare_to_store,        /* to_prepare_to_store */
3195   mips_xfer_memory,             /* to_xfer_memory */
3196   mips_files_info,              /* to_files_info */
3197   mips_insert_breakpoint,       /* to_insert_breakpoint */
3198   mips_remove_breakpoint,       /* to_remove_breakpoint */
3199   NULL,                         /* to_terminal_init */
3200   NULL,                         /* to_terminal_inferior */
3201   NULL,                         /* to_terminal_ours_for_output */
3202   NULL,                         /* to_terminal_ours */
3203   NULL,                         /* to_terminal_info */
3204   mips_kill,                    /* to_kill */
3205   mips_load,                    /* to_load */
3206   NULL,                         /* to_lookup_symbol */
3207   mips_create_inferior,         /* to_create_inferior */
3208   mips_mourn_inferior,          /* to_mourn_inferior */
3209   NULL,                         /* to_can_run */
3210   NULL,                         /* to_notice_signals */
3211   0,                            /* to_thread_alive */
3212   0,                            /* to_stop */
3213   process_stratum,              /* to_stratum */
3214   NULL,                         /* to_next */
3215   1,                            /* to_has_all_memory */
3216   1,                            /* to_has_memory */
3217   1,                            /* to_has_stack */
3218   1,                            /* to_has_registers */
3219   1,                            /* to_has_execution */
3220   NULL,                         /* sections */
3221   NULL,                         /* sections_end */
3222   OPS_MAGIC                     /* to_magic */
3223 };
3224 \f
3225 /* An alternative target vector: */
3226 struct target_ops pmon_ops =
3227 {
3228   "pmon",                       /* to_shortname */
3229   "Remote MIPS debugging over serial line",     /* to_longname */
3230   "\
3231 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3232 line. The argument is the device it is connected to or, if it contains a\n\
3233 colon, HOST:PORT to access a board over a network",  /* to_doc */
3234   pmon_open,                    /* to_open */
3235   mips_close,                   /* to_close */
3236   NULL,                         /* to_attach */
3237   mips_detach,                  /* to_detach */
3238   mips_resume,                  /* to_resume */
3239   pmon_wait,                    /* to_wait */
3240   mips_fetch_registers,         /* to_fetch_registers */
3241   mips_store_registers,         /* to_store_registers */
3242   mips_prepare_to_store,        /* to_prepare_to_store */
3243   mips_xfer_memory,             /* to_xfer_memory */
3244   mips_files_info,              /* to_files_info */
3245   mips_insert_breakpoint,       /* to_insert_breakpoint */
3246   mips_remove_breakpoint,       /* to_remove_breakpoint */
3247   NULL,                         /* to_terminal_init */
3248   NULL,                         /* to_terminal_inferior */
3249   NULL,                         /* to_terminal_ours_for_output */
3250   NULL,                         /* to_terminal_ours */
3251   NULL,                         /* to_terminal_info */
3252   mips_kill,                    /* to_kill */
3253   mips_load,                    /* to_load */
3254   NULL,                         /* to_lookup_symbol */
3255   mips_create_inferior,         /* to_create_inferior */
3256   mips_mourn_inferior,          /* to_mourn_inferior */
3257   NULL,                         /* to_can_run */
3258   NULL,                         /* to_notice_signals */
3259   0,                            /* to_thread_alive */
3260   0,                            /* to_stop */
3261   process_stratum,              /* to_stratum */
3262   NULL,                         /* to_next */
3263   1,                            /* to_has_all_memory */
3264   1,                            /* to_has_memory */
3265   1,                            /* to_has_stack */
3266   1,                            /* to_has_registers */
3267   1,                            /* to_has_execution */
3268   NULL,                         /* sections */
3269   NULL,                         /* sections_end */
3270   OPS_MAGIC                     /* to_magic */
3271 };
3272 \f
3273 /* Another alternative target vector. This is a PMON system, but with
3274    a different monitor prompt, aswell as some other operational
3275    differences: */
3276 struct target_ops ddb_ops =
3277 {
3278   "ddb",                        /* to_shortname */
3279   "Remote MIPS debugging over serial line",     /* to_longname */
3280   "\
3281 Debug a board using the PMON MIPS remote debugging protocol over a serial\n\
3282 line. The first argument is the device it is connected to or, if it contains\n\
3283 a colon, HOST:PORT to access a board over a network.  The optional second\n\
3284 parameter is the temporary file in the form HOST:FILENAME to be used for\n\
3285 TFTP downloads to the board.  The optional third parameter is the local\n\
3286 of the TFTP temporary file, if it differs from the filename seen by the board",
3287                                 /* to_doc */
3288   ddb_open,                     /* to_open */
3289   mips_close,                   /* to_close */
3290   NULL,                         /* to_attach */
3291   mips_detach,                  /* to_detach */
3292   mips_resume,                  /* to_resume */
3293   pmon_wait,                    /* to_wait */
3294   mips_fetch_registers,         /* to_fetch_registers */
3295   mips_store_registers,         /* to_store_registers */
3296   mips_prepare_to_store,        /* to_prepare_to_store */
3297   mips_xfer_memory,             /* to_xfer_memory */
3298   mips_files_info,              /* to_files_info */
3299   mips_insert_breakpoint,       /* to_insert_breakpoint */
3300   mips_remove_breakpoint,       /* to_remove_breakpoint */
3301   NULL,                         /* to_terminal_init */
3302   NULL,                         /* to_terminal_inferior */
3303   NULL,                         /* to_terminal_ours_for_output */
3304   NULL,                         /* to_terminal_ours */
3305   NULL,                         /* to_terminal_info */
3306   mips_kill,                    /* to_kill */
3307   mips_load,                    /* to_load */
3308   NULL,                         /* to_lookup_symbol */
3309   mips_create_inferior,         /* to_create_inferior */
3310   mips_mourn_inferior,          /* to_mourn_inferior */
3311   NULL,                         /* to_can_run */
3312   NULL,                         /* to_notice_signals */
3313   0,                            /* to_thread_alive */
3314   0,                            /* to_stop */
3315   process_stratum,              /* to_stratum */
3316   NULL,                         /* to_next */
3317   1,                            /* to_has_all_memory */
3318   1,                            /* to_has_memory */
3319   1,                            /* to_has_stack */
3320   1,                            /* to_has_registers */
3321   1,                            /* to_has_execution */
3322   NULL,                         /* sections */
3323   NULL,                         /* sections_end */
3324   OPS_MAGIC                     /* to_magic */
3325 };
3326 \f
3327 void
3328 _initialize_remote_mips ()
3329 {
3330   add_target (&mips_ops);
3331   add_target (&pmon_ops);
3332   add_target (&ddb_ops);
3333
3334   add_show_from_set (
3335     add_set_cmd ("timeout", no_class, var_zinteger,
3336                  (char *) &mips_receive_wait,
3337                  "Set timeout in seconds for remote MIPS serial I/O.",
3338                  &setlist),
3339         &showlist);
3340
3341   add_show_from_set (
3342     add_set_cmd ("retransmit-timeout", no_class, var_zinteger,
3343                  (char *) &mips_retransmit_wait,
3344          "Set retransmit timeout in seconds for remote MIPS serial I/O.\n\
3345 This is the number of seconds to wait for an acknowledgement to a packet\n\
3346 before resending the packet.", &setlist),
3347         &showlist);
3348
3349   add_show_from_set (
3350     add_set_cmd ("syn-garbage-limit", no_class, var_zinteger,
3351                  (char *) &mips_syn_garbage,
3352 "Set the maximum number of characters to ignore when scanning for a SYN.\n\
3353 This is the maximum number of characters GDB will ignore when trying to\n\
3354 synchronize with the remote system.  A value of -1 means that there is no limit\n\
3355 (Note that these characters are printed out even though they are ignored.)",
3356                  &setlist),
3357                      &showlist);
3358 }