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