* linux-nat.c (linux_nat_wait): Adjust.
[external/binutils.git] / gdb / remote-sim.c
1 /* Generic remote debugging interface for simulators.
2
3    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
4    2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6    Contributed by Cygnus Support.
7    Steve Chamberlain (sac@cygnus.com).
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
23
24 #include "defs.h"
25 #include "inferior.h"
26 #include "value.h"
27 #include "gdb_string.h"
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <setjmp.h>
32 #include <errno.h>
33 #include "terminal.h"
34 #include "target.h"
35 #include "gdbcore.h"
36 #include "gdb/callback.h"
37 #include "gdb/remote-sim.h"
38 #include "command.h"
39 #include "regcache.h"
40 #include "gdb_assert.h"
41 #include "sim-regno.h"
42 #include "arch-utils.h"
43 #include "readline/readline.h"
44 #include "gdbthread.h"
45
46 /* Prototypes */
47
48 extern void _initialize_remote_sim (void);
49
50 static void dump_mem (char *buf, int len);
51
52 static void init_callbacks (void);
53
54 static void end_callbacks (void);
55
56 static int gdb_os_write_stdout (host_callback *, const char *, int);
57
58 static void gdb_os_flush_stdout (host_callback *);
59
60 static int gdb_os_write_stderr (host_callback *, const char *, int);
61
62 static void gdb_os_flush_stderr (host_callback *);
63
64 static int gdb_os_poll_quit (host_callback *);
65
66 /* printf_filtered is depreciated */
67 static void gdb_os_printf_filtered (host_callback *, const char *, ...);
68
69 static void gdb_os_vprintf_filtered (host_callback *, const char *, va_list);
70
71 static void gdb_os_evprintf_filtered (host_callback *, const char *, va_list);
72
73 static void gdb_os_error (host_callback *, const char *, ...) ATTR_NORETURN;
74
75 static void gdbsim_fetch_register (struct regcache *regcache, int regno);
76
77 static void gdbsim_store_register (struct regcache *regcache, int regno);
78
79 static void gdbsim_kill (void);
80
81 static void gdbsim_load (char *prog, int fromtty);
82
83 static void gdbsim_open (char *args, int from_tty);
84
85 static void gdbsim_close (int quitting);
86
87 static void gdbsim_detach (struct target_ops *ops, char *args, int from_tty);
88
89 static void gdbsim_resume (ptid_t ptid, int step, enum target_signal siggnal);
90
91 static void gdbsim_prepare_to_store (struct regcache *regcache);
92
93 static void gdbsim_files_info (struct target_ops *target);
94
95 static void gdbsim_mourn_inferior (struct target_ops *target);
96
97 static void gdbsim_stop (ptid_t ptid);
98
99 void simulator_command (char *args, int from_tty);
100
101 /* Naming convention:
102
103    sim_* are the interface to the simulator (see remote-sim.h).
104    gdbsim_* are stuff which is internal to gdb.  */
105
106 /* Forward data declarations */
107 extern struct target_ops gdbsim_ops;
108
109 static int program_loaded = 0;
110
111 /* We must keep track of whether the simulator has been opened or not because
112    GDB can call a target's close routine twice, but sim_close doesn't allow
113    this.  We also need to record the result of sim_open so we can pass it
114    back to the other sim_foo routines.  */
115 static SIM_DESC gdbsim_desc = 0;
116
117 /* This is the ptid we use while we're connected to the simulator.
118    Its value is arbitrary, as the simulator target don't have a notion
119    or processes or threads, but we need something non-null to place in
120    inferior_ptid.  */
121 static ptid_t remote_sim_ptid;
122
123 static void
124 dump_mem (char *buf, int len)
125 {
126   if (len <= 8)
127     {
128       if (len == 8 || len == 4)
129         {
130           long l[2];
131           memcpy (l, buf, len);
132           printf_filtered ("\t0x%lx", l[0]);
133           if (len == 8)
134             printf_filtered (" 0x%lx", l[1]);
135           printf_filtered ("\n");
136         }
137       else
138         {
139           int i;
140           printf_filtered ("\t");
141           for (i = 0; i < len; i++)
142             printf_filtered ("0x%x ", buf[i]);
143           printf_filtered ("\n");
144         }
145     }
146 }
147
148 static host_callback gdb_callback;
149 static int callbacks_initialized = 0;
150
151 /* Initialize gdb_callback.  */
152
153 static void
154 init_callbacks (void)
155 {
156   if (!callbacks_initialized)
157     {
158       gdb_callback = default_callback;
159       gdb_callback.init (&gdb_callback);
160       gdb_callback.write_stdout = gdb_os_write_stdout;
161       gdb_callback.flush_stdout = gdb_os_flush_stdout;
162       gdb_callback.write_stderr = gdb_os_write_stderr;
163       gdb_callback.flush_stderr = gdb_os_flush_stderr;
164       gdb_callback.printf_filtered = gdb_os_printf_filtered;
165       gdb_callback.vprintf_filtered = gdb_os_vprintf_filtered;
166       gdb_callback.evprintf_filtered = gdb_os_evprintf_filtered;
167       gdb_callback.error = gdb_os_error;
168       gdb_callback.poll_quit = gdb_os_poll_quit;
169       gdb_callback.magic = HOST_CALLBACK_MAGIC;
170       callbacks_initialized = 1;
171     }
172 }
173
174 /* Release callbacks (free resources used by them).  */
175
176 static void
177 end_callbacks (void)
178 {
179   if (callbacks_initialized)
180     {
181       gdb_callback.shutdown (&gdb_callback);
182       callbacks_initialized = 0;
183     }
184 }
185
186 /* GDB version of os_write_stdout callback.  */
187
188 static int
189 gdb_os_write_stdout (host_callback *p, const char *buf, int len)
190 {
191   int i;
192   char b[2];
193
194   ui_file_write (gdb_stdtarg, buf, len);
195   return len;
196 }
197
198 /* GDB version of os_flush_stdout callback.  */
199
200 static void
201 gdb_os_flush_stdout (host_callback *p)
202 {
203   gdb_flush (gdb_stdtarg);
204 }
205
206 /* GDB version of os_write_stderr callback.  */
207
208 static int
209 gdb_os_write_stderr (host_callback *p, const char *buf, int len)
210 {
211   int i;
212   char b[2];
213
214   for (i = 0; i < len; i++)
215     {
216       b[0] = buf[i];
217       b[1] = 0;
218       fputs_unfiltered (b, gdb_stdtargerr);
219     }
220   return len;
221 }
222
223 /* GDB version of os_flush_stderr callback.  */
224
225 static void
226 gdb_os_flush_stderr (host_callback *p)
227 {
228   gdb_flush (gdb_stdtargerr);
229 }
230
231 /* GDB version of printf_filtered callback.  */
232
233 static void
234 gdb_os_printf_filtered (host_callback * p, const char *format,...)
235 {
236   va_list args;
237   va_start (args, format);
238
239   vfprintf_filtered (gdb_stdout, format, args);
240
241   va_end (args);
242 }
243
244 /* GDB version of error vprintf_filtered.  */
245
246 static void
247 gdb_os_vprintf_filtered (host_callback * p, const char *format, va_list ap)
248 {
249   vfprintf_filtered (gdb_stdout, format, ap);
250 }
251
252 /* GDB version of error evprintf_filtered.  */
253
254 static void
255 gdb_os_evprintf_filtered (host_callback * p, const char *format, va_list ap)
256 {
257   vfprintf_filtered (gdb_stderr, format, ap);
258 }
259
260 /* GDB version of error callback.  */
261
262 static void
263 gdb_os_error (host_callback * p, const char *format, ...)
264 {
265   va_list args;
266   va_start (args, format);
267   verror (format, args);
268   va_end (args);
269 }
270
271 int
272 one2one_register_sim_regno (struct gdbarch *gdbarch, int regnum)
273 {
274   /* Only makes sense to supply raw registers.  */
275   gdb_assert (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch));
276   return regnum;
277 }
278
279 static void
280 gdbsim_fetch_register (struct regcache *regcache, int regno)
281 {
282   struct gdbarch *gdbarch = get_regcache_arch (regcache);
283   if (regno == -1)
284     {
285       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
286         gdbsim_fetch_register (regcache, regno);
287       return;
288     }
289
290   switch (gdbarch_register_sim_regno (gdbarch, regno))
291     {
292     case LEGACY_SIM_REGNO_IGNORE:
293       break;
294     case SIM_REGNO_DOES_NOT_EXIST:
295       {
296         /* For moment treat a `does not exist' register the same way
297            as an ``unavailable'' register.  */
298         char buf[MAX_REGISTER_SIZE];
299         int nr_bytes;
300         memset (buf, 0, MAX_REGISTER_SIZE);
301         regcache_raw_supply (regcache, regno, buf);
302         break;
303       }
304       
305     default:
306       {
307         static int warn_user = 1;
308         char buf[MAX_REGISTER_SIZE];
309         int nr_bytes;
310         gdb_assert (regno >= 0 && regno < gdbarch_num_regs (gdbarch));
311         memset (buf, 0, MAX_REGISTER_SIZE);
312         nr_bytes = sim_fetch_register (gdbsim_desc,
313                                        gdbarch_register_sim_regno
314                                          (gdbarch, regno),
315                                        buf,
316                                        register_size (gdbarch, regno));
317         if (nr_bytes > 0
318             && nr_bytes != register_size (gdbarch, regno) && warn_user)
319           {
320             fprintf_unfiltered (gdb_stderr,
321                                 "Size of register %s (%d/%d) incorrect (%d instead of %d))",
322                                 gdbarch_register_name (gdbarch, regno),
323                                 regno,
324                                 gdbarch_register_sim_regno
325                                   (gdbarch, regno),
326                                 nr_bytes, register_size (gdbarch, regno));
327             warn_user = 0;
328           }
329         /* FIXME: cagney/2002-05-27: Should check `nr_bytes == 0'
330            indicating that GDB and the SIM have different ideas about
331            which registers are fetchable.  */
332         /* Else if (nr_bytes < 0): an old simulator, that doesn't
333            think to return the register size.  Just assume all is ok.  */
334         regcache_raw_supply (regcache, regno, buf);
335         if (remote_debug)
336           {
337             printf_filtered ("gdbsim_fetch_register: %d", regno);
338             /* FIXME: We could print something more intelligible.  */
339             dump_mem (buf, register_size (gdbarch, regno));
340           }
341         break;
342       }
343     }
344 }
345
346
347 static void
348 gdbsim_store_register (struct regcache *regcache, int regno)
349 {
350   struct gdbarch *gdbarch = get_regcache_arch (regcache);
351   if (regno == -1)
352     {
353       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
354         gdbsim_store_register (regcache, regno);
355       return;
356     }
357   else if (gdbarch_register_sim_regno (gdbarch, regno) >= 0)
358     {
359       char tmp[MAX_REGISTER_SIZE];
360       int nr_bytes;
361       regcache_cooked_read (regcache, regno, tmp);
362       nr_bytes = sim_store_register (gdbsim_desc,
363                                      gdbarch_register_sim_regno
364                                        (gdbarch, regno),
365                                      tmp, register_size (gdbarch, regno));
366       if (nr_bytes > 0 && nr_bytes != register_size (gdbarch, regno))
367         internal_error (__FILE__, __LINE__,
368                         _("Register size different to expected"));
369       /* FIXME: cagney/2002-05-27: Should check `nr_bytes == 0'
370          indicating that GDB and the SIM have different ideas about
371          which registers are fetchable.  */
372       if (remote_debug)
373         {
374           printf_filtered ("gdbsim_store_register: %d", regno);
375           /* FIXME: We could print something more intelligible.  */
376           dump_mem (tmp, register_size (gdbarch, regno));
377         }
378     }
379 }
380
381 /* Kill the running program.  This may involve closing any open files
382    and releasing other resources acquired by the simulated program.  */
383
384 static void
385 gdbsim_kill (void)
386 {
387   if (remote_debug)
388     printf_filtered ("gdbsim_kill\n");
389
390   /* There is no need to `kill' running simulator - the simulator is
391      not running.  Mourning it is enough.  */
392   target_mourn_inferior ();
393 }
394
395 /* Load an executable file into the target process.  This is expected to
396    not only bring new code into the target process, but also to update
397    GDB's symbol tables to match.  */
398
399 static void
400 gdbsim_load (char *args, int fromtty)
401 {
402   char **argv;
403   char *prog;
404
405   if (args == NULL)
406       error_no_arg (_("program to load"));
407
408   argv = gdb_buildargv (args);
409   make_cleanup_freeargv (argv);
410
411   prog = tilde_expand (argv[0]);
412
413   if (argv[1] != NULL)
414     error (_("GDB sim does not yet support a load offset."));
415
416   if (remote_debug)
417     printf_filtered ("gdbsim_load: prog \"%s\"\n", prog);
418
419   /* FIXME: We will print two messages on error.
420      Need error to either not print anything if passed NULL or need
421      another routine that doesn't take any arguments.  */
422   if (sim_load (gdbsim_desc, prog, NULL, fromtty) == SIM_RC_FAIL)
423     error (_("unable to load program"));
424
425   /* FIXME: If a load command should reset the targets registers then
426      a call to sim_create_inferior() should go here. */
427
428   program_loaded = 1;
429 }
430
431
432 /* Start an inferior process and set inferior_ptid to its pid.
433    EXEC_FILE is the file to run.
434    ARGS is a string containing the arguments to the program.
435    ENV is the environment vector to pass.  Errors reported with error().
436    On VxWorks and various standalone systems, we ignore exec_file.  */
437 /* This is called not only when we first attach, but also when the
438    user types "run" after having attached.  */
439
440 static void
441 gdbsim_create_inferior (struct target_ops *target, char *exec_file, char *args,
442                         char **env, int from_tty)
443 {
444   int len;
445   char *arg_buf, **argv;
446
447   if (exec_file == 0 || exec_bfd == 0)
448     warning (_("No executable file specified."));
449   if (!program_loaded)
450     warning (_("No program loaded."));
451
452   if (remote_debug)
453     printf_filtered ("gdbsim_create_inferior: exec_file \"%s\", args \"%s\"\n",
454                      (exec_file ? exec_file : "(NULL)"),
455                      args);
456
457   if (ptid_equal (inferior_ptid, remote_sim_ptid))
458     gdbsim_kill ();
459   remove_breakpoints ();
460   init_wait_for_inferior ();
461
462   if (exec_file != NULL)
463     {
464       len = strlen (exec_file) + 1 + strlen (args) + 1 + /*slop */ 10;
465       arg_buf = (char *) alloca (len);
466       arg_buf[0] = '\0';
467       strcat (arg_buf, exec_file);
468       strcat (arg_buf, " ");
469       strcat (arg_buf, args);
470       argv = gdb_buildargv (arg_buf);
471       make_cleanup_freeargv (argv);
472     }
473   else
474     argv = NULL;
475   sim_create_inferior (gdbsim_desc, exec_bfd, argv, env);
476
477   inferior_ptid = remote_sim_ptid;
478   add_inferior_silent (ptid_get_pid (inferior_ptid));
479   add_thread_silent (inferior_ptid);
480
481   target_mark_running (&gdbsim_ops);
482   insert_breakpoints ();        /* Needed to get correct instruction in cache */
483
484   clear_proceed_status ();
485 }
486
487 /* The open routine takes the rest of the parameters from the command,
488    and (if successful) pushes a new target onto the stack.
489    Targets should supply this routine, if only to provide an error message.  */
490 /* Called when selecting the simulator. EG: (gdb) target sim name.  */
491
492 static void
493 gdbsim_open (char *args, int from_tty)
494 {
495   int len;
496   char *arg_buf;
497   char **argv;
498
499   if (remote_debug)
500     printf_filtered ("gdbsim_open: args \"%s\"\n", args ? args : "(null)");
501
502   /* Remove current simulator if one exists.  Only do this if the simulator
503      has been opened because sim_close requires it.
504      This is important because the call to push_target below will cause
505      sim_close to be called if the simulator is already open, but push_target
506      is called after sim_open!  We can't move the call to push_target before
507      the call to sim_open because sim_open may invoke `error'.  */
508   if (gdbsim_desc != NULL)
509     unpush_target (&gdbsim_ops);
510
511   len = (7 + 1                  /* gdbsim */
512          + strlen (" -E little")
513          + strlen (" --architecture=xxxxxxxxxx")
514          + (args ? strlen (args) : 0)
515          + 50) /* slack */ ;
516   arg_buf = (char *) alloca (len);
517   strcpy (arg_buf, "gdbsim");   /* 7 */
518   /* Specify the byte order for the target when it is explicitly
519      specified by the user (not auto detected). */
520   switch (selected_byte_order ())
521     {
522     case BFD_ENDIAN_BIG:
523       strcat (arg_buf, " -E big");
524       break;
525     case BFD_ENDIAN_LITTLE:
526       strcat (arg_buf, " -E little");
527       break;
528     case BFD_ENDIAN_UNKNOWN:
529       break;
530     }
531   /* Specify the architecture of the target when it has been
532      explicitly specified */
533   if (selected_architecture_name () != NULL)
534     {
535       strcat (arg_buf, " --architecture=");
536       strcat (arg_buf, selected_architecture_name ());
537     }
538   /* finally, any explicit args */
539   if (args)
540     {
541       strcat (arg_buf, " ");    /* 1 */
542       strcat (arg_buf, args);
543     }
544   argv = gdb_buildargv (arg_buf);
545   make_cleanup_freeargv (argv);
546
547   init_callbacks ();
548   gdbsim_desc = sim_open (SIM_OPEN_DEBUG, &gdb_callback, exec_bfd, argv);
549
550   if (gdbsim_desc == 0)
551     error (_("unable to create simulator instance"));
552
553   push_target (&gdbsim_ops);
554   printf_filtered ("Connected to the simulator.\n");
555
556   /* There's nothing running after "target sim" or "load"; not until
557      "run".  */
558   inferior_ptid = null_ptid;
559   target_mark_exited (&gdbsim_ops);
560 }
561
562 /* Does whatever cleanup is required for a target that we are no longer
563    going to be calling.  Argument says whether we are quitting gdb and
564    should not get hung in case of errors, or whether we want a clean
565    termination even if it takes a while.  This routine is automatically
566    always called just before a routine is popped off the target stack.
567    Closing file descriptors and freeing memory are typical things it should
568    do.  */
569 /* Close out all files and local state before this target loses control. */
570
571 static void
572 gdbsim_close (int quitting)
573 {
574   if (remote_debug)
575     printf_filtered ("gdbsim_close: quitting %d\n", quitting);
576
577   program_loaded = 0;
578
579   if (gdbsim_desc != NULL)
580     {
581       sim_close (gdbsim_desc, quitting);
582       gdbsim_desc = NULL;
583     }
584
585   end_callbacks ();
586   generic_mourn_inferior ();
587   delete_thread_silent (remote_sim_ptid);
588   delete_inferior_silent (ptid_get_pid (remote_sim_ptid));
589 }
590
591 /* Takes a program previously attached to and detaches it.
592    The program may resume execution (some targets do, some don't) and will
593    no longer stop on signals, etc.  We better not have left any breakpoints
594    in the program or it'll die when it hits one.  ARGS is arguments
595    typed by the user (e.g. a signal to send the process).  FROM_TTY
596    says whether to be verbose or not.  */
597 /* Terminate the open connection to the remote debugger.
598    Use this when you want to detach and do something else with your gdb.  */
599
600 static void
601 gdbsim_detach (struct target_ops *ops, char *args, int from_tty)
602 {
603   if (remote_debug)
604     printf_filtered ("gdbsim_detach: args \"%s\"\n", args);
605
606   pop_target ();                /* calls gdbsim_close to do the real work */
607   if (from_tty)
608     printf_filtered ("Ending simulator %s debugging\n", target_shortname);
609 }
610
611 /* Resume execution of the target process.  STEP says whether to single-step
612    or to run free; SIGGNAL is the signal value (e.g. SIGINT) to be given
613    to the target, or zero for no signal.  */
614
615 static enum target_signal resume_siggnal;
616 static int resume_step;
617
618 static void
619 gdbsim_resume (ptid_t ptid, int step, enum target_signal siggnal)
620 {
621   if (!ptid_equal (inferior_ptid, remote_sim_ptid))
622     error (_("The program is not being run."));
623
624   if (remote_debug)
625     printf_filtered ("gdbsim_resume: step %d, signal %d\n", step, siggnal);
626
627   resume_siggnal = siggnal;
628   resume_step = step;
629 }
630
631 /* Notify the simulator of an asynchronous request to stop.
632
633    The simulator shall ensure that the stop request is eventually
634    delivered to the simulator.  If the call is made while the
635    simulator is not running then the stop request is processed when
636    the simulator is next resumed.
637
638    For simulators that do not support this operation, just abort */
639
640 static void
641 gdbsim_stop (ptid_t ptid)
642 {
643   if (!sim_stop (gdbsim_desc))
644     {
645       quit ();
646     }
647 }
648
649 /* GDB version of os_poll_quit callback.
650    Taken from gdb/util.c - should be in a library.  */
651
652 static int
653 gdb_os_poll_quit (host_callback *p)
654 {
655   if (deprecated_ui_loop_hook != NULL)
656     deprecated_ui_loop_hook (0);
657
658   if (quit_flag)                /* gdb's idea of quit */
659     {
660       quit_flag = 0;            /* we've stolen it */
661       return 1;
662     }
663   else if (immediate_quit)
664     {
665       return 1;
666     }
667   return 0;
668 }
669
670 /* Wait for inferior process to do something.  Return pid of child,
671    or -1 in case of error; store status through argument pointer STATUS,
672    just as `wait' would. */
673
674 static void
675 gdbsim_cntrl_c (int signo)
676 {
677   gdbsim_stop (remote_sim_ptid);
678 }
679
680 static ptid_t
681 gdbsim_wait (struct target_ops *ops,
682              ptid_t ptid, struct target_waitstatus *status)
683 {
684   static RETSIGTYPE (*prev_sigint) ();
685   int sigrc = 0;
686   enum sim_stop reason = sim_running;
687
688   if (remote_debug)
689     printf_filtered ("gdbsim_wait\n");
690
691 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
692   {
693     struct sigaction sa, osa;
694     sa.sa_handler = gdbsim_cntrl_c;
695     sigemptyset (&sa.sa_mask);
696     sa.sa_flags = 0;
697     sigaction (SIGINT, &sa, &osa);
698     prev_sigint = osa.sa_handler;
699   }
700 #else
701   prev_sigint = signal (SIGINT, gdbsim_cntrl_c);
702 #endif
703   sim_resume (gdbsim_desc, resume_step, resume_siggnal);
704   signal (SIGINT, prev_sigint);
705   resume_step = 0;
706
707   sim_stop_reason (gdbsim_desc, &reason, &sigrc);
708
709   switch (reason)
710     {
711     case sim_exited:
712       status->kind = TARGET_WAITKIND_EXITED;
713       status->value.integer = sigrc;
714       break;
715     case sim_stopped:
716       switch (sigrc)
717         {
718         case TARGET_SIGNAL_ABRT:
719           quit ();
720           break;
721         case TARGET_SIGNAL_INT:
722         case TARGET_SIGNAL_TRAP:
723         default:
724           status->kind = TARGET_WAITKIND_STOPPED;
725           status->value.sig = sigrc;
726           break;
727         }
728       break;
729     case sim_signalled:
730       status->kind = TARGET_WAITKIND_SIGNALLED;
731       status->value.sig = sigrc;
732       break;
733     case sim_running:
734     case sim_polling:
735       /* FIXME: Is this correct? */
736       break;
737     }
738
739   return inferior_ptid;
740 }
741
742 /* Get ready to modify the registers array.  On machines which store
743    individual registers, this doesn't need to do anything.  On machines
744    which store all the registers in one fell swoop, this makes sure
745    that registers contains all the registers from the program being
746    debugged.  */
747
748 static void
749 gdbsim_prepare_to_store (struct regcache *regcache)
750 {
751   /* Do nothing, since we can store individual regs */
752 }
753
754 /* Transfer LEN bytes between GDB address MYADDR and target address
755    MEMADDR.  If WRITE is non-zero, transfer them to the target,
756    otherwise transfer them from the target.  TARGET is unused.
757
758    Returns the number of bytes transferred. */
759
760 static int
761 gdbsim_xfer_inferior_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len,
762                              int write, struct mem_attrib *attrib,
763                              struct target_ops *target)
764 {
765   /* If no program is running yet, then ignore the simulator for
766      memory.  Pass the request down to the next target, hopefully
767      an exec file.  */
768   if (!target_has_execution)
769     return 0;
770
771   if (!program_loaded)
772     error (_("No program loaded."));
773
774   if (remote_debug)
775     {
776       /* FIXME: Send to something other than STDOUT? */
777       printf_filtered ("gdbsim_xfer_inferior_memory: myaddr 0x");
778       gdb_print_host_address (myaddr, gdb_stdout);
779       printf_filtered (", memaddr 0x%s, len %d, write %d\n",
780                        paddr_nz (memaddr), len, write);
781       if (remote_debug && write)
782         dump_mem (myaddr, len);
783     }
784
785   if (write)
786     {
787       len = sim_write (gdbsim_desc, memaddr, myaddr, len);
788     }
789   else
790     {
791       len = sim_read (gdbsim_desc, memaddr, myaddr, len);
792       if (remote_debug && len > 0)
793         dump_mem (myaddr, len);
794     }
795   return len;
796 }
797
798 static void
799 gdbsim_files_info (struct target_ops *target)
800 {
801   char *file = "nothing";
802
803   if (exec_bfd)
804     file = bfd_get_filename (exec_bfd);
805
806   if (remote_debug)
807     printf_filtered ("gdbsim_files_info: file \"%s\"\n", file);
808
809   if (exec_bfd)
810     {
811       printf_filtered ("\tAttached to %s running program %s\n",
812                        target_shortname, file);
813       sim_info (gdbsim_desc, 0);
814     }
815 }
816
817 /* Clear the simulator's notion of what the break points are.  */
818
819 static void
820 gdbsim_mourn_inferior (struct target_ops *target)
821 {
822   if (remote_debug)
823     printf_filtered ("gdbsim_mourn_inferior:\n");
824
825   remove_breakpoints ();
826   target_mark_exited (target);
827   generic_mourn_inferior ();
828   delete_thread_silent (remote_sim_ptid);
829 }
830
831 /* Pass the command argument through to the simulator verbatim.  The
832    simulator must do any command interpretation work.  */
833
834 void
835 simulator_command (char *args, int from_tty)
836 {
837   if (gdbsim_desc == NULL)
838     {
839
840       /* PREVIOUSLY: The user may give a command before the simulator
841          is opened. [...] (??? assuming of course one wishes to
842          continue to allow commands to be sent to unopened simulators,
843          which isn't entirely unreasonable). */
844
845       /* The simulator is a builtin abstraction of a remote target.
846          Consistent with that model, access to the simulator, via sim
847          commands, is restricted to the period when the channel to the
848          simulator is open. */
849
850       error (_("Not connected to the simulator target"));
851     }
852
853   sim_do_command (gdbsim_desc, args);
854
855   /* Invalidate the register cache, in case the simulator command does
856      something funny. */
857   registers_changed ();
858 }
859
860 /* Check to see if a thread is still alive.  */
861
862 static int
863 gdbsim_thread_alive (ptid_t ptid)
864 {
865   if (ptid_equal (ptid, remote_sim_ptid))
866     /* The simulators' task is always alive.  */
867     return 1;
868
869   return 0;
870 }
871
872 /* Convert a thread ID to a string.  Returns the string in a static
873    buffer.  */
874
875 static char *
876 gdbsim_pid_to_str (struct target_ops *ops, ptid_t ptid)
877 {
878   static char buf[64];
879
880   if (ptid_equal (remote_sim_ptid, ptid))
881     {
882       xsnprintf (buf, sizeof buf, "Thread <main>");
883       return buf;
884     }
885
886   return normal_pid_to_str (ptid);
887 }
888
889 /* Define the target subroutine names */
890
891 struct target_ops gdbsim_ops;
892
893 static void
894 init_gdbsim_ops (void)
895 {
896   gdbsim_ops.to_shortname = "sim";
897   gdbsim_ops.to_longname = "simulator";
898   gdbsim_ops.to_doc = "Use the compiled-in simulator.";
899   gdbsim_ops.to_open = gdbsim_open;
900   gdbsim_ops.to_close = gdbsim_close;
901   gdbsim_ops.to_detach = gdbsim_detach;
902   gdbsim_ops.to_resume = gdbsim_resume;
903   gdbsim_ops.to_wait = gdbsim_wait;
904   gdbsim_ops.to_fetch_registers = gdbsim_fetch_register;
905   gdbsim_ops.to_store_registers = gdbsim_store_register;
906   gdbsim_ops.to_prepare_to_store = gdbsim_prepare_to_store;
907   gdbsim_ops.deprecated_xfer_memory = gdbsim_xfer_inferior_memory;
908   gdbsim_ops.to_files_info = gdbsim_files_info;
909   gdbsim_ops.to_insert_breakpoint = memory_insert_breakpoint;
910   gdbsim_ops.to_remove_breakpoint = memory_remove_breakpoint;
911   gdbsim_ops.to_kill = gdbsim_kill;
912   gdbsim_ops.to_load = gdbsim_load;
913   gdbsim_ops.to_create_inferior = gdbsim_create_inferior;
914   gdbsim_ops.to_mourn_inferior = gdbsim_mourn_inferior;
915   gdbsim_ops.to_stop = gdbsim_stop;
916   gdbsim_ops.to_thread_alive = gdbsim_thread_alive;
917   gdbsim_ops.to_pid_to_str = gdbsim_pid_to_str;
918   gdbsim_ops.to_stratum = process_stratum;
919   gdbsim_ops.to_has_all_memory = 1;
920   gdbsim_ops.to_has_memory = 1;
921   gdbsim_ops.to_has_stack = 1;
922   gdbsim_ops.to_has_registers = 1;
923   gdbsim_ops.to_has_execution = 1;
924   gdbsim_ops.to_magic = OPS_MAGIC;
925 }
926
927 void
928 _initialize_remote_sim (void)
929 {
930   init_gdbsim_ops ();
931   add_target (&gdbsim_ops);
932
933   add_com ("sim", class_obscure, simulator_command,
934            _("Send a command to the simulator."));
935
936   /* Yes, 42000 is arbitrary.  The only sense out of it, is that it
937      isn't 0.  */
938   remote_sim_ptid = ptid_build (42000, 0, 42000);
939 }