Refactor svr4_create_solib_event_breakpoints
[external/binutils.git] / gdb / remote-sim.c
1 /* Generic remote debugging interface for simulators.
2
3    Copyright (C) 1993-2019 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support.
6    Steve Chamberlain (sac@cygnus.com).
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 #include "defs.h"
24 #include "gdb_bfd.h"
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "value.h"
28 #include <ctype.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <setjmp.h>
32 #include "terminal.h"
33 #include "target.h"
34 #include "process-stratum-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 "sim-regno.h"
41 #include "arch-utils.h"
42 #include "readline/readline.h"
43 #include "gdbthread.h"
44 #include "gdbsupport/byte-vector.h"
45
46 /* Prototypes */
47
48 static void init_callbacks (void);
49
50 static void end_callbacks (void);
51
52 static int gdb_os_write_stdout (host_callback *, const char *, int);
53
54 static void gdb_os_flush_stdout (host_callback *);
55
56 static int gdb_os_write_stderr (host_callback *, const char *, int);
57
58 static void gdb_os_flush_stderr (host_callback *);
59
60 static int gdb_os_poll_quit (host_callback *);
61
62 /* printf_filtered is depreciated.  */
63 static void gdb_os_printf_filtered (host_callback *, const char *, ...);
64
65 static void gdb_os_vprintf_filtered (host_callback *, const char *, va_list);
66
67 static void gdb_os_evprintf_filtered (host_callback *, const char *, va_list);
68
69 static void gdb_os_error (host_callback *, const char *, ...)
70      ATTRIBUTE_NORETURN;
71
72 void simulator_command (char *args, int from_tty);
73
74 /* Naming convention:
75
76    sim_* are the interface to the simulator (see remote-sim.h).
77    gdbsim_* are stuff which is internal to gdb.  */
78
79 static const target_info gdbsim_target_info = {
80   "sim",
81   N_("simulator"),
82   N_("Use the compiled-in simulator.")
83 };
84
85 struct gdbsim_target final
86   : public memory_breakpoint_target<process_stratum_target>
87 {
88   gdbsim_target () = default;
89
90   const target_info &info () const override
91   { return gdbsim_target_info; }
92
93   void close () override;
94
95   void detach (inferior *inf, int) override;
96
97   void resume (ptid_t, int, enum gdb_signal) override;
98   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
99
100   void fetch_registers (struct regcache *, int) override;
101   void store_registers (struct regcache *, int) override;
102   void prepare_to_store (struct regcache *) override;
103
104   enum target_xfer_status xfer_partial (enum target_object object,
105                                         const char *annex,
106                                         gdb_byte *readbuf,
107                                         const gdb_byte *writebuf,
108                                         ULONGEST offset, ULONGEST len,
109                                         ULONGEST *xfered_len) override;
110
111   void files_info () override;
112
113   void kill () override;
114
115   void load (const char *, int) override;
116
117   bool can_create_inferior () override { return true; }
118   void create_inferior (const char *, const std::string &,
119                         char **, int) override;
120
121   void mourn_inferior () override;
122
123   void interrupt () override;
124
125   bool thread_alive (ptid_t ptid) override;
126
127   std::string pid_to_str (ptid_t) override;
128
129   bool has_all_memory ()  override;
130   bool has_memory ()  override;
131 };
132
133 static struct gdbsim_target gdbsim_ops;
134
135 /* Value of the next pid to allocate for an inferior.  As indicated
136    elsewhere, its initial value is somewhat arbitrary; it's critical
137    though that it's not zero or negative.  */
138 static int next_pid;
139 #define INITIAL_PID 42000
140
141 /* Simulator-specific, per-inferior state.  */
142 struct sim_inferior_data {
143   explicit sim_inferior_data (SIM_DESC desc)
144     : gdbsim_desc (desc),
145       remote_sim_ptid (next_pid, 0, next_pid)
146   {
147     ++next_pid;
148   }
149
150   ~sim_inferior_data ();
151
152   /* Flag which indicates whether or not the program has been loaded.  */
153   int program_loaded = 0;
154
155   /* Simulator descriptor for this inferior.  */
156   SIM_DESC gdbsim_desc;
157
158   /* This is the ptid we use for this particular simulator instance.  Its
159      value is somewhat arbitrary, as the simulator target don't have a
160      notion of tasks or threads, but we need something non-null to place
161      in inferior_ptid.  For simulators which permit multiple instances,
162      we also need a unique identifier to use for each inferior.  */
163   ptid_t remote_sim_ptid;
164
165   /* Signal with which to resume.  */
166   enum gdb_signal resume_siggnal = GDB_SIGNAL_0;
167
168   /* Flag which indicates whether resume should step or not.  */
169   int resume_step = 0;
170 };
171
172 static inferior_key<sim_inferior_data> sim_inferior_data_key;
173
174 /* Flag indicating the "open" status of this module.  It's set to 1
175    in gdbsim_open() and 0 in gdbsim_close().  */
176 static int gdbsim_is_open = 0;
177
178 /* Argument list to pass to sim_open().  It is allocated in gdbsim_open()
179    and deallocated in gdbsim_close().  The lifetime needs to extend beyond
180    the call to gdbsim_open() due to the fact that other sim instances other
181    than the first will be allocated after the gdbsim_open() call.  */
182 static char **sim_argv = NULL;
183
184 /* OS-level callback functions for write, flush, etc.  */
185 static host_callback gdb_callback;
186 static int callbacks_initialized = 0;
187
188 /* Callback for iterate_over_inferiors.  It checks to see if the sim
189    descriptor passed via ARG is the same as that for the inferior
190    designated by INF.  Return true if so; false otherwise.  */
191
192 static int
193 check_for_duplicate_sim_descriptor (struct inferior *inf, void *arg)
194 {
195   struct sim_inferior_data *sim_data;
196   SIM_DESC new_sim_desc = (SIM_DESC) arg;
197
198   sim_data = sim_inferior_data_key.get (inf);
199
200   return (sim_data != NULL && sim_data->gdbsim_desc == new_sim_desc);
201 }
202
203 /* Flags indicating whether or not a sim instance is needed.  One of these
204    flags should be passed to get_sim_inferior_data().  */
205
206 enum {SIM_INSTANCE_NOT_NEEDED = 0, SIM_INSTANCE_NEEDED = 1};
207
208 /* Obtain pointer to per-inferior simulator data, allocating it if necessary.
209    Attempt to open the sim if SIM_INSTANCE_NEEDED is true.  */
210
211 static struct sim_inferior_data *
212 get_sim_inferior_data (struct inferior *inf, int sim_instance_needed)
213 {
214   SIM_DESC sim_desc = NULL;
215   struct sim_inferior_data *sim_data = sim_inferior_data_key.get (inf);
216
217   /* Try to allocate a new sim instance, if needed.  We do this ahead of
218      a potential allocation of a sim_inferior_data struct in order to
219      avoid needlessly allocating that struct in the event that the sim
220      instance allocation fails.  */
221   if (sim_instance_needed == SIM_INSTANCE_NEEDED
222       && (sim_data == NULL || sim_data->gdbsim_desc == NULL))
223     {
224       struct inferior *idup;
225       sim_desc = sim_open (SIM_OPEN_DEBUG, &gdb_callback, exec_bfd, sim_argv);
226       if (sim_desc == NULL)
227         error (_("Unable to create simulator instance for inferior %d."),
228                inf->num);
229
230       idup = iterate_over_inferiors (check_for_duplicate_sim_descriptor,
231                                      sim_desc);
232       if (idup != NULL)
233         {
234           /* We don't close the descriptor due to the fact that it's
235              shared with some other inferior.  If we were to close it,
236              that might needlessly muck up the other inferior.  Of
237              course, it's possible that the damage has already been
238              done...  Note that it *will* ultimately be closed during
239              cleanup of the other inferior.  */
240           sim_desc = NULL;
241           error (
242  _("Inferior %d and inferior %d would have identical simulator state.\n"
243    "(This simulator does not support the running of more than one inferior.)"),
244                  inf->num, idup->num);
245         }
246     }
247
248   if (sim_data == NULL)
249     {
250       sim_data = sim_inferior_data_key.emplace (inf, sim_desc);
251     }
252   else if (sim_desc)
253     {
254       /* This handles the case where sim_data was allocated prior to
255          needing a sim instance.  */
256       sim_data->gdbsim_desc = sim_desc;
257     }
258
259
260   return sim_data;
261 }
262
263 /* Return pointer to per-inferior simulator data using PTID to find the
264    inferior in question.  Return NULL when no inferior is found or
265    when ptid has a zero or negative pid component.  */
266
267 static struct sim_inferior_data *
268 get_sim_inferior_data_by_ptid (ptid_t ptid, int sim_instance_needed)
269 {
270   struct inferior *inf;
271   int pid = ptid.pid ();
272
273   if (pid <= 0)
274     return NULL;
275
276   inf = find_inferior_pid (pid);
277
278   if (inf)
279     return get_sim_inferior_data (inf, sim_instance_needed);
280   else
281     return NULL;
282 }
283
284 /* Free the per-inferior simulator data.  */
285
286 sim_inferior_data::~sim_inferior_data ()
287 {
288   if (gdbsim_desc)
289     sim_close (gdbsim_desc, 0);
290 }
291
292 static void
293 dump_mem (const gdb_byte *buf, int len)
294 {
295   fputs_unfiltered ("\t", gdb_stdlog);
296
297   if (len == 8 || len == 4)
298     {
299       uint32_t l[2];
300
301       memcpy (l, buf, len);
302       fprintf_unfiltered (gdb_stdlog, "0x%08x", l[0]);
303       if (len == 8)
304         fprintf_unfiltered (gdb_stdlog, " 0x%08x", l[1]);
305     }
306   else
307     {
308       int i;
309
310       for (i = 0; i < len; i++)
311         fprintf_unfiltered (gdb_stdlog, "0x%02x ", buf[i]);
312     }
313
314   fputs_unfiltered ("\n", gdb_stdlog);
315 }
316
317 /* Initialize gdb_callback.  */
318
319 static void
320 init_callbacks (void)
321 {
322   if (!callbacks_initialized)
323     {
324       gdb_callback = default_callback;
325       gdb_callback.init (&gdb_callback);
326       gdb_callback.write_stdout = gdb_os_write_stdout;
327       gdb_callback.flush_stdout = gdb_os_flush_stdout;
328       gdb_callback.write_stderr = gdb_os_write_stderr;
329       gdb_callback.flush_stderr = gdb_os_flush_stderr;
330       gdb_callback.printf_filtered = gdb_os_printf_filtered;
331       gdb_callback.vprintf_filtered = gdb_os_vprintf_filtered;
332       gdb_callback.evprintf_filtered = gdb_os_evprintf_filtered;
333       gdb_callback.error = gdb_os_error;
334       gdb_callback.poll_quit = gdb_os_poll_quit;
335       gdb_callback.magic = HOST_CALLBACK_MAGIC;
336       callbacks_initialized = 1;
337     }
338 }
339
340 /* Release callbacks (free resources used by them).  */
341
342 static void
343 end_callbacks (void)
344 {
345   if (callbacks_initialized)
346     {
347       gdb_callback.shutdown (&gdb_callback);
348       callbacks_initialized = 0;
349     }
350 }
351
352 /* GDB version of os_write_stdout callback.  */
353
354 static int
355 gdb_os_write_stdout (host_callback *p, const char *buf, int len)
356 {
357   ui_file_write (gdb_stdtarg, buf, len);
358   return len;
359 }
360
361 /* GDB version of os_flush_stdout callback.  */
362
363 static void
364 gdb_os_flush_stdout (host_callback *p)
365 {
366   gdb_flush (gdb_stdtarg);
367 }
368
369 /* GDB version of os_write_stderr callback.  */
370
371 static int
372 gdb_os_write_stderr (host_callback *p, const char *buf, int len)
373 {
374   int i;
375   char b[2];
376
377   for (i = 0; i < len; i++)
378     {
379       b[0] = buf[i];
380       b[1] = 0;
381       fputs_unfiltered (b, gdb_stdtargerr);
382     }
383   return len;
384 }
385
386 /* GDB version of os_flush_stderr callback.  */
387
388 static void
389 gdb_os_flush_stderr (host_callback *p)
390 {
391   gdb_flush (gdb_stdtargerr);
392 }
393
394 /* GDB version of printf_filtered callback.  */
395
396 static void ATTRIBUTE_PRINTF (2, 3)
397 gdb_os_printf_filtered (host_callback * p, const char *format, ...)
398 {
399   va_list args;
400
401   va_start (args, format);
402   vfprintf_filtered (gdb_stdout, format, args);
403   va_end (args);
404 }
405
406 /* GDB version of error vprintf_filtered.  */
407
408 static void ATTRIBUTE_PRINTF (2, 0)
409 gdb_os_vprintf_filtered (host_callback * p, const char *format, va_list ap)
410 {
411   vfprintf_filtered (gdb_stdout, format, ap);
412 }
413
414 /* GDB version of error evprintf_filtered.  */
415
416 static void ATTRIBUTE_PRINTF (2, 0)
417 gdb_os_evprintf_filtered (host_callback * p, const char *format, va_list ap)
418 {
419   vfprintf_filtered (gdb_stderr, format, ap);
420 }
421
422 /* GDB version of error callback.  */
423
424 static void ATTRIBUTE_PRINTF (2, 3)
425 gdb_os_error (host_callback * p, const char *format, ...)
426 {
427   va_list args;
428
429   va_start (args, format);
430   verror (format, args);
431   va_end (args);
432 }
433
434 int
435 one2one_register_sim_regno (struct gdbarch *gdbarch, int regnum)
436 {
437   /* Only makes sense to supply raw registers.  */
438   gdb_assert (regnum >= 0 && regnum < gdbarch_num_regs (gdbarch));
439   return regnum;
440 }
441
442 void
443 gdbsim_target::fetch_registers (struct regcache *regcache, int regno)
444 {
445   struct gdbarch *gdbarch = regcache->arch ();
446   struct inferior *inf = find_inferior_ptid (regcache->ptid ());
447   struct sim_inferior_data *sim_data
448     = get_sim_inferior_data (inf, SIM_INSTANCE_NEEDED);
449
450   if (regno == -1)
451     {
452       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
453         fetch_registers (regcache, regno);
454       return;
455     }
456
457   switch (gdbarch_register_sim_regno (gdbarch, regno))
458     {
459     case LEGACY_SIM_REGNO_IGNORE:
460       break;
461     case SIM_REGNO_DOES_NOT_EXIST:
462       {
463         /* For moment treat a `does not exist' register the same way
464            as an ``unavailable'' register.  */
465         regcache->raw_supply_zeroed (regno);
466         break;
467       }
468
469     default:
470       {
471         static int warn_user = 1;
472         int regsize = register_size (gdbarch, regno);
473         gdb::byte_vector buf (regsize, 0);
474         int nr_bytes;
475
476         gdb_assert (regno >= 0 && regno < gdbarch_num_regs (gdbarch));
477         nr_bytes = sim_fetch_register (sim_data->gdbsim_desc,
478                                        gdbarch_register_sim_regno
479                                          (gdbarch, regno),
480                                        buf.data (), regsize);
481         if (nr_bytes > 0 && nr_bytes != regsize && warn_user)
482           {
483             fprintf_unfiltered (gdb_stderr,
484                                 "Size of register %s (%d/%d) "
485                                 "incorrect (%d instead of %d))",
486                                 gdbarch_register_name (gdbarch, regno),
487                                 regno,
488                                 gdbarch_register_sim_regno (gdbarch, regno),
489                                 nr_bytes, regsize);
490             warn_user = 0;
491           }
492         /* FIXME: cagney/2002-05-27: Should check `nr_bytes == 0'
493            indicating that GDB and the SIM have different ideas about
494            which registers are fetchable.  */
495         /* Else if (nr_bytes < 0): an old simulator, that doesn't
496            think to return the register size.  Just assume all is ok.  */
497         regcache->raw_supply (regno, buf.data ());
498         if (remote_debug)
499           {
500             fprintf_unfiltered (gdb_stdlog,
501                                 "gdbsim_fetch_register: %d", regno);
502             /* FIXME: We could print something more intelligible.  */
503             dump_mem (buf.data (), regsize);
504           }
505         break;
506       }
507     }
508 }
509
510
511 void
512 gdbsim_target::store_registers (struct regcache *regcache, int regno)
513 {
514   struct gdbarch *gdbarch = regcache->arch ();
515   struct inferior *inf = find_inferior_ptid (regcache->ptid ());
516   struct sim_inferior_data *sim_data
517     = get_sim_inferior_data (inf, SIM_INSTANCE_NEEDED);
518
519   if (regno == -1)
520     {
521       for (regno = 0; regno < gdbarch_num_regs (gdbarch); regno++)
522         store_registers (regcache, regno);
523       return;
524     }
525   else if (gdbarch_register_sim_regno (gdbarch, regno) >= 0)
526     {
527       int regsize = register_size (gdbarch, regno);
528       gdb::byte_vector tmp (regsize);
529       int nr_bytes;
530
531       regcache->cooked_read (regno, tmp.data ());
532       nr_bytes = sim_store_register (sim_data->gdbsim_desc,
533                                      gdbarch_register_sim_regno
534                                        (gdbarch, regno),
535                                      tmp.data (), regsize);
536
537       if (nr_bytes > 0 && nr_bytes != regsize)
538         internal_error (__FILE__, __LINE__,
539                         _("Register size different to expected"));
540       if (nr_bytes < 0)
541         internal_error (__FILE__, __LINE__,
542                         _("Register %d not updated"), regno);
543       if (nr_bytes == 0)
544         warning (_("Register %s not updated"),
545                  gdbarch_register_name (gdbarch, regno));
546
547       if (remote_debug)
548         {
549           fprintf_unfiltered (gdb_stdlog, "gdbsim_store_register: %d", regno);
550           /* FIXME: We could print something more intelligible.  */
551           dump_mem (tmp.data (), regsize);
552         }
553     }
554 }
555
556 /* Kill the running program.  This may involve closing any open files
557    and releasing other resources acquired by the simulated program.  */
558
559 void
560 gdbsim_target::kill ()
561 {
562   if (remote_debug)
563     fprintf_unfiltered (gdb_stdlog, "gdbsim_kill\n");
564
565   /* There is no need to `kill' running simulator - the simulator is
566      not running.  Mourning it is enough.  */
567   target_mourn_inferior (inferior_ptid);
568 }
569
570 /* Load an executable file into the target process.  This is expected to
571    not only bring new code into the target process, but also to update
572    GDB's symbol tables to match.  */
573
574 void
575 gdbsim_target::load (const char *args, int fromtty)
576 {
577   const char *prog;
578   struct sim_inferior_data *sim_data
579     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NEEDED);
580
581   if (args == NULL)
582       error_no_arg (_("program to load"));
583
584   gdb_argv argv (args);
585
586   prog = tilde_expand (argv[0]);
587
588   if (argv[1] != NULL)
589     error (_("GDB sim does not yet support a load offset."));
590
591   if (remote_debug)
592     fprintf_unfiltered (gdb_stdlog, "gdbsim_load: prog \"%s\"\n", prog);
593
594   /* FIXME: We will print two messages on error.
595      Need error to either not print anything if passed NULL or need
596      another routine that doesn't take any arguments.  */
597   if (sim_load (sim_data->gdbsim_desc, prog, NULL, fromtty) == SIM_RC_FAIL)
598     error (_("unable to load program"));
599
600   /* FIXME: If a load command should reset the targets registers then
601      a call to sim_create_inferior() should go here.  */
602
603   sim_data->program_loaded = 1;
604 }
605
606
607 /* Start an inferior process and set inferior_ptid to its pid.
608    EXEC_FILE is the file to run.
609    ARGS is a string containing the arguments to the program.
610    ENV is the environment vector to pass.  Errors reported with error().
611    On VxWorks and various standalone systems, we ignore exec_file.  */
612 /* This is called not only when we first attach, but also when the
613    user types "run" after having attached.  */
614
615 void
616 gdbsim_target::create_inferior (const char *exec_file,
617                                 const std::string &allargs,
618                                 char **env, int from_tty)
619 {
620   struct sim_inferior_data *sim_data
621     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NEEDED);
622   int len;
623   char *arg_buf;
624   const char *args = allargs.c_str ();
625
626   if (exec_file == 0 || exec_bfd == 0)
627     warning (_("No executable file specified."));
628   if (!sim_data->program_loaded)
629     warning (_("No program loaded."));
630
631   if (remote_debug)
632     fprintf_unfiltered (gdb_stdlog,
633                         "gdbsim_create_inferior: exec_file \"%s\", args \"%s\"\n",
634                         (exec_file ? exec_file : "(NULL)"),
635                         args);
636
637   if (inferior_ptid == sim_data->remote_sim_ptid)
638     kill ();
639   remove_breakpoints ();
640   init_wait_for_inferior ();
641
642   gdb_argv built_argv;
643   if (exec_file != NULL)
644     {
645       len = strlen (exec_file) + 1 + allargs.size () + 1 + /*slop */ 10;
646       arg_buf = (char *) alloca (len);
647       arg_buf[0] = '\0';
648       strcat (arg_buf, exec_file);
649       strcat (arg_buf, " ");
650       strcat (arg_buf, args);
651       built_argv.reset (arg_buf);
652     }
653
654   if (sim_create_inferior (sim_data->gdbsim_desc, exec_bfd,
655                            built_argv.get (), env)
656       != SIM_RC_OK)
657     error (_("Unable to create sim inferior."));
658
659   inferior_ptid = sim_data->remote_sim_ptid;
660   inferior_appeared (current_inferior (), inferior_ptid.pid ());
661   add_thread_silent (inferior_ptid);
662
663   insert_breakpoints ();        /* Needed to get correct instruction
664                                    in cache.  */
665
666   clear_proceed_status (0);
667 }
668
669 /* The open routine takes the rest of the parameters from the command,
670    and (if successful) pushes a new target onto the stack.
671    Targets should supply this routine, if only to provide an error message.  */
672 /* Called when selecting the simulator.  E.g. (gdb) target sim name.  */
673
674 static void
675 gdbsim_target_open (const char *args, int from_tty)
676 {
677   int len;
678   char *arg_buf;
679   struct sim_inferior_data *sim_data;
680   const char *sysroot;
681   SIM_DESC gdbsim_desc;
682
683   sysroot = gdb_sysroot;
684   if (is_target_filename (sysroot))
685     sysroot += strlen (TARGET_SYSROOT_PREFIX);
686
687   if (remote_debug)
688     fprintf_unfiltered (gdb_stdlog,
689                         "gdbsim_open: args \"%s\"\n", args ? args : "(null)");
690
691   /* Ensure that the sim target is not on the target stack.  This is
692      necessary, because if it is on the target stack, the call to
693      push_target below will invoke sim_close(), thus freeing various
694      state (including a sim instance) that we allocate prior to
695      invoking push_target().  We want to delay the push_target()
696      operation until after we complete those operations which could
697      error out.  */
698   if (gdbsim_is_open)
699     unpush_target (&gdbsim_ops);
700
701   len = (7 + 1                  /* gdbsim */
702          + strlen (" -E little")
703          + strlen (" --architecture=xxxxxxxxxx")
704          + strlen (" --sysroot=") + strlen (sysroot) +
705          + (args ? strlen (args) : 0)
706          + 50) /* slack */ ;
707   arg_buf = (char *) alloca (len);
708   strcpy (arg_buf, "gdbsim");   /* 7 */
709   /* Specify the byte order for the target when it is explicitly
710      specified by the user (not auto detected).  */
711   switch (selected_byte_order ())
712     {
713     case BFD_ENDIAN_BIG:
714       strcat (arg_buf, " -E big");
715       break;
716     case BFD_ENDIAN_LITTLE:
717       strcat (arg_buf, " -E little");
718       break;
719     case BFD_ENDIAN_UNKNOWN:
720       break;
721     }
722   /* Specify the architecture of the target when it has been
723      explicitly specified */
724   if (selected_architecture_name () != NULL)
725     {
726       strcat (arg_buf, " --architecture=");
727       strcat (arg_buf, selected_architecture_name ());
728     }
729   /* Pass along gdb's concept of the sysroot.  */
730   strcat (arg_buf, " --sysroot=");
731   strcat (arg_buf, sysroot);
732   /* finally, any explicit args */
733   if (args)
734     {
735       strcat (arg_buf, " ");    /* 1 */
736       strcat (arg_buf, args);
737     }
738
739   gdb_argv argv (arg_buf);
740   sim_argv = argv.release ();
741
742   init_callbacks ();
743   gdbsim_desc = sim_open (SIM_OPEN_DEBUG, &gdb_callback, exec_bfd, sim_argv);
744
745   if (gdbsim_desc == 0)
746     {
747       freeargv (sim_argv);
748       sim_argv = NULL;
749       error (_("unable to create simulator instance"));
750     }
751
752   /* Reset the pid numberings for this batch of sim instances.  */
753   next_pid = INITIAL_PID;
754
755   /* Allocate the inferior data, but do not allocate a sim instance
756      since we've already just done that.  */
757   sim_data = get_sim_inferior_data (current_inferior (),
758                                     SIM_INSTANCE_NOT_NEEDED);
759
760   sim_data->gdbsim_desc = gdbsim_desc;
761
762   push_target (&gdbsim_ops);
763   printf_filtered ("Connected to the simulator.\n");
764
765   /* There's nothing running after "target sim" or "load"; not until
766      "run".  */
767   inferior_ptid = null_ptid;
768
769   gdbsim_is_open = 1;
770 }
771
772 /* Callback for iterate_over_inferiors.  Called (indirectly) by
773    gdbsim_close().  */
774
775 static int
776 gdbsim_close_inferior (struct inferior *inf, void *arg)
777 {
778   struct sim_inferior_data *sim_data = sim_inferior_data_key.get (inf);
779   if (sim_data != NULL)
780     {
781       ptid_t ptid = sim_data->remote_sim_ptid;
782
783       sim_inferior_data_key.clear (inf);
784
785       /* Having a ptid allocated and stored in remote_sim_ptid does
786          not mean that a corresponding inferior was ever created.
787          Thus we need to verify the existence of an inferior using the
788          pid in question before setting inferior_ptid via
789          switch_to_thread() or mourning the inferior.  */
790       if (find_inferior_ptid (ptid) != NULL)
791         {
792           switch_to_thread (ptid);
793           generic_mourn_inferior ();
794         }
795     }
796
797   return 0;
798 }
799
800 /* Close out all files and local state before this target loses control.  */
801
802 void
803 gdbsim_target::close ()
804 {
805   if (remote_debug)
806     fprintf_unfiltered (gdb_stdlog, "gdbsim_close\n");
807
808   iterate_over_inferiors (gdbsim_close_inferior, NULL);
809
810   if (sim_argv != NULL)
811     {
812       freeargv (sim_argv);
813       sim_argv = NULL;
814     }
815
816   end_callbacks ();
817
818   gdbsim_is_open = 0;
819 }
820
821 /* Takes a program previously attached to and detaches it.
822    The program may resume execution (some targets do, some don't) and will
823    no longer stop on signals, etc.  We better not have left any breakpoints
824    in the program or it'll die when it hits one.  FROM_TTY says whether to be
825    verbose or not.  */
826 /* Terminate the open connection to the remote debugger.
827    Use this when you want to detach and do something else with your gdb.  */
828
829 void
830 gdbsim_target::detach (inferior *inf, int from_tty)
831 {
832   if (remote_debug)
833     fprintf_unfiltered (gdb_stdlog, "gdbsim_detach\n");
834
835   unpush_target (this);         /* calls gdbsim_close to do the real work */
836   if (from_tty)
837     printf_filtered ("Ending simulator %s debugging\n", target_shortname);
838 }
839
840 /* Resume execution of the target process.  STEP says whether to single-step
841    or to run free; SIGGNAL is the signal value (e.g. SIGINT) to be given
842    to the target, or zero for no signal.  */
843
844 struct resume_data
845 {
846   enum gdb_signal siggnal;
847   int step;
848 };
849
850 static int
851 gdbsim_resume_inferior (struct inferior *inf, void *arg)
852 {
853   struct sim_inferior_data *sim_data
854     = get_sim_inferior_data (inf, SIM_INSTANCE_NOT_NEEDED);
855   struct resume_data *rd = (struct resume_data *) arg;
856
857   if (sim_data)
858     {
859       sim_data->resume_siggnal = rd->siggnal;
860       sim_data->resume_step = rd->step;
861
862       if (remote_debug)
863         fprintf_unfiltered (gdb_stdlog,
864                             _("gdbsim_resume: pid %d, step %d, signal %d\n"),
865                             inf->pid, rd->step, rd->siggnal);
866     }
867
868   /* When called from iterate_over_inferiors, a zero return causes the
869      iteration process to proceed until there are no more inferiors to
870      consider.  */
871   return 0;
872 }
873
874 void
875 gdbsim_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
876 {
877   struct resume_data rd;
878   struct sim_inferior_data *sim_data
879     = get_sim_inferior_data_by_ptid (ptid, SIM_INSTANCE_NOT_NEEDED);
880
881   rd.siggnal = siggnal;
882   rd.step = step;
883
884   /* We don't access any sim_data members within this function.
885      What's of interest is whether or not the call to
886      get_sim_inferior_data_by_ptid(), above, is able to obtain a
887      non-NULL pointer.  If it managed to obtain a non-NULL pointer, we
888      know we have a single inferior to consider.  If it's NULL, we
889      either have multiple inferiors to resume or an error condition.  */
890
891   if (sim_data)
892     gdbsim_resume_inferior (find_inferior_ptid (ptid), &rd);
893   else if (ptid == minus_one_ptid)
894     iterate_over_inferiors (gdbsim_resume_inferior, &rd);
895   else
896     error (_("The program is not being run."));
897 }
898
899 /* Notify the simulator of an asynchronous request to interrupt.
900
901    The simulator shall ensure that the interrupt request is eventually
902    delivered to the simulator.  If the call is made while the
903    simulator is not running then the interrupt request is processed when
904    the simulator is next resumed.
905
906    For simulators that do not support this operation, just abort.  */
907
908 static int
909 gdbsim_interrupt_inferior (struct inferior *inf, void *arg)
910 {
911   struct sim_inferior_data *sim_data
912     = get_sim_inferior_data (inf, SIM_INSTANCE_NEEDED);
913
914   if (sim_data)
915     {
916       if (!sim_stop (sim_data->gdbsim_desc))
917         {
918           quit ();
919         }
920     }
921
922   /* When called from iterate_over_inferiors, a zero return causes the
923      iteration process to proceed until there are no more inferiors to
924      consider.  */
925   return 0;
926 }
927
928 void
929 gdbsim_target::interrupt ()
930 {
931   iterate_over_inferiors (gdbsim_interrupt_inferior, NULL);
932 }
933
934 /* GDB version of os_poll_quit callback.
935    Taken from gdb/util.c - should be in a library.  */
936
937 static int
938 gdb_os_poll_quit (host_callback *p)
939 {
940   if (deprecated_ui_loop_hook != NULL)
941     deprecated_ui_loop_hook (0);
942
943   if (check_quit_flag ())       /* gdb's idea of quit */
944     return 1;
945   return 0;
946 }
947
948 /* Wait for inferior process to do something.  Return pid of child,
949    or -1 in case of error; store status through argument pointer STATUS,
950    just as `wait' would.  */
951
952 static void
953 gdbsim_cntrl_c (int signo)
954 {
955   gdbsim_ops.interrupt ();
956 }
957
958 ptid_t
959 gdbsim_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
960 {
961   struct sim_inferior_data *sim_data;
962   static sighandler_t prev_sigint;
963   int sigrc = 0;
964   enum sim_stop reason = sim_running;
965
966   /* This target isn't able to (yet) resume more than one inferior at a time.
967      When ptid is minus_one_ptid, just use the current inferior.  If we're
968      given an explicit pid, we'll try to find it and use that instead.  */
969   if (ptid == minus_one_ptid)
970     sim_data = get_sim_inferior_data (current_inferior (),
971                                       SIM_INSTANCE_NEEDED);
972   else
973     {
974       sim_data = get_sim_inferior_data_by_ptid (ptid, SIM_INSTANCE_NEEDED);
975       if (sim_data == NULL)
976         error (_("Unable to wait for pid %d.  Inferior not found."),
977                ptid.pid ());
978       inferior_ptid = ptid;
979     }
980
981   if (remote_debug)
982     fprintf_unfiltered (gdb_stdlog, "gdbsim_wait\n");
983
984 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
985   {
986     struct sigaction sa, osa;
987     sa.sa_handler = gdbsim_cntrl_c;
988     sigemptyset (&sa.sa_mask);
989     sa.sa_flags = 0;
990     sigaction (SIGINT, &sa, &osa);
991     prev_sigint = osa.sa_handler;
992   }
993 #else
994   prev_sigint = signal (SIGINT, gdbsim_cntrl_c);
995 #endif
996   sim_resume (sim_data->gdbsim_desc, sim_data->resume_step,
997               sim_data->resume_siggnal);
998
999   signal (SIGINT, prev_sigint);
1000   sim_data->resume_step = 0;
1001
1002   sim_stop_reason (sim_data->gdbsim_desc, &reason, &sigrc);
1003
1004   switch (reason)
1005     {
1006     case sim_exited:
1007       status->kind = TARGET_WAITKIND_EXITED;
1008       status->value.integer = sigrc;
1009       break;
1010     case sim_stopped:
1011       switch (sigrc)
1012         {
1013         case GDB_SIGNAL_ABRT:
1014           quit ();
1015           break;
1016         case GDB_SIGNAL_INT:
1017         case GDB_SIGNAL_TRAP:
1018         default:
1019           status->kind = TARGET_WAITKIND_STOPPED;
1020           status->value.sig = (enum gdb_signal) sigrc;
1021           break;
1022         }
1023       break;
1024     case sim_signalled:
1025       status->kind = TARGET_WAITKIND_SIGNALLED;
1026       status->value.sig = (enum gdb_signal) sigrc;
1027       break;
1028     case sim_running:
1029     case sim_polling:
1030       /* FIXME: Is this correct?  */
1031       break;
1032     }
1033
1034   return inferior_ptid;
1035 }
1036
1037 /* Get ready to modify the registers array.  On machines which store
1038    individual registers, this doesn't need to do anything.  On machines
1039    which store all the registers in one fell swoop, this makes sure
1040    that registers contains all the registers from the program being
1041    debugged.  */
1042
1043 void
1044 gdbsim_target::prepare_to_store (struct regcache *regcache)
1045 {
1046   /* Do nothing, since we can store individual regs.  */
1047 }
1048
1049 /* Helper for gdbsim_xfer_partial that handles memory transfers.
1050    Arguments are like target_xfer_partial.  */
1051
1052 static enum target_xfer_status
1053 gdbsim_xfer_memory (struct target_ops *target,
1054                     gdb_byte *readbuf, const gdb_byte *writebuf,
1055                     ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
1056 {
1057   struct sim_inferior_data *sim_data
1058     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NOT_NEEDED);
1059   int l;
1060
1061   /* If this target doesn't have memory yet, return 0 causing the
1062      request to be passed to a lower target, hopefully an exec
1063      file.  */
1064   if (!target->has_memory ())
1065     return TARGET_XFER_EOF;
1066
1067   if (!sim_data->program_loaded)
1068     error (_("No program loaded."));
1069
1070   /* Note that we obtained the sim_data pointer above using
1071      SIM_INSTANCE_NOT_NEEDED.  We do this so that we don't needlessly
1072      allocate a sim instance prior to loading a program.   If we
1073      get to this point in the code though, gdbsim_desc should be
1074      non-NULL.  (Note that a sim instance is needed in order to load
1075      the program...)  */
1076   gdb_assert (sim_data->gdbsim_desc != NULL);
1077
1078   if (remote_debug)
1079     fprintf_unfiltered (gdb_stdlog,
1080                         "gdbsim_xfer_memory: readbuf %s, writebuf %s, "
1081                         "memaddr %s, len %s\n",
1082                         host_address_to_string (readbuf),
1083                         host_address_to_string (writebuf),
1084                         paddress (target_gdbarch (), memaddr),
1085                         pulongest (len));
1086
1087   if (writebuf)
1088     {
1089       if (remote_debug && len > 0)
1090         dump_mem (writebuf, len);
1091       l = sim_write (sim_data->gdbsim_desc, memaddr, writebuf, len);
1092     }
1093   else
1094     {
1095       l = sim_read (sim_data->gdbsim_desc, memaddr, readbuf, len);
1096       if (remote_debug && len > 0)
1097         dump_mem (readbuf, len);
1098     }
1099   if (l > 0)
1100     {
1101       *xfered_len = (ULONGEST) l;
1102       return TARGET_XFER_OK;
1103     }
1104   else if (l == 0)
1105     return TARGET_XFER_EOF;
1106   else
1107     return TARGET_XFER_E_IO;
1108 }
1109
1110 /* Target to_xfer_partial implementation.  */
1111
1112 enum target_xfer_status
1113 gdbsim_target::xfer_partial (enum target_object object,
1114                              const char *annex, gdb_byte *readbuf,
1115                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
1116                              ULONGEST *xfered_len)
1117 {
1118   switch (object)
1119     {
1120     case TARGET_OBJECT_MEMORY:
1121       return gdbsim_xfer_memory (this, readbuf, writebuf, offset, len,
1122                                  xfered_len);
1123
1124     default:
1125       return TARGET_XFER_E_IO;
1126     }
1127 }
1128
1129 void
1130 gdbsim_target::files_info ()
1131 {
1132   struct sim_inferior_data *sim_data
1133     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NEEDED);
1134   const char *file = "nothing";
1135
1136   if (exec_bfd)
1137     file = bfd_get_filename (exec_bfd);
1138
1139   if (remote_debug)
1140     fprintf_unfiltered (gdb_stdlog, "gdbsim_files_info: file \"%s\"\n", file);
1141
1142   if (exec_bfd)
1143     {
1144       fprintf_unfiltered (gdb_stdlog, "\tAttached to %s running program %s\n",
1145                           target_shortname, file);
1146       sim_info (sim_data->gdbsim_desc, 0);
1147     }
1148 }
1149
1150 /* Clear the simulator's notion of what the break points are.  */
1151
1152 void
1153 gdbsim_target::mourn_inferior ()
1154 {
1155   if (remote_debug)
1156     fprintf_unfiltered (gdb_stdlog, "gdbsim_mourn_inferior:\n");
1157
1158   remove_breakpoints ();
1159   generic_mourn_inferior ();
1160 }
1161
1162 /* Pass the command argument through to the simulator verbatim.  The
1163    simulator must do any command interpretation work.  */
1164
1165 void
1166 simulator_command (const char *args, int from_tty)
1167 {
1168   struct sim_inferior_data *sim_data;
1169
1170   /* We use inferior_data() instead of get_sim_inferior_data() here in
1171      order to avoid attaching a sim_inferior_data struct to an
1172      inferior unnecessarily.  The reason we take such care here is due
1173      to the fact that this function, simulator_command(), may be called
1174      even when the sim target is not active.  If we were to use
1175      get_sim_inferior_data() here, it is possible that this call would
1176      be made either prior to gdbsim_open() or after gdbsim_close(),
1177      thus allocating memory that would not be garbage collected until
1178      the ultimate destruction of the associated inferior.  */
1179
1180   sim_data  = sim_inferior_data_key.get (current_inferior ());
1181   if (sim_data == NULL || sim_data->gdbsim_desc == NULL)
1182     {
1183
1184       /* PREVIOUSLY: The user may give a command before the simulator
1185          is opened. [...] (??? assuming of course one wishes to
1186          continue to allow commands to be sent to unopened simulators,
1187          which isn't entirely unreasonable).  */
1188
1189       /* The simulator is a builtin abstraction of a remote target.
1190          Consistent with that model, access to the simulator, via sim
1191          commands, is restricted to the period when the channel to the
1192          simulator is open.  */
1193
1194       error (_("Not connected to the simulator target"));
1195     }
1196
1197   sim_do_command (sim_data->gdbsim_desc, args);
1198
1199   /* Invalidate the register cache, in case the simulator command does
1200      something funny.  */
1201   registers_changed ();
1202 }
1203
1204 static void
1205 sim_command_completer (struct cmd_list_element *ignore,
1206                        completion_tracker &tracker,
1207                        const char *text, const char *word)
1208 {
1209   struct sim_inferior_data *sim_data;
1210
1211   sim_data = sim_inferior_data_key.get (current_inferior ());
1212   if (sim_data == NULL || sim_data->gdbsim_desc == NULL)
1213     return;
1214
1215   /* sim_complete_command returns a NULL-terminated malloc'ed array of
1216      malloc'ed strings.  */
1217   struct sim_completions_deleter
1218   {
1219     void operator() (char **ptr) const
1220     {
1221       for (size_t i = 0; ptr[i] != NULL; i++)
1222         xfree (ptr[i]);
1223       xfree (ptr);
1224     }
1225   };
1226
1227   std::unique_ptr<char *[], sim_completions_deleter> sim_completions
1228     (sim_complete_command (sim_data->gdbsim_desc, text, word));
1229   if (sim_completions == NULL)
1230     return;
1231
1232   /* Count the elements and add completions from tail to head because
1233      below we'll swap elements out of the array in case add_completion
1234      throws and the deleter deletes until it finds a NULL element.  */
1235   size_t count = 0;
1236   while (sim_completions[count] != NULL)
1237     count++;
1238
1239   for (size_t i = count; i > 0; i--)
1240     {
1241       gdb::unique_xmalloc_ptr<char> match (sim_completions[i - 1]);
1242       sim_completions[i - 1] = NULL;
1243       tracker.add_completion (std::move (match));
1244     }
1245 }
1246
1247 /* Check to see if a thread is still alive.  */
1248
1249 bool
1250 gdbsim_target::thread_alive (ptid_t ptid)
1251 {
1252   struct sim_inferior_data *sim_data
1253     = get_sim_inferior_data_by_ptid (ptid, SIM_INSTANCE_NOT_NEEDED);
1254
1255   if (sim_data == NULL)
1256     return false;
1257
1258   if (ptid == sim_data->remote_sim_ptid)
1259     /* The simulators' task is always alive.  */
1260     return true;
1261
1262   return false;
1263 }
1264
1265 /* Convert a thread ID to a string.  */
1266
1267 std::string
1268 gdbsim_target::pid_to_str (ptid_t ptid)
1269 {
1270   return normal_pid_to_str (ptid);
1271 }
1272
1273 /* Simulator memory may be accessed after the program has been loaded.  */
1274
1275 bool
1276 gdbsim_target::has_all_memory ()
1277 {
1278   struct sim_inferior_data *sim_data
1279     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NOT_NEEDED);
1280
1281   if (!sim_data->program_loaded)
1282     return false;
1283
1284   return true;
1285 }
1286
1287 bool
1288 gdbsim_target::has_memory ()
1289 {
1290   struct sim_inferior_data *sim_data
1291     = get_sim_inferior_data (current_inferior (), SIM_INSTANCE_NOT_NEEDED);
1292
1293   if (!sim_data->program_loaded)
1294     return false;
1295
1296   return true;
1297 }
1298
1299 void
1300 _initialize_remote_sim (void)
1301 {
1302   struct cmd_list_element *c;
1303
1304   add_target (gdbsim_target_info, gdbsim_target_open);
1305
1306   c = add_com ("sim", class_obscure, simulator_command,
1307                _("Send a command to the simulator."));
1308   set_cmd_completer (c, sim_command_completer);
1309 }