* serial.h (SERIAL_SET_TTY_STATE): Comment return value.
[external/binutils.git] / gdb / remote-es.c
1 /* Memory-access and commands for remote es1800 processes, for GDB.
2    Copyright (C) 1988, 1992 Free Software Foundation, Inc.
3
4    This file is added to GDB to make it possible to do debugging via an
5    ES-1800 emulator. The code was originally written by Johan Holmberg
6    TT/SJ Ericsson Telecom AB and later modified by Johan Henriksson
7    TT/SJ. It was modified for gdb 4.0 by TX/DK Jan Nordenand by TX/DKG
8    Harald Johansen.
9
10 This file is part of GDB.
11
12 GDB is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 1, or (at your option)
15 any later version.
16
17 GDB is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GDB; see the file COPYING.  If not, write to
24 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
25
26
27 /* Emulator communication protocol.
28    All values are encoded in ascii hex digits.
29
30         Request
31 Command
32 Reply
33         read registers:
34 DR<cr>
35      - 0 -    - 1 -    - 2 -    - 3 -      - 4 -    - 5 -    -- 6 -   - 7 - 
36 D = XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX   XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
37 A = XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX   XXXXXXXX XXXXXXXX XXXXXXXX 
38     PC = XXXXXX       SSP = XXXXXX    USP = XXXXXX     SR = XXXXXXXX
39  >
40 Each byte of register data is described by two hex digits.
41
42         write regs
43 D0=XXXXXXXX<cr>
44  >D1=XXXXXXXX<cr>
45  >D2=XXXXXXXX<cr>
46  >D3=XXXXXXXX<cr>
47  >D4=XXXXXXXX<cr>
48  >D5=XXXXXXXX<cr>
49  >D6=XXXXXXXX<cr>
50  >D7=XXXXXXXX<cr>
51  >A0=XXXXXXXX<cr>
52  >A1=XXXXXXXX<cr>
53  >A2=XXXXXXXX<cr>
54  >A3=XXXXXXXX<cr>
55  >A4=XXXXXXXX<cr>
56  >A5=XXXXXXXX<cr>
57  >A6=XXXXXXXX<cr>
58  >A7=XXXXXXXX<cr>
59  >SR=XXXXXXXX<cr>
60  >PC=XXXXXX<cr>
61  >
62 Each byte of register data is described by two hex digits.
63
64         read mem
65 @.BAA..AA
66 $FFFFFFXX
67  >
68 AA..AA is address, XXXXXXX is the contents
69
70         write mem
71         @.BAA..AA=$XXXXXXXX
72  >
73 AA..AA is address, XXXXXXXX is data
74
75         cont
76 PC=$AA..AA
77  >RBK
78 R>
79 AA..AA is address to resume. If AA..AA is omitted, resume at same address.
80
81         step
82 PC=$AA..AA
83  >STP
84 R>
85 AA..AA is address to resume. If AA..AA is omitted, resume at same address.
86
87         kill req
88 STP
89  >
90 */
91
92
93 #include <stdio.h>
94 #include <signal.h>
95 #include <sys/ioctl.h>
96 #include <sys/file.h>
97 #include <errno.h>
98 #include <ctype.h>
99 #include <string.h>
100 #include <setjmp.h>
101 #include <fcntl.h>
102 #include "defs.h"
103 #include "frame.h"
104 #include "inferior.h"
105 #include "target.h"
106 #include "wait.h"
107 #include "command.h"
108 #include "remote-utils.h"
109 #include "gdbcore.h"
110 #include "serial.h"
111
112 /* Prototypes for local functions */
113
114 static void
115 es1800_child_detach PARAMS ((char *, int));
116
117 static void
118 es1800_child_open PARAMS ((char *, int));
119
120 static void 
121 es1800_transparent PARAMS ((char *, int));
122
123 static void
124 es1800_create_inferior PARAMS ((char *, char *, char **));
125
126 static void
127 es1800_load PARAMS ((char *, int));
128
129 static void
130 es1800_kill PARAMS ((void));
131
132 static int
133 verify_break PARAMS ((int));
134
135 static int
136 es1800_remove_breakpoint PARAMS ((CORE_ADDR, char *));
137
138 static int
139 es1800_insert_breakpoint PARAMS ((CORE_ADDR, char *));
140
141 static void
142 es1800_files_info PARAMS ((struct target_ops *));
143
144 static int
145 es1800_xfer_inferior_memory PARAMS ((CORE_ADDR, char *, int, int,
146                                      struct target_ops *));
147
148 static void 
149 es1800_prepare_to_store PARAMS ((void));
150
151 static int es1800_wait PARAMS ((int, struct target_waitstatus *));
152
153 static void es1800_resume PARAMS ((int, int, enum target_signal));
154
155 static void
156 es1800_detach PARAMS ((char *, int));
157
158 static void
159 es1800_attach PARAMS ((char *, int));
160
161 static int
162 damn_b PARAMS ((char *));
163
164 static void
165 es1800_open PARAMS ((char *, int));
166
167 static void
168 es1800_timer PARAMS ((void));
169
170 static void
171 es1800_reset PARAMS ((char *));
172
173 static void
174 es1800_request_quit PARAMS ((void));
175
176 static int
177 readchar PARAMS ((void));
178
179 static void
180 expect PARAMS ((char *, int));
181
182 static void
183 expect_prompt PARAMS ((void));
184
185 static void
186 download PARAMS ((FILE *, int, int));
187
188 #if 0
189 static void
190 bfd_copy PARAMS ((bfd *, bfd *));
191 #endif
192
193 static void
194 get_break_addr PARAMS ((int, CORE_ADDR *));
195
196 static int
197 fromhex PARAMS ((int));
198
199 static int
200 tohex PARAMS ((int));
201
202 static void
203 es1800_close PARAMS ((int));
204
205 static void
206 es1800_fetch_registers PARAMS ((void));
207
208 static void
209 es1800_fetch_register PARAMS ((int));
210
211 static void
212 es1800_store_register PARAMS ((int));
213
214 static void
215 es1800_read_bytes PARAMS ((CORE_ADDR, char *, int));
216
217 static void
218 es1800_write_bytes PARAMS ((CORE_ADDR, char *, int));
219
220 static void
221 send_with_reply PARAMS ((char *, char *, int));
222
223 static void
224 send_command PARAMS ((char *));
225
226 static void
227 send PARAMS ((char *));
228
229 static void
230 getmessage PARAMS ((char *, int));
231
232 static void
233 es1800_mourn_inferior PARAMS ((void));
234
235 static void
236 es1800_create_break_insn PARAMS ((char *, int));
237
238 static void
239 es1800_init_break PARAMS ((char *, int));
240
241 /* Local variables */
242
243 /* FIXME: Convert this to use "set remotedebug" instead.  */
244 #define LOG_FILE "es1800.log"
245 #if defined (LOG_FILE)
246 static FILE *log_file;
247 #endif
248
249 extern struct target_ops es1800_ops;            /* Forward decl */
250 extern struct target_ops es1800_child_ops;      /* Forward decl */
251
252 static int kiodebug;
253 static int timeout = 100; 
254 static char *savename;                          /* Name of i/o device used */
255 static serial_ttystate es1800_saved_ttystate;
256 static int es1800_fc_save;                      /* Save fcntl state */
257
258 /* indicates that the emulator uses 32-bit data-adress (68020-mode) 
259    instead of 24-bit (68000 -mode) */
260
261 static int m68020;
262
263 #define MODE (m68020 ? "M68020" : "M68000" )
264 #define ES1800_BREAK_VEC (0xf)
265
266 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
267    es1800_open knows that we don't have a file open when the program
268    starts.  */
269
270 static serial_t es1800_desc = NULL;
271
272 #define PBUFSIZ 1000
273 #define HDRLEN sizeof("@.BAAAAAAAA=$VV\r")
274
275 /* Maximum number of bytes to read/write at once.  The value here
276    is chosen to fill up a packet.  */
277
278 #define MAXBUFBYTES ((PBUFSIZ-150)*16/75 )
279
280 static int es1800_break_vec = 0;
281 static char es1800_break_insn[2];
282 static long es1800_break_address;
283 static void (*old_sigint)();            /* Old signal-handler for sigint */
284 static jmp_buf interrupt;
285
286 /* Local signalhandler to allow breaking tranfers or program run.
287    Rely on global variables: old_sigint(), interrupt */
288
289 static void
290 es1800_request_quit ()
291 {
292   /* restore original signalhandler */
293   signal (SIGINT, old_sigint);
294   longjmp (interrupt, 1);
295 }
296
297
298 /* Reset emulator.
299    Sending reset character(octal 32) to emulator.
300    quit - return to '(esgdb)' prompt or continue        */
301
302 static void
303 es1800_reset (quit)
304      char *quit;
305 {
306   char buf[80];
307
308   if (quit)
309     {
310       printf ("\nResetting emulator...  ");
311     }
312   strcpy (buf, "\032");
313   send (buf);
314   expect_prompt ();
315   if (quit)
316     {
317       error ("done\n");
318     }
319 }
320
321
322 /* Open a connection to a remote debugger and push the new target
323    onto the stack. Check if the emulator is responding and find out
324    what kind of processor the emulator is connected to.
325    Initiate the breakpoint handling in the emulator.
326
327    name     - the filename used for communication (ex. '/dev/tta')
328    from_tty - says whether to be verbose or not */
329
330 static void
331 es1800_open (name, from_tty)
332      char *name;
333      int from_tty;
334 {
335   char buf[PBUFSIZ];
336   char *p;
337   int i, fcflag;
338
339   m68020 = 0;
340
341   if (!name)           /* no device name given in target command */
342     {
343       error_no_arg ("serial port device name");
344     }
345
346   target_preopen (from_tty);
347   es1800_close (0);
348
349   /* open the device and configure it for communication */
350
351 #ifndef DEBUG_STDIN
352
353   es1800_desc = SERIAL_OPEN (name);
354   if (es1800_desc == NULL)
355     {
356       perror_with_name (name);
357     }
358   savename = savestring (name, strlen (name));
359
360   es1800_saved_ttystate = SERIAL_GET_TTY_STATE (es1800_desc);
361
362   if ((fcflag = fcntl (es1800_desc->fd, F_GETFL, 0)) == -1)
363     {
364       perror_with_name ("fcntl serial");
365     }
366   es1800_fc_save = fcflag;
367
368   fcflag = (fcflag & (FREAD | FWRITE)); /* mask out any funny stuff */
369   if (fcntl (es1800_desc->fd, F_SETFL, fcflag) == -1)
370     {
371       perror_with_name ("fcntl serial");
372     }
373
374   if (SERIAL_SETBAUDRATE (es1800_desc, baud_rate))
375     {
376       SERIAL_CLOSE (es1800_desc);
377       perror_with_name (name);
378     }
379
380   SERIAL_RAW (es1800_desc);
381
382   /* If there is something sitting in the buffer we might take it as a
383      response to a command, which would be bad.  */
384   SERIAL_FLUSH_INPUT (es1800_desc);
385
386 #endif  /* DEBUG_STDIN */
387
388   push_target (&es1800_ops);    /* Switch to using remote target now */
389   if (from_tty)
390     {
391       printf ("Remote ES1800 debugging using %s\n", name);
392     }
393
394 #if defined (LOG_FILE)
395
396   log_file = fopen (LOG_FILE, "w");
397   if (log_file == NULL)
398     {
399       perror_with_name (LOG_FILE);
400     }
401
402 #endif  /* LOG_FILE */
403
404   /* Hello?  Are you there?, also check mode  */
405
406   /*  send_with_reply( "DB 0 TO 1", buf, sizeof(buf)); */
407   /*  for (p = buf, i = 0; *p++ =='0';)  */   /* count the number of zeros */
408   /*      i++; */
409
410   send ("\032");
411   getmessage (buf, sizeof (buf));  /* send reset character */
412
413   if (from_tty)
414     {
415       printf ("Checking mode.... ");
416     }
417   /*  m68020 = (i==8); */   /* if eight zeros then we are in m68020 mode */
418
419   /* What kind of processor am i talking to ?*/
420   p = buf;
421   while (*p++ != '\n') {;}
422   while (*p++ != '\n') {;}
423   while (*p++ != '\n') {;}
424   for (i = 0; i < 20; i++, p++) {;}
425   m68020 = !strncmp (p, "68020", 5);
426   if (from_tty)
427     {
428       printf ("You are in %s(%c%c%c%c%c)-mode\n", MODE, p[0], p[1], p[2],
429               p[3], p[4]);
430     }
431
432   /* if no init_break statement is present in .gdb file we have to check 
433      whether to download a breakpoint routine or not */
434
435 #if 0
436   if ((es1800_break_vec == 0) || (verify_break (es1800_break_vec) != 0)
437       && query ("No breakpoint routine in ES 1800 emulator!\nDownload a breakpoint routine to the emulator? "))
438     {
439       CORE_ADDR memaddress;
440       printf ("Give the start address of the breakpoint routine: ");
441       scanf ("%li", &memaddress);
442       es1800_init_break ((es1800_break_vec ? es1800_break_vec :
443                           ES1800_BREAK_VEC), memaddress);
444     }
445 #endif
446
447 }
448
449 /*  Close out all files and local state before this target loses control.
450     quitting - are we quitting gdb now? */
451
452 static void
453 es1800_close (quitting)
454      int quitting;
455 {
456   if (es1800_desc != NULL)
457     {
458       printf ("\nClosing connection to emulator...\n");
459       if (SERIAL_SET_TTY_STATE (es1800_desc, es1800_saved_ttystate) < 0)
460         print_sys_errmsg ("warning: unable to restore tty state", errno);
461       fcntl (es1800_desc->fd, F_SETFL, es1800_fc_save);
462       SERIAL_CLOSE (es1800_desc);
463       es1800_desc = NULL;
464     }
465   if (savename != NULL)
466     {
467       free (savename);
468     }
469   savename = NULL;
470
471 #if defined (LOG_FILE)
472
473   if (log_file != NULL)
474     {
475       if (ferror (log_file))
476         {
477           printf ("Error writing log file.\n");
478         }
479       if (fclose (log_file) != 0)
480         {
481           printf ("Error closing log file.\n");
482         }
483       log_file = NULL;
484     }
485
486 #endif  /* LOG_FILE */
487
488 }
489
490 /*  Attaches to a process on the target side
491     proc_id  - the id of the process to be attached.
492     from_tty - says whether to be verbose or not */
493
494 static void
495 es1800_attach (args, from_tty)
496     char *args;
497     int from_tty;
498 {
499   error ("Cannot attach to pid %s, this feature is not implemented yet.",
500          args);
501 }
502
503
504 /* Takes a program previously attached to and detaches it.
505    We better not have left any breakpoints
506    in the program or it'll die when it hits one.
507    Close the open connection to the remote debugger.
508    Use this when you want to detach and do something else
509    with your gdb.
510  
511    args     - arguments given to the 'detach' command
512    from_tty - says whether to be verbose or not */
513
514 static void
515 es1800_detach (args, from_tty)
516      char *args;
517      int from_tty;
518 {
519   if (args)
520     {
521       error ("Argument given to \"detach\" when remotely debugging.");
522     }
523   pop_target ();
524   if (from_tty)
525     {
526       printf ("Ending es1800 remote debugging.\n");
527     }
528 }
529
530
531 /* Tell the remote machine to resume.
532    step    - single-step or run free
533    siggnal - the signal value to be given to the target (0 = no signal) */
534
535 static void
536 es1800_resume (pid, step, siggnal)
537      int pid;
538      int step;
539      enum target_signal siggnal;
540 {
541   char buf[PBUFSIZ];
542
543   if (siggnal)
544     {
545       error ("Can't send signals to a remote system.");
546     }
547   if (step)
548     {
549       strcpy (buf,"STP\r");
550       send (buf);
551     }
552   else
553     {
554       send_command ("RBK");
555     }
556 }
557
558 /* Wait until the remote machine stops, then return,
559    storing status in STATUS just as `wait' would.
560    status -  */
561  
562 static int
563 es1800_wait (pid, status)
564      int pid;
565      struct target_waitstatus *status;
566 {
567   unsigned char buf[PBUFSIZ];
568   int old_timeout = timeout;
569
570   status->kind = TARGET_WAITKIND_EXITED;
571   status->value.integer = 0;
572
573   timeout = 0;          /* Don't time out -- user program is running. */
574   if (!setjmp (interrupt))
575     {
576       old_sigint = signal (SIGINT, es1800_request_quit);
577       while (1)
578         {
579           getmessage (buf, sizeof(buf));
580           if (strncmp ( buf, "\r\n* BREAK *", 11) == 0) 
581             {
582               status->kind = TARGET_WAITKIND_STOPPED;
583               status->value.sig = TARGET_SIGNAL_TRAP;
584               send_command ("STP");     /* Restore stack and PC and such */
585               if (m68020)
586                 {
587                   send_command ("STP");
588                 }
589               break;
590             }
591           if (strncmp (buf, "STP\r\n ", 6) == 0)
592             {
593               status->kind = TARGET_WAITKIND_STOPPED;
594               status->value.sig = TARGET_SIGNAL_TRAP;
595               break;
596             }
597           if (buf[strlen (buf) - 2] == 'R')
598             {
599               printf ("Unexpected emulator reply: \n%s\n", buf);
600             }
601           else
602             {
603               printf ("Unexpected stop: \n%s\n", buf);
604               status->kind = TARGET_WAITKIND_STOPPED;
605               status->value.sig = TARGET_SIGNAL_QUIT;
606               break;
607             }
608         }
609     }
610   else
611     {
612       fflush (stdin);
613       printf ("\nStopping emulator...");
614       if (!setjmp (interrupt))
615         {
616           old_sigint = signal (SIGINT, es1800_request_quit);
617           send_command ("STP");
618           printf (" emulator stopped\n");
619           status->kind = TARGET_WAITKIND_STOPPED;
620           status->value.sig = TARGET_SIGNAL_INT;
621         }
622       else
623         {
624           fflush (stdin);
625           es1800_reset ((char*) 1);
626         }
627     }
628   signal (SIGINT, old_sigint);
629   timeout = old_timeout;
630   return (0);
631 }
632
633
634 /* Fetch register values from remote machine.
635    regno - the register to be fetched (fetch all registers if -1) */
636
637 static void
638 es1800_fetch_register (regno)
639      int regno;
640 {
641   char buf[PBUFSIZ];
642   int k;
643   int r;
644   char *p;
645   static char regtab[18][4] = 
646     {
647       "D0 ", "D1 ", "D2 ", "D3 ", "D4 ", "D5 ", "D6 ", "D7 ",
648       "A0 ", "A1 ", "A2 ", "A3 ", "A4 ", "A5 ", "A6 ", "SSP",
649       "SR ", "PC "
650     };
651
652   if ((regno < 15) || (regno == 16) || (regno == 17))
653     {
654       r = regno * 4;
655       send_with_reply (regtab[regno], buf, sizeof (buf));
656       p = buf;
657       for (k = 0; k < 4; k++)
658         {
659           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
660             {
661               error ("Emulator reply is too short: %s", buf);
662             }
663           registers[r++] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
664         }
665     }
666   else
667     {
668       es1800_fetch_registers ();
669     }
670 }
671
672 /* Read the remote registers into REGISTERS.
673    Always fetches all registers. */
674
675 static void
676 es1800_fetch_registers ()
677 {
678   char buf[PBUFSIZ];
679   char SR_buf[PBUFSIZ];
680   int i;
681   int k;
682   int r;
683   char *p;
684
685   send_with_reply ("DR", buf, sizeof (buf));
686
687   /* Reply is edited to a string that describes registers byte by byte,
688      each byte encoded as two hex characters.  */
689
690   p = buf;
691   r = 0;
692
693   /*  parsing row one - D0-D7-registers  */
694
695   while (*p++ != '\n') {;}
696   for (i = 4; i < 70; i += (i == 39 ? 3 : 1))
697     {
698       for (k = 0; k < 4; k++)
699         {
700           if (p[i+0] == 0 || p[i+1] == 0)
701             {
702               error ("Emulator reply is too short: %s", buf);
703             }
704           registers[r++] = (fromhex (p[i+0]) * 16) + fromhex (p[i+1]);
705           i += 2;
706         }
707     }
708   p += i;
709
710   /*  parsing row two - A0-A6-registers  */
711
712   while (*p++ != '\n') {;}
713   for (i = 4; i < 61; i += (i == 39 ? 3 : 1))
714     {
715       for (k = 0; k < 4; k++)
716         {
717           if (p[i+0] == 0 || p[i+1] == 0)
718             {
719               error ("Emulator reply is too short: %s", buf);
720             }
721           registers[r++] = (fromhex (p[i+0])) * 16 + fromhex (p[i+1]);
722           i += 2;
723         }
724     }
725   p += i;
726
727   while (*p++ != '\n') {;}
728
729   /* fetch SSP-, SR- and PC-registers  */
730
731   /* first - check STATUS-word and decide which stackpointer to use */
732
733   send_with_reply ("SR", SR_buf, sizeof (SR_buf));
734   p = SR_buf;
735   p += 5;
736
737   if (m68020)
738     {
739       if (*p == '3')             /* use masterstackpointer MSP */
740         {
741           send_with_reply ("MSP", buf, sizeof (buf));
742         }
743       else if (*p == '2')       /* use interruptstackpointer ISP  */
744         {
745           send_with_reply ("ISP", buf, sizeof (buf));
746         }
747       else                      /* use userstackpointer USP  */
748         {
749           send_with_reply ("USP", buf, sizeof (buf)); 
750         }
751       p = buf;
752       for (k = 0; k<4; k++)
753         {
754           if (p[k*2+1] == 0 || p[k*2+2] == 0)
755             {
756               error ("Emulator reply is too short: %s", buf);
757             }
758           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
759         }
760
761       p = SR_buf;
762       for (k = 0; k < 4; k++)
763         {
764           if (p[k*2+1] == 0 || p[k*2+2] == 0)
765             {
766               error ("Emulator reply is too short: %s", buf);
767             }
768           registers[r++] =
769             fromhex (SR_buf[k*2+1]) * 16 + fromhex (SR_buf[k*2+2]);
770         }
771       send_with_reply ("PC", buf, sizeof (buf));
772       p = buf;
773       for (k = 0; k<4; k++)
774         {
775           if (p[k*2+1] == 0 || p[k*2+2] == 0)
776             {
777               error ("Emulator reply is too short: %s", buf);
778             }
779           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
780         }
781     }
782   else    /* 68000-mode */
783     {                       
784       if (*p == '2') /* use supervisorstackpointer SSP  */
785         {
786           send_with_reply ("SSP", buf, sizeof (buf)); 
787         }
788       else  /* use userstackpointer USP  */
789         {
790           send_with_reply ("USP", buf, sizeof (buf)); 
791         }
792
793       /* fetch STACKPOINTER */
794
795       p = buf;
796       for (k = 0; k < 4; k++)
797         {
798           if (p[k*2 + 1] == 0 || p[k*2 + 2] == 0)
799             {
800               error ("Emulator reply is too short: %s", buf);
801             }
802           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
803         }
804
805       /* fetch STATUS */
806
807       p = SR_buf;
808       for (k = 0; k < 4; k++)
809         {
810           if (p[k*2+1] == 0 || p[k*2+2] == 0)
811             {
812               error ("Emulator reply is too short: %s", buf);
813             }
814           registers[r++] =
815             fromhex (SR_buf[k*2+1]) * 16 + fromhex (SR_buf[k*2+2]);
816         }
817
818       /* fetch PC */
819
820       send_with_reply ("PC", buf, sizeof (buf)); 
821       p = buf;
822       for (k = 0; k < 4; k++)
823         {
824           if (p[k*2+1] == 0 || p[k*2+2] == 0)
825             {
826               error ("Emulator reply is too short: %s", buf);
827             }
828           registers[r++] = fromhex (buf[k*2+1]) * 16 + fromhex (buf[k*2+2]);
829         }    
830     }
831 }
832
833 /* Store register value, located in REGISTER, on the target processor.
834    regno - the register-number of the register to store
835            (-1 means store them all)
836    FIXME: Return errno value.  */
837
838 static void
839 es1800_store_register(regno)
840      int regno;
841 {
842
843   static char regtab[18][4] =
844     {
845       "D0 ", "D1 ", "D2 ", "D3 ", "D4 ", "D5 ", "D6 ", "D7 ",
846       "A0 ", "A1 ", "A2 ", "A3 ", "A4 ", "A5 ", "A6 ", "SSP",
847       "SR ", "PC "
848     };
849
850   char buf[PBUFSIZ];
851   char SR_buf[PBUFSIZ];
852   char stack_pointer[4];
853   char *p;
854   int i;
855   int j;
856   int k;
857   unsigned char *r;
858
859   r = (unsigned char *) registers;
860
861   if (regno == -1)  /* write all registers */
862     {
863       j = 0;
864       k = 18;
865     }
866   else              /* write one register */
867     {
868       j = regno;
869       k = regno+1;
870       r += regno * 4; 
871     }    
872
873   if ((regno == -1) || (regno == 15))
874     {
875       /* fetch current status */
876       send_with_reply ("SR", SR_buf, sizeof (SR_buf));
877       p = SR_buf;
878       p += 5;
879       if (m68020)
880         {
881           if (*p == '3') /* use masterstackpointer MSP */
882             {
883               strcpy (stack_pointer,"MSP");  
884             }
885           else
886             {
887               if (*p == '2') /* use interruptstackpointer ISP  */
888                 {
889                   strcpy (stack_pointer,"ISP");  
890                 }
891               else
892                 {
893                   strcpy (stack_pointer,"USP");  /* use userstackpointer USP  */
894                 }
895             }
896         }
897       else  /* 68000-mode */
898         {
899           if (*p == '2') /* use supervisorstackpointer SSP  */
900             {
901               strcpy (stack_pointer,"SSP");  
902             }
903           else
904             {
905               strcpy (stack_pointer,"USP");/* use userstackpointer USP  */  
906             }
907         }
908       strcpy (regtab[15],stack_pointer);
909     }
910
911   for (i = j; i<k; i++)
912     {
913       buf[0] = regtab[i][0];
914       buf[1] = regtab[i][1];
915       buf[2] = regtab[i][2];
916       buf[3] = '=';
917       buf[4] = '$';
918       buf[5] = tohex ((*r >> 4) & 0x0f);
919       buf[6] = tohex (*r++ & 0x0f);
920       buf[7] = tohex ((*r >> 4) & 0x0f);
921       buf[8] = tohex (*r++ & 0x0f);
922       buf[9] = tohex ((*r >> 4) & 0x0f);
923       buf[10] = tohex (*r++ & 0x0f);
924       buf[11] = tohex ((*r >> 4) & 0x0f);
925       buf[12] = tohex (*r++ & 0x0f);
926       buf[13] = 0;
927
928       send_with_reply (buf, buf, sizeof (buf)); /* FIXME, reply not used? */
929     }
930 }
931
932
933 /* Prepare to store registers.  */
934
935 static void 
936 es1800_prepare_to_store ()
937 {
938   /* Do nothing, since we can store individual regs */
939 }
940
941 /* Convert hex digit A to a number.  */
942
943 static int
944 fromhex (a)
945      int a;
946 {
947   if (a >= '0' && a <= '9')
948     {
949       return a - '0';
950     }
951   else if (a >= 'a' && a <= 'f')
952     {
953       return a - 'a' + 10;
954     }
955   else if (a >= 'A' && a <= 'F')
956     {
957       return a - 'A' + 10;
958     }
959   else
960     {
961       error ("Reply contains invalid hex digit");
962     }
963   return (-1);
964 }
965
966
967 /* Convert number NIB to a hex digit.  */
968
969 static int
970 tohex (nib)
971      int nib;
972 {
973   if (nib < 10)
974     {
975       return ('0' + nib);
976     }
977   else
978     {
979       return ('A' + nib - 10);
980     }
981 }
982
983 /* Read or write LEN bytes from inferior memory at MEMADDR, transferring
984    to or from debugger address MYADDR.  Write to inferior if WRITE is
985    nonzero.  Returns length of data written or read; 0 for error. 
986  
987    memaddr - the target's address
988    myaddr  - gdb's address
989    len     - number of bytes 
990    write   - write if != 0 otherwise read       */
991
992 static int
993 es1800_xfer_inferior_memory (memaddr, myaddr, len, write, tops)
994      CORE_ADDR memaddr;
995      char *myaddr;
996      int len;
997      int write;
998      struct target_ops *tops;   /* Unused */
999 {
1000   int origlen = len;
1001   int xfersize;
1002
1003   while (len > 0)
1004     {
1005       xfersize = len > MAXBUFBYTES ? MAXBUFBYTES : len;
1006       if (write)
1007         {
1008           es1800_write_bytes (memaddr, myaddr, xfersize);
1009         }
1010       else
1011         {
1012           es1800_read_bytes (memaddr, myaddr, xfersize);
1013         }
1014       memaddr += xfersize;
1015       myaddr += xfersize;
1016       len -= xfersize;
1017     }
1018   return (origlen); /* no error possible */
1019 }
1020
1021
1022 /* Write memory data directly to the emulator.
1023    This does not inform the data cache; the data cache uses this.
1024    MEMADDR is the address in the remote memory space.
1025    MYADDR is the address of the buffer in our space.
1026    LEN is the number of bytes.
1027  
1028    memaddr - the target's address
1029    myaddr  - gdb's address
1030    len     - number of bytes   */
1031
1032 static void
1033 es1800_write_bytes (memaddr, myaddr, len)
1034      CORE_ADDR memaddr;
1035      char *myaddr;
1036      int len;
1037 {
1038   char buf[PBUFSIZ];
1039   int i;
1040   char *p;
1041
1042   p = myaddr;
1043   for (i = 0; i < len; i++)
1044     {
1045       sprintf (buf, "@.B$%x=$%x", memaddr+i, (*p++) & 0xff);
1046       send_with_reply (buf, buf, sizeof (buf));      /* FIXME send_command? */
1047     }
1048 }
1049
1050
1051 /* Read memory data directly from the emulator.
1052    This does not use the data cache; the data cache uses this.
1053  
1054    memaddr - the target's address
1055    myaddr  - gdb's address
1056    len     - number of bytes   */
1057
1058 static void
1059 es1800_read_bytes (memaddr, myaddr, len)
1060      CORE_ADDR memaddr;
1061      char *myaddr;
1062      int len;
1063 {
1064   static int DB_tab[16] = {8,11,14,17,20,23,26,29,34,37,40,43,46,49,52,55};
1065   char buf[PBUFSIZ];
1066   int i;
1067   int low_addr;
1068   char *p;
1069   char *b;
1070
1071   if (len > PBUFSIZ / 2 - 1)
1072     {
1073       abort ();
1074     }
1075
1076   if (len == 1) /* The emulator does not like expressions like:  */
1077     {
1078       len = 2;  /* DB.B $20018 TO $20018                       */
1079     }
1080
1081   /* Reply describes registers byte by byte, each byte encoded as two hex
1082      characters.  */
1083
1084   sprintf (buf, "DB.B $%x TO $%x", memaddr, memaddr+len-1);
1085   send_with_reply (buf, buf, sizeof (buf));
1086   b = buf;
1087   low_addr = memaddr&0x0f;
1088   for (i = low_addr; i < low_addr + len; i++)
1089     {
1090       if ((!(i % 16)) && i)
1091         {   /* if (i = 16,32,48)  */
1092           while (*p++!='\n') {;}
1093           b = p;
1094         }
1095       p = b + DB_tab[i%16] + (m68020 ? 2 : 0);
1096       if (p[0] == 32 || p[1] == 32)
1097         {
1098           error ("Emulator reply is too short: %s", buf);
1099         }
1100       myaddr[i-low_addr] = fromhex (p[0]) * 16 + fromhex (p[1]);
1101     }
1102 }
1103
1104 /* Information about the current target  */
1105
1106 static void
1107 es1800_files_info (tops)
1108      struct target_ops *tops;   /* Unused */
1109 {
1110   printf ("ES1800 Attached to %s at %d baud in %s mode\n", savename, 19200,
1111           MODE);
1112 }
1113
1114
1115 /* We read the contents of the target location and stash it,
1116    then overwrite it with a breakpoint instruction.
1117  
1118    addr           - is the target location in the target machine.
1119    contents_cache - is a pointer to memory allocated for saving the target contents.
1120                     It is guaranteed by the caller to be long enough to save sizeof 
1121                     BREAKPOINT bytes.
1122  
1123    FIXME: This size is target_arch dependent and should be available in
1124    the target_arch transfer vector, if we ever have one...  */
1125
1126 static int
1127 es1800_insert_breakpoint (addr, contents_cache)
1128      CORE_ADDR addr;
1129      char *contents_cache;
1130 {
1131   int val; 
1132
1133   val = target_read_memory (addr, contents_cache, sizeof (es1800_break_insn));
1134
1135   if (val == 0)
1136     {
1137       val = target_write_memory (addr, es1800_break_insn,
1138                                  sizeof (es1800_break_insn));
1139     }
1140
1141   return (val);
1142 }
1143
1144
1145 /* Write back the stashed instruction
1146  
1147    addr           - is the target location in the target machine.
1148    contents_cache - is a pointer to memory allocated for saving the target contents.
1149                     It is guaranteed by the caller to be long enough to save sizeof 
1150                     BREAKPOINT bytes.   */
1151  
1152 static int
1153 es1800_remove_breakpoint (addr, contents_cache)
1154      CORE_ADDR addr;
1155      char *contents_cache;
1156 {
1157
1158   return (target_write_memory (addr, contents_cache,
1159                                sizeof (es1800_break_insn)));
1160 }
1161
1162 /* create_break_insn ()
1163    Primitive datastructures containing the es1800 breakpoint instruction  */
1164
1165 static void
1166 es1800_create_break_insn (ins, vec)
1167      char *ins;
1168      int vec;
1169 {
1170   if (vec == 15)
1171     {
1172       ins[0] = 0x4e;
1173       ins[1] = 0x4f;
1174     }
1175 }
1176
1177
1178 /* verify_break ()
1179    Seach for breakpoint routine in emulator memory.
1180    returns non-zero on failure
1181    vec - trap vector used for breakpoints  */
1182
1183 static int
1184 verify_break (vec)
1185      int vec;
1186 {
1187   CORE_ADDR memaddress;
1188   char buf[8];
1189   char *instr = "NqNqNqNs";      /* breakpoint routine */
1190   int status;
1191
1192   get_break_addr (vec, &memaddress);
1193
1194   if (memaddress)
1195     {
1196       status = target_read_memory (memaddress, buf, 8); 
1197       if (status != 0)
1198         {
1199           memory_error (status, memaddress);
1200         }
1201       return (STRCMP (instr, buf));
1202     }
1203     return (-1);
1204 }
1205
1206
1207 /* get_break_addr ()
1208    find address of breakpint routine
1209    vec - trap vector used for breakpoints
1210    addrp - store the address here       */
1211
1212 static void
1213 get_break_addr (vec, addrp)
1214      int vec;
1215      CORE_ADDR *addrp;
1216 {
1217   CORE_ADDR memaddress = 0;
1218   int status;
1219   int k;
1220   char buf[PBUFSIZ];
1221   char base_addr[4];
1222   char *p;
1223
1224   if (m68020)
1225     {
1226       send_with_reply ("VBR ", buf, sizeof (buf));
1227       p = buf;
1228       for (k = 0; k < 4; k++)
1229         {
1230           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
1231             {
1232               error ("Emulator reply is too short: %s", buf);
1233             }
1234           base_addr[k] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
1235         }
1236       /* base addr of exception vector table */
1237       memaddress = *((CORE_ADDR *) base_addr);
1238     }
1239
1240     memaddress += (vec + 32) * 4;     /* address of trap vector */
1241     status = target_read_memory (memaddress, (char *) addrp, 4); 
1242     if (status != 0)                                                   
1243       {
1244         memory_error (status, memaddress);
1245       }
1246 }
1247
1248
1249 /* Kill an inferior process */
1250
1251 static void
1252 es1800_kill ()
1253 {
1254   if (inferior_pid != 0)
1255     {
1256       inferior_pid = 0;
1257       es1800_mourn_inferior ();
1258     }
1259 }
1260
1261
1262 /* Load a file to the ES1800 emulator. 
1263    Converts the file from a.out format into Extended Tekhex format
1264    before the file is loaded.
1265    Also loads the trap routine, and sets the ES1800 breakpoint on it
1266    filename - the a.out to be loaded
1267    from_tty - says whether to be verbose or not
1268    FIXME Uses emulator overlay memory for trap routine  */
1269  
1270 static void
1271 es1800_load (filename, from_tty)
1272      char *filename;
1273      int from_tty;
1274 {
1275
1276   FILE *instream;
1277   char loadname[15];
1278   char buf[160];
1279   struct cleanup *old_chain;
1280   int es1800_load_format = 5;
1281
1282   if (es1800_desc == NULL) 
1283     {
1284       printf ("No emulator attached, type emulator-command first\n");
1285       return;
1286     }
1287
1288   filename = tilde_expand (filename);
1289   make_cleanup (free, filename);
1290
1291   switch (es1800_load_format)
1292     {
1293       case 2:   /* Extended Tekhex  */
1294         if (from_tty)
1295           {
1296             printf ("Converting \"%s\" to Extended Tekhex Format\n", filename);
1297           }
1298         sprintf (buf, "tekhex %s", filename);
1299         system (buf);
1300         sprintf (loadname, "out.hex");
1301         break;
1302
1303       case 5:   /* Motorola S-rec  */
1304         if (from_tty)
1305           {
1306             printf ("Converting \"%s\" to Motorola S-record format\n",
1307                     filename);
1308           }
1309         /* in the future the source code in copy (part of binutils-1.93) will
1310            be included in this file */
1311         sprintf (buf,
1312                  "copy -s \"a.out-sunos-big\" -d \"srec\" %s /tmp/out.hex",
1313                  filename);
1314         system (buf);
1315         sprintf (loadname, "/tmp/out.hex");
1316         break;
1317
1318       default:
1319         error ("Downloading format not defined\n");
1320     }
1321  
1322   breakpoint_init_inferior ();
1323   inferior_pid = 0;
1324   if (from_tty)
1325     {
1326       printf ("Downloading \"%s\" to the ES 1800\n",filename);
1327     }
1328   if ((instream = fopen (loadname, "r")) == NULL)
1329     {
1330       perror_with_name ("fopen:");
1331     }
1332
1333   old_chain = make_cleanup (fclose, instream);
1334   immediate_quit++;
1335
1336   es1800_reset (0);
1337
1338   download (instream, from_tty, es1800_load_format);
1339
1340   /* if breakpoint routine is not present anymore we have to check 
1341      whether to download a new breakpoint routine or not */
1342
1343   if ((verify_break (es1800_break_vec) != 0)
1344       && query ("No breakpoint routine in ES 1800 emulator!\nDownload a breakpoint routine to the emulator? "))
1345     {
1346       char buf[128];
1347       printf ("Using break vector 0x%x\n", es1800_break_vec);
1348       sprintf (buf, "0x%x ", es1800_break_vec);
1349       printf ("Give the start address of the breakpoint routine: ");
1350       fgets (buf + strlen (buf), sizeof (buf) - strlen (buf), stdin);
1351       es1800_init_break (buf, 0);
1352     }
1353
1354   do_cleanups (old_chain);
1355   expect_prompt ();
1356   readchar ();  /* FIXME I am getting a ^G = 7 after the prompt  */
1357   printf ("\n");
1358
1359   if (fclose (instream) == EOF)
1360     {
1361       ;
1362     }
1363
1364   if (es1800_load_format != 2)
1365     {
1366       sprintf (buf, "/usr/bin/rm %s", loadname);
1367       system (buf);
1368     }
1369
1370   symbol_file_command (filename, from_tty);   /* reading symbol table */
1371   immediate_quit--;
1372 }
1373
1374 #if 0
1375
1376 #define NUMCPYBYTES 20
1377
1378 static void
1379 bfd_copy (from_bfd, to_bfd)
1380      bfd *from_bfd;
1381      bfd *to_bfd;
1382 {
1383   asection *p, *new;
1384   int i;
1385   char buf[NUMCPYBYTES];
1386
1387   for (p = from_bfd->sections; p != NULL; p = p->next)
1388     {
1389       printf ("  Copying section %s. Size = %x.\n", p->name, p->_cooked_size);
1390       printf ("    vma = %x,  offset = %x,  output_sec = %x\n",
1391               p->vma, p->output_offset, p->output_section);
1392       new = bfd_make_section (to_bfd, p->name);
1393       if (p->_cooked_size &&
1394           !bfd_set_section_size (to_bfd, new, p->_cooked_size))
1395         {
1396           error ("Wrong BFD size!\n");
1397         }
1398       if (!bfd_set_section_flags (to_bfd, new, p->flags))
1399         {
1400           error ("bfd_set_section_flags");
1401         }
1402       new->vma = p->vma;
1403       
1404       for (i = 0; (i + NUMCPYBYTES) < p->_cooked_size ; i += NUMCPYBYTES)
1405         {
1406           if (!bfd_get_section_contents (from_bfd, p, (PTR) buf, (file_ptr) i,
1407                                         (bfd_size_type) NUMCPYBYTES))
1408             {
1409               error ("bfd_get_section_contents\n");
1410             }
1411         if (!bfd_set_section_contents (to_bfd, new, (PTR) buf, (file_ptr) i,
1412                                       (bfd_size_type) NUMCPYBYTES))
1413           {
1414             error ("bfd_set_section_contents\n");
1415           }
1416       }
1417       bfd_get_section_contents (from_bfd, p, (PTR) buf, (file_ptr) i,
1418                                 (bfd_size_type) (p->_cooked_size - i));
1419       bfd_set_section_contents (to_bfd, new, (PTR) buf,(file_ptr) i,
1420                                 (bfd_size_type) (p->_cooked_size - i));
1421     }
1422 }
1423
1424 #endif
1425
1426 /* Start an process on the es1800 and set inferior_pid to the new
1427    process' pid.
1428    execfile - the file to run
1429    args     - arguments passed to the program
1430    env      - the environment vector to pass    */
1431
1432 static void
1433 es1800_create_inferior (execfile, args, env)
1434      char *execfile;
1435      char *args;
1436      char **env;
1437 {
1438   int entry_pt;
1439   int pid;
1440 #if 0
1441   struct expression *expr;
1442   register struct cleanup *old_chain = 0;
1443   register value val;
1444 #endif
1445
1446   if (args && *args)
1447     {
1448       error ("Can't pass arguments to remote ES1800 process");
1449     }
1450
1451 #if 0
1452   if (query ("Use 'start' as entry point? "))
1453     {
1454       expr = parse_c_expression ("start");
1455       old_chain = make_cleanup (free_current_contents, &expr);
1456       val = evaluate_expression (expr);
1457       entry_pt = (val->location).address;
1458     }
1459   else
1460     {
1461       printf ("Enter the program's entry point (in hexadecimal): ");
1462       scanf ("%x", &entry_pt);
1463     }
1464 #endif
1465
1466   if (execfile == 0 || exec_bfd == 0)
1467     {
1468       error ("No exec file specified");
1469     }
1470
1471   entry_pt = (int) bfd_get_start_address (exec_bfd);
1472
1473   pid = 42;
1474
1475   /* Now that we have a child process, make it our target.  */
1476
1477   push_target (&es1800_child_ops);
1478
1479   /* The "process" (board) is already stopped awaiting our commands, and
1480      the program is already downloaded.  We just set its PC and go.  */
1481
1482   inferior_pid = pid;           /* Needed for wait_for_inferior below */
1483
1484   clear_proceed_status ();
1485
1486   /* Tell wait_for_inferior that we've started a new process.  */
1487
1488   init_wait_for_inferior ();
1489
1490   /* Set up the "saved terminal modes" of the inferior
1491      based on what modes we are starting it with.  */
1492
1493   target_terminal_init ();
1494
1495   /* Install inferior's terminal modes.  */
1496
1497   target_terminal_inferior ();
1498
1499   /* remote_start (args); */
1500   /* trap_expected = 0; */
1501   /* insert_step_breakpoint ();  FIXME, do we need this?  */
1502
1503   /* Let 'er rip... */
1504   proceed ((CORE_ADDR) entry_pt, TARGET_SIGNAL_DEFAULT, 0);
1505
1506 }
1507
1508
1509 /* The process has died, clean up.  */
1510
1511 static void
1512 es1800_mourn_inferior ()
1513 {
1514   remove_breakpoints ();
1515   unpush_target (&es1800_child_ops);
1516   generic_mourn_inferior ();    /* Do all the proper things now */
1517 }
1518
1519 /* ES1800-protocol specific routines */
1520
1521 /* Keep discarding input from the remote system, until STRING is found. 
1522    Let the user break out immediately. 
1523    string - the string to expect
1524    nowait - break out if string not the emulator's first respond otherwise
1525             read until string is found (== 0)   */
1526  
1527 static void
1528 expect (string, nowait)
1529      char *string;
1530     int nowait;
1531 {
1532   char c;
1533   char *p = string;
1534
1535   immediate_quit++;
1536   while (1)
1537     {
1538       c = readchar ();
1539       if (isalpha (c))
1540         {
1541           c = toupper (c);
1542         }
1543       if (c == toupper (*p))
1544         {
1545           p++;
1546           if (*p == '\0')
1547             {
1548               immediate_quit--;
1549               return;
1550             }
1551         }
1552       else if (!nowait)
1553         {
1554           p = string;
1555         }
1556       else
1557         {
1558           printf ("\'%s\' expected\n" , string);
1559           printf ("char %d is %d", p - string, c);
1560           error ("\n" );
1561         }
1562     }
1563 }
1564
1565 /* Keep discarding input until we see the prompt.  */
1566
1567 static void
1568 expect_prompt ()
1569 {
1570   expect (">", 0);
1571 }
1572
1573
1574 /* Read one character */
1575
1576 #ifdef DEBUG_STDIN
1577
1578 /* read from stdin */
1579
1580 static int
1581 readchar ()
1582 {
1583   char buf[1];
1584
1585   buf[0] = '\0';
1586   printf ("readchar, give one character\n");
1587   read (0, buf, 1);
1588
1589 #if defined (LOG_FILE)
1590   putc (buf[0] & 0x7f, log_file);
1591 #endif
1592
1593   return (buf[0] & 0x7f);
1594 }
1595
1596 #else   /* !DEBUG_STDIN */
1597
1598 /* Read a character from the remote system, doing all the fancy
1599    timeout stuff.  */
1600
1601 static int
1602 readchar ()
1603 {
1604   int ch;
1605
1606   ch = SERIAL_READCHAR (es1800_desc, timeout);
1607
1608   /* FIXME: doing an error() here will probably cause trouble, at least if from
1609      es1800_wait.  */
1610   if (ch == SERIAL_TIMEOUT)
1611     error ("Timeout reading from remote system.");
1612   else if (ch == SERIAL_ERROR)
1613     perror_with_name ("remote read");
1614
1615 #if defined (LOG_FILE)
1616   putc (ch & 0x7f, log_file);
1617   fflush (log_file);
1618 #endif
1619
1620   return (ch);
1621 }
1622
1623 #endif  /* DEBUG_STDIN */
1624
1625
1626 /* Send a command to the emulator and save the reply.
1627    Report an error if we get an error reply.
1628    string - the es1800 command
1629    buf    - containing the emulator reply on return
1630    len    - size of buf  */
1631
1632 static void
1633 send_with_reply (string, buf, len)
1634     char *string, *buf;
1635     int len;
1636 {
1637   send (string);
1638   SERIAL_WRITE (es1800_desc, "\r", 1);
1639
1640 #ifndef DEBUG_STDIN
1641   expect (string, 1);
1642   expect ("\r\n", 0);
1643 #endif
1644
1645   getmessage (buf, len);
1646 }
1647
1648
1649 /* Send the command in STR to the emulator adding \r. check
1650    the echo for consistency. 
1651    string - the es1800 command  */
1652  
1653 static void
1654 send_command (string)
1655      char *string;
1656 {
1657   send (string);
1658   SERIAL_WRITE (es1800_desc, "\r", 1);
1659
1660 #ifndef DEBUG_STDIN
1661   expect (string, 0);
1662   expect_prompt ();
1663 #endif
1664
1665 }
1666
1667 /* Send a string
1668    string - the es1800 command  */
1669
1670 static void
1671 send (string)
1672      char *string;
1673 {
1674   if (kiodebug) 
1675     {
1676       fprintf (stderr, "Sending: %s\n", string);
1677     }
1678   SERIAL_WRITE (es1800_desc, string, strlen (string));
1679 }
1680
1681
1682 /* Read a message from the emulator and store it in BUF. 
1683    buf    - containing the emulator reply on return
1684    len    - size of buf  */
1685  
1686 static void
1687 getmessage (buf, len)
1688      char *buf;
1689      int len;
1690 {
1691   char *bp;
1692   int c;
1693   int prompt_found = 0;
1694   extern kiodebug;
1695
1696 #if defined (LOG_FILE)
1697   /* This is a convenient place to do this.  The idea is to do it often
1698      enough that we never lose much data if we terminate abnormally.  */
1699   fflush (log_file);
1700 #endif
1701
1702   bp = buf;
1703   c = readchar ();
1704   do
1705     {
1706       if (c) 
1707         {
1708           if (len-- < 2) /* char and terminaling NULL */
1709             {
1710               error ("input buffer overrun\n");
1711             }
1712           *bp++ = c;
1713         }
1714       c = readchar ();
1715       if ((c == '>') && (*(bp - 1) == ' '))
1716         {
1717           prompt_found = 1;
1718         }
1719     }
1720   while (!prompt_found);
1721   *bp = 0;
1722   
1723   if (kiodebug)
1724     {
1725       fprintf (stderr,"message received :%s\n", buf);
1726     }
1727 }
1728
1729 static void
1730 download (instream, from_tty, format)
1731 FILE *instream;
1732      int from_tty;
1733      int format;
1734 {
1735   char c;
1736   char buf[160];
1737   int i = 0;
1738
1739   send_command ("SET #2,$1A");                  /* reset char = ^Z */
1740   send_command ("SET #3,$11,$13");              /* XON  XOFF */
1741   if (format == 2)
1742     {
1743       send_command ("SET #26,#2");
1744     }
1745   else
1746     {
1747       send_command ("SET #26,#5");              /* Format=Extended Tekhex */
1748     }
1749   send_command ("DFB = $10");
1750   send_command ("PUR");
1751   send_command ("CES");
1752   send ("DNL\r");
1753   expect ("DNL", 1);
1754   if (from_tty)
1755     {
1756       printf ("    0 records loaded...\r");
1757     }
1758   while (fgets (buf, 160, instream))
1759       {
1760         send (buf);
1761         if (from_tty)
1762           {
1763             printf ("%5d\b\b\b\b\b",++i);
1764             fflush (stdout);
1765           }
1766         if ((c = readchar ()) != 006) 
1767           {
1768             error ("expected ACK");
1769           }
1770       }
1771   if (from_tty)
1772     {
1773       printf ("- All");
1774     }
1775 }
1776
1777 /* Additional commands */
1778
1779 #if defined (TIOCGETP) && defined (FNDELAY) && defined (EWOULDBLOCK)
1780 #define PROVIDE_TRANSPARENT
1781 #endif
1782
1783 #ifdef PROVIDE_TRANSPARENT
1784 /* Talk directly to the emulator
1785    FIXME, uses busy wait, and is SUNOS (or at least BSD) specific  */
1786
1787 /*ARGSUSED*/
1788 static void 
1789 es1800_transparent (args, from_tty)
1790      char *args;
1791      int from_tty;
1792 {
1793   int console;
1794   struct sgttyb modebl;
1795   int fcflag;
1796   int cc;
1797   struct sgttyb console_mode_save;
1798   int console_fc_save;
1799   int es1800_fc_save;
1800   int inputcnt = 80;
1801   char inputbuf[80];
1802   int consolecnt = 0;
1803   char consolebuf[80];
1804   int es1800_cnt = 0;
1805   char es1800_buf[80];
1806   int i;
1807
1808   dont_repeat ();
1809   if (es1800_desc == NULL) 
1810     {
1811       printf ("No emulator attached, type emulator-command first\n");
1812       return;
1813     }
1814
1815   printf ("\n");
1816   printf ("You are now communicating directly with the ES 1800 emulator.\n");
1817   printf ("To leave this mode (transparent mode), press ^E.\n");
1818   printf ("\n");
1819   printf (" >");
1820   fflush (stdout);
1821
1822   if ((console = open ("/dev/tty", O_RDWR)) == -1) 
1823     {
1824       perror_with_name ("/dev/tty:");
1825     }
1826
1827   if ((fcflag = fcntl (console, F_GETFL, 0)) == -1)
1828     {
1829       perror_with_name ("fcntl console");
1830     }
1831
1832   console_fc_save = fcflag;
1833   fcflag = fcflag | FNDELAY;
1834
1835   if (fcntl (console, F_SETFL, fcflag) == -1)
1836     {
1837       perror_with_name ("fcntl console");
1838     }
1839
1840   if (ioctl (console, TIOCGETP, &modebl))
1841     {
1842       perror_with_name ("ioctl console");
1843     }
1844
1845   console_mode_save = modebl;
1846   modebl.sg_flags = RAW; 
1847
1848   if (ioctl (console, TIOCSETP, &modebl))
1849     {
1850       perror_with_name ("ioctl console");
1851     }
1852
1853   if ((fcflag = fcntl (es1800_desc->fd, F_GETFL, 0)) == -1)
1854     {
1855       perror_with_name ("fcntl serial");
1856     }
1857
1858   es1800_fc_save = fcflag;
1859   fcflag = fcflag | FNDELAY;
1860
1861   if (fcntl (es1800_desc->fd, F_SETFL, fcflag) == -1)
1862     {
1863       perror_with_name ("fcntl serial");
1864     }
1865
1866   while (1)
1867     { 
1868       cc = read (console, inputbuf, inputcnt);
1869       if (cc != -1)
1870         {
1871           if ((*inputbuf & 0x7f) == 0x05)
1872             {
1873               break;
1874             }
1875           for (i = 0; i < cc; )
1876             {
1877               es1800_buf[es1800_cnt++] = inputbuf[i++];
1878             }
1879           if ((cc = SERIAL_WRITE (es1800_desc, es1800_buf, es1800_cnt)) == -1)
1880             {
1881               perror_with_name ("FEL! write:");
1882             }
1883           es1800_cnt -= cc;
1884           if (es1800_cnt && cc) 
1885             {
1886               for (i = 0; i < es1800_cnt; i++)
1887                 {
1888                   es1800_buf[i] = es1800_buf[cc+i];
1889                 }
1890             }
1891         }
1892       else if (errno != EWOULDBLOCK)
1893         {
1894           perror_with_name ("FEL! read:");
1895         }
1896       
1897       cc = read (es1800_desc->fd,inputbuf,inputcnt);
1898       if (cc != -1)
1899         {
1900           for (i = 0; i < cc; )
1901             {
1902               consolebuf[consolecnt++] = inputbuf[i++];
1903             }
1904           if ((cc = write (console,consolebuf,consolecnt)) == -1)
1905             {
1906               perror_with_name ("FEL! write:");
1907             }
1908           consolecnt -= cc;
1909           if (consolecnt && cc) 
1910             {
1911               for (i = 0; i < consolecnt; i++)
1912                 {
1913                   consolebuf[i] = consolebuf[cc+i];
1914                 }
1915             }
1916         }
1917       else if (errno != EWOULDBLOCK)
1918         {
1919           perror_with_name ("FEL! read:");
1920         }
1921     }
1922
1923   console_fc_save = console_fc_save & !FNDELAY;
1924   if (fcntl (console, F_SETFL, console_fc_save) == -1)
1925     {
1926       perror_with_name ("FEL! fcntl");
1927     }
1928
1929   if (ioctl (console, TIOCSETP, &console_mode_save))
1930     {
1931       perror_with_name ("FEL! ioctl");
1932     }
1933
1934   close (console);
1935
1936   if (fcntl (es1800_desc->fd, F_SETFL, es1800_fc_save) == -1)
1937     {
1938       perror_with_name ("FEL! fcntl");
1939     }
1940
1941   printf ("\n");
1942
1943 }
1944 #endif /* PROVIDE_TRANSPARENT */
1945
1946 static void
1947 es1800_init_break (args, from_tty)
1948      char *args;
1949      int from_tty;
1950 {
1951   CORE_ADDR memaddress = 0;
1952   char buf[PBUFSIZ];
1953   char base_addr[4];
1954   char *space_index;
1955   char *p;
1956   int k;
1957
1958   if (args == NULL)
1959     {
1960       error_no_arg ("a trap vector");
1961     }
1962
1963   if (!(space_index = strchr (args, ' ')))
1964     {
1965       error ("Two arguments needed (trap vector and address of break routine).\n");
1966     }
1967
1968   *space_index = '\0';
1969
1970   es1800_break_vec = strtol (args, (char **) NULL, 0);
1971   es1800_break_address = parse_and_eval_address (space_index + 1);
1972
1973   es1800_create_break_insn (es1800_break_insn, es1800_break_vec);
1974
1975   if (m68020)
1976     {
1977       send_with_reply ("VBR ", buf, sizeof (buf));
1978       p = buf;
1979       for (k = 0; k < 4; k++)
1980         {
1981           if ((p[k*2 + 1] == 0) || (p[k*2 + 2] == 0))
1982             {
1983               error ("Emulator reply is too short: %s", buf);
1984             }
1985           base_addr[k] = (fromhex (p[k*2 + 1]) * 16) + fromhex (p[k*2 + 2]);
1986         }
1987       /* base addr of exception vector table */
1988       memaddress =  *((CORE_ADDR *) base_addr);
1989     }
1990
1991   memaddress += (es1800_break_vec + 32) * 4;     /* address of trap vector */
1992
1993   sprintf (buf, "@.L%lx=$%lx", memaddress, es1800_break_address);
1994   send_command (buf);   /* set the address of the break routine in the */
1995                        /* trap vector */
1996   
1997   sprintf (buf, "@.L%lx=$4E714E71", es1800_break_address);      /* NOP; NOP */
1998   send_command (buf);
1999   sprintf (buf, "@.L%lx=$4E714E73", es1800_break_address + 4);  /* NOP; RTE */
2000   send_command (buf);
2001   
2002   sprintf (buf, "AC2=$%lx", es1800_break_address + 4);
2003   /* breakpoint at es1800-break_address */
2004   send_command (buf);
2005   send_command ("WHEN AC2 THEN BRK");          /* ie in exception routine */
2006
2007   if (from_tty)
2008     {
2009       printf ("Breakpoint (trap $%x) routine at address: %lx\n",
2010               es1800_break_vec, es1800_break_address);
2011     }
2012 }         
2013
2014 static void
2015 es1800_child_open (arg, from_tty)
2016      char *arg;
2017      int from_tty;
2018 {
2019   error ("Use the \"run\" command to start a child process.");
2020 }
2021
2022 static void
2023 es1800_child_detach (args, from_tty)
2024      char *args;
2025      int from_tty;
2026 {
2027   if (args)
2028     {
2029       error ("Argument given to \"detach\" when remotely debugging.");
2030     }
2031   
2032   pop_target ();
2033   if (from_tty)
2034     {
2035       printf ("Ending debugging the process %d.\n", inferior_pid);
2036     }
2037 }
2038
2039
2040 /* Define the target subroutine names  */
2041
2042 static struct target_ops es1800_ops =
2043 {
2044   "es1800",                     /* to_shortname */
2045                                 /* to_longname */
2046   "Remote serial target in ES1800-emulator protocol",
2047                                 /* to_doc */
2048   "Remote debugging on the es1800 emulator via a serial line.\n\
2049 Specify the serial device it is connected to (e.g. /dev/ttya).",
2050   es1800_open,                  /* to_open */
2051   es1800_close,                 /* to_close */
2052   es1800_attach,                /* to_attach */
2053   es1800_detach,                /* to_detach */
2054   es1800_resume,                /* to_resume */
2055   NULL,                         /* to_wait */
2056   NULL,                         /* to_fetch_registers */
2057   NULL,                         /* to_store_registers */
2058   es1800_prepare_to_store,      /* to_prepare_to_store */
2059   es1800_xfer_inferior_memory,  /* to_xfer_memory */
2060   es1800_files_info,            /* to_files_info */
2061   es1800_insert_breakpoint,     /* to_insert_breakpoint */
2062   es1800_remove_breakpoint,     /* to_remove_breakpoint */
2063   NULL,                         /* to_terminal_init */
2064   NULL,                         /* to_terminal_inferior */
2065   NULL,                         /* to_terminal_ours_for_output */
2066   NULL,                         /* to_terminal_ours */
2067   NULL,                         /* to_terminal_info */
2068   NULL,                         /* to_kill */
2069   es1800_load,                  /* to_load */
2070   NULL,                         /* to_lookup_symbol */
2071   es1800_create_inferior,       /* to_create_inferior */
2072   NULL,                         /* to_mourn_inferior */
2073   0,                            /* to_can_run */
2074   0,                            /* notice_signals */
2075   core_stratum,                 /* to_stratum */
2076   0,                            /* to_next */
2077   0,                            /* to_has_all_memory */
2078   1,                            /* to_has_memory */
2079   0,                            /* to_has_stack */
2080   0,                            /* to_has_registers */
2081   0,                            /* to_has_execution */
2082   NULL,                         /* to_sections */
2083   NULL,                         /* to_sections_end */
2084   OPS_MAGIC                     /* to_magic (always last) */
2085 };
2086
2087 /* Define the target subroutine names  */
2088
2089 static struct target_ops es1800_child_ops =
2090 {
2091   "es1800_process",             /* to_shortname */
2092                                 /* to_longname */
2093   "Remote serial target in ES1800-emulator protocol",
2094                                 /* to_doc */
2095   "Remote debugging on the es1800 emulator via a serial line.\n\
2096 Specify the serial device it is connected to (e.g. /dev/ttya).",
2097   es1800_child_open,            /* to_open */
2098   NULL,                         /* to_close */
2099   es1800_attach,                /* to_attach */
2100   es1800_child_detach,          /* to_detach */
2101   es1800_resume,                /* to_resume */
2102   es1800_wait,                  /* to_wait */
2103   es1800_fetch_register,        /* to_fetch_registers */
2104   es1800_store_register,        /* to_store_registers */
2105   es1800_prepare_to_store,      /* to_prepare_to_store */
2106   es1800_xfer_inferior_memory,  /* to_xfer_memory */
2107   es1800_files_info,            /* to_files_info */
2108   es1800_insert_breakpoint,     /* to_insert_breakpoint */
2109   es1800_remove_breakpoint,     /* to_remove_breakpoint */
2110   NULL,                         /* to_terminal_init */
2111   NULL,                         /* to_terminal_inferior */
2112   NULL,                         /* to_terminal_ours_for_output */
2113   NULL,                         /* to_terminal_ours */
2114   NULL,                         /* to_terminal_info */
2115   es1800_kill,                  /* to_kill */
2116   es1800_load,                  /* to_load */
2117   NULL,                         /* to_lookup_symbol */
2118   es1800_create_inferior,       /* to_create_inferior */
2119   es1800_mourn_inferior,        /* to_mourn_inferior */
2120   0,                            /* to_can_run */
2121   0,                            /* notice_signals */
2122   process_stratum,              /* to_stratum */
2123   0,                            /* to_next */
2124   1,                            /* to_has_all_memory */
2125   1,                            /* to_has_memory */
2126   1,                            /* to_has_stack */
2127   1,                            /* to_has_registers */
2128   1,                            /* to_has_execution */
2129   NULL,                         /* to_sections */
2130   NULL,                         /* to_sections_end */
2131   OPS_MAGIC                     /* to_magic (always last) */
2132 };
2133
2134 void
2135 _initialize_es1800 ()
2136 {
2137   add_target (&es1800_ops);
2138   add_target (&es1800_child_ops);
2139 #ifdef PROVIDE_TRANSPARENT
2140   add_com ("transparent", class_support, es1800_transparent,
2141            "Start transparent communication with the ES 1800 emulator.");
2142 #endif /* PROVIDE_TRANSPARENT */
2143   add_com ("init_break", class_support, es1800_init_break,
2144            "Download break routine and initialize break facility on ES 1800");
2145 }