gdb/target.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Select target systems and architectures at runtime for GDB.

  2.    Copyright (C) 1990-2015 Free Software Foundation, Inc.

  3.    Contributed by Cygnus Support.

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. #include "defs.h"
  16. #include "target.h"
  17. #include "target-dcache.h"
  18. #include "gdbcmd.h"
  19. #include "symtab.h"
  20. #include "inferior.h"
  21. #include "infrun.h"
  22. #include "bfd.h"
  23. #include "symfile.h"
  24. #include "objfiles.h"
  25. #include "dcache.h"
  26. #include <signal.h>
  27. #include "regcache.h"
  28. #include "gdbcore.h"
  29. #include "target-descriptions.h"
  30. #include "gdbthread.h"
  31. #include "solib.h"
  32. #include "exec.h"
  33. #include "inline-frame.h"
  34. #include "tracepoint.h"
  35. #include "gdb/fileio.h"
  36. #include "agent.h"
  37. #include "auxv.h"
  38. #include "target-debug.h"

  39. static void target_info (char *, int);

  40. static void generic_tls_error (void) ATTRIBUTE_NORETURN;

  41. static void default_terminal_info (struct target_ops *, const char *, int);

  42. static int default_watchpoint_addr_within_range (struct target_ops *,
  43.                                                  CORE_ADDR, CORE_ADDR, int);

  44. static int default_region_ok_for_hw_watchpoint (struct target_ops *,
  45.                                                 CORE_ADDR, int);

  46. static void default_rcmd (struct target_ops *, const char *, struct ui_file *);

  47. static ptid_t default_get_ada_task_ptid (struct target_ops *self,
  48.                                          long lwp, long tid);

  49. static int default_follow_fork (struct target_ops *self, int follow_child,
  50.                                 int detach_fork);

  51. static void default_mourn_inferior (struct target_ops *self);

  52. static int default_search_memory (struct target_ops *ops,
  53.                                   CORE_ADDR start_addr,
  54.                                   ULONGEST search_space_len,
  55.                                   const gdb_byte *pattern,
  56.                                   ULONGEST pattern_len,
  57.                                   CORE_ADDR *found_addrp);

  58. static int default_verify_memory (struct target_ops *self,
  59.                                   const gdb_byte *data,
  60.                                   CORE_ADDR memaddr, ULONGEST size);

  61. static struct address_space *default_thread_address_space
  62.      (struct target_ops *self, ptid_t ptid);

  63. static void tcomplain (void) ATTRIBUTE_NORETURN;

  64. static int return_zero (struct target_ops *);

  65. static int return_zero_has_execution (struct target_ops *, ptid_t);

  66. static void target_command (char *, int);

  67. static struct target_ops *find_default_run_target (char *);

  68. static struct gdbarch *default_thread_architecture (struct target_ops *ops,
  69.                                                     ptid_t ptid);

  70. static int dummy_find_memory_regions (struct target_ops *self,
  71.                                       find_memory_region_ftype ignore1,
  72.                                       void *ignore2);

  73. static char *dummy_make_corefile_notes (struct target_ops *self,
  74.                                         bfd *ignore1, int *ignore2);

  75. static char *default_pid_to_str (struct target_ops *ops, ptid_t ptid);

  76. static enum exec_direction_kind default_execution_direction
  77.     (struct target_ops *self);

  78. static CORE_ADDR default_target_decr_pc_after_break (struct target_ops *ops,
  79.                                                      struct gdbarch *gdbarch);

  80. static struct target_ops debug_target;

  81. #include "target-delegates.c"

  82. static void init_dummy_target (void);

  83. static void update_current_target (void);

  84. /* Vector of existing target structures. */
  85. typedef struct target_ops *target_ops_p;
  86. DEF_VEC_P (target_ops_p);
  87. static VEC (target_ops_p) *target_structs;

  88. /* The initial current target, so that there is always a semi-valid
  89.    current target.  */

  90. static struct target_ops dummy_target;

  91. /* Top of target stack.  */

  92. static struct target_ops *target_stack;

  93. /* The target structure we are currently using to talk to a process
  94.    or file or whatever "inferior" we have.  */

  95. struct target_ops current_target;

  96. /* Command list for target.  */

  97. static struct cmd_list_element *targetlist = NULL;

  98. /* Nonzero if we should trust readonly sections from the
  99.    executable when reading memory.  */

  100. static int trust_readonly = 0;

  101. /* Nonzero if we should show true memory content including
  102.    memory breakpoint inserted by gdb.  */

  103. static int show_memory_breakpoints = 0;

  104. /* These globals control whether GDB attempts to perform these
  105.    operations; they are useful for targets that need to prevent
  106.    inadvertant disruption, such as in non-stop mode.  */

  107. int may_write_registers = 1;

  108. int may_write_memory = 1;

  109. int may_insert_breakpoints = 1;

  110. int may_insert_tracepoints = 1;

  111. int may_insert_fast_tracepoints = 1;

  112. int may_stop = 1;

  113. /* Non-zero if we want to see trace of target level stuff.  */

  114. static unsigned int targetdebug = 0;

  115. static void
  116. set_targetdebug  (char *args, int from_tty, struct cmd_list_element *c)
  117. {
  118.   update_current_target ();
  119. }

  120. static void
  121. show_targetdebug (struct ui_file *file, int from_tty,
  122.                   struct cmd_list_element *c, const char *value)
  123. {
  124.   fprintf_filtered (file, _("Target debugging is %s.\n"), value);
  125. }

  126. static void setup_target_debug (void);

  127. /* The user just typed 'target' without the name of a target.  */

  128. static void
  129. target_command (char *arg, int from_tty)
  130. {
  131.   fputs_filtered ("Argument required (target name).  Try `help target'\n",
  132.                   gdb_stdout);
  133. }

  134. /* Default target_has_* methods for process_stratum targets.  */

  135. int
  136. default_child_has_all_memory (struct target_ops *ops)
  137. {
  138.   /* If no inferior selected, then we can't read memory here.  */
  139.   if (ptid_equal (inferior_ptid, null_ptid))
  140.     return 0;

  141.   return 1;
  142. }

  143. int
  144. default_child_has_memory (struct target_ops *ops)
  145. {
  146.   /* If no inferior selected, then we can't read memory here.  */
  147.   if (ptid_equal (inferior_ptid, null_ptid))
  148.     return 0;

  149.   return 1;
  150. }

  151. int
  152. default_child_has_stack (struct target_ops *ops)
  153. {
  154.   /* If no inferior selected, there's no stack.  */
  155.   if (ptid_equal (inferior_ptid, null_ptid))
  156.     return 0;

  157.   return 1;
  158. }

  159. int
  160. default_child_has_registers (struct target_ops *ops)
  161. {
  162.   /* Can't read registers from no inferior.  */
  163.   if (ptid_equal (inferior_ptid, null_ptid))
  164.     return 0;

  165.   return 1;
  166. }

  167. int
  168. default_child_has_execution (struct target_ops *ops, ptid_t the_ptid)
  169. {
  170.   /* If there's no thread selected, then we can't make it run through
  171.      hoops.  */
  172.   if (ptid_equal (the_ptid, null_ptid))
  173.     return 0;

  174.   return 1;
  175. }


  176. int
  177. target_has_all_memory_1 (void)
  178. {
  179.   struct target_ops *t;

  180.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  181.     if (t->to_has_all_memory (t))
  182.       return 1;

  183.   return 0;
  184. }

  185. int
  186. target_has_memory_1 (void)
  187. {
  188.   struct target_ops *t;

  189.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  190.     if (t->to_has_memory (t))
  191.       return 1;

  192.   return 0;
  193. }

  194. int
  195. target_has_stack_1 (void)
  196. {
  197.   struct target_ops *t;

  198.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  199.     if (t->to_has_stack (t))
  200.       return 1;

  201.   return 0;
  202. }

  203. int
  204. target_has_registers_1 (void)
  205. {
  206.   struct target_ops *t;

  207.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  208.     if (t->to_has_registers (t))
  209.       return 1;

  210.   return 0;
  211. }

  212. int
  213. target_has_execution_1 (ptid_t the_ptid)
  214. {
  215.   struct target_ops *t;

  216.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  217.     if (t->to_has_execution (t, the_ptid))
  218.       return 1;

  219.   return 0;
  220. }

  221. int
  222. target_has_execution_current (void)
  223. {
  224.   return target_has_execution_1 (inferior_ptid);
  225. }

  226. /* Complete initialization of T.  This ensures that various fields in
  227.    T are set, if needed by the target implementation.  */

  228. void
  229. complete_target_initialization (struct target_ops *t)
  230. {
  231.   /* Provide default values for all "must have" methods.  */

  232.   if (t->to_has_all_memory == NULL)
  233.     t->to_has_all_memory = return_zero;

  234.   if (t->to_has_memory == NULL)
  235.     t->to_has_memory = return_zero;

  236.   if (t->to_has_stack == NULL)
  237.     t->to_has_stack = return_zero;

  238.   if (t->to_has_registers == NULL)
  239.     t->to_has_registers = return_zero;

  240.   if (t->to_has_execution == NULL)
  241.     t->to_has_execution = return_zero_has_execution;

  242.   /* These methods can be called on an unpushed target and so require
  243.      a default implementation if the target might plausibly be the
  244.      default run target.  */
  245.   gdb_assert (t->to_can_run == NULL || (t->to_can_async_p != NULL
  246.                                         && t->to_supports_non_stop != NULL));

  247.   install_delegators (t);
  248. }

  249. /* This is used to implement the various target commands.  */

  250. static void
  251. open_target (char *args, int from_tty, struct cmd_list_element *command)
  252. {
  253.   struct target_ops *ops = get_cmd_context (command);

  254.   if (targetdebug)
  255.     fprintf_unfiltered (gdb_stdlog, "-> %s->to_open (...)\n",
  256.                         ops->to_shortname);

  257.   ops->to_open (args, from_tty);

  258.   if (targetdebug)
  259.     fprintf_unfiltered (gdb_stdlog, "<- %s->to_open (%s, %d)\n",
  260.                         ops->to_shortname, args, from_tty);
  261. }

  262. /* Add possible target architecture T to the list and add a new
  263.    command 'target T->to_shortname'.  Set COMPLETER as the command's
  264.    completer if not NULL.  */

  265. void
  266. add_target_with_completer (struct target_ops *t,
  267.                            completer_ftype *completer)
  268. {
  269.   struct cmd_list_element *c;

  270.   complete_target_initialization (t);

  271.   VEC_safe_push (target_ops_p, target_structs, t);

  272.   if (targetlist == NULL)
  273.     add_prefix_cmd ("target", class_run, target_command, _("\
  274. Connect to a target machine or process.\n\
  275. The first argument is the type or protocol of the target machine.\n\
  276. Remaining arguments are interpreted by the target protocol.  For more\n\
  277. information on the arguments for a particular protocol, type\n\
  278. `help target ' followed by the protocol name."),
  279.                     &targetlist, "target ", 0, &cmdlist);
  280.   c = add_cmd (t->to_shortname, no_class, NULL, t->to_doc, &targetlist);
  281.   set_cmd_sfunc (c, open_target);
  282.   set_cmd_context (c, t);
  283.   if (completer != NULL)
  284.     set_cmd_completer (c, completer);
  285. }

  286. /* Add a possible target architecture to the list.  */

  287. void
  288. add_target (struct target_ops *t)
  289. {
  290.   add_target_with_completer (t, NULL);
  291. }

  292. /* See target.h.  */

  293. void
  294. add_deprecated_target_alias (struct target_ops *t, char *alias)
  295. {
  296.   struct cmd_list_element *c;
  297.   char *alt;

  298.   /* If we use add_alias_cmd, here, we do not get the deprecated warning,
  299.      see PR cli/15104.  */
  300.   c = add_cmd (alias, no_class, NULL, t->to_doc, &targetlist);
  301.   set_cmd_sfunc (c, open_target);
  302.   set_cmd_context (c, t);
  303.   alt = xstrprintf ("target %s", t->to_shortname);
  304.   deprecate_cmd (c, alt);
  305. }

  306. /* Stub functions */

  307. void
  308. target_kill (void)
  309. {
  310.   current_target.to_kill (&current_target);
  311. }

  312. void
  313. target_load (const char *arg, int from_tty)
  314. {
  315.   target_dcache_invalidate ();
  316.   (*current_target.to_load) (&current_target, arg, from_tty);
  317. }

  318. /* Possible terminal states.  */

  319. enum terminal_state
  320.   {
  321.     /* The inferior's terminal settings are in effect.  */
  322.     terminal_is_inferior = 0,

  323.     /* Some of our terminal settings are in effect, enough to get
  324.        proper output.  */
  325.     terminal_is_ours_for_output = 1,

  326.     /* Our terminal settings are in effect, for output and input.  */
  327.     terminal_is_ours = 2
  328.   };

  329. static enum terminal_state terminal_state;

  330. /* See target.h.  */

  331. void
  332. target_terminal_init (void)
  333. {
  334.   (*current_target.to_terminal_init) (&current_target);

  335.   terminal_state = terminal_is_ours;
  336. }

  337. /* See target.h.  */

  338. int
  339. target_terminal_is_inferior (void)
  340. {
  341.   return (terminal_state == terminal_is_inferior);
  342. }

  343. /* See target.h.  */

  344. void
  345. target_terminal_inferior (void)
  346. {
  347.   /* A background resume (``run&'') should leave GDB in control of the
  348.      terminal.  Use target_can_async_p, not target_is_async_p, since at
  349.      this point the target is not async yet.  However, if sync_execution
  350.      is not set, we know it will become async prior to resume.  */
  351.   if (target_can_async_p () && !sync_execution)
  352.     return;

  353.   if (terminal_state == terminal_is_inferior)
  354.     return;

  355.   /* If GDB is resuming the inferior in the foreground, install
  356.      inferior's terminal modes.  */
  357.   (*current_target.to_terminal_inferior) (&current_target);
  358.   terminal_state = terminal_is_inferior;
  359. }

  360. /* See target.h.  */

  361. void
  362. target_terminal_ours (void)
  363. {
  364.   if (terminal_state == terminal_is_ours)
  365.     return;

  366.   (*current_target.to_terminal_ours) (&current_target);
  367.   terminal_state = terminal_is_ours;
  368. }

  369. /* See target.h.  */

  370. void
  371. target_terminal_ours_for_output (void)
  372. {
  373.   if (terminal_state != terminal_is_inferior)
  374.     return;
  375.   (*current_target.to_terminal_ours_for_output) (&current_target);
  376.   terminal_state = terminal_is_ours_for_output;
  377. }

  378. /* See target.h.  */

  379. int
  380. target_supports_terminal_ours (void)
  381. {
  382.   struct target_ops *t;

  383.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  384.     {
  385.       if (t->to_terminal_ours != delegate_terminal_ours
  386.           && t->to_terminal_ours != tdefault_terminal_ours)
  387.         return 1;
  388.     }

  389.   return 0;
  390. }

  391. /* Restore the terminal to its previous state (helper for
  392.    make_cleanup_restore_target_terminal). */

  393. static void
  394. cleanup_restore_target_terminal (void *arg)
  395. {
  396.   enum terminal_state *previous_state = arg;

  397.   switch (*previous_state)
  398.     {
  399.     case terminal_is_ours:
  400.       target_terminal_ours ();
  401.       break;
  402.     case terminal_is_ours_for_output:
  403.       target_terminal_ours_for_output ();
  404.       break;
  405.     case terminal_is_inferior:
  406.       target_terminal_inferior ();
  407.       break;
  408.     }
  409. }

  410. /* See target.h. */

  411. struct cleanup *
  412. make_cleanup_restore_target_terminal (void)
  413. {
  414.   enum terminal_state *ts = xmalloc (sizeof (*ts));

  415.   *ts = terminal_state;

  416.   return make_cleanup_dtor (cleanup_restore_target_terminal, ts, xfree);
  417. }

  418. static void
  419. tcomplain (void)
  420. {
  421.   error (_("You can't do that when your target is `%s'"),
  422.          current_target.to_shortname);
  423. }

  424. void
  425. noprocess (void)
  426. {
  427.   error (_("You can't do that without a process to debug."));
  428. }

  429. static void
  430. default_terminal_info (struct target_ops *self, const char *args, int from_tty)
  431. {
  432.   printf_unfiltered (_("No saved terminal information.\n"));
  433. }

  434. /* A default implementation for the to_get_ada_task_ptid target method.

  435.    This function builds the PTID by using both LWP and TID as part of
  436.    the PTID lwp and tid elements.  The pid used is the pid of the
  437.    inferior_ptid.  */

  438. static ptid_t
  439. default_get_ada_task_ptid (struct target_ops *self, long lwp, long tid)
  440. {
  441.   return ptid_build (ptid_get_pid (inferior_ptid), lwp, tid);
  442. }

  443. static enum exec_direction_kind
  444. default_execution_direction (struct target_ops *self)
  445. {
  446.   if (!target_can_execute_reverse)
  447.     return EXEC_FORWARD;
  448.   else if (!target_can_async_p ())
  449.     return EXEC_FORWARD;
  450.   else
  451.     gdb_assert_not_reached ("\
  452. to_execution_direction must be implemented for reverse async");
  453. }

  454. /* Go through the target stack from top to bottom, copying over zero
  455.    entries in current_target, then filling in still empty entries.  In
  456.    effect, we are doing class inheritance through the pushed target
  457.    vectors.

  458.    NOTE: cagney/2003-10-17: The problem with this inheritance, as it
  459.    is currently implemented, is that it discards any knowledge of
  460.    which target an inherited method originally belonged to.
  461.    Consequently, new new target methods should instead explicitly and
  462.    locally search the target stack for the target that can handle the
  463.    request.  */

  464. static void
  465. update_current_target (void)
  466. {
  467.   struct target_ops *t;

  468.   /* First, reset current's contents.  */
  469.   memset (&current_target, 0, sizeof (current_target));

  470.   /* Install the delegators.  */
  471.   install_delegators (&current_target);

  472.   current_target.to_stratum = target_stack->to_stratum;

  473. #define INHERIT(FIELD, TARGET) \
  474.       if (!current_target.FIELD) \
  475.         current_target.FIELD = (TARGET)->FIELD

  476.   /* Do not add any new INHERITs here.  Instead, use the delegation
  477.      mechanism provided by make-target-delegates.  */
  478.   for (t = target_stack; t; t = t->beneath)
  479.     {
  480.       INHERIT (to_shortname, t);
  481.       INHERIT (to_longname, t);
  482.       INHERIT (to_attach_no_wait, t);
  483.       INHERIT (to_have_steppable_watchpoint, t);
  484.       INHERIT (to_have_continuable_watchpoint, t);
  485.       INHERIT (to_has_thread_control, t);
  486.     }
  487. #undef INHERIT

  488.   /* Finally, position the target-stack beneath the squashed
  489.      "current_target".  That way code looking for a non-inherited
  490.      target method can quickly and simply find it.  */
  491.   current_target.beneath = target_stack;

  492.   if (targetdebug)
  493.     setup_target_debug ();
  494. }

  495. /* Push a new target type into the stack of the existing target accessors,
  496.    possibly superseding some of the existing accessors.

  497.    Rather than allow an empty stack, we always have the dummy target at
  498.    the bottom stratum, so we can call the function vectors without
  499.    checking them.  */

  500. void
  501. push_target (struct target_ops *t)
  502. {
  503.   struct target_ops **cur;

  504.   /* Check magic number.  If wrong, it probably means someone changed
  505.      the struct definition, but not all the places that initialize one.  */
  506.   if (t->to_magic != OPS_MAGIC)
  507.     {
  508.       fprintf_unfiltered (gdb_stderr,
  509.                           "Magic number of %s target struct wrong\n",
  510.                           t->to_shortname);
  511.       internal_error (__FILE__, __LINE__,
  512.                       _("failed internal consistency check"));
  513.     }

  514.   /* Find the proper stratum to install this target in.  */
  515.   for (cur = &target_stack; (*cur) != NULL; cur = &(*cur)->beneath)
  516.     {
  517.       if ((int) (t->to_stratum) >= (int) (*cur)->to_stratum)
  518.         break;
  519.     }

  520.   /* If there's already targets at this stratum, remove them.  */
  521.   /* FIXME: cagney/2003-10-15: I think this should be popping all
  522.      targets to CUR, and not just those at this stratum level.  */
  523.   while ((*cur) != NULL && t->to_stratum == (*cur)->to_stratum)
  524.     {
  525.       /* There's already something at this stratum level.  Close it,
  526.          and un-hook it from the stack.  */
  527.       struct target_ops *tmp = (*cur);

  528.       (*cur) = (*cur)->beneath;
  529.       tmp->beneath = NULL;
  530.       target_close (tmp);
  531.     }

  532.   /* We have removed all targets in our stratum, now add the new one.  */
  533.   t->beneath = (*cur);
  534.   (*cur) = t;

  535.   update_current_target ();
  536. }

  537. /* Remove a target_ops vector from the stack, wherever it may be.
  538.    Return how many times it was removed (0 or 1).  */

  539. int
  540. unpush_target (struct target_ops *t)
  541. {
  542.   struct target_ops **cur;
  543.   struct target_ops *tmp;

  544.   if (t->to_stratum == dummy_stratum)
  545.     internal_error (__FILE__, __LINE__,
  546.                     _("Attempt to unpush the dummy target"));

  547.   /* Look for the specified target.  Note that we assume that a target
  548.      can only occur once in the target stack.  */

  549.   for (cur = &target_stack; (*cur) != NULL; cur = &(*cur)->beneath)
  550.     {
  551.       if ((*cur) == t)
  552.         break;
  553.     }

  554.   /* If we don't find target_ops, quit.  Only open targets should be
  555.      closed.  */
  556.   if ((*cur) == NULL)
  557.     return 0;

  558.   /* Unchain the target.  */
  559.   tmp = (*cur);
  560.   (*cur) = (*cur)->beneath;
  561.   tmp->beneath = NULL;

  562.   update_current_target ();

  563.   /* Finally close the target.  Note we do this after unchaining, so
  564.      any target method calls from within the target_close
  565.      implementation don't end up in T anymore.  */
  566.   target_close (t);

  567.   return 1;
  568. }

  569. void
  570. pop_all_targets_above (enum strata above_stratum)
  571. {
  572.   while ((int) (current_target.to_stratum) > (int) above_stratum)
  573.     {
  574.       if (!unpush_target (target_stack))
  575.         {
  576.           fprintf_unfiltered (gdb_stderr,
  577.                               "pop_all_targets couldn't find target %s\n",
  578.                               target_stack->to_shortname);
  579.           internal_error (__FILE__, __LINE__,
  580.                           _("failed internal consistency check"));
  581.           break;
  582.         }
  583.     }
  584. }

  585. void
  586. pop_all_targets (void)
  587. {
  588.   pop_all_targets_above (dummy_stratum);
  589. }

  590. /* Return 1 if T is now pushed in the target stack.  Return 0 otherwise.  */

  591. int
  592. target_is_pushed (struct target_ops *t)
  593. {
  594.   struct target_ops *cur;

  595.   /* Check magic number.  If wrong, it probably means someone changed
  596.      the struct definition, but not all the places that initialize one.  */
  597.   if (t->to_magic != OPS_MAGIC)
  598.     {
  599.       fprintf_unfiltered (gdb_stderr,
  600.                           "Magic number of %s target struct wrong\n",
  601.                           t->to_shortname);
  602.       internal_error (__FILE__, __LINE__,
  603.                       _("failed internal consistency check"));
  604.     }

  605.   for (cur = target_stack; cur != NULL; cur = cur->beneath)
  606.     if (cur == t)
  607.       return 1;

  608.   return 0;
  609. }

  610. /* Default implementation of to_get_thread_local_address.  */

  611. static void
  612. generic_tls_error (void)
  613. {
  614.   throw_error (TLS_GENERIC_ERROR,
  615.                _("Cannot find thread-local variables on this target"));
  616. }

  617. /* Using the objfile specified in OBJFILE, find the address for the
  618.    current thread's thread-local storage with offset OFFSET.  */
  619. CORE_ADDR
  620. target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset)
  621. {
  622.   volatile CORE_ADDR addr = 0;
  623.   struct target_ops *target = &current_target;

  624.   if (gdbarch_fetch_tls_load_module_address_p (target_gdbarch ()))
  625.     {
  626.       ptid_t ptid = inferior_ptid;
  627.       volatile struct gdb_exception ex;

  628.       TRY_CATCH (ex, RETURN_MASK_ALL)
  629.         {
  630.           CORE_ADDR lm_addr;

  631.           /* Fetch the load module address for this objfile.  */
  632.           lm_addr = gdbarch_fetch_tls_load_module_address (target_gdbarch (),
  633.                                                            objfile);

  634.           addr = target->to_get_thread_local_address (target, ptid,
  635.                                                       lm_addr, offset);
  636.         }
  637.       /* If an error occurred, print TLS related messages here.  Otherwise,
  638.          throw the error to some higher catcher.  */
  639.       if (ex.reason < 0)
  640.         {
  641.           int objfile_is_library = (objfile->flags & OBJF_SHARED);

  642.           switch (ex.error)
  643.             {
  644.             case TLS_NO_LIBRARY_SUPPORT_ERROR:
  645.               error (_("Cannot find thread-local variables "
  646.                        "in this thread library."));
  647.               break;
  648.             case TLS_LOAD_MODULE_NOT_FOUND_ERROR:
  649.               if (objfile_is_library)
  650.                 error (_("Cannot find shared library `%s' in dynamic"
  651.                          " linker's load module list"), objfile_name (objfile));
  652.               else
  653.                 error (_("Cannot find executable file `%s' in dynamic"
  654.                          " linker's load module list"), objfile_name (objfile));
  655.               break;
  656.             case TLS_NOT_ALLOCATED_YET_ERROR:
  657.               if (objfile_is_library)
  658.                 error (_("The inferior has not yet allocated storage for"
  659.                          " thread-local variables in\n"
  660.                          "the shared library `%s'\n"
  661.                          "for %s"),
  662.                        objfile_name (objfile), target_pid_to_str (ptid));
  663.               else
  664.                 error (_("The inferior has not yet allocated storage for"
  665.                          " thread-local variables in\n"
  666.                          "the executable `%s'\n"
  667.                          "for %s"),
  668.                        objfile_name (objfile), target_pid_to_str (ptid));
  669.               break;
  670.             case TLS_GENERIC_ERROR:
  671.               if (objfile_is_library)
  672.                 error (_("Cannot find thread-local storage for %s, "
  673.                          "shared library %s:\n%s"),
  674.                        target_pid_to_str (ptid),
  675.                        objfile_name (objfile), ex.message);
  676.               else
  677.                 error (_("Cannot find thread-local storage for %s, "
  678.                          "executable file %s:\n%s"),
  679.                        target_pid_to_str (ptid),
  680.                        objfile_name (objfile), ex.message);
  681.               break;
  682.             default:
  683.               throw_exception (ex);
  684.               break;
  685.             }
  686.         }
  687.     }
  688.   /* It wouldn't be wrong here to try a gdbarch method, too; finding
  689.      TLS is an ABI-specific thing.  But we don't do that yet.  */
  690.   else
  691.     error (_("Cannot find thread-local variables on this target"));

  692.   return addr;
  693. }

  694. const char *
  695. target_xfer_status_to_string (enum target_xfer_status status)
  696. {
  697. #define CASE(X) case X: return #X
  698.   switch (status)
  699.     {
  700.       CASE(TARGET_XFER_E_IO);
  701.       CASE(TARGET_XFER_UNAVAILABLE);
  702.     default:
  703.       return "<unknown>";
  704.     }
  705. #undef CASE
  706. };


  707. #undef        MIN
  708. #define MIN(A, B) (((A) <= (B)) ? (A) : (B))

  709. /* target_read_string -- read a null terminated string, up to LEN bytes,
  710.    from MEMADDR in target.  Set *ERRNOP to the errno code, or 0 if successful.
  711.    Set *STRING to a pointer to malloc'd memory containing the data; the caller
  712.    is responsible for freeing it.  Return the number of bytes successfully
  713.    read.  */

  714. int
  715. target_read_string (CORE_ADDR memaddr, char **string, int len, int *errnop)
  716. {
  717.   int tlen, offset, i;
  718.   gdb_byte buf[4];
  719.   int errcode = 0;
  720.   char *buffer;
  721.   int buffer_allocated;
  722.   char *bufptr;
  723.   unsigned int nbytes_read = 0;

  724.   gdb_assert (string);

  725.   /* Small for testing.  */
  726.   buffer_allocated = 4;
  727.   buffer = xmalloc (buffer_allocated);
  728.   bufptr = buffer;

  729.   while (len > 0)
  730.     {
  731.       tlen = MIN (len, 4 - (memaddr & 3));
  732.       offset = memaddr & 3;

  733.       errcode = target_read_memory (memaddr & ~3, buf, sizeof buf);
  734.       if (errcode != 0)
  735.         {
  736.           /* The transfer request might have crossed the boundary to an
  737.              unallocated region of memory.  Retry the transfer, requesting
  738.              a single byte.  */
  739.           tlen = 1;
  740.           offset = 0;
  741.           errcode = target_read_memory (memaddr, buf, 1);
  742.           if (errcode != 0)
  743.             goto done;
  744.         }

  745.       if (bufptr - buffer + tlen > buffer_allocated)
  746.         {
  747.           unsigned int bytes;

  748.           bytes = bufptr - buffer;
  749.           buffer_allocated *= 2;
  750.           buffer = xrealloc (buffer, buffer_allocated);
  751.           bufptr = buffer + bytes;
  752.         }

  753.       for (i = 0; i < tlen; i++)
  754.         {
  755.           *bufptr++ = buf[i + offset];
  756.           if (buf[i + offset] == '\000')
  757.             {
  758.               nbytes_read += i + 1;
  759.               goto done;
  760.             }
  761.         }

  762.       memaddr += tlen;
  763.       len -= tlen;
  764.       nbytes_read += tlen;
  765.     }
  766. done:
  767.   *string = buffer;
  768.   if (errnop != NULL)
  769.     *errnop = errcode;
  770.   return nbytes_read;
  771. }

  772. struct target_section_table *
  773. target_get_section_table (struct target_ops *target)
  774. {
  775.   return (*target->to_get_section_table) (target);
  776. }

  777. /* Find a section containing ADDR.  */

  778. struct target_section *
  779. target_section_by_addr (struct target_ops *target, CORE_ADDR addr)
  780. {
  781.   struct target_section_table *table = target_get_section_table (target);
  782.   struct target_section *secp;

  783.   if (table == NULL)
  784.     return NULL;

  785.   for (secp = table->sections; secp < table->sections_end; secp++)
  786.     {
  787.       if (addr >= secp->addr && addr < secp->endaddr)
  788.         return secp;
  789.     }
  790.   return NULL;
  791. }


  792. /* Helper for the memory xfer routines.  Checks the attributes of the
  793.    memory region of MEMADDR against the read or write being attempted.
  794.    If the access is permitted returns true, otherwise returns false.
  795.    REGION_P is an optional output parameter.  If not-NULL, it is
  796.    filled with a pointer to the memory region of MEMADDR.  REG_LEN
  797.    returns LEN trimmed to the end of the region.  This is how much the
  798.    caller can continue requesting, if the access is permitted.  A
  799.    single xfer request must not straddle memory region boundaries.  */

  800. static int
  801. memory_xfer_check_region (gdb_byte *readbuf, const gdb_byte *writebuf,
  802.                           ULONGEST memaddr, ULONGEST len, ULONGEST *reg_len,
  803.                           struct mem_region **region_p)
  804. {
  805.   struct mem_region *region;

  806.   region = lookup_mem_region (memaddr);

  807.   if (region_p != NULL)
  808.     *region_p = region;

  809.   switch (region->attrib.mode)
  810.     {
  811.     case MEM_RO:
  812.       if (writebuf != NULL)
  813.         return 0;
  814.       break;

  815.     case MEM_WO:
  816.       if (readbuf != NULL)
  817.         return 0;
  818.       break;

  819.     case MEM_FLASH:
  820.       /* We only support writing to flash during "load" for now.  */
  821.       if (writebuf != NULL)
  822.         error (_("Writing to flash memory forbidden in this context"));
  823.       break;

  824.     case MEM_NONE:
  825.       return 0;
  826.     }

  827.   /* region->hi == 0 means there's no upper bound.  */
  828.   if (memaddr + len < region->hi || region->hi == 0)
  829.     *reg_len = len;
  830.   else
  831.     *reg_len = region->hi - memaddr;

  832.   return 1;
  833. }

  834. /* Read memory from more than one valid target.  A core file, for
  835.    instance, could have some of memory but delegate other bits to
  836.    the target below it.  So, we must manually try all targets.  */

  837. static enum target_xfer_status
  838. raw_memory_xfer_partial (struct target_ops *ops, gdb_byte *readbuf,
  839.                          const gdb_byte *writebuf, ULONGEST memaddr, LONGEST len,
  840.                          ULONGEST *xfered_len)
  841. {
  842.   enum target_xfer_status res;

  843.   do
  844.     {
  845.       res = ops->to_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
  846.                                   readbuf, writebuf, memaddr, len,
  847.                                   xfered_len);
  848.       if (res == TARGET_XFER_OK)
  849.         break;

  850.       /* Stop if the target reports that the memory is not available.  */
  851.       if (res == TARGET_XFER_UNAVAILABLE)
  852.         break;

  853.       /* We want to continue past core files to executables, but not
  854.          past a running target's memory.  */
  855.       if (ops->to_has_all_memory (ops))
  856.         break;

  857.       ops = ops->beneath;
  858.     }
  859.   while (ops != NULL);

  860.   /* The cache works at the raw memory level.  Make sure the cache
  861.      gets updated with raw contents no matter what kind of memory
  862.      object was originally being written.  Note we do write-through
  863.      first, so that if it fails, we don't write to the cache contents
  864.      that never made it to the target.  */
  865.   if (writebuf != NULL
  866.       && !ptid_equal (inferior_ptid, null_ptid)
  867.       && target_dcache_init_p ()
  868.       && (stack_cache_enabled_p () || code_cache_enabled_p ()))
  869.     {
  870.       DCACHE *dcache = target_dcache_get ();

  871.       /* Note that writing to an area of memory which wasn't present
  872.          in the cache doesn't cause it to be loaded in.  */
  873.       dcache_update (dcache, res, memaddr, writebuf, *xfered_len);
  874.     }

  875.   return res;
  876. }

  877. /* Perform a partial memory transfer.
  878.    For docs see target.h, to_xfer_partial.  */

  879. static enum target_xfer_status
  880. memory_xfer_partial_1 (struct target_ops *ops, enum target_object object,
  881.                        gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST memaddr,
  882.                        ULONGEST len, ULONGEST *xfered_len)
  883. {
  884.   enum target_xfer_status res;
  885.   ULONGEST reg_len;
  886.   struct mem_region *region;
  887.   struct inferior *inf;

  888.   /* For accesses to unmapped overlay sections, read directly from
  889.      files.  Must do this first, as MEMADDR may need adjustment.  */
  890.   if (readbuf != NULL && overlay_debugging)
  891.     {
  892.       struct obj_section *section = find_pc_overlay (memaddr);

  893.       if (pc_in_unmapped_range (memaddr, section))
  894.         {
  895.           struct target_section_table *table
  896.             = target_get_section_table (ops);
  897.           const char *section_name = section->the_bfd_section->name;

  898.           memaddr = overlay_mapped_address (memaddr, section);
  899.           return section_table_xfer_memory_partial (readbuf, writebuf,
  900.                                                     memaddr, len, xfered_len,
  901.                                                     table->sections,
  902.                                                     table->sections_end,
  903.                                                     section_name);
  904.         }
  905.     }

  906.   /* Try the executable files, if "trust-readonly-sections" is set.  */
  907.   if (readbuf != NULL && trust_readonly)
  908.     {
  909.       struct target_section *secp;
  910.       struct target_section_table *table;

  911.       secp = target_section_by_addr (ops, memaddr);
  912.       if (secp != NULL
  913.           && (bfd_get_section_flags (secp->the_bfd_section->owner,
  914.                                      secp->the_bfd_section)
  915.               & SEC_READONLY))
  916.         {
  917.           table = target_get_section_table (ops);
  918.           return section_table_xfer_memory_partial (readbuf, writebuf,
  919.                                                     memaddr, len, xfered_len,
  920.                                                     table->sections,
  921.                                                     table->sections_end,
  922.                                                     NULL);
  923.         }
  924.     }

  925.   /* Try GDB's internal data cache.  */

  926.   if (!memory_xfer_check_region (readbuf, writebuf, memaddr, len, &reg_len,
  927.                                  &region))
  928.     return TARGET_XFER_E_IO;

  929.   if (!ptid_equal (inferior_ptid, null_ptid))
  930.     inf = find_inferior_ptid (inferior_ptid);
  931.   else
  932.     inf = NULL;

  933.   if (inf != NULL
  934.       && readbuf != NULL
  935.       /* The dcache reads whole cache lines; that doesn't play well
  936.          with reading from a trace buffer, because reading outside of
  937.          the collected memory range fails.  */
  938.       && get_traceframe_number () == -1
  939.       && (region->attrib.cache
  940.           || (stack_cache_enabled_p () && object == TARGET_OBJECT_STACK_MEMORY)
  941.           || (code_cache_enabled_p () && object == TARGET_OBJECT_CODE_MEMORY)))
  942.     {
  943.       DCACHE *dcache = target_dcache_get_or_init ();

  944.       return dcache_read_memory_partial (ops, dcache, memaddr, readbuf,
  945.                                          reg_len, xfered_len);
  946.     }

  947.   /* If none of those methods found the memory we wanted, fall back
  948.      to a target partial transfer.  Normally a single call to
  949.      to_xfer_partial is enough; if it doesn't recognize an object
  950.      it will call the to_xfer_partial of the next target down.
  951.      But for memory this won't do.  Memory is the only target
  952.      object which can be read from more than one valid target.
  953.      A core file, for instance, could have some of memory but
  954.      delegate other bits to the target below it.  So, we must
  955.      manually try all targets.  */

  956.   res = raw_memory_xfer_partial (ops, readbuf, writebuf, memaddr, reg_len,
  957.                                  xfered_len);

  958.   /* If we still haven't got anything, return the last error.  We
  959.      give up.  */
  960.   return res;
  961. }

  962. /* Perform a partial memory transfer.  For docs see target.h,
  963.    to_xfer_partial.  */

  964. static enum target_xfer_status
  965. memory_xfer_partial (struct target_ops *ops, enum target_object object,
  966.                      gdb_byte *readbuf, const gdb_byte *writebuf,
  967.                      ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  968. {
  969.   enum target_xfer_status res;

  970.   /* Zero length requests are ok and require no work.  */
  971.   if (len == 0)
  972.     return TARGET_XFER_EOF;

  973.   /* Fill in READBUF with breakpoint shadows, or WRITEBUF with
  974.      breakpoint insns, thus hiding out from higher layers whether
  975.      there are software breakpoints inserted in the code stream.  */
  976.   if (readbuf != NULL)
  977.     {
  978.       res = memory_xfer_partial_1 (ops, object, readbuf, NULL, memaddr, len,
  979.                                    xfered_len);

  980.       if (res == TARGET_XFER_OK && !show_memory_breakpoints)
  981.         breakpoint_xfer_memory (readbuf, NULL, NULL, memaddr, *xfered_len);
  982.     }
  983.   else
  984.     {
  985.       void *buf;
  986.       struct cleanup *old_chain;

  987.       /* A large write request is likely to be partially satisfied
  988.          by memory_xfer_partial_1.  We will continually malloc
  989.          and free a copy of the entire write request for breakpoint
  990.          shadow handling even though we only end up writing a small
  991.          subset of it.  Cap writes to 4KB to mitigate this.  */
  992.       len = min (4096, len);

  993.       buf = xmalloc (len);
  994.       old_chain = make_cleanup (xfree, buf);
  995.       memcpy (buf, writebuf, len);

  996.       breakpoint_xfer_memory (NULL, buf, writebuf, memaddr, len);
  997.       res = memory_xfer_partial_1 (ops, object, NULL, buf, memaddr, len,
  998.                                    xfered_len);

  999.       do_cleanups (old_chain);
  1000.     }

  1001.   return res;
  1002. }

  1003. static void
  1004. restore_show_memory_breakpoints (void *arg)
  1005. {
  1006.   show_memory_breakpoints = (uintptr_t) arg;
  1007. }

  1008. struct cleanup *
  1009. make_show_memory_breakpoints_cleanup (int show)
  1010. {
  1011.   int current = show_memory_breakpoints;

  1012.   show_memory_breakpoints = show;
  1013.   return make_cleanup (restore_show_memory_breakpoints,
  1014.                        (void *) (uintptr_t) current);
  1015. }

  1016. /* For docs see target.h, to_xfer_partial.  */

  1017. enum target_xfer_status
  1018. target_xfer_partial (struct target_ops *ops,
  1019.                      enum target_object object, const char *annex,
  1020.                      gdb_byte *readbuf, const gdb_byte *writebuf,
  1021.                      ULONGEST offset, ULONGEST len,
  1022.                      ULONGEST *xfered_len)
  1023. {
  1024.   enum target_xfer_status retval;

  1025.   gdb_assert (ops->to_xfer_partial != NULL);

  1026.   /* Transfer is done when LEN is zero.  */
  1027.   if (len == 0)
  1028.     return TARGET_XFER_EOF;

  1029.   if (writebuf && !may_write_memory)
  1030.     error (_("Writing to memory is not allowed (addr %s, len %s)"),
  1031.            core_addr_to_string_nz (offset), plongest (len));

  1032.   *xfered_len = 0;

  1033.   /* If this is a memory transfer, let the memory-specific code
  1034.      have a look at it instead.  Memory transfers are more
  1035.      complicated.  */
  1036.   if (object == TARGET_OBJECT_MEMORY || object == TARGET_OBJECT_STACK_MEMORY
  1037.       || object == TARGET_OBJECT_CODE_MEMORY)
  1038.     retval = memory_xfer_partial (ops, object, readbuf,
  1039.                                   writebuf, offset, len, xfered_len);
  1040.   else if (object == TARGET_OBJECT_RAW_MEMORY)
  1041.     {
  1042.       /* Skip/avoid accessing the target if the memory region
  1043.          attributes block the access.  Check this here instead of in
  1044.          raw_memory_xfer_partial as otherwise we'd end up checking
  1045.          this twice in the case of the memory_xfer_partial path is
  1046.          taken; once before checking the dcache, and another in the
  1047.          tail call to raw_memory_xfer_partial.  */
  1048.       if (!memory_xfer_check_region (readbuf, writebuf, offset, len, &len,
  1049.                                      NULL))
  1050.         return TARGET_XFER_E_IO;

  1051.       /* Request the normal memory object from other layers.  */
  1052.       retval = raw_memory_xfer_partial (ops, readbuf, writebuf, offset, len,
  1053.                                         xfered_len);
  1054.     }
  1055.   else
  1056.     retval = ops->to_xfer_partial (ops, object, annex, readbuf,
  1057.                                    writebuf, offset, len, xfered_len);

  1058.   if (targetdebug)
  1059.     {
  1060.       const unsigned char *myaddr = NULL;

  1061.       fprintf_unfiltered (gdb_stdlog,
  1062.                           "%s:target_xfer_partial "
  1063.                           "(%d, %s, %s, %s, %s, %s) = %d, %s",
  1064.                           ops->to_shortname,
  1065.                           (int) object,
  1066.                           (annex ? annex : "(null)"),
  1067.                           host_address_to_string (readbuf),
  1068.                           host_address_to_string (writebuf),
  1069.                           core_addr_to_string_nz (offset),
  1070.                           pulongest (len), retval,
  1071.                           pulongest (*xfered_len));

  1072.       if (readbuf)
  1073.         myaddr = readbuf;
  1074.       if (writebuf)
  1075.         myaddr = writebuf;
  1076.       if (retval == TARGET_XFER_OK && myaddr != NULL)
  1077.         {
  1078.           int i;

  1079.           fputs_unfiltered (", bytes =", gdb_stdlog);
  1080.           for (i = 0; i < *xfered_len; i++)
  1081.             {
  1082.               if ((((intptr_t) &(myaddr[i])) & 0xf) == 0)
  1083.                 {
  1084.                   if (targetdebug < 2 && i > 0)
  1085.                     {
  1086.                       fprintf_unfiltered (gdb_stdlog, " ...");
  1087.                       break;
  1088.                     }
  1089.                   fprintf_unfiltered (gdb_stdlog, "\n");
  1090.                 }

  1091.               fprintf_unfiltered (gdb_stdlog, " %02x", myaddr[i] & 0xff);
  1092.             }
  1093.         }

  1094.       fputc_unfiltered ('\n', gdb_stdlog);
  1095.     }

  1096.   /* Check implementations of to_xfer_partial update *XFERED_LEN
  1097.      properly.  Do assertion after printing debug messages, so that we
  1098.      can find more clues on assertion failure from debugging messages.  */
  1099.   if (retval == TARGET_XFER_OK || retval == TARGET_XFER_UNAVAILABLE)
  1100.     gdb_assert (*xfered_len > 0);

  1101.   return retval;
  1102. }

  1103. /* Read LEN bytes of target memory at address MEMADDR, placing the
  1104.    results in GDB's memory at MYADDR.  Returns either 0 for success or
  1105.    TARGET_XFER_E_IO if any error occurs.

  1106.    If an error occurs, no guarantee is made about the contents of the data at
  1107.    MYADDR.  In particular, the caller should not depend upon partial reads
  1108.    filling the buffer with good data.  There is no way for the caller to know
  1109.    how much good data might have been transfered anyway.  Callers that can
  1110.    deal with partial reads should call target_read (which will retry until
  1111.    it makes no progress, and then return how much was transferred).  */

  1112. int
  1113. target_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
  1114. {
  1115.   /* Dispatch to the topmost target, not the flattened current_target.
  1116.      Memory accesses check target->to_has_(all_)memory, and the
  1117.      flattened target doesn't inherit those.  */
  1118.   if (target_read (current_target.beneath, TARGET_OBJECT_MEMORY, NULL,
  1119.                    myaddr, memaddr, len) == len)
  1120.     return 0;
  1121.   else
  1122.     return TARGET_XFER_E_IO;
  1123. }

  1124. /* See target/target.h.  */

  1125. int
  1126. target_read_uint32 (CORE_ADDR memaddr, uint32_t *result)
  1127. {
  1128.   gdb_byte buf[4];
  1129.   int r;

  1130.   r = target_read_memory (memaddr, buf, sizeof buf);
  1131.   if (r != 0)
  1132.     return r;
  1133.   *result = extract_unsigned_integer (buf, sizeof buf,
  1134.                                       gdbarch_byte_order (target_gdbarch ()));
  1135.   return 0;
  1136. }

  1137. /* Like target_read_memory, but specify explicitly that this is a read
  1138.    from the target's raw memory.  That is, this read bypasses the
  1139.    dcache, breakpoint shadowing, etc.  */

  1140. int
  1141. target_read_raw_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
  1142. {
  1143.   /* See comment in target_read_memory about why the request starts at
  1144.      current_target.beneath.  */
  1145.   if (target_read (current_target.beneath, TARGET_OBJECT_RAW_MEMORY, NULL,
  1146.                    myaddr, memaddr, len) == len)
  1147.     return 0;
  1148.   else
  1149.     return TARGET_XFER_E_IO;
  1150. }

  1151. /* Like target_read_memory, but specify explicitly that this is a read from
  1152.    the target's stack.  This may trigger different cache behavior.  */

  1153. int
  1154. target_read_stack (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
  1155. {
  1156.   /* See comment in target_read_memory about why the request starts at
  1157.      current_target.beneath.  */
  1158.   if (target_read (current_target.beneath, TARGET_OBJECT_STACK_MEMORY, NULL,
  1159.                    myaddr, memaddr, len) == len)
  1160.     return 0;
  1161.   else
  1162.     return TARGET_XFER_E_IO;
  1163. }

  1164. /* Like target_read_memory, but specify explicitly that this is a read from
  1165.    the target's code.  This may trigger different cache behavior.  */

  1166. int
  1167. target_read_code (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
  1168. {
  1169.   /* See comment in target_read_memory about why the request starts at
  1170.      current_target.beneath.  */
  1171.   if (target_read (current_target.beneath, TARGET_OBJECT_CODE_MEMORY, NULL,
  1172.                    myaddr, memaddr, len) == len)
  1173.     return 0;
  1174.   else
  1175.     return TARGET_XFER_E_IO;
  1176. }

  1177. /* Write LEN bytes from MYADDR to target memory at address MEMADDR.
  1178.    Returns either 0 for success or TARGET_XFER_E_IO if any
  1179.    error occurs.  If an error occurs, no guarantee is made about how
  1180.    much data got written.  Callers that can deal with partial writes
  1181.    should call target_write.  */

  1182. int
  1183. target_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
  1184. {
  1185.   /* See comment in target_read_memory about why the request starts at
  1186.      current_target.beneath.  */
  1187.   if (target_write (current_target.beneath, TARGET_OBJECT_MEMORY, NULL,
  1188.                     myaddr, memaddr, len) == len)
  1189.     return 0;
  1190.   else
  1191.     return TARGET_XFER_E_IO;
  1192. }

  1193. /* Write LEN bytes from MYADDR to target raw memory at address
  1194.    MEMADDR.  Returns either 0 for success or TARGET_XFER_E_IO
  1195.    if any error occurs.  If an error occurs, no guarantee is made
  1196.    about how much data got written.  Callers that can deal with
  1197.    partial writes should call target_write.  */

  1198. int
  1199. target_write_raw_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
  1200. {
  1201.   /* See comment in target_read_memory about why the request starts at
  1202.      current_target.beneath.  */
  1203.   if (target_write (current_target.beneath, TARGET_OBJECT_RAW_MEMORY, NULL,
  1204.                     myaddr, memaddr, len) == len)
  1205.     return 0;
  1206.   else
  1207.     return TARGET_XFER_E_IO;
  1208. }

  1209. /* Fetch the target's memory map.  */

  1210. VEC(mem_region_s) *
  1211. target_memory_map (void)
  1212. {
  1213.   VEC(mem_region_s) *result;
  1214.   struct mem_region *last_one, *this_one;
  1215.   int ix;
  1216.   struct target_ops *t;

  1217.   result = current_target.to_memory_map (&current_target);
  1218.   if (result == NULL)
  1219.     return NULL;

  1220.   qsort (VEC_address (mem_region_s, result),
  1221.          VEC_length (mem_region_s, result),
  1222.          sizeof (struct mem_region), mem_region_cmp);

  1223.   /* Check that regions do not overlap.  Simultaneously assign
  1224.      a numbering for the "mem" commands to use to refer to
  1225.      each region.  */
  1226.   last_one = NULL;
  1227.   for (ix = 0; VEC_iterate (mem_region_s, result, ix, this_one); ix++)
  1228.     {
  1229.       this_one->number = ix;

  1230.       if (last_one && last_one->hi > this_one->lo)
  1231.         {
  1232.           warning (_("Overlapping regions in memory map: ignoring"));
  1233.           VEC_free (mem_region_s, result);
  1234.           return NULL;
  1235.         }
  1236.       last_one = this_one;
  1237.     }

  1238.   return result;
  1239. }

  1240. void
  1241. target_flash_erase (ULONGEST address, LONGEST length)
  1242. {
  1243.   current_target.to_flash_erase (&current_target, address, length);
  1244. }

  1245. void
  1246. target_flash_done (void)
  1247. {
  1248.   current_target.to_flash_done (&current_target);
  1249. }

  1250. static void
  1251. show_trust_readonly (struct ui_file *file, int from_tty,
  1252.                      struct cmd_list_element *c, const char *value)
  1253. {
  1254.   fprintf_filtered (file,
  1255.                     _("Mode for reading from readonly sections is %s.\n"),
  1256.                     value);
  1257. }

  1258. /* Target vector read/write partial wrapper functions.  */

  1259. static enum target_xfer_status
  1260. target_read_partial (struct target_ops *ops,
  1261.                      enum target_object object,
  1262.                      const char *annex, gdb_byte *buf,
  1263.                      ULONGEST offset, ULONGEST len,
  1264.                      ULONGEST *xfered_len)
  1265. {
  1266.   return target_xfer_partial (ops, object, annex, buf, NULL, offset, len,
  1267.                               xfered_len);
  1268. }

  1269. static enum target_xfer_status
  1270. target_write_partial (struct target_ops *ops,
  1271.                       enum target_object object,
  1272.                       const char *annex, const gdb_byte *buf,
  1273.                       ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
  1274. {
  1275.   return target_xfer_partial (ops, object, annex, NULL, buf, offset, len,
  1276.                               xfered_len);
  1277. }

  1278. /* Wrappers to perform the full transfer.  */

  1279. /* For docs on target_read see target.h.  */

  1280. LONGEST
  1281. target_read (struct target_ops *ops,
  1282.              enum target_object object,
  1283.              const char *annex, gdb_byte *buf,
  1284.              ULONGEST offset, LONGEST len)
  1285. {
  1286.   LONGEST xfered = 0;

  1287.   while (xfered < len)
  1288.     {
  1289.       ULONGEST xfered_len;
  1290.       enum target_xfer_status status;

  1291.       status = target_read_partial (ops, object, annex,
  1292.                                     (gdb_byte *) buf + xfered,
  1293.                                     offset + xfered, len - xfered,
  1294.                                     &xfered_len);

  1295.       /* Call an observer, notifying them of the xfer progress?  */
  1296.       if (status == TARGET_XFER_EOF)
  1297.         return xfered;
  1298.       else if (status == TARGET_XFER_OK)
  1299.         {
  1300.           xfered += xfered_len;
  1301.           QUIT;
  1302.         }
  1303.       else
  1304.         return -1;

  1305.     }
  1306.   return len;
  1307. }

  1308. /* Assuming that the entire [begin, end) range of memory cannot be
  1309.    read, try to read whatever subrange is possible to read.

  1310.    The function returns, in RESULT, either zero or one memory block.
  1311.    If there's a readable subrange at the beginning, it is completely
  1312.    read and returned.  Any further readable subrange will not be read.
  1313.    Otherwise, if there's a readable subrange at the end, it will be
  1314.    completely read and returned.  Any readable subranges before it
  1315.    (obviously, not starting at the beginning), will be ignored.  In
  1316.    other cases -- either no readable subrange, or readable subrange(s)
  1317.    that is neither at the beginning, or end, nothing is returned.

  1318.    The purpose of this function is to handle a read across a boundary
  1319.    of accessible memory in a case when memory map is not available.
  1320.    The above restrictions are fine for this case, but will give
  1321.    incorrect results if the memory is 'patchy'.  However, supporting
  1322.    'patchy' memory would require trying to read every single byte,
  1323.    and it seems unacceptable solution.  Explicit memory map is
  1324.    recommended for this case -- and target_read_memory_robust will
  1325.    take care of reading multiple ranges then.  */

  1326. static void
  1327. read_whatever_is_readable (struct target_ops *ops,
  1328.                            ULONGEST begin, ULONGEST end,
  1329.                            VEC(memory_read_result_s) **result)
  1330. {
  1331.   gdb_byte *buf = xmalloc (end - begin);
  1332.   ULONGEST current_begin = begin;
  1333.   ULONGEST current_end = end;
  1334.   int forward;
  1335.   memory_read_result_s r;
  1336.   ULONGEST xfered_len;

  1337.   /* If we previously failed to read 1 byte, nothing can be done here.  */
  1338.   if (end - begin <= 1)
  1339.     {
  1340.       xfree (buf);
  1341.       return;
  1342.     }

  1343.   /* Check that either first or the last byte is readable, and give up
  1344.      if not.  This heuristic is meant to permit reading accessible memory
  1345.      at the boundary of accessible region.  */
  1346.   if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
  1347.                            buf, begin, 1, &xfered_len) == TARGET_XFER_OK)
  1348.     {
  1349.       forward = 1;
  1350.       ++current_begin;
  1351.     }
  1352.   else if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
  1353.                                 buf + (end-begin) - 1, end - 1, 1,
  1354.                                 &xfered_len) == TARGET_XFER_OK)
  1355.     {
  1356.       forward = 0;
  1357.       --current_end;
  1358.     }
  1359.   else
  1360.     {
  1361.       xfree (buf);
  1362.       return;
  1363.     }

  1364.   /* Loop invariant is that the [current_begin, current_end) was previously
  1365.      found to be not readable as a whole.

  1366.      Note loop condition -- if the range has 1 byte, we can't divide the range
  1367.      so there's no point trying further.  */
  1368.   while (current_end - current_begin > 1)
  1369.     {
  1370.       ULONGEST first_half_begin, first_half_end;
  1371.       ULONGEST second_half_begin, second_half_end;
  1372.       LONGEST xfer;
  1373.       ULONGEST middle = current_begin + (current_end - current_begin)/2;

  1374.       if (forward)
  1375.         {
  1376.           first_half_begin = current_begin;
  1377.           first_half_end = middle;
  1378.           second_half_begin = middle;
  1379.           second_half_end = current_end;
  1380.         }
  1381.       else
  1382.         {
  1383.           first_half_begin = middle;
  1384.           first_half_end = current_end;
  1385.           second_half_begin = current_begin;
  1386.           second_half_end = middle;
  1387.         }

  1388.       xfer = target_read (ops, TARGET_OBJECT_MEMORY, NULL,
  1389.                           buf + (first_half_begin - begin),
  1390.                           first_half_begin,
  1391.                           first_half_end - first_half_begin);

  1392.       if (xfer == first_half_end - first_half_begin)
  1393.         {
  1394.           /* This half reads up fine.  So, the error must be in the
  1395.              other half.  */
  1396.           current_begin = second_half_begin;
  1397.           current_end = second_half_end;
  1398.         }
  1399.       else
  1400.         {
  1401.           /* This half is not readable.  Because we've tried one byte, we
  1402.              know some part of this half if actually redable.  Go to the next
  1403.              iteration to divide again and try to read.

  1404.              We don't handle the other half, because this function only tries
  1405.              to read a single readable subrange.  */
  1406.           current_begin = first_half_begin;
  1407.           current_end = first_half_end;
  1408.         }
  1409.     }

  1410.   if (forward)
  1411.     {
  1412.       /* The [begin, current_begin) range has been read.  */
  1413.       r.begin = begin;
  1414.       r.end = current_begin;
  1415.       r.data = buf;
  1416.     }
  1417.   else
  1418.     {
  1419.       /* The [current_end, end) range has been read.  */
  1420.       LONGEST rlen = end - current_end;

  1421.       r.data = xmalloc (rlen);
  1422.       memcpy (r.data, buf + current_end - begin, rlen);
  1423.       r.begin = current_end;
  1424.       r.end = end;
  1425.       xfree (buf);
  1426.     }
  1427.   VEC_safe_push(memory_read_result_s, (*result), &r);
  1428. }

  1429. void
  1430. free_memory_read_result_vector (void *x)
  1431. {
  1432.   VEC(memory_read_result_s) *v = x;
  1433.   memory_read_result_s *current;
  1434.   int ix;

  1435.   for (ix = 0; VEC_iterate (memory_read_result_s, v, ix, current); ++ix)
  1436.     {
  1437.       xfree (current->data);
  1438.     }
  1439.   VEC_free (memory_read_result_s, v);
  1440. }

  1441. VEC(memory_read_result_s) *
  1442. read_memory_robust (struct target_ops *ops, ULONGEST offset, LONGEST len)
  1443. {
  1444.   VEC(memory_read_result_s) *result = 0;

  1445.   LONGEST xfered = 0;
  1446.   while (xfered < len)
  1447.     {
  1448.       struct mem_region *region = lookup_mem_region (offset + xfered);
  1449.       LONGEST rlen;

  1450.       /* If there is no explicit region, a fake one should be created.  */
  1451.       gdb_assert (region);

  1452.       if (region->hi == 0)
  1453.         rlen = len - xfered;
  1454.       else
  1455.         rlen = region->hi - offset;

  1456.       if (region->attrib.mode == MEM_NONE || region->attrib.mode == MEM_WO)
  1457.         {
  1458.           /* Cannot read this region.  Note that we can end up here only
  1459.              if the region is explicitly marked inaccessible, or
  1460.              'inaccessible-by-default' is in effect.  */
  1461.           xfered += rlen;
  1462.         }
  1463.       else
  1464.         {
  1465.           LONGEST to_read = min (len - xfered, rlen);
  1466.           gdb_byte *buffer = (gdb_byte *)xmalloc (to_read);

  1467.           LONGEST xfer = target_read (ops, TARGET_OBJECT_MEMORY, NULL,
  1468.                                       (gdb_byte *) buffer,
  1469.                                       offset + xfered, to_read);
  1470.           /* Call an observer, notifying them of the xfer progress?  */
  1471.           if (xfer <= 0)
  1472.             {
  1473.               /* Got an error reading full chunk.  See if maybe we can read
  1474.                  some subrange.  */
  1475.               xfree (buffer);
  1476.               read_whatever_is_readable (ops, offset + xfered,
  1477.                                          offset + xfered + to_read, &result);
  1478.               xfered += to_read;
  1479.             }
  1480.           else
  1481.             {
  1482.               struct memory_read_result r;
  1483.               r.data = buffer;
  1484.               r.begin = offset + xfered;
  1485.               r.end = r.begin + xfer;
  1486.               VEC_safe_push (memory_read_result_s, result, &r);
  1487.               xfered += xfer;
  1488.             }
  1489.           QUIT;
  1490.         }
  1491.     }
  1492.   return result;
  1493. }


  1494. /* An alternative to target_write with progress callbacks.  */

  1495. LONGEST
  1496. target_write_with_progress (struct target_ops *ops,
  1497.                             enum target_object object,
  1498.                             const char *annex, const gdb_byte *buf,
  1499.                             ULONGEST offset, LONGEST len,
  1500.                             void (*progress) (ULONGEST, void *), void *baton)
  1501. {
  1502.   LONGEST xfered = 0;

  1503.   /* Give the progress callback a chance to set up.  */
  1504.   if (progress)
  1505.     (*progress) (0, baton);

  1506.   while (xfered < len)
  1507.     {
  1508.       ULONGEST xfered_len;
  1509.       enum target_xfer_status status;

  1510.       status = target_write_partial (ops, object, annex,
  1511.                                      (gdb_byte *) buf + xfered,
  1512.                                      offset + xfered, len - xfered,
  1513.                                      &xfered_len);

  1514.       if (status != TARGET_XFER_OK)
  1515.         return status == TARGET_XFER_EOF ? xfered : -1;

  1516.       if (progress)
  1517.         (*progress) (xfered_len, baton);

  1518.       xfered += xfered_len;
  1519.       QUIT;
  1520.     }
  1521.   return len;
  1522. }

  1523. /* For docs on target_write see target.h.  */

  1524. LONGEST
  1525. target_write (struct target_ops *ops,
  1526.               enum target_object object,
  1527.               const char *annex, const gdb_byte *buf,
  1528.               ULONGEST offset, LONGEST len)
  1529. {
  1530.   return target_write_with_progress (ops, object, annex, buf, offset, len,
  1531.                                      NULL, NULL);
  1532. }

  1533. /* Read OBJECT/ANNEX using OPS.  Store the result in *BUF_P and return
  1534.    the size of the transferred data.  PADDING additional bytes are
  1535.    available in *BUF_P.  This is a helper function for
  1536.    target_read_alloc; see the declaration of that function for more
  1537.    information.  */

  1538. static LONGEST
  1539. target_read_alloc_1 (struct target_ops *ops, enum target_object object,
  1540.                      const char *annex, gdb_byte **buf_p, int padding)
  1541. {
  1542.   size_t buf_alloc, buf_pos;
  1543.   gdb_byte *buf;

  1544.   /* This function does not have a length parameter; it reads the
  1545.      entire OBJECT).  Also, it doesn't support objects fetched partly
  1546.      from one target and partly from another (in a different stratum,
  1547.      e.g. a core file and an executable).  Both reasons make it
  1548.      unsuitable for reading memory.  */
  1549.   gdb_assert (object != TARGET_OBJECT_MEMORY);

  1550.   /* Start by reading up to 4K at a time.  The target will throttle
  1551.      this number down if necessary.  */
  1552.   buf_alloc = 4096;
  1553.   buf = xmalloc (buf_alloc);
  1554.   buf_pos = 0;
  1555.   while (1)
  1556.     {
  1557.       ULONGEST xfered_len;
  1558.       enum target_xfer_status status;

  1559.       status = target_read_partial (ops, object, annex, &buf[buf_pos],
  1560.                                     buf_pos, buf_alloc - buf_pos - padding,
  1561.                                     &xfered_len);

  1562.       if (status == TARGET_XFER_EOF)
  1563.         {
  1564.           /* Read all there was.  */
  1565.           if (buf_pos == 0)
  1566.             xfree (buf);
  1567.           else
  1568.             *buf_p = buf;
  1569.           return buf_pos;
  1570.         }
  1571.       else if (status != TARGET_XFER_OK)
  1572.         {
  1573.           /* An error occurred.  */
  1574.           xfree (buf);
  1575.           return TARGET_XFER_E_IO;
  1576.         }

  1577.       buf_pos += xfered_len;

  1578.       /* If the buffer is filling up, expand it.  */
  1579.       if (buf_alloc < buf_pos * 2)
  1580.         {
  1581.           buf_alloc *= 2;
  1582.           buf = xrealloc (buf, buf_alloc);
  1583.         }

  1584.       QUIT;
  1585.     }
  1586. }

  1587. /* Read OBJECT/ANNEX using OPS.  Store the result in *BUF_P and return
  1588.    the size of the transferred data.  See the declaration in "target.h"
  1589.    function for more information about the return value.  */

  1590. LONGEST
  1591. target_read_alloc (struct target_ops *ops, enum target_object object,
  1592.                    const char *annex, gdb_byte **buf_p)
  1593. {
  1594.   return target_read_alloc_1 (ops, object, annex, buf_p, 0);
  1595. }

  1596. /* Read OBJECT/ANNEX using OPS.  The result is NUL-terminated and
  1597.    returned as a string, allocated using xmalloc.  If an error occurs
  1598.    or the transfer is unsupported, NULL is returned.  Empty objects
  1599.    are returned as allocated but empty strings.  A warning is issued
  1600.    if the result contains any embedded NUL bytes.  */

  1601. char *
  1602. target_read_stralloc (struct target_ops *ops, enum target_object object,
  1603.                       const char *annex)
  1604. {
  1605.   gdb_byte *buffer;
  1606.   char *bufstr;
  1607.   LONGEST i, transferred;

  1608.   transferred = target_read_alloc_1 (ops, object, annex, &buffer, 1);
  1609.   bufstr = (char *) buffer;

  1610.   if (transferred < 0)
  1611.     return NULL;

  1612.   if (transferred == 0)
  1613.     return xstrdup ("");

  1614.   bufstr[transferred] = 0;

  1615.   /* Check for embedded NUL bytes; but allow trailing NULs.  */
  1616.   for (i = strlen (bufstr); i < transferred; i++)
  1617.     if (bufstr[i] != 0)
  1618.       {
  1619.         warning (_("target object %d, annex %s, "
  1620.                    "contained unexpected null characters"),
  1621.                  (int) object, annex ? annex : "(none)");
  1622.         break;
  1623.       }

  1624.   return bufstr;
  1625. }

  1626. /* Memory transfer methods.  */

  1627. void
  1628. get_target_memory (struct target_ops *ops, CORE_ADDR addr, gdb_byte *buf,
  1629.                    LONGEST len)
  1630. {
  1631.   /* This method is used to read from an alternate, non-current
  1632.      target.  This read must bypass the overlay support (as symbols
  1633.      don't match this target), and GDB's internal cache (wrong cache
  1634.      for this target).  */
  1635.   if (target_read (ops, TARGET_OBJECT_RAW_MEMORY, NULL, buf, addr, len)
  1636.       != len)
  1637.     memory_error (TARGET_XFER_E_IO, addr);
  1638. }

  1639. ULONGEST
  1640. get_target_memory_unsigned (struct target_ops *ops, CORE_ADDR addr,
  1641.                             int len, enum bfd_endian byte_order)
  1642. {
  1643.   gdb_byte buf[sizeof (ULONGEST)];

  1644.   gdb_assert (len <= sizeof (buf));
  1645.   get_target_memory (ops, addr, buf, len);
  1646.   return extract_unsigned_integer (buf, len, byte_order);
  1647. }

  1648. /* See target.h.  */

  1649. int
  1650. target_insert_breakpoint (struct gdbarch *gdbarch,
  1651.                           struct bp_target_info *bp_tgt)
  1652. {
  1653.   if (!may_insert_breakpoints)
  1654.     {
  1655.       warning (_("May not insert breakpoints"));
  1656.       return 1;
  1657.     }

  1658.   return current_target.to_insert_breakpoint (&current_target,
  1659.                                               gdbarch, bp_tgt);
  1660. }

  1661. /* See target.h.  */

  1662. int
  1663. target_remove_breakpoint (struct gdbarch *gdbarch,
  1664.                           struct bp_target_info *bp_tgt)
  1665. {
  1666.   /* This is kind of a weird case to handle, but the permission might
  1667.      have been changed after breakpoints were inserted - in which case
  1668.      we should just take the user literally and assume that any
  1669.      breakpoints should be left in place.  */
  1670.   if (!may_insert_breakpoints)
  1671.     {
  1672.       warning (_("May not remove breakpoints"));
  1673.       return 1;
  1674.     }

  1675.   return current_target.to_remove_breakpoint (&current_target,
  1676.                                               gdbarch, bp_tgt);
  1677. }

  1678. static void
  1679. target_info (char *args, int from_tty)
  1680. {
  1681.   struct target_ops *t;
  1682.   int has_all_mem = 0;

  1683.   if (symfile_objfile != NULL)
  1684.     printf_unfiltered (_("Symbols from \"%s\".\n"),
  1685.                        objfile_name (symfile_objfile));

  1686.   for (t = target_stack; t != NULL; t = t->beneath)
  1687.     {
  1688.       if (!(*t->to_has_memory) (t))
  1689.         continue;

  1690.       if ((int) (t->to_stratum) <= (int) dummy_stratum)
  1691.         continue;
  1692.       if (has_all_mem)
  1693.         printf_unfiltered (_("\tWhile running this, "
  1694.                              "GDB does not access memory from...\n"));
  1695.       printf_unfiltered ("%s:\n", t->to_longname);
  1696.       (t->to_files_info) (t);
  1697.       has_all_mem = (*t->to_has_all_memory) (t);
  1698.     }
  1699. }

  1700. /* This function is called before any new inferior is created, e.g.
  1701.    by running a program, attaching, or connecting to a target.
  1702.    It cleans up any state from previous invocations which might
  1703.    change between runs.  This is a subset of what target_preopen
  1704.    resets (things which might change between targets).  */

  1705. void
  1706. target_pre_inferior (int from_tty)
  1707. {
  1708.   /* Clear out solib state.  Otherwise the solib state of the previous
  1709.      inferior might have survived and is entirely wrong for the new
  1710.      target.  This has been observed on GNU/Linux using glibc 2.3.  How
  1711.      to reproduce:

  1712.      bash$ ./foo&
  1713.      [1] 4711
  1714.      bash$ ./foo&
  1715.      [1] 4712
  1716.      bash$ gdb ./foo
  1717.      [...]
  1718.      (gdb) attach 4711
  1719.      (gdb) detach
  1720.      (gdb) attach 4712
  1721.      Cannot access memory at address 0xdeadbeef
  1722.   */

  1723.   /* In some OSs, the shared library list is the same/global/shared
  1724.      across inferiors.  If code is shared between processes, so are
  1725.      memory regions and features.  */
  1726.   if (!gdbarch_has_global_solist (target_gdbarch ()))
  1727.     {
  1728.       no_shared_libraries (NULL, from_tty);

  1729.       invalidate_target_mem_regions ();

  1730.       target_clear_description ();
  1731.     }

  1732.   agent_capability_invalidate ();
  1733. }

  1734. /* Callback for iterate_over_inferiors.  Gets rid of the given
  1735.    inferior.  */

  1736. static int
  1737. dispose_inferior (struct inferior *inf, void *args)
  1738. {
  1739.   struct thread_info *thread;

  1740.   thread = any_thread_of_process (inf->pid);
  1741.   if (thread)
  1742.     {
  1743.       switch_to_thread (thread->ptid);

  1744.       /* Core inferiors actually should be detached, not killed.  */
  1745.       if (target_has_execution)
  1746.         target_kill ();
  1747.       else
  1748.         target_detach (NULL, 0);
  1749.     }

  1750.   return 0;
  1751. }

  1752. /* This is to be called by the open routine before it does
  1753.    anything.  */

  1754. void
  1755. target_preopen (int from_tty)
  1756. {
  1757.   dont_repeat ();

  1758.   if (have_inferiors ())
  1759.     {
  1760.       if (!from_tty
  1761.           || !have_live_inferiors ()
  1762.           || query (_("A program is being debugged already.  Kill it? ")))
  1763.         iterate_over_inferiors (dispose_inferior, NULL);
  1764.       else
  1765.         error (_("Program not killed."));
  1766.     }

  1767.   /* Calling target_kill may remove the target from the stack.  But if
  1768.      it doesn't (which seems like a win for UDI), remove it now.  */
  1769.   /* Leave the exec target, though.  The user may be switching from a
  1770.      live process to a core of the same program.  */
  1771.   pop_all_targets_above (file_stratum);

  1772.   target_pre_inferior (from_tty);
  1773. }

  1774. /* Detach a target after doing deferred register stores.  */

  1775. void
  1776. target_detach (const char *args, int from_tty)
  1777. {
  1778.   struct target_ops* t;

  1779.   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
  1780.     /* Don't remove global breakpoints here.  They're removed on
  1781.        disconnection from the target.  */
  1782.     ;
  1783.   else
  1784.     /* If we're in breakpoints-always-inserted mode, have to remove
  1785.        them before detaching.  */
  1786.     remove_breakpoints_pid (ptid_get_pid (inferior_ptid));

  1787.   prepare_for_detach ();

  1788.   current_target.to_detach (&current_target, args, from_tty);
  1789. }

  1790. void
  1791. target_disconnect (const char *args, int from_tty)
  1792. {
  1793.   /* If we're in breakpoints-always-inserted mode or if breakpoints
  1794.      are global across processes, we have to remove them before
  1795.      disconnecting.  */
  1796.   remove_breakpoints ();

  1797.   current_target.to_disconnect (&current_target, args, from_tty);
  1798. }

  1799. ptid_t
  1800. target_wait (ptid_t ptid, struct target_waitstatus *status, int options)
  1801. {
  1802.   return (current_target.to_wait) (&current_target, ptid, status, options);
  1803. }

  1804. char *
  1805. target_pid_to_str (ptid_t ptid)
  1806. {
  1807.   return (*current_target.to_pid_to_str) (&current_target, ptid);
  1808. }

  1809. char *
  1810. target_thread_name (struct thread_info *info)
  1811. {
  1812.   return current_target.to_thread_name (&current_target, info);
  1813. }

  1814. void
  1815. target_resume (ptid_t ptid, int step, enum gdb_signal signal)
  1816. {
  1817.   struct target_ops *t;

  1818.   target_dcache_invalidate ();

  1819.   current_target.to_resume (&current_target, ptid, step, signal);

  1820.   registers_changed_ptid (ptid);
  1821.   /* We only set the internal executing state here.  The user/frontend
  1822.      running state is set at a higher level.  */
  1823.   set_executing (ptid, 1);
  1824.   clear_inline_frame_state (ptid);
  1825. }

  1826. void
  1827. target_pass_signals (int numsigs, unsigned char *pass_signals)
  1828. {
  1829.   (*current_target.to_pass_signals) (&current_target, numsigs, pass_signals);
  1830. }

  1831. void
  1832. target_program_signals (int numsigs, unsigned char *program_signals)
  1833. {
  1834.   (*current_target.to_program_signals) (&current_target,
  1835.                                         numsigs, program_signals);
  1836. }

  1837. static int
  1838. default_follow_fork (struct target_ops *self, int follow_child,
  1839.                      int detach_fork)
  1840. {
  1841.   /* Some target returned a fork event, but did not know how to follow it.  */
  1842.   internal_error (__FILE__, __LINE__,
  1843.                   _("could not find a target to follow fork"));
  1844. }

  1845. /* Look through the list of possible targets for a target that can
  1846.    follow forks.  */

  1847. int
  1848. target_follow_fork (int follow_child, int detach_fork)
  1849. {
  1850.   return current_target.to_follow_fork (&current_target,
  1851.                                         follow_child, detach_fork);
  1852. }

  1853. static void
  1854. default_mourn_inferior (struct target_ops *self)
  1855. {
  1856.   internal_error (__FILE__, __LINE__,
  1857.                   _("could not find a target to follow mourn inferior"));
  1858. }

  1859. void
  1860. target_mourn_inferior (void)
  1861. {
  1862.   current_target.to_mourn_inferior (&current_target);

  1863.   /* We no longer need to keep handles on any of the object files.
  1864.      Make sure to release them to avoid unnecessarily locking any
  1865.      of them while we're not actually debugging.  */
  1866.   bfd_cache_close_all ();
  1867. }

  1868. /* Look for a target which can describe architectural features, starting
  1869.    from TARGET.  If we find one, return its description.  */

  1870. const struct target_desc *
  1871. target_read_description (struct target_ops *target)
  1872. {
  1873.   return target->to_read_description (target);
  1874. }

  1875. /* This implements a basic search of memory, reading target memory and
  1876.    performing the search here (as opposed to performing the search in on the
  1877.    target side with, for example, gdbserver).  */

  1878. int
  1879. simple_search_memory (struct target_ops *ops,
  1880.                       CORE_ADDR start_addr, ULONGEST search_space_len,
  1881.                       const gdb_byte *pattern, ULONGEST pattern_len,
  1882.                       CORE_ADDR *found_addrp)
  1883. {
  1884.   /* NOTE: also defined in find.c testcase.  */
  1885. #define SEARCH_CHUNK_SIZE 16000
  1886.   const unsigned chunk_size = SEARCH_CHUNK_SIZE;
  1887.   /* Buffer to hold memory contents for searching.  */
  1888.   gdb_byte *search_buf;
  1889.   unsigned search_buf_size;
  1890.   struct cleanup *old_cleanups;

  1891.   search_buf_size = chunk_size + pattern_len - 1;

  1892.   /* No point in trying to allocate a buffer larger than the search space.  */
  1893.   if (search_space_len < search_buf_size)
  1894.     search_buf_size = search_space_len;

  1895.   search_buf = malloc (search_buf_size);
  1896.   if (search_buf == NULL)
  1897.     error (_("Unable to allocate memory to perform the search."));
  1898.   old_cleanups = make_cleanup (free_current_contents, &search_buf);

  1899.   /* Prime the search buffer.  */

  1900.   if (target_read (ops, TARGET_OBJECT_MEMORY, NULL,
  1901.                    search_buf, start_addr, search_buf_size) != search_buf_size)
  1902.     {
  1903.       warning (_("Unable to access %s bytes of target "
  1904.                  "memory at %s, halting search."),
  1905.                pulongest (search_buf_size), hex_string (start_addr));
  1906.       do_cleanups (old_cleanups);
  1907.       return -1;
  1908.     }

  1909.   /* Perform the search.

  1910.      The loop is kept simple by allocating [N + pattern-length - 1] bytes.
  1911.      When we've scanned N bytes we copy the trailing bytes to the start and
  1912.      read in another N bytes.  */

  1913.   while (search_space_len >= pattern_len)
  1914.     {
  1915.       gdb_byte *found_ptr;
  1916.       unsigned nr_search_bytes = min (search_space_len, search_buf_size);

  1917.       found_ptr = memmem (search_buf, nr_search_bytes,
  1918.                           pattern, pattern_len);

  1919.       if (found_ptr != NULL)
  1920.         {
  1921.           CORE_ADDR found_addr = start_addr + (found_ptr - search_buf);

  1922.           *found_addrp = found_addr;
  1923.           do_cleanups (old_cleanups);
  1924.           return 1;
  1925.         }

  1926.       /* Not found in this chunk, skip to next chunk.  */

  1927.       /* Don't let search_space_len wrap here, it's unsigned.  */
  1928.       if (search_space_len >= chunk_size)
  1929.         search_space_len -= chunk_size;
  1930.       else
  1931.         search_space_len = 0;

  1932.       if (search_space_len >= pattern_len)
  1933.         {
  1934.           unsigned keep_len = search_buf_size - chunk_size;
  1935.           CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
  1936.           int nr_to_read;

  1937.           /* Copy the trailing part of the previous iteration to the front
  1938.              of the buffer for the next iteration.  */
  1939.           gdb_assert (keep_len == pattern_len - 1);
  1940.           memcpy (search_buf, search_buf + chunk_size, keep_len);

  1941.           nr_to_read = min (search_space_len - keep_len, chunk_size);

  1942.           if (target_read (ops, TARGET_OBJECT_MEMORY, NULL,
  1943.                            search_buf + keep_len, read_addr,
  1944.                            nr_to_read) != nr_to_read)
  1945.             {
  1946.               warning (_("Unable to access %s bytes of target "
  1947.                          "memory at %s, halting search."),
  1948.                        plongest (nr_to_read),
  1949.                        hex_string (read_addr));
  1950.               do_cleanups (old_cleanups);
  1951.               return -1;
  1952.             }

  1953.           start_addr += chunk_size;
  1954.         }
  1955.     }

  1956.   /* Not found.  */

  1957.   do_cleanups (old_cleanups);
  1958.   return 0;
  1959. }

  1960. /* Default implementation of memory-searching.  */

  1961. static int
  1962. default_search_memory (struct target_ops *self,
  1963.                        CORE_ADDR start_addr, ULONGEST search_space_len,
  1964.                        const gdb_byte *pattern, ULONGEST pattern_len,
  1965.                        CORE_ADDR *found_addrp)
  1966. {
  1967.   /* Start over from the top of the target stack.  */
  1968.   return simple_search_memory (current_target.beneath,
  1969.                                start_addr, search_space_len,
  1970.                                pattern, pattern_len, found_addrp);
  1971. }

  1972. /* Search SEARCH_SPACE_LEN bytes beginning at START_ADDR for the
  1973.    sequence of bytes in PATTERN with length PATTERN_LEN.

  1974.    The result is 1 if found, 0 if not found, and -1 if there was an error
  1975.    requiring halting of the search (e.g. memory read error).
  1976.    If the pattern is found the address is recorded in FOUND_ADDRP.  */

  1977. int
  1978. target_search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
  1979.                       const gdb_byte *pattern, ULONGEST pattern_len,
  1980.                       CORE_ADDR *found_addrp)
  1981. {
  1982.   return current_target.to_search_memory (&current_target, start_addr,
  1983.                                           search_space_len,
  1984.                                           pattern, pattern_len, found_addrp);
  1985. }

  1986. /* Look through the currently pushed targets.  If none of them will
  1987.    be able to restart the currently running process, issue an error
  1988.    message.  */

  1989. void
  1990. target_require_runnable (void)
  1991. {
  1992.   struct target_ops *t;

  1993.   for (t = target_stack; t != NULL; t = t->beneath)
  1994.     {
  1995.       /* If this target knows how to create a new program, then
  1996.          assume we will still be able to after killing the current
  1997.          one.  Either killing and mourning will not pop T, or else
  1998.          find_default_run_target will find it again.  */
  1999.       if (t->to_create_inferior != NULL)
  2000.         return;

  2001.       /* Do not worry about targets at certain strata that can not
  2002.          create inferiors.  Assume they will be pushed again if
  2003.          necessary, and continue to the process_stratum.  */
  2004.       if (t->to_stratum == thread_stratum
  2005.           || t->to_stratum == record_stratum
  2006.           || t->to_stratum == arch_stratum)
  2007.         continue;

  2008.       error (_("The \"%s\" target does not support \"run\".  "
  2009.                "Try \"help target\" or \"continue\"."),
  2010.              t->to_shortname);
  2011.     }

  2012.   /* This function is only called if the target is running.  In that
  2013.      case there should have been a process_stratum target and it
  2014.      should either know how to create inferiors, or not...  */
  2015.   internal_error (__FILE__, __LINE__, _("No targets found"));
  2016. }

  2017. /* Whether GDB is allowed to fall back to the default run target for
  2018.    "run", "attach", etc. when no target is connected yet.  */
  2019. static int auto_connect_native_target = 1;

  2020. static void
  2021. show_auto_connect_native_target (struct ui_file *file, int from_tty,
  2022.                                  struct cmd_list_element *c, const char *value)
  2023. {
  2024.   fprintf_filtered (file,
  2025.                     _("Whether GDB may automatically connect to the "
  2026.                       "native target is %s.\n"),
  2027.                     value);
  2028. }

  2029. /* Look through the list of possible targets for a target that can
  2030.    execute a run or attach command without any other data.  This is
  2031.    used to locate the default process stratum.

  2032.    If DO_MESG is not NULL, the result is always valid (error() is
  2033.    called for errors); else, return NULL on error.  */

  2034. static struct target_ops *
  2035. find_default_run_target (char *do_mesg)
  2036. {
  2037.   struct target_ops *runable = NULL;

  2038.   if (auto_connect_native_target)
  2039.     {
  2040.       struct target_ops *t;
  2041.       int count = 0;
  2042.       int i;

  2043.       for (i = 0; VEC_iterate (target_ops_p, target_structs, i, t); ++i)
  2044.         {
  2045.           if (t->to_can_run != delegate_can_run && target_can_run (t))
  2046.             {
  2047.               runable = t;
  2048.               ++count;
  2049.             }
  2050.         }

  2051.       if (count != 1)
  2052.         runable = NULL;
  2053.     }

  2054.   if (runable == NULL)
  2055.     {
  2056.       if (do_mesg)
  2057.         error (_("Don't know how to %s.  Try \"help target\"."), do_mesg);
  2058.       else
  2059.         return NULL;
  2060.     }

  2061.   return runable;
  2062. }

  2063. /* See target.h.  */

  2064. struct target_ops *
  2065. find_attach_target (void)
  2066. {
  2067.   struct target_ops *t;

  2068.   /* If a target on the current stack can attach, use it.  */
  2069.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  2070.     {
  2071.       if (t->to_attach != NULL)
  2072.         break;
  2073.     }

  2074.   /* Otherwise, use the default run target for attaching.  */
  2075.   if (t == NULL)
  2076.     t = find_default_run_target ("attach");

  2077.   return t;
  2078. }

  2079. /* See target.h.  */

  2080. struct target_ops *
  2081. find_run_target (void)
  2082. {
  2083.   struct target_ops *t;

  2084.   /* If a target on the current stack can attach, use it.  */
  2085.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  2086.     {
  2087.       if (t->to_create_inferior != NULL)
  2088.         break;
  2089.     }

  2090.   /* Otherwise, use the default run target.  */
  2091.   if (t == NULL)
  2092.     t = find_default_run_target ("run");

  2093.   return t;
  2094. }

  2095. /* Implement the "info proc" command.  */

  2096. int
  2097. target_info_proc (const char *args, enum info_proc_what what)
  2098. {
  2099.   struct target_ops *t;

  2100.   /* If we're already connected to something that can get us OS
  2101.      related data, use it.  Otherwise, try using the native
  2102.      target.  */
  2103.   if (current_target.to_stratum >= process_stratum)
  2104.     t = current_target.beneath;
  2105.   else
  2106.     t = find_default_run_target (NULL);

  2107.   for (; t != NULL; t = t->beneath)
  2108.     {
  2109.       if (t->to_info_proc != NULL)
  2110.         {
  2111.           t->to_info_proc (t, args, what);

  2112.           if (targetdebug)
  2113.             fprintf_unfiltered (gdb_stdlog,
  2114.                                 "target_info_proc (\"%s\", %d)\n", args, what);

  2115.           return 1;
  2116.         }
  2117.     }

  2118.   return 0;
  2119. }

  2120. static int
  2121. find_default_supports_disable_randomization (struct target_ops *self)
  2122. {
  2123.   struct target_ops *t;

  2124.   t = find_default_run_target (NULL);
  2125.   if (t && t->to_supports_disable_randomization)
  2126.     return (t->to_supports_disable_randomization) (t);
  2127.   return 0;
  2128. }

  2129. int
  2130. target_supports_disable_randomization (void)
  2131. {
  2132.   struct target_ops *t;

  2133.   for (t = &current_target; t != NULL; t = t->beneath)
  2134.     if (t->to_supports_disable_randomization)
  2135.       return t->to_supports_disable_randomization (t);

  2136.   return 0;
  2137. }

  2138. char *
  2139. target_get_osdata (const char *type)
  2140. {
  2141.   struct target_ops *t;

  2142.   /* If we're already connected to something that can get us OS
  2143.      related data, use it.  Otherwise, try using the native
  2144.      target.  */
  2145.   if (current_target.to_stratum >= process_stratum)
  2146.     t = current_target.beneath;
  2147.   else
  2148.     t = find_default_run_target ("get OS data");

  2149.   if (!t)
  2150.     return NULL;

  2151.   return target_read_stralloc (t, TARGET_OBJECT_OSDATA, type);
  2152. }

  2153. static struct address_space *
  2154. default_thread_address_space (struct target_ops *self, ptid_t ptid)
  2155. {
  2156.   struct inferior *inf;

  2157.   /* Fall-back to the "main" address space of the inferior.  */
  2158.   inf = find_inferior_ptid (ptid);

  2159.   if (inf == NULL || inf->aspace == NULL)
  2160.     internal_error (__FILE__, __LINE__,
  2161.                     _("Can't determine the current "
  2162.                       "address space of thread %s\n"),
  2163.                     target_pid_to_str (ptid));

  2164.   return inf->aspace;
  2165. }

  2166. /* Determine the current address space of thread PTID.  */

  2167. struct address_space *
  2168. target_thread_address_space (ptid_t ptid)
  2169. {
  2170.   struct address_space *aspace;

  2171.   aspace = current_target.to_thread_address_space (&current_target, ptid);
  2172.   gdb_assert (aspace != NULL);

  2173.   return aspace;
  2174. }


  2175. /* Target file operations.  */

  2176. static struct target_ops *
  2177. default_fileio_target (void)
  2178. {
  2179.   /* If we're already connected to something that can perform
  2180.      file I/O, use it. Otherwise, try using the native target.  */
  2181.   if (current_target.to_stratum >= process_stratum)
  2182.     return current_target.beneath;
  2183.   else
  2184.     return find_default_run_target ("file I/O");
  2185. }

  2186. /* Open FILENAME on the target, using FLAGS and MODE.  Return a
  2187.    target file descriptor, or -1 if an error occurs (and set
  2188.    *TARGET_ERRNO).  */
  2189. int
  2190. target_fileio_open (const char *filename, int flags, int mode,
  2191.                     int *target_errno)
  2192. {
  2193.   struct target_ops *t;

  2194.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2195.     {
  2196.       if (t->to_fileio_open != NULL)
  2197.         {
  2198.           int fd = t->to_fileio_open (t, filename, flags, mode, target_errno);

  2199.           if (targetdebug)
  2200.             fprintf_unfiltered (gdb_stdlog,
  2201.                                 "target_fileio_open (%s,0x%x,0%o) = %d (%d)\n",
  2202.                                 filename, flags, mode,
  2203.                                 fd, fd != -1 ? 0 : *target_errno);
  2204.           return fd;
  2205.         }
  2206.     }

  2207.   *target_errno = FILEIO_ENOSYS;
  2208.   return -1;
  2209. }

  2210. /* Write up to LEN bytes from WRITE_BUF to FD on the target.
  2211.    Return the number of bytes written, or -1 if an error occurs
  2212.    (and set *TARGET_ERRNO).  */
  2213. int
  2214. target_fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
  2215.                       ULONGEST offset, int *target_errno)
  2216. {
  2217.   struct target_ops *t;

  2218.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2219.     {
  2220.       if (t->to_fileio_pwrite != NULL)
  2221.         {
  2222.           int ret = t->to_fileio_pwrite (t, fd, write_buf, len, offset,
  2223.                                          target_errno);

  2224.           if (targetdebug)
  2225.             fprintf_unfiltered (gdb_stdlog,
  2226.                                 "target_fileio_pwrite (%d,...,%d,%s) "
  2227.                                 "= %d (%d)\n",
  2228.                                 fd, len, pulongest (offset),
  2229.                                 ret, ret != -1 ? 0 : *target_errno);
  2230.           return ret;
  2231.         }
  2232.     }

  2233.   *target_errno = FILEIO_ENOSYS;
  2234.   return -1;
  2235. }

  2236. /* Read up to LEN bytes FD on the target into READ_BUF.
  2237.    Return the number of bytes read, or -1 if an error occurs
  2238.    (and set *TARGET_ERRNO).  */
  2239. int
  2240. target_fileio_pread (int fd, gdb_byte *read_buf, int len,
  2241.                      ULONGEST offset, int *target_errno)
  2242. {
  2243.   struct target_ops *t;

  2244.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2245.     {
  2246.       if (t->to_fileio_pread != NULL)
  2247.         {
  2248.           int ret = t->to_fileio_pread (t, fd, read_buf, len, offset,
  2249.                                         target_errno);

  2250.           if (targetdebug)
  2251.             fprintf_unfiltered (gdb_stdlog,
  2252.                                 "target_fileio_pread (%d,...,%d,%s) "
  2253.                                 "= %d (%d)\n",
  2254.                                 fd, len, pulongest (offset),
  2255.                                 ret, ret != -1 ? 0 : *target_errno);
  2256.           return ret;
  2257.         }
  2258.     }

  2259.   *target_errno = FILEIO_ENOSYS;
  2260.   return -1;
  2261. }

  2262. /* Close FD on the target.  Return 0, or -1 if an error occurs
  2263.    (and set *TARGET_ERRNO).  */
  2264. int
  2265. target_fileio_close (int fd, int *target_errno)
  2266. {
  2267.   struct target_ops *t;

  2268.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2269.     {
  2270.       if (t->to_fileio_close != NULL)
  2271.         {
  2272.           int ret = t->to_fileio_close (t, fd, target_errno);

  2273.           if (targetdebug)
  2274.             fprintf_unfiltered (gdb_stdlog,
  2275.                                 "target_fileio_close (%d) = %d (%d)\n",
  2276.                                 fd, ret, ret != -1 ? 0 : *target_errno);
  2277.           return ret;
  2278.         }
  2279.     }

  2280.   *target_errno = FILEIO_ENOSYS;
  2281.   return -1;
  2282. }

  2283. /* Unlink FILENAME on the target.  Return 0, or -1 if an error
  2284.    occurs (and set *TARGET_ERRNO).  */
  2285. int
  2286. target_fileio_unlink (const char *filename, int *target_errno)
  2287. {
  2288.   struct target_ops *t;

  2289.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2290.     {
  2291.       if (t->to_fileio_unlink != NULL)
  2292.         {
  2293.           int ret = t->to_fileio_unlink (t, filename, target_errno);

  2294.           if (targetdebug)
  2295.             fprintf_unfiltered (gdb_stdlog,
  2296.                                 "target_fileio_unlink (%s) = %d (%d)\n",
  2297.                                 filename, ret, ret != -1 ? 0 : *target_errno);
  2298.           return ret;
  2299.         }
  2300.     }

  2301.   *target_errno = FILEIO_ENOSYS;
  2302.   return -1;
  2303. }

  2304. /* Read value of symbolic link FILENAME on the target.  Return a
  2305.    null-terminated string allocated via xmalloc, or NULL if an error
  2306.    occurs (and set *TARGET_ERRNO).  */
  2307. char *
  2308. target_fileio_readlink (const char *filename, int *target_errno)
  2309. {
  2310.   struct target_ops *t;

  2311.   for (t = default_fileio_target (); t != NULL; t = t->beneath)
  2312.     {
  2313.       if (t->to_fileio_readlink != NULL)
  2314.         {
  2315.           char *ret = t->to_fileio_readlink (t, filename, target_errno);

  2316.           if (targetdebug)
  2317.             fprintf_unfiltered (gdb_stdlog,
  2318.                                 "target_fileio_readlink (%s) = %s (%d)\n",
  2319.                                 filename, ret? ret : "(nil)",
  2320.                                 ret? 0 : *target_errno);
  2321.           return ret;
  2322.         }
  2323.     }

  2324.   *target_errno = FILEIO_ENOSYS;
  2325.   return NULL;
  2326. }

  2327. static void
  2328. target_fileio_close_cleanup (void *opaque)
  2329. {
  2330.   int fd = *(int *) opaque;
  2331.   int target_errno;

  2332.   target_fileio_close (fd, &target_errno);
  2333. }

  2334. /* Read target file FILENAME.  Store the result in *BUF_P and
  2335.    return the size of the transferred data.  PADDING additional bytes are
  2336.    available in *BUF_P.  This is a helper function for
  2337.    target_fileio_read_alloc; see the declaration of that function for more
  2338.    information.  */

  2339. static LONGEST
  2340. target_fileio_read_alloc_1 (const char *filename,
  2341.                             gdb_byte **buf_p, int padding)
  2342. {
  2343.   struct cleanup *close_cleanup;
  2344.   size_t buf_alloc, buf_pos;
  2345.   gdb_byte *buf;
  2346.   LONGEST n;
  2347.   int fd;
  2348.   int target_errno;

  2349.   fd = target_fileio_open (filename, FILEIO_O_RDONLY, 0700, &target_errno);
  2350.   if (fd == -1)
  2351.     return -1;

  2352.   close_cleanup = make_cleanup (target_fileio_close_cleanup, &fd);

  2353.   /* Start by reading up to 4K at a time.  The target will throttle
  2354.      this number down if necessary.  */
  2355.   buf_alloc = 4096;
  2356.   buf = xmalloc (buf_alloc);
  2357.   buf_pos = 0;
  2358.   while (1)
  2359.     {
  2360.       n = target_fileio_pread (fd, &buf[buf_pos],
  2361.                                buf_alloc - buf_pos - padding, buf_pos,
  2362.                                &target_errno);
  2363.       if (n < 0)
  2364.         {
  2365.           /* An error occurred.  */
  2366.           do_cleanups (close_cleanup);
  2367.           xfree (buf);
  2368.           return -1;
  2369.         }
  2370.       else if (n == 0)
  2371.         {
  2372.           /* Read all there was.  */
  2373.           do_cleanups (close_cleanup);
  2374.           if (buf_pos == 0)
  2375.             xfree (buf);
  2376.           else
  2377.             *buf_p = buf;
  2378.           return buf_pos;
  2379.         }

  2380.       buf_pos += n;

  2381.       /* If the buffer is filling up, expand it.  */
  2382.       if (buf_alloc < buf_pos * 2)
  2383.         {
  2384.           buf_alloc *= 2;
  2385.           buf = xrealloc (buf, buf_alloc);
  2386.         }

  2387.       QUIT;
  2388.     }
  2389. }

  2390. /* Read target file FILENAME.  Store the result in *BUF_P and return
  2391.    the size of the transferred data.  See the declaration in "target.h"
  2392.    function for more information about the return value.  */

  2393. LONGEST
  2394. target_fileio_read_alloc (const char *filename, gdb_byte **buf_p)
  2395. {
  2396.   return target_fileio_read_alloc_1 (filename, buf_p, 0);
  2397. }

  2398. /* Read target file FILENAME.  The result is NUL-terminated and
  2399.    returned as a string, allocated using xmalloc.  If an error occurs
  2400.    or the transfer is unsupported, NULL is returned.  Empty objects
  2401.    are returned as allocated but empty strings.  A warning is issued
  2402.    if the result contains any embedded NUL bytes.  */

  2403. char *
  2404. target_fileio_read_stralloc (const char *filename)
  2405. {
  2406.   gdb_byte *buffer;
  2407.   char *bufstr;
  2408.   LONGEST i, transferred;

  2409.   transferred = target_fileio_read_alloc_1 (filename, &buffer, 1);
  2410.   bufstr = (char *) buffer;

  2411.   if (transferred < 0)
  2412.     return NULL;

  2413.   if (transferred == 0)
  2414.     return xstrdup ("");

  2415.   bufstr[transferred] = 0;

  2416.   /* Check for embedded NUL bytes; but allow trailing NULs.  */
  2417.   for (i = strlen (bufstr); i < transferred; i++)
  2418.     if (bufstr[i] != 0)
  2419.       {
  2420.         warning (_("target file %s "
  2421.                    "contained unexpected null characters"),
  2422.                  filename);
  2423.         break;
  2424.       }

  2425.   return bufstr;
  2426. }


  2427. static int
  2428. default_region_ok_for_hw_watchpoint (struct target_ops *self,
  2429.                                      CORE_ADDR addr, int len)
  2430. {
  2431.   return (len <= gdbarch_ptr_bit (target_gdbarch ()) / TARGET_CHAR_BIT);
  2432. }

  2433. static int
  2434. default_watchpoint_addr_within_range (struct target_ops *target,
  2435.                                       CORE_ADDR addr,
  2436.                                       CORE_ADDR start, int length)
  2437. {
  2438.   return addr >= start && addr < start + length;
  2439. }

  2440. static struct gdbarch *
  2441. default_thread_architecture (struct target_ops *ops, ptid_t ptid)
  2442. {
  2443.   return target_gdbarch ();
  2444. }

  2445. static int
  2446. return_zero (struct target_ops *ignore)
  2447. {
  2448.   return 0;
  2449. }

  2450. static int
  2451. return_zero_has_execution (struct target_ops *ignore, ptid_t ignore2)
  2452. {
  2453.   return 0;
  2454. }

  2455. /*
  2456. * Find the next target down the stack from the specified target.
  2457. */

  2458. struct target_ops *
  2459. find_target_beneath (struct target_ops *t)
  2460. {
  2461.   return t->beneath;
  2462. }

  2463. /* See target.h.  */

  2464. struct target_ops *
  2465. find_target_at (enum strata stratum)
  2466. {
  2467.   struct target_ops *t;

  2468.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  2469.     if (t->to_stratum == stratum)
  2470.       return t;

  2471.   return NULL;
  2472. }


  2473. /* The inferior process has died.  Long live the inferior!  */

  2474. void
  2475. generic_mourn_inferior (void)
  2476. {
  2477.   ptid_t ptid;

  2478.   ptid = inferior_ptid;
  2479.   inferior_ptid = null_ptid;

  2480.   /* Mark breakpoints uninserted in case something tries to delete a
  2481.      breakpoint while we delete the inferior's threads (which would
  2482.      fail, since the inferior is long gone).  */
  2483.   mark_breakpoints_out ();

  2484.   if (!ptid_equal (ptid, null_ptid))
  2485.     {
  2486.       int pid = ptid_get_pid (ptid);
  2487.       exit_inferior (pid);
  2488.     }

  2489.   /* Note this wipes step-resume breakpoints, so needs to be done
  2490.      after exit_inferior, which ends up referencing the step-resume
  2491.      breakpoints through clear_thread_inferior_resources.  */
  2492.   breakpoint_init_inferior (inf_exited);

  2493.   registers_changed ();

  2494.   reopen_exec_file ();
  2495.   reinit_frame_cache ();

  2496.   if (deprecated_detach_hook)
  2497.     deprecated_detach_hook ();
  2498. }

  2499. /* Convert a normal process ID to a string.  Returns the string in a
  2500.    static buffer.  */

  2501. char *
  2502. normal_pid_to_str (ptid_t ptid)
  2503. {
  2504.   static char buf[32];

  2505.   xsnprintf (buf, sizeof buf, "process %d", ptid_get_pid (ptid));
  2506.   return buf;
  2507. }

  2508. static char *
  2509. default_pid_to_str (struct target_ops *ops, ptid_t ptid)
  2510. {
  2511.   return normal_pid_to_str (ptid);
  2512. }

  2513. /* Error-catcher for target_find_memory_regions.  */
  2514. static int
  2515. dummy_find_memory_regions (struct target_ops *self,
  2516.                            find_memory_region_ftype ignore1, void *ignore2)
  2517. {
  2518.   error (_("Command not implemented for this target."));
  2519.   return 0;
  2520. }

  2521. /* Error-catcher for target_make_corefile_notes.  */
  2522. static char *
  2523. dummy_make_corefile_notes (struct target_ops *self,
  2524.                            bfd *ignore1, int *ignore2)
  2525. {
  2526.   error (_("Command not implemented for this target."));
  2527.   return NULL;
  2528. }

  2529. /* Set up the handful of non-empty slots needed by the dummy target
  2530.    vector.  */

  2531. static void
  2532. init_dummy_target (void)
  2533. {
  2534.   dummy_target.to_shortname = "None";
  2535.   dummy_target.to_longname = "None";
  2536.   dummy_target.to_doc = "";
  2537.   dummy_target.to_supports_disable_randomization
  2538.     = find_default_supports_disable_randomization;
  2539.   dummy_target.to_stratum = dummy_stratum;
  2540.   dummy_target.to_has_all_memory = return_zero;
  2541.   dummy_target.to_has_memory = return_zero;
  2542.   dummy_target.to_has_stack = return_zero;
  2543.   dummy_target.to_has_registers = return_zero;
  2544.   dummy_target.to_has_execution = return_zero_has_execution;
  2545.   dummy_target.to_magic = OPS_MAGIC;

  2546.   install_dummy_methods (&dummy_target);
  2547. }


  2548. void
  2549. target_close (struct target_ops *targ)
  2550. {
  2551.   gdb_assert (!target_is_pushed (targ));

  2552.   if (targ->to_xclose != NULL)
  2553.     targ->to_xclose (targ);
  2554.   else if (targ->to_close != NULL)
  2555.     targ->to_close (targ);

  2556.   if (targetdebug)
  2557.     fprintf_unfiltered (gdb_stdlog, "target_close ()\n");
  2558. }

  2559. int
  2560. target_thread_alive (ptid_t ptid)
  2561. {
  2562.   return current_target.to_thread_alive (&current_target, ptid);
  2563. }

  2564. void
  2565. target_update_thread_list (void)
  2566. {
  2567.   current_target.to_update_thread_list (&current_target);
  2568. }

  2569. void
  2570. target_stop (ptid_t ptid)
  2571. {
  2572.   if (!may_stop)
  2573.     {
  2574.       warning (_("May not interrupt or stop the target, ignoring attempt"));
  2575.       return;
  2576.     }

  2577.   (*current_target.to_stop) (&current_target, ptid);
  2578. }

  2579. /* See target/target.h.  */

  2580. void
  2581. target_stop_and_wait (ptid_t ptid)
  2582. {
  2583.   struct target_waitstatus status;
  2584.   int was_non_stop = non_stop;

  2585.   non_stop = 1;
  2586.   target_stop (ptid);

  2587.   memset (&status, 0, sizeof (status));
  2588.   target_wait (ptid, &status, 0);

  2589.   non_stop = was_non_stop;
  2590. }

  2591. /* See target/target.h.  */

  2592. void
  2593. target_continue_no_signal (ptid_t ptid)
  2594. {
  2595.   target_resume (ptid, 0, GDB_SIGNAL_0);
  2596. }

  2597. /* Concatenate ELEM to LIST, a comma separate list, and return the
  2598.    result.  The LIST incoming argument is released.  */

  2599. static char *
  2600. str_comma_list_concat_elem (char *list, const char *elem)
  2601. {
  2602.   if (list == NULL)
  2603.     return xstrdup (elem);
  2604.   else
  2605.     return reconcat (list, list, ", ", elem, (char *) NULL);
  2606. }

  2607. /* Helper for target_options_to_string.  If OPT is present in
  2608.    TARGET_OPTIONS, append the OPT_STR (string version of OPT) in RET.
  2609.    Returns the new resulting string.  OPT is removed from
  2610.    TARGET_OPTIONS.  */

  2611. static char *
  2612. do_option (int *target_options, char *ret,
  2613.            int opt, char *opt_str)
  2614. {
  2615.   if ((*target_options & opt) != 0)
  2616.     {
  2617.       ret = str_comma_list_concat_elem (ret, opt_str);
  2618.       *target_options &= ~opt;
  2619.     }

  2620.   return ret;
  2621. }

  2622. char *
  2623. target_options_to_string (int target_options)
  2624. {
  2625.   char *ret = NULL;

  2626. #define DO_TARG_OPTION(OPT) \
  2627.   ret = do_option (&target_options, ret, OPT, #OPT)

  2628.   DO_TARG_OPTION (TARGET_WNOHANG);

  2629.   if (target_options != 0)
  2630.     ret = str_comma_list_concat_elem (ret, "unknown???");

  2631.   if (ret == NULL)
  2632.     ret = xstrdup ("");
  2633.   return ret;
  2634. }

  2635. static void
  2636. debug_print_register (const char * func,
  2637.                       struct regcache *regcache, int regno)
  2638. {
  2639.   struct gdbarch *gdbarch = get_regcache_arch (regcache);

  2640.   fprintf_unfiltered (gdb_stdlog, "%s ", func);
  2641.   if (regno >= 0 && regno < gdbarch_num_regs (gdbarch)
  2642.       && gdbarch_register_name (gdbarch, regno) != NULL
  2643.       && gdbarch_register_name (gdbarch, regno)[0] != '\0')
  2644.     fprintf_unfiltered (gdb_stdlog, "(%s)",
  2645.                         gdbarch_register_name (gdbarch, regno));
  2646.   else
  2647.     fprintf_unfiltered (gdb_stdlog, "(%d)", regno);
  2648.   if (regno >= 0 && regno < gdbarch_num_regs (gdbarch))
  2649.     {
  2650.       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  2651.       int i, size = register_size (gdbarch, regno);
  2652.       gdb_byte buf[MAX_REGISTER_SIZE];

  2653.       regcache_raw_collect (regcache, regno, buf);
  2654.       fprintf_unfiltered (gdb_stdlog, " = ");
  2655.       for (i = 0; i < size; i++)
  2656.         {
  2657.           fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
  2658.         }
  2659.       if (size <= sizeof (LONGEST))
  2660.         {
  2661.           ULONGEST val = extract_unsigned_integer (buf, size, byte_order);

  2662.           fprintf_unfiltered (gdb_stdlog, " %s %s",
  2663.                               core_addr_to_string_nz (val), plongest (val));
  2664.         }
  2665.     }
  2666.   fprintf_unfiltered (gdb_stdlog, "\n");
  2667. }

  2668. void
  2669. target_fetch_registers (struct regcache *regcache, int regno)
  2670. {
  2671.   current_target.to_fetch_registers (&current_target, regcache, regno);
  2672.   if (targetdebug)
  2673.     debug_print_register ("target_fetch_registers", regcache, regno);
  2674. }

  2675. void
  2676. target_store_registers (struct regcache *regcache, int regno)
  2677. {
  2678.   struct target_ops *t;

  2679.   if (!may_write_registers)
  2680.     error (_("Writing to registers is not allowed (regno %d)"), regno);

  2681.   current_target.to_store_registers (&current_target, regcache, regno);
  2682.   if (targetdebug)
  2683.     {
  2684.       debug_print_register ("target_store_registers", regcache, regno);
  2685.     }
  2686. }

  2687. int
  2688. target_core_of_thread (ptid_t ptid)
  2689. {
  2690.   return current_target.to_core_of_thread (&current_target, ptid);
  2691. }

  2692. int
  2693. simple_verify_memory (struct target_ops *ops,
  2694.                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
  2695. {
  2696.   LONGEST total_xfered = 0;

  2697.   while (total_xfered < size)
  2698.     {
  2699.       ULONGEST xfered_len;
  2700.       enum target_xfer_status status;
  2701.       gdb_byte buf[1024];
  2702.       ULONGEST howmuch = min (sizeof (buf), size - total_xfered);

  2703.       status = target_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
  2704.                                     buf, NULL, lma + total_xfered, howmuch,
  2705.                                     &xfered_len);
  2706.       if (status == TARGET_XFER_OK
  2707.           && memcmp (data + total_xfered, buf, xfered_len) == 0)
  2708.         {
  2709.           total_xfered += xfered_len;
  2710.           QUIT;
  2711.         }
  2712.       else
  2713.         return 0;
  2714.     }
  2715.   return 1;
  2716. }

  2717. /* Default implementation of memory verification.  */

  2718. static int
  2719. default_verify_memory (struct target_ops *self,
  2720.                        const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
  2721. {
  2722.   /* Start over from the top of the target stack.  */
  2723.   return simple_verify_memory (current_target.beneath,
  2724.                                data, memaddr, size);
  2725. }

  2726. int
  2727. target_verify_memory (const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
  2728. {
  2729.   return current_target.to_verify_memory (&current_target,
  2730.                                           data, memaddr, size);
  2731. }

  2732. /* The documentation for this function is in its prototype declaration in
  2733.    target.h.  */

  2734. int
  2735. target_insert_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask, int rw)
  2736. {
  2737.   return current_target.to_insert_mask_watchpoint (&current_target,
  2738.                                                    addr, mask, rw);
  2739. }

  2740. /* The documentation for this function is in its prototype declaration in
  2741.    target.h.  */

  2742. int
  2743. target_remove_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask, int rw)
  2744. {
  2745.   return current_target.to_remove_mask_watchpoint (&current_target,
  2746.                                                    addr, mask, rw);
  2747. }

  2748. /* The documentation for this function is in its prototype declaration
  2749.    in target.h.  */

  2750. int
  2751. target_masked_watch_num_registers (CORE_ADDR addr, CORE_ADDR mask)
  2752. {
  2753.   return current_target.to_masked_watch_num_registers (&current_target,
  2754.                                                        addr, mask);
  2755. }

  2756. /* The documentation for this function is in its prototype declaration
  2757.    in target.h.  */

  2758. int
  2759. target_ranged_break_num_registers (void)
  2760. {
  2761.   return current_target.to_ranged_break_num_registers (&current_target);
  2762. }

  2763. /* See target.h.  */

  2764. struct btrace_target_info *
  2765. target_enable_btrace (ptid_t ptid)
  2766. {
  2767.   return current_target.to_enable_btrace (&current_target, ptid);
  2768. }

  2769. /* See target.h.  */

  2770. void
  2771. target_disable_btrace (struct btrace_target_info *btinfo)
  2772. {
  2773.   current_target.to_disable_btrace (&current_target, btinfo);
  2774. }

  2775. /* See target.h.  */

  2776. void
  2777. target_teardown_btrace (struct btrace_target_info *btinfo)
  2778. {
  2779.   current_target.to_teardown_btrace (&current_target, btinfo);
  2780. }

  2781. /* See target.h.  */

  2782. enum btrace_error
  2783. target_read_btrace (VEC (btrace_block_s) **btrace,
  2784.                     struct btrace_target_info *btinfo,
  2785.                     enum btrace_read_type type)
  2786. {
  2787.   return current_target.to_read_btrace (&current_target, btrace, btinfo, type);
  2788. }

  2789. /* See target.h.  */

  2790. void
  2791. target_stop_recording (void)
  2792. {
  2793.   current_target.to_stop_recording (&current_target);
  2794. }

  2795. /* See target.h.  */

  2796. void
  2797. target_save_record (const char *filename)
  2798. {
  2799.   current_target.to_save_record (&current_target, filename);
  2800. }

  2801. /* See target.h.  */

  2802. int
  2803. target_supports_delete_record (void)
  2804. {
  2805.   struct target_ops *t;

  2806.   for (t = current_target.beneath; t != NULL; t = t->beneath)
  2807.     if (t->to_delete_record != delegate_delete_record
  2808.         && t->to_delete_record != tdefault_delete_record)
  2809.       return 1;

  2810.   return 0;
  2811. }

  2812. /* See target.h.  */

  2813. void
  2814. target_delete_record (void)
  2815. {
  2816.   current_target.to_delete_record (&current_target);
  2817. }

  2818. /* See target.h.  */

  2819. int
  2820. target_record_is_replaying (void)
  2821. {
  2822.   return current_target.to_record_is_replaying (&current_target);
  2823. }

  2824. /* See target.h.  */

  2825. void
  2826. target_goto_record_begin (void)
  2827. {
  2828.   current_target.to_goto_record_begin (&current_target);
  2829. }

  2830. /* See target.h.  */

  2831. void
  2832. target_goto_record_end (void)
  2833. {
  2834.   current_target.to_goto_record_end (&current_target);
  2835. }

  2836. /* See target.h.  */

  2837. void
  2838. target_goto_record (ULONGEST insn)
  2839. {
  2840.   current_target.to_goto_record (&current_target, insn);
  2841. }

  2842. /* See target.h.  */

  2843. void
  2844. target_insn_history (int size, int flags)
  2845. {
  2846.   current_target.to_insn_history (&current_target, size, flags);
  2847. }

  2848. /* See target.h.  */

  2849. void
  2850. target_insn_history_from (ULONGEST from, int size, int flags)
  2851. {
  2852.   current_target.to_insn_history_from (&current_target, from, size, flags);
  2853. }

  2854. /* See target.h.  */

  2855. void
  2856. target_insn_history_range (ULONGEST begin, ULONGEST end, int flags)
  2857. {
  2858.   current_target.to_insn_history_range (&current_target, begin, end, flags);
  2859. }

  2860. /* See target.h.  */

  2861. void
  2862. target_call_history (int size, int flags)
  2863. {
  2864.   current_target.to_call_history (&current_target, size, flags);
  2865. }

  2866. /* See target.h.  */

  2867. void
  2868. target_call_history_from (ULONGEST begin, int size, int flags)
  2869. {
  2870.   current_target.to_call_history_from (&current_target, begin, size, flags);
  2871. }

  2872. /* See target.h.  */

  2873. void
  2874. target_call_history_range (ULONGEST begin, ULONGEST end, int flags)
  2875. {
  2876.   current_target.to_call_history_range (&current_target, begin, end, flags);
  2877. }

  2878. /* See target.h.  */

  2879. const struct frame_unwind *
  2880. target_get_unwinder (void)
  2881. {
  2882.   return current_target.to_get_unwinder (&current_target);
  2883. }

  2884. /* See target.h.  */

  2885. const struct frame_unwind *
  2886. target_get_tailcall_unwinder (void)
  2887. {
  2888.   return current_target.to_get_tailcall_unwinder (&current_target);
  2889. }

  2890. /* Default implementation of to_decr_pc_after_break.  */

  2891. static CORE_ADDR
  2892. default_target_decr_pc_after_break (struct target_ops *ops,
  2893.                                     struct gdbarch *gdbarch)
  2894. {
  2895.   return gdbarch_decr_pc_after_break (gdbarch);
  2896. }

  2897. /* See target.h.  */

  2898. CORE_ADDR
  2899. target_decr_pc_after_break (struct gdbarch *gdbarch)
  2900. {
  2901.   return current_target.to_decr_pc_after_break (&current_target, gdbarch);
  2902. }

  2903. /* See target.h.  */

  2904. void
  2905. target_prepare_to_generate_core (void)
  2906. {
  2907.   current_target.to_prepare_to_generate_core (&current_target);
  2908. }

  2909. /* See target.h.  */

  2910. void
  2911. target_done_generating_core (void)
  2912. {
  2913.   current_target.to_done_generating_core (&current_target);
  2914. }

  2915. static void
  2916. setup_target_debug (void)
  2917. {
  2918.   memcpy (&debug_target, &current_target, sizeof debug_target);

  2919.   init_debug_target (&current_target);
  2920. }


  2921. static char targ_desc[] =
  2922. "Names of targets and files being debugged.\nShows the entire \
  2923. stack of targets currently in use (including the exec-file,\n\
  2924. core-file, and process, if any), as well as the symbol file name.";

  2925. static void
  2926. default_rcmd (struct target_ops *self, const char *command,
  2927.               struct ui_file *output)
  2928. {
  2929.   error (_("\"monitor\" command not supported by this target."));
  2930. }

  2931. static void
  2932. do_monitor_command (char *cmd,
  2933.                  int from_tty)
  2934. {
  2935.   target_rcmd (cmd, gdb_stdtarg);
  2936. }

  2937. /* Print the name of each layers of our target stack.  */

  2938. static void
  2939. maintenance_print_target_stack (char *cmd, int from_tty)
  2940. {
  2941.   struct target_ops *t;

  2942.   printf_filtered (_("The current target stack is:\n"));

  2943.   for (t = target_stack; t != NULL; t = t->beneath)
  2944.     {
  2945.       printf_filtered ("  - %s (%s)\n", t->to_shortname, t->to_longname);
  2946.     }
  2947. }

  2948. /* Controls if targets can report that they can/are async.  This is
  2949.    just for maintainers to use when debugging gdb.  */
  2950. int target_async_permitted = 1;

  2951. /* The set command writes to this variable.  If the inferior is
  2952.    executing, target_async_permitted is *not* updated.  */
  2953. static int target_async_permitted_1 = 1;

  2954. static void
  2955. maint_set_target_async_command (char *args, int from_tty,
  2956.                                 struct cmd_list_element *c)
  2957. {
  2958.   if (have_live_inferiors ())
  2959.     {
  2960.       target_async_permitted_1 = target_async_permitted;
  2961.       error (_("Cannot change this setting while the inferior is running."));
  2962.     }

  2963.   target_async_permitted = target_async_permitted_1;
  2964. }

  2965. static void
  2966. maint_show_target_async_command (struct ui_file *file, int from_tty,
  2967.                                  struct cmd_list_element *c,
  2968.                                  const char *value)
  2969. {
  2970.   fprintf_filtered (file,
  2971.                     _("Controlling the inferior in "
  2972.                       "asynchronous mode is %s.\n"), value);
  2973. }

  2974. /* Temporary copies of permission settings.  */

  2975. static int may_write_registers_1 = 1;
  2976. static int may_write_memory_1 = 1;
  2977. static int may_insert_breakpoints_1 = 1;
  2978. static int may_insert_tracepoints_1 = 1;
  2979. static int may_insert_fast_tracepoints_1 = 1;
  2980. static int may_stop_1 = 1;

  2981. /* Make the user-set values match the real values again.  */

  2982. void
  2983. update_target_permissions (void)
  2984. {
  2985.   may_write_registers_1 = may_write_registers;
  2986.   may_write_memory_1 = may_write_memory;
  2987.   may_insert_breakpoints_1 = may_insert_breakpoints;
  2988.   may_insert_tracepoints_1 = may_insert_tracepoints;
  2989.   may_insert_fast_tracepoints_1 = may_insert_fast_tracepoints;
  2990.   may_stop_1 = may_stop;
  2991. }

  2992. /* The one function handles (most of) the permission flags in the same
  2993.    way.  */

  2994. static void
  2995. set_target_permissions (char *args, int from_tty,
  2996.                         struct cmd_list_element *c)
  2997. {
  2998.   if (target_has_execution)
  2999.     {
  3000.       update_target_permissions ();
  3001.       error (_("Cannot change this setting while the inferior is running."));
  3002.     }

  3003.   /* Make the real values match the user-changed values.  */
  3004.   may_write_registers = may_write_registers_1;
  3005.   may_insert_breakpoints = may_insert_breakpoints_1;
  3006.   may_insert_tracepoints = may_insert_tracepoints_1;
  3007.   may_insert_fast_tracepoints = may_insert_fast_tracepoints_1;
  3008.   may_stop = may_stop_1;
  3009.   update_observer_mode ();
  3010. }

  3011. /* Set memory write permission independently of observer mode.  */

  3012. static void
  3013. set_write_memory_permission (char *args, int from_tty,
  3014.                         struct cmd_list_element *c)
  3015. {
  3016.   /* Make the real values match the user-changed values.  */
  3017.   may_write_memory = may_write_memory_1;
  3018.   update_observer_mode ();
  3019. }


  3020. void
  3021. initialize_targets (void)
  3022. {
  3023.   init_dummy_target ();
  3024.   push_target (&dummy_target);

  3025.   add_info ("target", target_info, targ_desc);
  3026.   add_info ("files", target_info, targ_desc);

  3027.   add_setshow_zuinteger_cmd ("target", class_maintenance, &targetdebug, _("\
  3028. Set target debugging."), _("\
  3029. Show target debugging."), _("\
  3030. When non-zero, target debugging is enabled.  Higher numbers are more\n\
  3031. verbose."),
  3032.                              set_targetdebug,
  3033.                              show_targetdebug,
  3034.                              &setdebuglist, &showdebuglist);

  3035.   add_setshow_boolean_cmd ("trust-readonly-sections", class_support,
  3036.                            &trust_readonly, _("\
  3037. Set mode for reading from readonly sections."), _("\
  3038. Show mode for reading from readonly sections."), _("\
  3039. When this mode is on, memory reads from readonly sections (such as .text)\n\
  3040. will be read from the object file instead of from the target.  This will\n\
  3041. result in significant performance improvement for remote targets."),
  3042.                            NULL,
  3043.                            show_trust_readonly,
  3044.                            &setlist, &showlist);

  3045.   add_com ("monitor", class_obscure, do_monitor_command,
  3046.            _("Send a command to the remote monitor (remote targets only)."));

  3047.   add_cmd ("target-stack", class_maintenance, maintenance_print_target_stack,
  3048.            _("Print the name of each layer of the internal target stack."),
  3049.            &maintenanceprintlist);

  3050.   add_setshow_boolean_cmd ("target-async", no_class,
  3051.                            &target_async_permitted_1, _("\
  3052. Set whether gdb controls the inferior in asynchronous mode."), _("\
  3053. Show whether gdb controls the inferior in asynchronous mode."), _("\
  3054. Tells gdb whether to control the inferior in asynchronous mode."),
  3055.                            maint_set_target_async_command,
  3056.                            maint_show_target_async_command,
  3057.                            &maintenance_set_cmdlist,
  3058.                            &maintenance_show_cmdlist);

  3059.   add_setshow_boolean_cmd ("may-write-registers", class_support,
  3060.                            &may_write_registers_1, _("\
  3061. Set permission to write into registers."), _("\
  3062. Show permission to write into registers."), _("\
  3063. When this permission is on, GDB may write into the target's registers.\n\
  3064. Otherwise, any sort of write attempt will result in an error."),
  3065.                            set_target_permissions, NULL,
  3066.                            &setlist, &showlist);

  3067.   add_setshow_boolean_cmd ("may-write-memory", class_support,
  3068.                            &may_write_memory_1, _("\
  3069. Set permission to write into target memory."), _("\
  3070. Show permission to write into target memory."), _("\
  3071. When this permission is on, GDB may write into the target's memory.\n\
  3072. Otherwise, any sort of write attempt will result in an error."),
  3073.                            set_write_memory_permission, NULL,
  3074.                            &setlist, &showlist);

  3075.   add_setshow_boolean_cmd ("may-insert-breakpoints", class_support,
  3076.                            &may_insert_breakpoints_1, _("\
  3077. Set permission to insert breakpoints in the target."), _("\
  3078. Show permission to insert breakpoints in the target."), _("\
  3079. When this permission is on, GDB may insert breakpoints in the program.\n\
  3080. Otherwise, any sort of insertion attempt will result in an error."),
  3081.                            set_target_permissions, NULL,
  3082.                            &setlist, &showlist);

  3083.   add_setshow_boolean_cmd ("may-insert-tracepoints", class_support,
  3084.                            &may_insert_tracepoints_1, _("\
  3085. Set permission to insert tracepoints in the target."), _("\
  3086. Show permission to insert tracepoints in the target."), _("\
  3087. When this permission is on, GDB may insert tracepoints in the program.\n\
  3088. Otherwise, any sort of insertion attempt will result in an error."),
  3089.                            set_target_permissions, NULL,
  3090.                            &setlist, &showlist);

  3091.   add_setshow_boolean_cmd ("may-insert-fast-tracepoints", class_support,
  3092.                            &may_insert_fast_tracepoints_1, _("\
  3093. Set permission to insert fast tracepoints in the target."), _("\
  3094. Show permission to insert fast tracepoints in the target."), _("\
  3095. When this permission is on, GDB may insert fast tracepoints.\n\
  3096. Otherwise, any sort of insertion attempt will result in an error."),
  3097.                            set_target_permissions, NULL,
  3098.                            &setlist, &showlist);

  3099.   add_setshow_boolean_cmd ("may-interrupt", class_support,
  3100.                            &may_stop_1, _("\
  3101. Set permission to interrupt or signal the target."), _("\
  3102. Show permission to interrupt or signal the target."), _("\
  3103. When this permission is on, GDB may interrupt/stop the target's execution.\n\
  3104. Otherwise, any attempt to interrupt or stop will be ignored."),
  3105.                            set_target_permissions, NULL,
  3106.                            &setlist, &showlist);

  3107.   add_setshow_boolean_cmd ("auto-connect-native-target", class_support,
  3108.                            &auto_connect_native_target, _("\
  3109. Set whether GDB may automatically connect to the native target."), _("\
  3110. Show whether GDB may automatically connect to the native target."), _("\
  3111. When on, and GDB is not connected to a target yet, GDB\n\
  3112. attempts \"run\" and other commands with the native target."),
  3113.                            NULL, show_auto_connect_native_target,
  3114.                            &setlist, &showlist);
  3115. }