* Makefile.in: Add rules for monitor.o and rom68k-rom.o to make
[binutils-gdb.git] / gdb / monitor.c
1 /* Remote debugging interface for boot monitors, for GDB.
2 Copyright 1990, 1991, 1992, 1993, 1995 Free Software Foundation, Inc.
3 Contributed by Cygnus Support. Written by Rob Savoye for Cygnus.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
20
21 /* This file was derived from various remote-* modules. It is a collection
22 of generic support functions so GDB can talk directly to a ROM based
23 monitor. This saves use from having to hack an exception based handler
24 into existance, and makes for quick porting.
25
26 This module talks to a debug monitor called 'MONITOR', which
27 We communicate with MONITOR via either a direct serial line, or a TCP
28 (or possibly TELNET) stream to a terminal multiplexor,
29 which in turn talks to the target board. */
30
31 #include "defs.h"
32 #include "gdbcore.h"
33 #include "target.h"
34 #include "wait.h"
35 #include <varargs.h>
36 #include <signal.h>
37 #include <string.h>
38 #include <sys/types.h>
39 #include "command.h"
40 #include "serial.h"
41 #include "monitor.h"
42 #include "gdbcmd.h"
43 #include "inferior.h"
44
45 static void make_xmodem_packet ();
46 static void print_xmodem_packet ();
47
48 static void monitor_load_ascii_srec PARAMS ((char *file, int fromtty));
49
50 static int monitor_make_srec PARAMS ((char *buffer, int type,
51 CORE_ADDR memaddr,
52 unsigned char *myaddr, int len));
53
54 static void monitor_fetch_register PARAMS ((int regno));
55 static void monitor_store_register PARAMS ((int regno));
56
57 static int from_hex ();
58 static unsigned long get_hex_word PARAMS ((void));
59
60 struct monitor_ops *current_monitor;
61
62 static char *loadtype_str = "srec";
63 static char *loadproto_str = "none";
64
65 static int hashmark; /* flag set by "set hash" */
66
67 static int timeout = 30;
68
69 static int expect PARAMS ((char *string, char *buf, int buflen));
70 static int expect_prompt PARAMS ((char *buf, int buflen));
71
72 /* Having this larger than 400 causes us to be incompatible with m68k-stub.c
73 and i386-stub.c. Normally, no one would notice because it only matters
74 for writing large chunks of memory (e.g. in downloads). Also, this needs
75 to be more than 400 if required to hold the registers (see below, where
76 we round it up based on REGISTER_BYTES). */
77
78 #define PBUFSIZ 400
79
80 /* Descriptor for I/O to remote machine. Initialize it to NULL so
81 that monitor_open knows that we don't have a file open when the
82 program starts. */
83
84 static serial_t monitor_desc = NULL;
85
86 static void monitor_load_srec ();
87
88 /* These definitions are for xmodem protocol. */
89
90 #define SOH 0x01
91 #define ACK 0x06
92 #define NAK 0x15
93 #define EOT 0x04
94 #define CANCEL 0x18
95 #define GETACK getacknak(ACK)
96 #define GETNAK getacknak(NAK)
97 #define XMODEM_DATASIZE 128 /* the data size is ALWAYS 128 */
98 #define XMODEM_PACKETSIZE 131 /* the packet size is ALWAYS 132 (zero based) */
99 #define XMODEM 1
100
101 static unsigned char output_buf[0x200];
102 static int obp;
103
104 static void
105 debug_save_output (buf, len)
106 unsigned char *buf;
107 int len;
108 {
109 #if 0
110 for (; len > 0; len--)
111 output_buf[obp++ & 0x1ff] = *buf++;
112 #else
113 fputs_unfiltered (buf, gdb_stdout);
114 #endif
115 }
116
117 static unsigned char input_buf[0x200];
118 static int ibp;
119
120 static void
121 debug_save_input_char (c)
122 int c;
123 {
124 #if 0
125 input_buf[ibp++ & 0x1ff] = c;
126 #else
127 fputc_unfiltered (c, gdb_stdout);
128 #endif
129 }
130
131 /* printf_monitor -- send data to monitor. Works just like printf. */
132
133 static void
134 printf_monitor (va_alist)
135 va_dcl
136 {
137 va_list args;
138 char *pattern;
139 char buf[PBUFSIZ];
140
141 va_start (args);
142
143 pattern = va_arg (args, char *);
144
145 vsprintf (buf, pattern, args);
146
147 if (remote_debug > 0)
148 debug_save_output (buf, strlen (buf));
149
150 if (strlen (buf) > PBUFSIZ)
151 error ("printf_monitor(): string too long");
152 if (SERIAL_WRITE(monitor_desc, buf, strlen (buf)))
153 fprintf_unfiltered (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror (errno));
154 }
155
156 /* Send raw data to monitor. */
157
158 static void
159 write_monitor (data, len)
160 char *data;
161 int len;
162 {
163 if (SERIAL_WRITE (monitor_desc, data, len))
164 fprintf_unfiltered (stderr, "SERIAL_WRITE failed: %s\n", safe_strerror(errno));
165
166 *(data + len + 1) = '\0';
167 }
168
169 /* Read a character from the remote system, doing all the fancy
170 timeout stuff. */
171
172 static int
173 readchar (timeout)
174 int timeout;
175 {
176 int c;
177
178 c = SERIAL_READCHAR (monitor_desc, timeout);
179
180 if (remote_debug > 0)
181 debug_save_input_char (c & 0x7f);
182
183 if (c >= 0)
184 return c & 0x7f;
185
186 if (c == SERIAL_TIMEOUT)
187 {
188 if (timeout == 0)
189 return c; /* Polls shouldn't generate timeout errors */
190 error ("Timeout reading from remote system.");
191 }
192 perror_with_name ("remote-monitor");
193 }
194
195 /* Scan input from the remote system, until STRING is found. If BUF is non-
196 zero, then collect input until either STRING has been collected or BUFLEN
197 chars have been collected. If input overflows BUF because STRING can't be
198 found, return -1, else return number of chars in BUF (including STRING). */
199
200 static int
201 expect (string, buf, buflen)
202 char *string;
203 char *buf;
204 int buflen;
205 {
206 char *p = string;
207 int obuflen = buflen;
208 int c;
209
210 immediate_quit = 1;
211 while (1)
212 {
213 if (buf)
214 {
215 if (buflen <= 0)
216 {
217 immediate_quit = 0;
218 return -1;
219 }
220
221 c = readchar (timeout);
222 *buf++ = c;
223 buflen--;
224 }
225 else
226 c = readchar (timeout);
227
228 if (c == *p++)
229 {
230 if (*p == '\0')
231 {
232 immediate_quit = 0;
233
234 return obuflen - buflen;
235 }
236 }
237 else
238 {
239 p = string;
240 if (c == *p)
241 p++;
242 }
243 }
244 }
245
246 /* Keep discarding input until we see the MONITOR prompt.
247
248 The convention for dealing with the prompt is that you
249 o give your command
250 o *then* wait for the prompt.
251
252 Thus the last thing that a procedure does with the serial line
253 will be an expect_prompt(). Exception: monitor_resume does not
254 wait for the prompt, because the terminal is being handed over
255 to the inferior. However, the next thing which happens after that
256 is a monitor_wait which does wait for the prompt.
257 Note that this includes abnormal exit, e.g. error(). This is
258 necessary to prevent getting into states from which we can't
259 recover. */
260
261 static int
262 expect_prompt (buf, buflen)
263 char *buf;
264 int buflen;
265 {
266 return expect (PROMPT, buf, buflen);
267 }
268
269 /* Ignore junk characters. Returns a 1 if junk, 0 otherwise. */
270
271 static int
272 junk (ch)
273 char ch;
274 {
275 switch (ch)
276 {
277 case '\0':
278 case ' ':
279 case '-':
280 case '\t':
281 case '\r':
282 case '\n':
283 return 1;
284 default:
285 return 0;
286 }
287 }
288
289 /* Get a hex digit from the remote system & return its value. If
290 ignore is nonzero, ignore spaces, newline & tabs. */
291
292 static int
293 get_hex_digit (ignore)
294 int ignore;
295 {
296 static int ch;
297
298 while (1)
299 {
300 ch = readchar (timeout);
301 if (junk (ch))
302 continue;
303
304 if (ch >= '0' && ch <= '9')
305 return ch - '0';
306 else if (ch >= 'A' && ch <= 'F')
307 return ch - 'A' + 10;
308 else if (ch >= 'a' && ch <= 'f')
309 return ch - 'a' + 10;
310 else if (ch == ' ' && ignore)
311 ;
312 else
313 {
314 expect_prompt (NULL, 0);
315 error ("Invalid hex digit from remote system. (0x%x)", ch);
316 }
317 }
318 }
319
320 /* Get a byte from monitor and put it in *BYT. Accept any number of
321 leading spaces. */
322
323 static void
324 get_hex_byte (byt)
325 char *byt;
326 {
327 int val;
328
329 val = get_hex_digit (1) << 4;
330
331 val |= get_hex_digit (0);
332 *byt = val;
333 }
334
335 /* Get N 32-bit words from remote, each preceded by a space, and put
336 them in registers starting at REGNO. */
337
338 static unsigned long
339 get_hex_word ()
340 {
341 unsigned long val;
342 int i;
343 int ch;
344
345 do
346 ch = readchar (timeout);
347 while (isspace(ch));
348
349 val = from_hex (ch);
350
351 for (i = 7; i >= 1; i--)
352 {
353 ch = readchar (timeout);
354 if (!isxdigit (ch))
355 break;
356 val = (val << 4) | from_hex (ch);
357 }
358
359 return val;
360 }
361
362 /* This is called not only when we first attach, but also when the
363 user types "run" after having attached. */
364
365 void
366 monitor_create_inferior (execfile, args, env)
367 char *execfile;
368 char *args;
369 char **env;
370 {
371 int entry_pt;
372
373 if (args && *args)
374 error ("Can't pass arguments to remote MONITOR process");
375
376 if (execfile == 0 || exec_bfd == 0)
377 error ("No exec file specified");
378
379 entry_pt = (int) bfd_get_start_address (exec_bfd);
380
381 /* The "process" (board) is already stopped awaiting our commands, and
382 the program is already downloaded. We just set its PC and go. */
383
384 clear_proceed_status ();
385
386 /* Tell wait_for_inferior that we've started a new process. */
387 init_wait_for_inferior ();
388
389 /* Set up the "saved terminal modes" of the inferior
390 based on what modes we are starting it with. */
391 target_terminal_init ();
392
393 /* Install inferior's terminal modes. */
394 target_terminal_inferior ();
395
396 /* insert_step_breakpoint (); FIXME, do we need this? */
397
398 /* Let 'er rip... */
399 proceed ((CORE_ADDR)entry_pt, TARGET_SIGNAL_DEFAULT, 0);
400 }
401
402 /* Open a connection to a remote debugger. NAME is the filename used
403 for communication. */
404
405 static char *dev_name;
406
407 void
408 monitor_open (args, mon_ops, from_tty)
409 char *args;
410 struct monitor_ops *mon_ops;
411 int from_tty;
412 {
413 struct target_ops *targ_ops;
414 char *name;
415 int i;
416
417 targ_ops = mon_ops->target;
418 name = targ_ops->to_shortname;
419
420 if (!args)
421 error ("Use `target %s DEVICE-NAME' to use a serial port, or \n\
422 `target %s HOST-NAME:PORT-NUMBER' to use a network connection.", name, name);
423
424 target_preopen (from_tty);
425
426 unpush_target (targ_ops);
427
428 if (dev_name)
429 free (dev_name);
430 dev_name = strsave (args);
431
432 monitor_desc = SERIAL_OPEN (dev_name);
433
434 if (!monitor_desc)
435 perror_with_name (dev_name);
436
437 if (baud_rate != -1)
438 {
439 if (SERIAL_SETBAUDRATE (monitor_desc, baud_rate))
440 {
441 SERIAL_CLOSE (monitor_desc);
442 perror_with_name (dev_name);
443 }
444 }
445
446 SERIAL_RAW (monitor_desc);
447
448 SERIAL_FLUSH_INPUT (monitor_desc);
449
450 /* some systems only work with 2 stop bits */
451
452 SERIAL_SETSTOPBITS (monitor_desc, mon_ops->stopbits);
453
454 current_monitor = mon_ops;
455
456 /* see if the target is alive. For a ROM monitor, we can just try to
457 force the prompt to print a few times. */
458
459 /* wake up the monitor and see if it's alive */
460 printf_monitor (mon_ops->init);
461 expect_prompt (NULL, 0); /* See if we get a prompt */
462
463 /* try again to be sure */
464 printf_monitor (mon_ops->init);
465 expect_prompt (NULL, 0); /* See if we get a prompt */
466
467 /* Setup the suffixes for the `set remoteloadtype' command */
468
469 add_show_from_set (add_set_enum_cmd ("remoteloadtype", no_class,
470 mon_ops->loadtypes,
471 (char *)&loadtype_str,
472 "Set the remote load type.",
473 &setlist),
474 &showlist);
475
476 /* Setup the suffixes for the `set remoteloadprotocol' command */
477
478 add_show_from_set (add_set_enum_cmd ("remoteloadprotocol", no_class,
479 mon_ops->loadprotos,
480 (char *)&loadproto_str,
481 "Set the remote load protocol.",
482 &setlist),
483 &showlist);
484
485 if (from_tty)
486 printf_unfiltered ("Remote target %s connected to %s\n", name, dev_name);
487
488 push_target (targ_ops);
489
490 inferior_pid = 42000; /* Make run command think we are busy... */
491
492 printf_monitor ("\r");
493
494 start_remote ();
495 }
496
497 /* Close out all files and local state before this target loses
498 control. */
499
500 void
501 monitor_close (quitting)
502 int quitting;
503 {
504 if (monitor_desc)
505 SERIAL_CLOSE (monitor_desc);
506 monitor_desc = NULL;
507 }
508
509 /* Terminate the open connection to the remote debugger. Use this
510 when you want to detach and do something else with your gdb. */
511
512 void
513 monitor_detach (args, from_tty)
514 char *args;
515 int from_tty;
516 {
517 pop_target (); /* calls monitor_close to do the real work */
518 if (from_tty)
519 printf_unfiltered ("Ending remote %s debugging\n", target_shortname);
520 }
521
522 /* Tell the remote machine to resume. */
523
524 void
525 monitor_resume (pid, step, sig)
526 int pid, step;
527 enum target_signal sig;
528 {
529 if (step)
530 printf_monitor (STEP_CMD);
531 else
532 printf_monitor (CONT_CMD);
533 }
534
535 /* Wait until the remote machine stops, then return, storing status in
536 status just as `wait' would. */
537
538 int
539 monitor_wait (pid, status)
540 int pid;
541 struct target_waitstatus *status;
542 {
543 int old_timeout = timeout;
544
545 status->kind = TARGET_WAITKIND_EXITED;
546 status->value.integer = 0;
547
548 timeout = -1; /* Don't time out -- user program is running. */
549
550 expect_prompt (NULL, 0); /* Wait for prompt, outputting extraneous text */
551
552 status->kind = TARGET_WAITKIND_STOPPED;
553 status->value.sig = TARGET_SIGNAL_TRAP;
554
555 timeout = old_timeout;
556
557 return inferior_pid;
558 }
559
560 /* Return the name of register number regno in the form input and output by
561 monitor. Currently, register_names just happens to contain exactly what
562 monitor wants. Lets take advantage of that just as long as possible! */
563
564 static char *
565 get_reg_name (regno)
566 int regno;
567 {
568 if (regno < 0 || regno > NUM_REGS)
569 return NULL;
570 else
571 return REGNAMES (regno);
572 }
573
574 /* Fetch register REGNO, or all registers if REGNO is -1. Returns
575 errno value. */
576
577 static void
578 monitor_fetch_register (regno)
579 int regno;
580 {
581 unsigned LONGEST val;
582 unsigned char regbuf[MAX_REGISTER_RAW_SIZE];
583 char buf[200];
584 char *p, *p1;
585 char *name;
586 int resp_len;
587
588 name = get_reg_name (regno);
589
590 if (!name)
591 return;
592
593 /* send the register examine command */
594
595 printf_monitor (current_monitor->getreg.cmd, name);
596
597 /* If TERM is present, we wait for that to show up. Also, (if TERM is
598 present), we will send TERM_CMD if that is present. In any case, we collect
599 all of the output into buf, and then wait for the normal prompt. */
600
601 if (current_monitor->getreg.term)
602 {
603 resp_len = expect (current_monitor->getreg.term, buf, sizeof buf); /* get response */
604
605 if (resp_len <= 0)
606 error ("monitor_fetch_register (%d): excessive response from monitor: %.*s.", resp_len, buf);
607
608 if (current_monitor->getreg.term_cmd)
609 {
610 SERIAL_WRITE (monitor_desc, current_monitor->getreg.term_cmd,
611 strlen (current_monitor->getreg.term_cmd));
612 expect_prompt (NULL, 0);
613 }
614 }
615 else
616 resp_len = expect_prompt (buf, sizeof buf); /* get response */
617
618
619 /* If RESP_DELIM is specified, we search for that as a leading delimiter for
620 the register value. Otherwise, we just start searching from the start of
621 the buf. */
622
623 if (current_monitor->getreg.resp_delim)
624 {
625 p = strstr (buf, current_monitor->getreg.resp_delim);
626 if (!p)
627 error ("monitor_fetch_register (%d): bad response from monitor: %.*s.", resp_len, buf);
628 p += strlen (current_monitor->getreg.resp_delim);
629 }
630 else
631 p = buf;
632
633 val = strtoul (p, &p1, 16);
634
635 if (val == 0 && p == p1)
636 error ("monitor_fetch_register (%d): bad value from monitor: %.*s.",
637 resp_len, buf);
638
639 /* supply register stores in target byte order, so swap here */
640
641 store_unsigned_integer (regbuf, REGISTER_RAW_SIZE (regno), val);
642
643 supply_register (regno, regbuf);
644 }
645
646 /* Read the remote registers into the block regs. */
647
648 void
649 monitor_fetch_registers (regno)
650 int regno;
651 {
652 if (regno >= 0)
653 {
654 monitor_fetch_register (regno);
655 return;
656 }
657
658 for (regno = 0; regno < NUM_REGS; regno++)
659 monitor_fetch_register (regno);
660 }
661
662 /* Store register REGNO, or all if REGNO == 0. Return errno value. */
663
664 static void
665 monitor_store_register (regno)
666 int regno;
667 {
668 char *name;
669 unsigned LONGEST val;
670
671 name = get_reg_name (regno);
672 if (!name)
673 return;
674
675 val = read_register (regno);
676
677 /* send the register deposit command */
678
679 printf_monitor (current_monitor->setreg.cmd, name, val);
680
681 /* It's possible that there are actually some monitors out there that will
682 prompt you when you set a register. In that case, you may need to add some
683 code here to deal with TERM and TERM_CMD (see monitor_fetch_register to get
684 an idea of what's needed...) */
685
686 expect_prompt (NULL, 0);
687 }
688
689 /* Store the remote registers. */
690
691 void
692 monitor_store_registers (regno)
693 int regno;
694 {
695 if (regno >= 0)
696 {
697 monitor_store_register (regno);
698 return;
699 }
700
701 for (regno = 0; regno < NUM_REGS; regno++)
702 monitor_store_register (regno);
703 }
704
705 /* Get ready to modify the registers array. On machines which store
706 individual registers, this doesn't need to do anything. On machines
707 which store all the registers in one fell swoop, this makes sure
708 that registers contains all the registers from the program being
709 debugged. */
710
711 void
712 monitor_prepare_to_store ()
713 {
714 /* Do nothing, since we can store individual regs */
715 }
716
717 void
718 monitor_files_info ()
719 {
720 printf_unfiltered ("\tAttached to %s at %d baud.\n", dev_name, baud_rate);
721 }
722
723 static int
724 monitor_write_memory (memaddr, myaddr, len)
725 CORE_ADDR memaddr;
726 unsigned char *myaddr;
727 int len;
728 {
729 /* send the memory deposit command */
730
731 printf_monitor (current_monitor->setmem.cmd, memaddr, *myaddr);
732
733 /* It's possible that there are actually some monitors out there that will
734 prompt you when you deposit to memory. In that case, you may need to add
735 some code here to deal with TERM and TERM_CMD (see monitor_read_memory to
736 get an idea of what's needed...) */
737
738 expect_prompt (NULL, 0);
739
740 return 1;
741 }
742
743 /* Copy LEN bytes of data from debugger memory at MYADDR to inferior's memory
744 at MEMADDR. Returns length moved. Currently, we only do one byte at a
745 time. */
746
747 static int
748 monitor_read_memory (memaddr, myaddr, len)
749 CORE_ADDR memaddr;
750 char *myaddr;
751 int len;
752 {
753 unsigned LONGEST val;
754 unsigned char regbuf[MAX_REGISTER_RAW_SIZE];
755 char buf[200];
756 char *p, *p1;
757 char *name;
758 int resp_len;
759
760 /* send the memory examine command */
761
762 printf_monitor (current_monitor->getmem.cmd, memaddr);
763
764 /* If TERM is present, we wait for that to show up. Also, (if TERM is
765 present), we will send TERM_CMD if that is present. In any case, we collect
766 all of the output into buf, and then wait for the normal prompt. */
767
768 if (current_monitor->getmem.term)
769 {
770 resp_len = expect (current_monitor->getmem.term, buf, sizeof buf); /* get response */
771
772 if (resp_len <= 0)
773 error ("monitor_read_memory (%d): excessive response from monitor: %.*s.", resp_len, buf);
774
775 if (current_monitor->getmem.term_cmd)
776 {
777 SERIAL_WRITE (monitor_desc, current_monitor->getmem.term_cmd,
778 strlen (current_monitor->getmem.term_cmd));
779 expect_prompt (NULL, 0);
780 }
781 }
782 else
783 resp_len = expect_prompt (buf, sizeof buf); /* get response */
784
785 /* If RESP_DELIM is specified, we search for that as a leading delimiter for
786 the register value. Otherwise, we just start searching from the start of
787 the buf. */
788
789 if (current_monitor->getmem.resp_delim)
790 {
791 p = strstr (buf, current_monitor->getmem.resp_delim);
792 if (!p)
793 error ("monitor_read_memory (%d): bad response from monitor: %.*s.", resp_len, buf);
794 p += strlen (current_monitor->getmem.resp_delim);
795 }
796 else
797 p = buf;
798
799 val = strtoul (p, &p1, 16);
800
801 if (val == 0 && p == p1)
802 error ("monitor_read_memory (%d): bad value from monitor: %.*s.",
803 resp_len, buf);
804
805 *myaddr = val;
806
807 return 1; /* Got 1 byte */
808 }
809
810 /* FIXME-someday! merge these two. */
811
812 int
813 monitor_xfer_memory (memaddr, myaddr, len, write, target)
814 CORE_ADDR memaddr;
815 char *myaddr;
816 int len;
817 int write;
818 struct target_ops *target; /* ignored */
819 {
820 if (write)
821 return monitor_write_memory (memaddr, myaddr, len);
822 else
823 return monitor_read_memory (memaddr, myaddr, len);
824 }
825
826 void
827 monitor_kill (args, from_tty)
828 char *args;
829 int from_tty;
830 {
831 return; /* ignore attempts to kill target system */
832 }
833
834 /* Clean up when a program exits.
835 The program actually lives on in the remote processor's RAM, and may be
836 run again without a download. Don't leave it full of breakpoint
837 instructions. */
838
839 void
840 monitor_mourn_inferior ()
841 {
842 remove_breakpoints ();
843 generic_mourn_inferior (); /* Do all the proper things now */
844 }
845
846 #define NUM_MONITOR_BREAKPOINTS 8
847
848 static CORE_ADDR breakaddr[NUM_MONITOR_BREAKPOINTS] = {0};
849
850 /* Tell the monitor to add a breakpoint. */
851
852 int
853 monitor_insert_breakpoint (addr, shadow)
854 CORE_ADDR addr;
855 char *shadow;
856 {
857 int i;
858 static unsigned char break_insn[] = BREAKPOINT;
859
860 for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
861 {
862 if (breakaddr[i] == 0)
863 {
864 breakaddr[i] = addr;
865 monitor_read_memory (addr, shadow, sizeof (break_insn));
866 printf_monitor (SET_BREAK_CMD, addr);
867 expect_prompt (NULL, 0);
868 return 0;
869 }
870 }
871
872 error ("Too many breakpoints (> %d) for monitor.", NUM_MONITOR_BREAKPOINTS);
873 }
874
875 /* Tell the monitor to remove a breakpoint. */
876
877 int
878 monitor_remove_breakpoint (addr, shadow)
879 CORE_ADDR addr;
880 char *shadow;
881 {
882 int i;
883
884 for (i = 0; i < NUM_MONITOR_BREAKPOINTS; i++)
885 {
886 if (breakaddr[i] == addr)
887 {
888 breakaddr[i] = 0;
889 /* some monitors remove breakpoints based on the address */
890 if (CLR_BREAK_ADDR)
891 printf_monitor(CLR_BREAK_CMD, addr);
892 else
893 printf_monitor(CLR_BREAK_CMD, i);
894 expect_prompt (NULL, 0);
895 return 0;
896 }
897 }
898 fprintf_unfiltered (stderr, "Can't find breakpoint associated with 0x%x\n", addr);
899 return 1;
900 }
901
902 /* monitor_load -- load a file. This file determines which of the
903 * supported formats to use. The current types are:
904 * FIXME: not all types supported yet.
905 * default - reads any file using bfd and writes it to memory. This
906 * is really slow.
907 * srec - reads binary file using bfd and writes it as an
908 * ascii srecord.
909 * xmodem-bin - reads a binary file using bfd, and downloads it
910 * using xmodem protocol.
911 * xmodem-srec - reads a binary file using bfd, and after converting
912 * it downloads it as an srecord using xmodem protocol.
913 * ascii-srec - reads a ascii srecord file and downloads it
914 * without a change.
915 * ascii-xmodem - reads a ascii file and downloads using xmodem
916 * protocol.
917 */
918
919 void
920 monitor_load (file, fromtty)
921 char *file;
922 int fromtty;
923 {
924 /* default, load a binary */
925 if (STREQ (loadtype_str, "default"))
926 {
927 error ("default load type not supported.");
928 }
929
930 /* load an srecord by converting */
931 if ((STREQ (loadtype_str, "srec")) && STREQ (loadproto_str, "xmodem"))
932 {
933 monitor_load_srec (file, XMODEM);
934 return;
935 }
936
937 /* load an srecord by converting */
938 if (STREQ (loadtype_str, "srec"))
939 {
940 monitor_load_srec (file, 0); /* if from a binary */
941 return;
942 }
943
944 /* load an srecord by converting */
945 if (STREQ (loadtype_str, "none"))
946 {
947 error ("Unimplemented");
948 return;
949 }
950
951 /* load an srecord file */
952 if (STREQ (loadproto_str, "none"))
953 {
954 monitor_load_ascii_srec (file, fromtty); /* if from a binary */
955 return;
956 }
957
958 if (STREQ (loadproto_str, "xmodem"))
959 {
960 monitor_load_srec (file, XMODEM);
961 return;
962 }
963 }
964
965 /* Download an ASCII srecord file. */
966
967 #define DOWNLOAD_LINE_SIZE 100
968
969 static void
970 monitor_load_ascii_srec (file, fromtty)
971 char *file;
972 int fromtty;
973 {
974 FILE *download;
975 char buf[DOWNLOAD_LINE_SIZE];
976 int i, bytes_read;
977
978 download = fopen (file, "r");
979 if (download == NULL)
980 {
981 error ("%s does not exist", file);
982 return;
983 }
984
985 printf_monitor (LOAD_CMD);
986 sleep (1);
987 while (!feof (download))
988 {
989 bytes_read = fread (buf, sizeof (char), DOWNLOAD_LINE_SIZE, download);
990 if (hashmark)
991 {
992 putchar_unfiltered ('.');
993 gdb_flush (gdb_stdout);
994 }
995 if (SERIAL_WRITE (monitor_desc, buf, bytes_read))
996 {
997 fprintf_unfiltered (stderr, "SERIAL_WRITE failed: (while downloading) %s\n",
998 safe_strerror (errno));
999 break;
1000 }
1001 i = 0;
1002 while (i++ <=200) {} ; /* Ugly HACK, probably needs flow control */
1003 if (bytes_read < DOWNLOAD_LINE_SIZE)
1004 {
1005 if (!feof (download))
1006 error ("Only read %d bytes\n", bytes_read);
1007 break;
1008 }
1009 }
1010
1011 if (hashmark)
1012 putchar_unfiltered ('\n');
1013
1014 if (!feof (download))
1015 error ("Never got EOF while downloading");
1016 expect_prompt (NULL, 0);
1017 fclose (download);
1018 }
1019
1020 /* Put a command string, in args, out to MONITOR. Output from MONITOR
1021 is placed on the users terminal until the prompt is seen. FIXME: We
1022 read the characters ourseleves here cause of a nasty echo. */
1023
1024 void
1025 monitor_command (args, fromtty)
1026 char *args;
1027 int fromtty;
1028 {
1029 char *p;
1030
1031 p = PROMPT;
1032
1033 if (monitor_desc == NULL)
1034 error ("monitor target not open.");
1035
1036 /* Send the command. Note that if no args were supplied, then we're
1037 just sending the monitor a newline, which is sometimes useful. */
1038
1039 printf_monitor ("%s\n", (args ? args : ""));
1040
1041 expect_prompt (NULL, 0);
1042 }
1043
1044 /* Download a binary file by converting it to srecords. This
1045 will also use xmodem to download the resulting file.
1046
1047 A download goes like this when using xmodem:
1048 Receiver: Sender
1049 NAK ---------->
1050 <-------- (packet) [SOH|1|1|data|SUM]
1051 ACK ---------->
1052 <-------- (packet) [SOH|2|2|data|SUM]
1053 ACK ---------->
1054 <-------- EOT
1055 ACK ---------->
1056
1057 ACK = 0x06
1058 NAK = 0x15
1059 EOT = 0x04
1060 */
1061
1062 static void
1063 monitor_load_srec (args, protocol)
1064 char *args;
1065 int protocol;
1066 {
1067 bfd *abfd;
1068 asection *s;
1069 char *buffer, srec[1024];
1070 char packet[XMODEM_PACKETSIZE];
1071 int i;
1072 int retries;
1073 int type = 0; /* default to a type 0, header record */
1074 int srec_frame = 57; /* FIXME: this must be 57 There is 12 bytes
1075 of header, and 2 bytes of checksum at the end.
1076 The problem is an xmodem packet holds exactly
1077 128 bytes. */
1078
1079 abfd = bfd_openr (args, 0);
1080 if (!abfd)
1081 {
1082 printf_filtered ("Unable to open file %s\n", args);
1083 return;
1084 }
1085
1086 if (bfd_check_format (abfd, bfd_object) == 0)
1087 {
1088 printf_filtered ("File is not an object file\n");
1089 return;
1090 }
1091
1092 printf_monitor (LOAD_CMD); /* tell the monitor to load */
1093 sleep (3);
1094 /* get the NAK from the target */
1095 if (protocol == XMODEM)
1096 {
1097 if (!GETNAK)
1098 {
1099 printf_monitor ("%c", EOT);
1100 error ("Never got the NAK to start loading");
1101 }
1102 }
1103
1104 s = abfd->sections;
1105 while (s != (asection *) NULL)
1106 {
1107 if (s->flags & SEC_LOAD)
1108 {
1109 buffer = xmalloc (srec_frame);
1110
1111 printf_filtered ("%s\t: 0x%4x .. 0x%4x ",
1112 s->name, s->vma, s->vma + s->_raw_size);
1113 gdb_flush (gdb_stdout);
1114 for (i = 0; i < s->_raw_size; i += srec_frame)
1115 {
1116 if (srec_frame > s->_raw_size - i)
1117 srec_frame = s->_raw_size - i;
1118
1119 bfd_get_section_contents (abfd, s, buffer, i, srec_frame);
1120 monitor_make_srec (srec, type, s->vma + i, buffer, srec_frame);
1121 /* send a packet using xmodem */
1122 if (protocol == XMODEM)
1123 {
1124 make_xmodem_packet (packet, srec, XMODEM_DATASIZE);
1125 write_monitor (packet, XMODEM_PACKETSIZE+1);
1126 retries = 0;
1127 while (retries++ <= 3)
1128 {
1129 /* Resend packet */
1130 if (GETNAK)
1131 {
1132 sleep (1);
1133 /* send it again */
1134 write_monitor (packet, XMODEM_PACKETSIZE+1);
1135 if (GETACK) /* ACKnowledged, get next data chunk */
1136 break;
1137 }
1138 else
1139 { /* assume we got an ACK */
1140 if (hashmark)
1141 {
1142 putchar_unfiltered ('#');
1143 gdb_flush (gdb_stdout);
1144 }
1145 break;
1146 }
1147 }
1148 if (retries >= 4)
1149 { /* too many tries, must be hosed */
1150 printf_monitor ("%c", EOT);
1151 error ("Never got a ACK after sending an xmodem packet");
1152 }
1153 }
1154 else
1155 { /* no protocols at all */
1156 printf_monitor ("%s\n", srec);
1157 }
1158 if (hashmark)
1159 {
1160 putchar_unfiltered ('#');
1161 gdb_flush (gdb_stdout);
1162 }
1163 type = 3; /* switch to a 4 byte address record */
1164 gdb_flush (gdb_stdout);
1165 }
1166 free (buffer);
1167 }
1168 s = s->next;
1169 }
1170 putchar_unfiltered ('\n');
1171
1172 /* Write a type 7 terminator record. no data for a type 7, and there
1173 is no data, so len is 0. */
1174
1175 if (protocol == XMODEM)
1176 {
1177 /* send a packet using xmodem */
1178 monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1179 make_xmodem_packet (packet, srec, XMODEM_DATASIZE);
1180 write_monitor (packet, XMODEM_PACKETSIZE+1);
1181 }
1182 else
1183 {
1184 monitor_make_srec (srec, 7, abfd->start_address, "", 0);
1185 printf_monitor ("%s\n", srec);
1186 }
1187 if (protocol == XMODEM)
1188 {
1189 printf_monitor ("%c", EOT);
1190 if (!GETACK)
1191 error ("Never got ACK after sending EOT");
1192 }
1193
1194 if (hashmark)
1195 putchar_unfiltered ('\n');
1196
1197 expect_prompt (NULL, 0);
1198 }
1199
1200 /* Get an ACK or a NAK from the target. returns 1 (true) or 0 (false)
1201 This is for xmodem. ANy string starting with "***" is an error
1202 message from the target. Here's a few from the WinBond w89k
1203 "Cougar" PA board:
1204 *** Too many errors found.
1205 *** Bad command
1206 *** Command syntax error
1207 */
1208
1209 int
1210 getacknak (byte)
1211 int byte;
1212 {
1213 char character;
1214 int i;
1215
1216 i = 0;
1217 while (i++ < 60)
1218 {
1219 character = (char) readchar (0);
1220 if ((character == 0xfffffffe) || (character == 0x7f))
1221 { /* empty uart */
1222 sleep (1);
1223 continue;
1224 }
1225 if (character == CANCEL)
1226 { /* target aborted load */
1227 expect_prompt (NULL, 0);
1228 error ("Got a CANCEL from the target.");
1229 }
1230 if (character == '*')
1231 { /* look for missed error message */
1232 expect_prompt (NULL, 0);
1233 error ("Got an error message from the target");
1234 }
1235 if (character == byte) /* got what we wanted */
1236 return 1;
1237 if (character == ((byte == ACK) ? NAK : ACK))
1238 return 0;
1239 sleep (1);
1240 }
1241
1242 return 0;
1243 }
1244
1245 /*
1246 * monitor_make_srec -- make an srecord. This writes each line, one at a
1247 * time, each with it's own header and trailer line.
1248 * An srecord looks like this:
1249 *
1250 * byte count-+ address
1251 * start ---+ | | data +- checksum
1252 * | | | |
1253 * S01000006F6B692D746573742E73726563E4
1254 * S315000448600000000000000000FC00005900000000E9
1255 * S31A0004000023C1400037DE00F023604000377B009020825000348D
1256 * S30B0004485A0000000000004E
1257 * S70500040000F6
1258 *
1259 * S<type><length><address><data><checksum>
1260 *
1261 * Where
1262 * - length
1263 * is the number of bytes following upto the checksum. Note that
1264 * this is not the number of chars following, since it takes two
1265 * chars to represent a byte.
1266 * - type
1267 * is one of:
1268 * 0) header record
1269 * 1) two byte address data record
1270 * 2) three byte address data record
1271 * 3) four byte address data record
1272 * 7) four byte address termination record
1273 * 8) three byte address termination record
1274 * 9) two byte address termination record
1275 *
1276 * - address
1277 * is the start address of the data following, or in the case of
1278 * a termination record, the start address of the image
1279 * - data
1280 * is the data.
1281 * - checksum
1282 * is the sum of all the raw byte data in the record, from the length
1283 * upwards, modulo 256 and subtracted from 255.
1284 */
1285
1286 static int
1287 monitor_make_srec (buffer, type, memaddr, myaddr, len)
1288 char *buffer;
1289 int type;
1290 CORE_ADDR memaddr;
1291 unsigned char *myaddr;
1292 int len;
1293 {
1294 int checksum;
1295 int i;
1296 char *buf;
1297
1298 buf = buffer;
1299
1300 checksum = 0;
1301
1302 /* Create the header for the srec. 4 is the number of bytes in the address,
1303 and 1 is the number of bytes in the count. */
1304
1305 if (type == 0) /* FIXME: type 0 is optional */
1306 type = 3; /* so use data as it works */
1307 sprintf (buf, "S%d%02X%08X", type, len + 4 + 1, memaddr);
1308 buf += 12;
1309
1310 checksum += (len + 4 + 1 /* calculate the checksum */
1311 + (memaddr & 0xff)
1312 + ((memaddr >> 8) & 0xff)
1313 + ((memaddr >> 16) & 0xff)
1314 + ((memaddr >> 24) & 0xff));
1315
1316 /* build the srecord */
1317 for (i = 0; i < len; i++)
1318 {
1319 sprintf (buf, "%02X", myaddr[i]);
1320 checksum += myaddr[i];
1321 buf += 2;
1322 }
1323
1324 sprintf(buf, "%02X", ~checksum & 0xff); /* add the checksum */
1325
1326 return 0;
1327 }
1328
1329 /* Take 128 bytes of data and make a packet out of it.
1330 *
1331 * Each packet looks like this:
1332 * +-----+-------+-------+------+-----+
1333 * | SOH | Seq1. | Seq2. | data | SUM |
1334 * +-----+-------+-------+------+-----+
1335 * SOH = 0x01
1336 * Seq1 = The sequence number.
1337 * Seq2 = The complement of the sequence number.
1338 * Data = A 128 bytes of data.
1339 * SUM = Add the contents of the 128 bytes and use the low-order
1340 * 8 bits of the result.
1341 */
1342
1343 static void
1344 make_xmodem_packet (packet, data, len)
1345 unsigned char *packet;
1346 unsigned char *data;
1347 int len;
1348 {
1349 static int sequence = 1;
1350 int i, sum;
1351 unsigned char *buf;
1352
1353 buf = data;
1354 /* build the packet header */
1355 packet[0] = SOH;
1356 packet[1] = sequence;
1357 packet[2] = 255 - sequence;
1358 sequence++;
1359 #if 0
1360 packet[2] = ~sequence++; /* the complement is the sequence checksum */
1361 #endif
1362
1363 sum = 0; /* calculate the data checksum */
1364 for (i = 3; i <= len + 2; i++) {
1365 packet[i] = *buf;
1366 sum += *buf;
1367 buf++;
1368 }
1369
1370 /* add padding for the rest of the packet */
1371 for (i = len+1 ; i <= XMODEM_DATASIZE ; i++)
1372 packet[i] = '0';
1373
1374 packet[XMODEM_PACKETSIZE] = sum & 0xff; /* add the checksum */
1375 }
1376
1377 /* Print the packet as a debug check. */
1378
1379 static void
1380 print_xmodem_packet (packet)
1381 char *packet;
1382 {
1383 int i;
1384 static int lastseq;
1385 int sum;
1386
1387 /* take apart the packet header the packet header */
1388 if (packet[0] == SOH)
1389 printf_unfiltered ("SOH");
1390 else
1391 error ("xmodem: SOH is wrong");
1392
1393 /* check the sequence */
1394 if (packet[1] != 0)
1395 {
1396 lastseq = packet[1];
1397 if (packet[2] != ~lastseq)
1398 error ("xmodem: Sequence checksum is wrong");
1399 else
1400 printf_filtered (" %d %d", lastseq, ~lastseq);
1401 }
1402
1403 /* check the data checksum */
1404 sum = 0;
1405 for (i = 3; i <= XMODEM_DATASIZE; i++)
1406 sum += packet[i];
1407
1408 /* ignore the data */
1409 #if 0
1410 printf_unfiltered (" [128 bytes of data] %d\n", sum & 0xff);
1411 #endif
1412 printf_filtered (" [%s] %d\n", packet, sum & 0xff);
1413
1414 if ((packet[XMODEM_PACKETSIZE] & 0xff) != (sum & 0xff))
1415 printf_unfiltered ("xmodem: data checksum wrong, got a %d",
1416 packet[XMODEM_PACKETSIZE] & 0xff);
1417
1418 putchar_unfiltered ('\n');
1419 }
1420
1421 /* Convert hex digit A to a number. */
1422
1423 static int
1424 from_hex (a)
1425 int a;
1426 {
1427 if (a >= '0' && a <= '9')
1428 return a - '0';
1429 if (a >= 'a' && a <= 'f')
1430 return a - 'a' + 10;
1431 if (a >= 'A' && a <= 'F')
1432 return a - 'A' + 10;
1433
1434 error ("Reply contains invalid hex digit 0x%x", a);
1435 }
1436
1437 /* Define additional commands that are usually only used by monitors. */
1438
1439 void
1440 _initialize_remote_monitors ()
1441 {
1442 add_show_from_set (add_set_cmd ("hash", no_class, var_boolean,
1443 (char *)&hashmark,
1444 "Set display of activity while downloading a file.\n\
1445 When enabled, a hashmark \'#\' is displayed.",
1446 &setlist),
1447 &showlist);
1448
1449 add_com ("monitor", class_obscure, monitor_command,
1450 "Send a command to the debug monitor.");
1451 }