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