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