* remote-sim.h (sim_state, SIM_DESC): New types.
[platform/upstream/binutils.git] / gdb / remote-sim.c
1 /* Generic remote debugging interface for simulators.
2    Copyright 1993, 1994, 1996, 1997 Free Software Foundation, Inc.
3    Contributed by Cygnus Support.
4    Steve Chamberlain (sac@cygnus.com).
5
6 This file is part of GDB.
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "wait.h"
25 #include "value.h"
26 #include "gdb_string.h"
27 #include <ctype.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <setjmp.h>
31 #include <errno.h>
32 #include "terminal.h"
33 #include "target.h"
34 #include "gdbcore.h"
35 #include "callback.h"
36 #include "remote-sim.h"
37 #include "remote-utils.h"
38
39 /* Prototypes */
40
41 static void dump_mem PARAMS ((char *buf, int len));
42
43 static void init_callbacks PARAMS ((void));
44
45 static void end_callbacks PARAMS ((void));
46
47 static int gdb_os_write_stdout PARAMS ((host_callback *, const char *, int));
48
49 static void gdb_os_printf_filtered PARAMS ((host_callback *, const char *, ...));
50
51 static void gdb_os_error PARAMS ((host_callback *, const char *, ...));
52
53 static void gdbsim_fetch_register PARAMS ((int regno));
54
55 static void gdbsim_store_register PARAMS ((int regno));
56
57 static void gdbsim_kill PARAMS ((void));
58
59 static void gdbsim_load PARAMS ((char *prog, int fromtty));
60
61 static void gdbsim_create_inferior PARAMS ((char *exec_file, char *args, char **env));
62
63 static void gdbsim_open PARAMS ((char *args, int from_tty));
64
65 static void gdbsim_close PARAMS ((int quitting));
66
67 static void gdbsim_detach PARAMS ((char *args, int from_tty));
68
69 static void gdbsim_resume PARAMS ((int pid, int step, enum target_signal siggnal));
70
71 static int gdbsim_wait PARAMS ((int pid, struct target_waitstatus *status));
72
73 static void gdbsim_prepare_to_store PARAMS ((void));
74
75 static int gdbsim_xfer_inferior_memory PARAMS ((CORE_ADDR memaddr,
76                                                 char *myaddr, int len,
77                                                 int write,
78                                                 struct target_ops *target));
79
80 static void gdbsim_files_info PARAMS ((struct target_ops *target));
81
82 static void gdbsim_mourn_inferior PARAMS ((void));
83
84 static void simulator_command PARAMS ((char *args, int from_tty));
85
86 /* Naming convention:
87
88    sim_* are the interface to the simulator (see remote-sim.h).
89    gdbsim_* are stuff which is internal to gdb.  */
90
91 /* Forward data declarations */
92 extern struct target_ops gdbsim_ops;
93
94 static int program_loaded = 0;
95
96 /* We must keep track of whether the simulator has been opened or not because
97    GDB can call a target's close routine twice, but sim_close doesn't allow
98    this.  We also need to record the result of sim_open so we can pass it
99    back to the other sim_foo routines.  */
100 static SIM_DESC gdbsim_desc = 0;
101
102 static void
103 dump_mem (buf, len)
104      char *buf;
105      int len;
106 {
107   if (len <= 8)
108     {
109       if (len == 8 || len == 4)
110         {
111           long l[2];
112           memcpy (l, buf, len);
113           printf_filtered ("\t0x%x", l[0]);
114           printf_filtered (len == 8 ? " 0x%x\n" : "\n", l[1]);
115         }
116       else
117         {
118           int i;
119           printf_filtered ("\t");
120           for (i = 0; i < len; i++)
121             printf_filtered ("0x%x ", buf[i]);
122           printf_filtered ("\n");
123         }
124     }
125 }
126
127 static host_callback gdb_callback;
128 static int callbacks_initialized = 0;
129
130 /* Initialize gdb_callback.  */
131
132 static void
133 init_callbacks ()
134 {
135   if (! callbacks_initialized)
136     {
137       gdb_callback = default_callback;
138       gdb_callback.init (&gdb_callback);
139       gdb_callback.write_stdout = gdb_os_write_stdout;
140       gdb_callback.printf_filtered = gdb_os_printf_filtered;
141       gdb_callback.error = gdb_os_error;
142       sim_set_callbacks (gdbsim_desc, &gdb_callback);
143       callbacks_initialized = 1;
144     }
145 }
146
147 /* Release callbacks (free resources used by them).  */
148
149 static void
150 end_callbacks ()
151 {
152   if (callbacks_initialized)
153     {
154       gdb_callback.shutdown (&gdb_callback);
155       callbacks_initialized = 0;
156     }
157 }
158
159 /* GDB version of os_write_stdout callback.  */
160
161 static int 
162 gdb_os_write_stdout (p, buf, len)
163      host_callback *p;
164      const char *buf;
165      int len;
166 {
167   int i;
168   char b[2];
169
170   for (i = 0; i < len; i++) 
171     {
172       b[0] = buf[i];
173       b[1] = 0;
174       if (target_output_hook)
175         target_output_hook (b);
176       else
177         fputs_filtered (b, gdb_stdout);
178     }
179   return len;
180 }
181
182 /* GDB version of printf_filtered callback.  */
183
184 /* VARARGS */
185 static void
186 #ifdef ANSI_PROTOTYPES
187 gdb_os_printf_filtered (host_callback *p, const char *format, ...)
188 #else
189 gdb_os_printf_filtered (p, va_alist)
190      host_callback *p;
191      va_dcl
192 #endif
193 {
194   va_list args;
195 #ifdef ANSI_PROTOTYPES
196   va_start (args, format);
197 #else
198   char *format;
199
200   va_start (args);
201   format = va_arg (args, char *);
202 #endif
203
204   vfprintf_filtered (gdb_stdout, format, args);
205
206   va_end (args);
207 }
208
209 /* GDB version of error callback.  */
210
211 /* VARARGS */
212 static void
213 #ifdef ANSI_PROTOTYPES
214 gdb_os_error (host_callback *p, const char *format, ...)
215 #else
216 gdb_os_error (p, va_alist)
217      host_callback *p;
218      va_dcl
219 #endif
220 {
221   if (error_hook)
222     (*error_hook) ();
223   else 
224     {
225       va_list args;
226 #ifdef ANSI_PROTOTYPES
227       va_start (args, format);
228 #else
229       char *format;
230
231       va_start (args);
232       format = va_arg (args, char *);
233 #endif
234
235       error_begin ();
236       vfprintf_filtered (gdb_stderr, format, args);
237       fprintf_filtered (gdb_stderr, "\n");
238       va_end (args);
239       return_to_top_level (RETURN_ERROR);
240     }
241 }
242
243 static void
244 gdbsim_fetch_register (regno)
245 int regno;
246 {
247   if (regno == -1) 
248     {
249       for (regno = 0; regno < NUM_REGS; regno++)
250         gdbsim_fetch_register (regno);
251     }
252   else
253     {
254       char buf[MAX_REGISTER_RAW_SIZE];
255
256       sim_fetch_register (gdbsim_desc, regno, buf);
257       supply_register (regno, buf);
258       if (sr_get_debug ())
259         {
260           printf_filtered ("gdbsim_fetch_register: %d", regno);
261           /* FIXME: We could print something more intelligible.  */
262           dump_mem (buf, REGISTER_RAW_SIZE (regno));
263         }
264     }
265 }
266
267
268 static void
269 gdbsim_store_register (regno)
270 int regno;
271 {
272   if (regno  == -1) 
273     {
274       for (regno = 0; regno < NUM_REGS; regno++)
275         gdbsim_store_register (regno);
276     }
277   else
278     {
279       /* FIXME: Until read_register() returns LONGEST, we have this.  */
280       char tmp[MAX_REGISTER_RAW_SIZE];
281       read_register_gen (regno, tmp);
282       sim_store_register (gdbsim_desc, regno, tmp);
283       if (sr_get_debug ())
284         {
285           printf_filtered ("gdbsim_store_register: %d", regno);
286           /* FIXME: We could print something more intelligible.  */
287           dump_mem (tmp, REGISTER_RAW_SIZE (regno));
288         }
289     }
290 }
291
292 /* Kill the running program.  This may involve closing any open files
293    and releasing other resources acquired by the simulated program.  */
294
295 static void
296 gdbsim_kill ()
297 {
298   if (sr_get_debug ())
299     printf_filtered ("gdbsim_kill\n");
300
301   sim_kill (gdbsim_desc);       /* close fd's, remove mappings, etc. */
302   inferior_pid = 0;
303 }
304
305 /* Load an executable file into the target process.  This is expected to
306    not only bring new code into the target process, but also to update
307    GDB's symbol tables to match.  */
308
309 static void
310 gdbsim_load (prog, fromtty)
311      char *prog;
312      int fromtty;
313 {
314   if (sr_get_debug ())
315     printf_filtered ("gdbsim_load: prog \"%s\"\n", prog);
316
317   inferior_pid = 0;
318
319   /* This must be done before calling gr_load_image.  */
320   program_loaded = 1;
321
322   if (sim_load (gdbsim_desc, prog, fromtty) != 0)
323     generic_load (prog, fromtty);
324 }
325
326
327 /* Start an inferior process and set inferior_pid to its pid.
328    EXEC_FILE is the file to run.
329    ARGS is a string containing the arguments to the program.
330    ENV is the environment vector to pass.  Errors reported with error().
331    On VxWorks and various standalone systems, we ignore exec_file.  */
332 /* This is called not only when we first attach, but also when the
333    user types "run" after having attached.  */
334
335 static void
336 gdbsim_create_inferior (exec_file, args, env)
337      char *exec_file;
338      char *args;
339      char **env;
340 {
341   int len;
342   char *arg_buf,**argv;
343   CORE_ADDR entry_pt;
344
345   if (! program_loaded)
346     error ("No program loaded.");
347
348   if (sr_get_debug ())
349     printf_filtered ("gdbsim_create_inferior: exec_file \"%s\", args \"%s\"\n",
350       exec_file, args);
351
352   if (exec_file == 0 || exec_bfd == 0)
353    error ("No exec file specified.");
354
355   entry_pt = (CORE_ADDR) bfd_get_start_address (exec_bfd);
356
357   gdbsim_kill ();        
358   remove_breakpoints ();
359   init_wait_for_inferior ();
360
361   len = strlen (exec_file) + 1 + strlen (args) + 1 + /*slop*/ 10;
362   arg_buf = (char *) alloca (len);
363   arg_buf[0] = '\0';
364   strcat (arg_buf, exec_file);
365   strcat (arg_buf, " ");
366   strcat (arg_buf, args);
367   argv = buildargv (arg_buf);
368   make_cleanup (freeargv, (char *) argv);
369   sim_create_inferior (gdbsim_desc, entry_pt, argv, env);
370
371   inferior_pid = 42;
372   insert_breakpoints ();        /* Needed to get correct instruction in cache */
373   proceed (entry_pt, TARGET_SIGNAL_DEFAULT, 0);
374 }
375
376 /* The open routine takes the rest of the parameters from the command,
377    and (if successful) pushes a new target onto the stack.
378    Targets should supply this routine, if only to provide an error message.  */
379 /* Called when selecting the simulator. EG: (gdb) target sim name.  */
380
381 static void
382 gdbsim_open (args, from_tty)
383      char *args;
384      int from_tty;
385 {
386   int len;
387   char *arg_buf;
388   char **argv;
389
390   if (sr_get_debug ())
391     printf_filtered ("gdbsim_open: args \"%s\"\n", args ? args : "(null)");
392
393   /* Remove current simulator if one exists.  Only do this if the simulator
394      has been opened because sim_close requires it.
395      This is important because the call to push_target below will cause
396      sim_close to be called if the simulator is already open, but push_target
397      is called after sim_open!  We can't move the call to push_target before
398      the call to sim_open because sim_open may invoke `error'.  */
399   if (gdbsim_desc != NULL)
400     unpush_target (&gdbsim_ops);
401
402   init_callbacks ();
403
404   len = 7 + 1 + (args ? strlen (args) : 0) + 1 + /*slop*/ 10;
405   arg_buf = (char *) alloca (len);
406   strcpy (arg_buf, "gdbsim");
407   if (args)
408     {
409       strcat (arg_buf, " ");
410       strcat (arg_buf, args);
411     }
412   argv = buildargv (arg_buf);
413   if (argv == NULL)
414     error ("Insufficient memory available to allocate simulator arg list.");
415   make_cleanup (freeargv, (char *) argv);
416
417   /* FIXME: sim_open may call `error' if it fails, but perhaps it should
418      just return an error indicator and let us call `error'.  */
419   gdbsim_desc = sim_open (argv);
420
421   push_target (&gdbsim_ops);
422   target_fetch_registers (-1);
423   printf_filtered ("Connected to the simulator.\n");
424 }
425
426 /* Does whatever cleanup is required for a target that we are no longer
427    going to be calling.  Argument says whether we are quitting gdb and
428    should not get hung in case of errors, or whether we want a clean
429    termination even if it takes a while.  This routine is automatically
430    always called just before a routine is popped off the target stack.
431    Closing file descriptors and freeing memory are typical things it should
432    do.  */
433 /* Close out all files and local state before this target loses control. */
434
435 static void
436 gdbsim_close (quitting)
437      int quitting;
438 {
439   if (sr_get_debug ())
440     printf_filtered ("gdbsim_close: quitting %d\n", quitting);
441
442   program_loaded = 0;
443
444   if (gdbsim_desc != NULL)
445     {
446       sim_close (gdbsim_desc, quitting);
447       gdbsim_desc = NULL;
448     }
449
450   end_callbacks ();
451 }
452
453 /* Takes a program previously attached to and detaches it.
454    The program may resume execution (some targets do, some don't) and will
455    no longer stop on signals, etc.  We better not have left any breakpoints
456    in the program or it'll die when it hits one.  ARGS is arguments
457    typed by the user (e.g. a signal to send the process).  FROM_TTY
458    says whether to be verbose or not.  */
459 /* Terminate the open connection to the remote debugger.
460    Use this when you want to detach and do something else with your gdb.  */
461
462 static void
463 gdbsim_detach (args,from_tty)
464      char *args;
465      int from_tty;
466 {
467   if (sr_get_debug ())
468     printf_filtered ("gdbsim_detach: args \"%s\"\n", args);
469
470   pop_target ();                /* calls gdbsim_close to do the real work */
471   if (from_tty)
472     printf_filtered ("Ending simulator %s debugging\n", target_shortname);
473 }
474  
475 /* Resume execution of the target process.  STEP says whether to single-step
476    or to run free; SIGGNAL is the signal value (e.g. SIGINT) to be given
477    to the target, or zero for no signal.  */
478
479 static void
480 gdbsim_resume (pid, step, siggnal)
481      int pid, step;
482      enum target_signal siggnal;
483 {
484   if (inferior_pid != 42)
485     error ("The program is not being run.");
486
487   if (sr_get_debug ())
488     printf_filtered ("gdbsim_resume: step %d, signal %d\n", step, siggnal);
489
490   sim_resume (gdbsim_desc, step, target_signal_to_host (siggnal));
491 }
492
493 /* Wait for inferior process to do something.  Return pid of child,
494    or -1 in case of error; store status through argument pointer STATUS,
495    just as `wait' would.  */
496
497 static int
498 gdbsim_wait (pid, status)
499      int pid;
500      struct target_waitstatus *status;
501 {
502   int sigrc;
503   enum sim_stop reason;
504
505   if (sr_get_debug ())
506     printf_filtered ("gdbsim_wait\n");
507
508   sim_stop_reason (gdbsim_desc, &reason, &sigrc);
509   switch (reason)
510     {
511     case sim_exited:
512       status->kind = TARGET_WAITKIND_EXITED;
513       status->value.integer = sigrc;
514       break;
515     case sim_stopped:
516       status->kind = TARGET_WAITKIND_STOPPED;
517       /* The signal in sigrc is a host signal.  That probably
518          should be fixed.  */
519       status->value.sig = target_signal_from_host (sigrc);
520       break;
521     case sim_signalled:
522       status->kind = TARGET_WAITKIND_SIGNALLED;
523       /* The signal in sigrc is a host signal.  That probably
524          should be fixed.  */
525       status->value.sig = target_signal_from_host (sigrc);
526       break;
527     }
528
529   return inferior_pid;
530 }
531
532 /* Get ready to modify the registers array.  On machines which store
533    individual registers, this doesn't need to do anything.  On machines
534    which store all the registers in one fell swoop, this makes sure
535    that registers contains all the registers from the program being
536    debugged.  */
537
538 static void
539 gdbsim_prepare_to_store ()
540 {
541   /* Do nothing, since we can store individual regs */
542 }
543
544 static int
545 gdbsim_xfer_inferior_memory (memaddr, myaddr, len, write, target)
546      CORE_ADDR memaddr;
547      char *myaddr;
548      int len;
549      int write;
550      struct target_ops *target;                 /* ignored */
551 {
552   if (! program_loaded)
553     error ("No program loaded.");
554
555   if (sr_get_debug ())
556     {
557       printf_filtered ("gdbsim_xfer_inferior_memory: myaddr 0x%x, memaddr 0x%x, len %d, write %d\n",
558                        myaddr, memaddr, len, write);
559       if (sr_get_debug () && write)
560         dump_mem(myaddr, len);
561     }
562
563   if (write)
564     {
565       len = sim_write (gdbsim_desc, memaddr, myaddr, len);
566     }
567   else 
568     {
569       len = sim_read (gdbsim_desc, memaddr, myaddr, len);
570       if (sr_get_debug () && len > 0)
571         dump_mem(myaddr, len);
572     } 
573   return len;
574 }
575
576 static void
577 gdbsim_files_info (target)
578      struct target_ops *target;
579 {
580   char *file = "nothing";
581
582   if (exec_bfd)
583     file = bfd_get_filename (exec_bfd);
584
585   if (sr_get_debug ())
586     printf_filtered ("gdbsim_files_info: file \"%s\"\n", file);
587
588   if (exec_bfd)
589     {
590       printf_filtered ("\tAttached to %s running program %s\n",
591                        target_shortname, file);
592       sim_info (gdbsim_desc, 0);
593     }
594 }
595
596 /* Clear the simulator's notion of what the break points are.  */
597
598 static void
599 gdbsim_mourn_inferior () 
600
601   if (sr_get_debug ())
602     printf_filtered ("gdbsim_mourn_inferior:\n");
603
604   remove_breakpoints ();
605   generic_mourn_inferior ();
606 }
607
608 /* Pass the command argument through to the simulator verbatim.  The
609    simulator must do any command interpretation work.  */
610
611 static void
612 simulator_command (args, from_tty)
613      char *args;
614      int from_tty;
615 {
616   /* The user may give a command before the simulator is opened, so
617      ensure that the callbacks have been set up.  */
618   init_callbacks ();
619
620   /* Note that if the simulator hasn't been opened, gdbsim_desc == NULL
621      which is correct (??? assuming of course one wishes to continue to
622      allow commands to be sent to unopened simulators, which isn't entirely
623      unreasonable).  */
624   sim_do_command (gdbsim_desc, args);
625 }
626
627 /* Define the target subroutine names */
628
629 struct target_ops gdbsim_ops = {
630   "sim",                        /* to_shortname */
631   "simulator",                  /* to_longname */
632   "Use the compiled-in simulator.",  /* to_doc */
633   gdbsim_open,                  /* to_open */
634   gdbsim_close,                 /* to_close */
635   NULL,                         /* to_attach */
636   gdbsim_detach,                /* to_detach */
637   gdbsim_resume,                /* to_resume */
638   gdbsim_wait,                  /* to_wait */
639   gdbsim_fetch_register,        /* to_fetch_registers */
640   gdbsim_store_register,        /* to_store_registers */
641   gdbsim_prepare_to_store,      /* to_prepare_to_store */
642   gdbsim_xfer_inferior_memory,  /* to_xfer_memory */
643   gdbsim_files_info,            /* to_files_info */
644   memory_insert_breakpoint,     /* to_insert_breakpoint */
645   memory_remove_breakpoint,     /* to_remove_breakpoint */
646   NULL,                         /* to_terminal_init */
647   NULL,                         /* to_terminal_inferior */
648   NULL,                         /* to_terminal_ours_for_output */
649   NULL,                         /* to_terminal_ours */
650   NULL,                         /* to_terminal_info */
651   gdbsim_kill,                  /* to_kill */
652   gdbsim_load,                  /* to_load */
653   NULL,                         /* to_lookup_symbol */
654   gdbsim_create_inferior,       /* to_create_inferior */ 
655   gdbsim_mourn_inferior,        /* to_mourn_inferior */
656   0,                            /* to_can_run */
657   0,                            /* to_notice_signals */
658   0,                            /* to_thread_alive */
659   0,                            /* to_stop */
660   process_stratum,              /* to_stratum */
661   NULL,                         /* to_next */
662   1,                            /* to_has_all_memory */
663   1,                            /* to_has_memory */
664   1,                            /* to_has_stack */
665   1,                            /* to_has_registers */
666   1,                            /* to_has_execution */
667   NULL,                         /* sections */
668   NULL,                         /* sections_end */
669   OPS_MAGIC,                    /* to_magic */
670 };
671
672 void
673 _initialize_remote_sim ()
674 {
675   add_target (&gdbsim_ops);
676
677   add_com ("sim <command>", class_obscure, simulator_command,
678            "Send a command to the simulator."); 
679 }