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