Per-inferior thread list, thread ranges/iterators, down with ALL_THREADS, etc.
[external/binutils.git] / gdb / target.c
1 /* Select target systems and architectures at runtime for GDB.
2
3    Copyright (C) 1990-2018 Free Software Foundation, Inc.
4
5    Contributed by Cygnus Support.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "target.h"
24 #include "target-dcache.h"
25 #include "gdbcmd.h"
26 #include "symtab.h"
27 #include "inferior.h"
28 #include "infrun.h"
29 #include "bfd.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "dcache.h"
33 #include <signal.h>
34 #include "regcache.h"
35 #include "gdbcore.h"
36 #include "target-descriptions.h"
37 #include "gdbthread.h"
38 #include "solib.h"
39 #include "exec.h"
40 #include "inline-frame.h"
41 #include "tracepoint.h"
42 #include "gdb/fileio.h"
43 #include "agent.h"
44 #include "auxv.h"
45 #include "target-debug.h"
46 #include "top.h"
47 #include "event-top.h"
48 #include <algorithm>
49 #include "byte-vector.h"
50 #include "terminal.h"
51 #include <algorithm>
52 #include <unordered_map>
53
54 static void generic_tls_error (void) ATTRIBUTE_NORETURN;
55
56 static void default_terminal_info (struct target_ops *, const char *, int);
57
58 static int default_watchpoint_addr_within_range (struct target_ops *,
59                                                  CORE_ADDR, CORE_ADDR, int);
60
61 static int default_region_ok_for_hw_watchpoint (struct target_ops *,
62                                                 CORE_ADDR, int);
63
64 static void default_rcmd (struct target_ops *, const char *, struct ui_file *);
65
66 static ptid_t default_get_ada_task_ptid (struct target_ops *self,
67                                          long lwp, long tid);
68
69 static int default_follow_fork (struct target_ops *self, int follow_child,
70                                 int detach_fork);
71
72 static void default_mourn_inferior (struct target_ops *self);
73
74 static int default_search_memory (struct target_ops *ops,
75                                   CORE_ADDR start_addr,
76                                   ULONGEST search_space_len,
77                                   const gdb_byte *pattern,
78                                   ULONGEST pattern_len,
79                                   CORE_ADDR *found_addrp);
80
81 static int default_verify_memory (struct target_ops *self,
82                                   const gdb_byte *data,
83                                   CORE_ADDR memaddr, ULONGEST size);
84
85 static struct address_space *default_thread_address_space
86      (struct target_ops *self, ptid_t ptid);
87
88 static void tcomplain (void) ATTRIBUTE_NORETURN;
89
90 static struct target_ops *find_default_run_target (const char *);
91
92 static struct gdbarch *default_thread_architecture (struct target_ops *ops,
93                                                     ptid_t ptid);
94
95 static int dummy_find_memory_regions (struct target_ops *self,
96                                       find_memory_region_ftype ignore1,
97                                       void *ignore2);
98
99 static char *dummy_make_corefile_notes (struct target_ops *self,
100                                         bfd *ignore1, int *ignore2);
101
102 static const char *default_pid_to_str (struct target_ops *ops, ptid_t ptid);
103
104 static enum exec_direction_kind default_execution_direction
105     (struct target_ops *self);
106
107 /* Mapping between target_info objects (which have address identity)
108    and corresponding open/factory function/callback.  Each add_target
109    call adds one entry to this map, and registers a "target
110    TARGET_NAME" command that when invoked calls the factory registered
111    here.  The target_info object is associated with the command via
112    the command's context.  */
113 static std::unordered_map<const target_info *, target_open_ftype *>
114   target_factories;
115
116 /* The initial current target, so that there is always a semi-valid
117    current target.  */
118
119 static struct target_ops *the_dummy_target;
120 static struct target_ops *the_debug_target;
121
122 /* The target stack.  */
123
124 static target_stack g_target_stack;
125
126 /* Top of target stack.  */
127 /* The target structure we are currently using to talk to a process
128    or file or whatever "inferior" we have.  */
129
130 target_ops *
131 current_top_target ()
132 {
133   return g_target_stack.top ();
134 }
135
136 /* Command list for target.  */
137
138 static struct cmd_list_element *targetlist = NULL;
139
140 /* Nonzero if we should trust readonly sections from the
141    executable when reading memory.  */
142
143 static int trust_readonly = 0;
144
145 /* Nonzero if we should show true memory content including
146    memory breakpoint inserted by gdb.  */
147
148 static int show_memory_breakpoints = 0;
149
150 /* These globals control whether GDB attempts to perform these
151    operations; they are useful for targets that need to prevent
152    inadvertant disruption, such as in non-stop mode.  */
153
154 int may_write_registers = 1;
155
156 int may_write_memory = 1;
157
158 int may_insert_breakpoints = 1;
159
160 int may_insert_tracepoints = 1;
161
162 int may_insert_fast_tracepoints = 1;
163
164 int may_stop = 1;
165
166 /* Non-zero if we want to see trace of target level stuff.  */
167
168 static unsigned int targetdebug = 0;
169
170 static void
171 set_targetdebug  (const char *args, int from_tty, struct cmd_list_element *c)
172 {
173   if (targetdebug)
174     push_target (the_debug_target);
175   else
176     unpush_target (the_debug_target);
177 }
178
179 static void
180 show_targetdebug (struct ui_file *file, int from_tty,
181                   struct cmd_list_element *c, const char *value)
182 {
183   fprintf_filtered (file, _("Target debugging is %s.\n"), value);
184 }
185
186 /* The user just typed 'target' without the name of a target.  */
187
188 static void
189 target_command (const char *arg, int from_tty)
190 {
191   fputs_filtered ("Argument required (target name).  Try `help target'\n",
192                   gdb_stdout);
193 }
194
195 #if GDB_SELF_TEST
196 namespace selftests {
197
198 /* A mock process_stratum target_ops that doesn't read/write registers
199    anywhere.  */
200
201 static const target_info test_target_info = {
202   "test",
203   N_("unit tests target"),
204   N_("You should never see this"),
205 };
206
207 const target_info &
208 test_target_ops::info () const
209 {
210   return test_target_info;
211 }
212
213 } /* namespace selftests */
214 #endif /* GDB_SELF_TEST */
215
216 /* Default target_has_* methods for process_stratum targets.  */
217
218 int
219 default_child_has_all_memory ()
220 {
221   /* If no inferior selected, then we can't read memory here.  */
222   if (inferior_ptid == null_ptid)
223     return 0;
224
225   return 1;
226 }
227
228 int
229 default_child_has_memory ()
230 {
231   /* If no inferior selected, then we can't read memory here.  */
232   if (inferior_ptid == null_ptid)
233     return 0;
234
235   return 1;
236 }
237
238 int
239 default_child_has_stack ()
240 {
241   /* If no inferior selected, there's no stack.  */
242   if (inferior_ptid == null_ptid)
243     return 0;
244
245   return 1;
246 }
247
248 int
249 default_child_has_registers ()
250 {
251   /* Can't read registers from no inferior.  */
252   if (inferior_ptid == null_ptid)
253     return 0;
254
255   return 1;
256 }
257
258 int
259 default_child_has_execution (ptid_t the_ptid)
260 {
261   /* If there's no thread selected, then we can't make it run through
262      hoops.  */
263   if (the_ptid == null_ptid)
264     return 0;
265
266   return 1;
267 }
268
269
270 int
271 target_has_all_memory_1 (void)
272 {
273   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
274     if (t->has_all_memory ())
275       return 1;
276
277   return 0;
278 }
279
280 int
281 target_has_memory_1 (void)
282 {
283   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
284     if (t->has_memory ())
285       return 1;
286
287   return 0;
288 }
289
290 int
291 target_has_stack_1 (void)
292 {
293   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
294     if (t->has_stack ())
295       return 1;
296
297   return 0;
298 }
299
300 int
301 target_has_registers_1 (void)
302 {
303   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
304     if (t->has_registers ())
305       return 1;
306
307   return 0;
308 }
309
310 int
311 target_has_execution_1 (ptid_t the_ptid)
312 {
313   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
314     if (t->has_execution (the_ptid))
315       return 1;
316
317   return 0;
318 }
319
320 int
321 target_has_execution_current (void)
322 {
323   return target_has_execution_1 (inferior_ptid);
324 }
325
326 /* This is used to implement the various target commands.  */
327
328 static void
329 open_target (const char *args, int from_tty, struct cmd_list_element *command)
330 {
331   auto *ti = static_cast<target_info *> (get_cmd_context (command));
332   target_open_ftype *func = target_factories[ti];
333
334   if (targetdebug)
335     fprintf_unfiltered (gdb_stdlog, "-> %s->open (...)\n",
336                         ti->shortname);
337
338   func (args, from_tty);
339
340   if (targetdebug)
341     fprintf_unfiltered (gdb_stdlog, "<- %s->open (%s, %d)\n",
342                         ti->shortname, args, from_tty);
343 }
344
345 /* See target.h.  */
346
347 void
348 add_target (const target_info &t, target_open_ftype *func,
349             completer_ftype *completer)
350 {
351   struct cmd_list_element *c;
352
353   auto &func_slot = target_factories[&t];
354   if (func_slot != nullptr)
355     internal_error (__FILE__, __LINE__,
356                     _("target already added (\"%s\")."), t.shortname);
357   func_slot = func;
358
359   if (targetlist == NULL)
360     add_prefix_cmd ("target", class_run, target_command, _("\
361 Connect to a target machine or process.\n\
362 The first argument is the type or protocol of the target machine.\n\
363 Remaining arguments are interpreted by the target protocol.  For more\n\
364 information on the arguments for a particular protocol, type\n\
365 `help target ' followed by the protocol name."),
366                     &targetlist, "target ", 0, &cmdlist);
367   c = add_cmd (t.shortname, no_class, t.doc, &targetlist);
368   set_cmd_context (c, (void *) &t);
369   set_cmd_sfunc (c, open_target);
370   if (completer != NULL)
371     set_cmd_completer (c, completer);
372 }
373
374 /* See target.h.  */
375
376 void
377 add_deprecated_target_alias (const target_info &tinfo, const char *alias)
378 {
379   struct cmd_list_element *c;
380   char *alt;
381
382   /* If we use add_alias_cmd, here, we do not get the deprecated warning,
383      see PR cli/15104.  */
384   c = add_cmd (alias, no_class, tinfo.doc, &targetlist);
385   set_cmd_sfunc (c, open_target);
386   set_cmd_context (c, (void *) &tinfo);
387   alt = xstrprintf ("target %s", tinfo.shortname);
388   deprecate_cmd (c, alt);
389 }
390
391 /* Stub functions */
392
393 void
394 target_kill (void)
395 {
396   current_top_target ()->kill ();
397 }
398
399 void
400 target_load (const char *arg, int from_tty)
401 {
402   target_dcache_invalidate ();
403   current_top_target ()->load (arg, from_tty);
404 }
405
406 /* Define it.  */
407
408 target_terminal_state target_terminal::m_terminal_state
409   = target_terminal_state::is_ours;
410
411 /* See target/target.h.  */
412
413 void
414 target_terminal::init (void)
415 {
416   current_top_target ()->terminal_init ();
417
418   m_terminal_state = target_terminal_state::is_ours;
419 }
420
421 /* See target/target.h.  */
422
423 void
424 target_terminal::inferior (void)
425 {
426   struct ui *ui = current_ui;
427
428   /* A background resume (``run&'') should leave GDB in control of the
429      terminal.  */
430   if (ui->prompt_state != PROMPT_BLOCKED)
431     return;
432
433   /* Since we always run the inferior in the main console (unless "set
434      inferior-tty" is in effect), when some UI other than the main one
435      calls target_terminal::inferior, then we leave the main UI's
436      terminal settings as is.  */
437   if (ui != main_ui)
438     return;
439
440   /* If GDB is resuming the inferior in the foreground, install
441      inferior's terminal modes.  */
442
443   struct inferior *inf = current_inferior ();
444
445   if (inf->terminal_state != target_terminal_state::is_inferior)
446     {
447       current_top_target ()->terminal_inferior ();
448       inf->terminal_state = target_terminal_state::is_inferior;
449     }
450
451   m_terminal_state = target_terminal_state::is_inferior;
452
453   /* If the user hit C-c before, pretend that it was hit right
454      here.  */
455   if (check_quit_flag ())
456     target_pass_ctrlc ();
457 }
458
459 /* See target/target.h.  */
460
461 void
462 target_terminal::restore_inferior (void)
463 {
464   struct ui *ui = current_ui;
465
466   /* See target_terminal::inferior().  */
467   if (ui->prompt_state != PROMPT_BLOCKED || ui != main_ui)
468     return;
469
470   /* Restore the terminal settings of inferiors that were in the
471      foreground but are now ours_for_output due to a temporary
472      target_target::ours_for_output() call.  */
473
474   {
475     scoped_restore_current_inferior restore_inferior;
476
477     for (struct inferior *inf : all_inferiors ())
478       {
479         if (inf->terminal_state == target_terminal_state::is_ours_for_output)
480           {
481             set_current_inferior (inf);
482             current_top_target ()->terminal_inferior ();
483             inf->terminal_state = target_terminal_state::is_inferior;
484           }
485       }
486   }
487
488   m_terminal_state = target_terminal_state::is_inferior;
489
490   /* If the user hit C-c before, pretend that it was hit right
491      here.  */
492   if (check_quit_flag ())
493     target_pass_ctrlc ();
494 }
495
496 /* Switch terminal state to DESIRED_STATE, either is_ours, or
497    is_ours_for_output.  */
498
499 static void
500 target_terminal_is_ours_kind (target_terminal_state desired_state)
501 {
502   scoped_restore_current_inferior restore_inferior;
503
504   /* Must do this in two passes.  First, have all inferiors save the
505      current terminal settings.  Then, after all inferiors have add a
506      chance to safely save the terminal settings, restore GDB's
507      terminal settings.  */
508
509   for (inferior *inf : all_inferiors ())
510     {
511       if (inf->terminal_state == target_terminal_state::is_inferior)
512         {
513           set_current_inferior (inf);
514           current_top_target ()->terminal_save_inferior ();
515         }
516     }
517
518   for (inferior *inf : all_inferiors ())
519     {
520       /* Note we don't check is_inferior here like above because we
521          need to handle 'is_ours_for_output -> is_ours' too.  Careful
522          to never transition from 'is_ours' to 'is_ours_for_output',
523          though.  */
524       if (inf->terminal_state != target_terminal_state::is_ours
525           && inf->terminal_state != desired_state)
526         {
527           set_current_inferior (inf);
528           if (desired_state == target_terminal_state::is_ours)
529             current_top_target ()->terminal_ours ();
530           else if (desired_state == target_terminal_state::is_ours_for_output)
531             current_top_target ()->terminal_ours_for_output ();
532           else
533             gdb_assert_not_reached ("unhandled desired state");
534           inf->terminal_state = desired_state;
535         }
536     }
537 }
538
539 /* See target/target.h.  */
540
541 void
542 target_terminal::ours ()
543 {
544   struct ui *ui = current_ui;
545
546   /* See target_terminal::inferior.  */
547   if (ui != main_ui)
548     return;
549
550   if (m_terminal_state == target_terminal_state::is_ours)
551     return;
552
553   target_terminal_is_ours_kind (target_terminal_state::is_ours);
554   m_terminal_state = target_terminal_state::is_ours;
555 }
556
557 /* See target/target.h.  */
558
559 void
560 target_terminal::ours_for_output ()
561 {
562   struct ui *ui = current_ui;
563
564   /* See target_terminal::inferior.  */
565   if (ui != main_ui)
566     return;
567
568   if (!target_terminal::is_inferior ())
569     return;
570
571   target_terminal_is_ours_kind (target_terminal_state::is_ours_for_output);
572   target_terminal::m_terminal_state = target_terminal_state::is_ours_for_output;
573 }
574
575 /* See target/target.h.  */
576
577 void
578 target_terminal::info (const char *arg, int from_tty)
579 {
580   current_top_target ()->terminal_info (arg, from_tty);
581 }
582
583 /* See target.h.  */
584
585 bool
586 target_supports_terminal_ours (void)
587 {
588   /* This can be called before there is any target, so we must check
589      for nullptr here.  */
590   target_ops *top = current_top_target ();
591
592   if (top == nullptr)
593     return false;
594   return top->supports_terminal_ours ();
595 }
596
597 static void
598 tcomplain (void)
599 {
600   error (_("You can't do that when your target is `%s'"),
601          current_top_target ()->shortname ());
602 }
603
604 void
605 noprocess (void)
606 {
607   error (_("You can't do that without a process to debug."));
608 }
609
610 static void
611 default_terminal_info (struct target_ops *self, const char *args, int from_tty)
612 {
613   printf_unfiltered (_("No saved terminal information.\n"));
614 }
615
616 /* A default implementation for the to_get_ada_task_ptid target method.
617
618    This function builds the PTID by using both LWP and TID as part of
619    the PTID lwp and tid elements.  The pid used is the pid of the
620    inferior_ptid.  */
621
622 static ptid_t
623 default_get_ada_task_ptid (struct target_ops *self, long lwp, long tid)
624 {
625   return ptid_t (inferior_ptid.pid (), lwp, tid);
626 }
627
628 static enum exec_direction_kind
629 default_execution_direction (struct target_ops *self)
630 {
631   if (!target_can_execute_reverse)
632     return EXEC_FORWARD;
633   else if (!target_can_async_p ())
634     return EXEC_FORWARD;
635   else
636     gdb_assert_not_reached ("\
637 to_execution_direction must be implemented for reverse async");
638 }
639
640 /* See target.h.  */
641
642 void
643 target_stack::push (target_ops *t)
644 {
645   /* If there's already a target at this stratum, remove it.  */
646   if (m_stack[t->to_stratum] != NULL)
647     {
648       target_ops *prev = m_stack[t->to_stratum];
649       m_stack[t->to_stratum] = NULL;
650       target_close (prev);
651     }
652
653   /* Now add the new one.  */
654   m_stack[t->to_stratum] = t;
655
656   if (m_top < t->to_stratum)
657     m_top = t->to_stratum;
658 }
659
660 /* See target.h.  */
661
662 void
663 push_target (struct target_ops *t)
664 {
665   g_target_stack.push (t);
666 }
667
668 /* See target.h.  */
669
670 int
671 unpush_target (struct target_ops *t)
672 {
673   return g_target_stack.unpush (t);
674 }
675
676 /* See target.h.  */
677
678 bool
679 target_stack::unpush (target_ops *t)
680 {
681   if (t->to_stratum == dummy_stratum)
682     internal_error (__FILE__, __LINE__,
683                     _("Attempt to unpush the dummy target"));
684
685   gdb_assert (t != NULL);
686
687   /* Look for the specified target.  Note that a target can only occur
688      once in the target stack.  */
689
690   if (m_stack[t->to_stratum] != t)
691     {
692       /* If T wasn't pushed, quit.  Only open targets should be
693          closed.  */
694       return false;
695     }
696
697   /* Unchain the target.  */
698   m_stack[t->to_stratum] = NULL;
699
700   if (m_top == t->to_stratum)
701     m_top = t->beneath ()->to_stratum;
702
703   /* Finally close the target.  Note we do this after unchaining, so
704      any target method calls from within the target_close
705      implementation don't end up in T anymore.  */
706   target_close (t);
707
708   return true;
709 }
710
711 /* Unpush TARGET and assert that it worked.  */
712
713 static void
714 unpush_target_and_assert (struct target_ops *target)
715 {
716   if (!unpush_target (target))
717     {
718       fprintf_unfiltered (gdb_stderr,
719                           "pop_all_targets couldn't find target %s\n",
720                           target->shortname ());
721       internal_error (__FILE__, __LINE__,
722                       _("failed internal consistency check"));
723     }
724 }
725
726 void
727 pop_all_targets_above (enum strata above_stratum)
728 {
729   while ((int) (current_top_target ()->to_stratum) > (int) above_stratum)
730     unpush_target_and_assert (current_top_target ());
731 }
732
733 /* See target.h.  */
734
735 void
736 pop_all_targets_at_and_above (enum strata stratum)
737 {
738   while ((int) (current_top_target ()->to_stratum) >= (int) stratum)
739     unpush_target_and_assert (current_top_target ());
740 }
741
742 void
743 pop_all_targets (void)
744 {
745   pop_all_targets_above (dummy_stratum);
746 }
747
748 /* Return 1 if T is now pushed in the target stack.  Return 0 otherwise.  */
749
750 int
751 target_is_pushed (struct target_ops *t)
752 {
753   return g_target_stack.is_pushed (t);
754 }
755
756 /* Default implementation of to_get_thread_local_address.  */
757
758 static void
759 generic_tls_error (void)
760 {
761   throw_error (TLS_GENERIC_ERROR,
762                _("Cannot find thread-local variables on this target"));
763 }
764
765 /* Using the objfile specified in OBJFILE, find the address for the
766    current thread's thread-local storage with offset OFFSET.  */
767 CORE_ADDR
768 target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset)
769 {
770   volatile CORE_ADDR addr = 0;
771   struct target_ops *target = current_top_target ();
772
773   if (gdbarch_fetch_tls_load_module_address_p (target_gdbarch ()))
774     {
775       ptid_t ptid = inferior_ptid;
776
777       TRY
778         {
779           CORE_ADDR lm_addr;
780           
781           /* Fetch the load module address for this objfile.  */
782           lm_addr = gdbarch_fetch_tls_load_module_address (target_gdbarch (),
783                                                            objfile);
784
785           addr = target->get_thread_local_address (ptid, lm_addr, offset);
786         }
787       /* If an error occurred, print TLS related messages here.  Otherwise,
788          throw the error to some higher catcher.  */
789       CATCH (ex, RETURN_MASK_ALL)
790         {
791           int objfile_is_library = (objfile->flags & OBJF_SHARED);
792
793           switch (ex.error)
794             {
795             case TLS_NO_LIBRARY_SUPPORT_ERROR:
796               error (_("Cannot find thread-local variables "
797                        "in this thread library."));
798               break;
799             case TLS_LOAD_MODULE_NOT_FOUND_ERROR:
800               if (objfile_is_library)
801                 error (_("Cannot find shared library `%s' in dynamic"
802                          " linker's load module list"), objfile_name (objfile));
803               else
804                 error (_("Cannot find executable file `%s' in dynamic"
805                          " linker's load module list"), objfile_name (objfile));
806               break;
807             case TLS_NOT_ALLOCATED_YET_ERROR:
808               if (objfile_is_library)
809                 error (_("The inferior has not yet allocated storage for"
810                          " thread-local variables in\n"
811                          "the shared library `%s'\n"
812                          "for %s"),
813                        objfile_name (objfile), target_pid_to_str (ptid));
814               else
815                 error (_("The inferior has not yet allocated storage for"
816                          " thread-local variables in\n"
817                          "the executable `%s'\n"
818                          "for %s"),
819                        objfile_name (objfile), target_pid_to_str (ptid));
820               break;
821             case TLS_GENERIC_ERROR:
822               if (objfile_is_library)
823                 error (_("Cannot find thread-local storage for %s, "
824                          "shared library %s:\n%s"),
825                        target_pid_to_str (ptid),
826                        objfile_name (objfile), ex.message);
827               else
828                 error (_("Cannot find thread-local storage for %s, "
829                          "executable file %s:\n%s"),
830                        target_pid_to_str (ptid),
831                        objfile_name (objfile), ex.message);
832               break;
833             default:
834               throw_exception (ex);
835               break;
836             }
837         }
838       END_CATCH
839     }
840   /* It wouldn't be wrong here to try a gdbarch method, too; finding
841      TLS is an ABI-specific thing.  But we don't do that yet.  */
842   else
843     error (_("Cannot find thread-local variables on this target"));
844
845   return addr;
846 }
847
848 const char *
849 target_xfer_status_to_string (enum target_xfer_status status)
850 {
851 #define CASE(X) case X: return #X
852   switch (status)
853     {
854       CASE(TARGET_XFER_E_IO);
855       CASE(TARGET_XFER_UNAVAILABLE);
856     default:
857       return "<unknown>";
858     }
859 #undef CASE
860 };
861
862
863 #undef  MIN
864 #define MIN(A, B) (((A) <= (B)) ? (A) : (B))
865
866 /* target_read_string -- read a null terminated string, up to LEN bytes,
867    from MEMADDR in target.  Set *ERRNOP to the errno code, or 0 if successful.
868    Set *STRING to a pointer to malloc'd memory containing the data; the caller
869    is responsible for freeing it.  Return the number of bytes successfully
870    read.  */
871
872 int
873 target_read_string (CORE_ADDR memaddr, gdb::unique_xmalloc_ptr<char> *string,
874                     int len, int *errnop)
875 {
876   int tlen, offset, i;
877   gdb_byte buf[4];
878   int errcode = 0;
879   char *buffer;
880   int buffer_allocated;
881   char *bufptr;
882   unsigned int nbytes_read = 0;
883
884   gdb_assert (string);
885
886   /* Small for testing.  */
887   buffer_allocated = 4;
888   buffer = (char *) xmalloc (buffer_allocated);
889   bufptr = buffer;
890
891   while (len > 0)
892     {
893       tlen = MIN (len, 4 - (memaddr & 3));
894       offset = memaddr & 3;
895
896       errcode = target_read_memory (memaddr & ~3, buf, sizeof buf);
897       if (errcode != 0)
898         {
899           /* The transfer request might have crossed the boundary to an
900              unallocated region of memory.  Retry the transfer, requesting
901              a single byte.  */
902           tlen = 1;
903           offset = 0;
904           errcode = target_read_memory (memaddr, buf, 1);
905           if (errcode != 0)
906             goto done;
907         }
908
909       if (bufptr - buffer + tlen > buffer_allocated)
910         {
911           unsigned int bytes;
912
913           bytes = bufptr - buffer;
914           buffer_allocated *= 2;
915           buffer = (char *) xrealloc (buffer, buffer_allocated);
916           bufptr = buffer + bytes;
917         }
918
919       for (i = 0; i < tlen; i++)
920         {
921           *bufptr++ = buf[i + offset];
922           if (buf[i + offset] == '\000')
923             {
924               nbytes_read += i + 1;
925               goto done;
926             }
927         }
928
929       memaddr += tlen;
930       len -= tlen;
931       nbytes_read += tlen;
932     }
933 done:
934   string->reset (buffer);
935   if (errnop != NULL)
936     *errnop = errcode;
937   return nbytes_read;
938 }
939
940 struct target_section_table *
941 target_get_section_table (struct target_ops *target)
942 {
943   return target->get_section_table ();
944 }
945
946 /* Find a section containing ADDR.  */
947
948 struct target_section *
949 target_section_by_addr (struct target_ops *target, CORE_ADDR addr)
950 {
951   struct target_section_table *table = target_get_section_table (target);
952   struct target_section *secp;
953
954   if (table == NULL)
955     return NULL;
956
957   for (secp = table->sections; secp < table->sections_end; secp++)
958     {
959       if (addr >= secp->addr && addr < secp->endaddr)
960         return secp;
961     }
962   return NULL;
963 }
964
965
966 /* Helper for the memory xfer routines.  Checks the attributes of the
967    memory region of MEMADDR against the read or write being attempted.
968    If the access is permitted returns true, otherwise returns false.
969    REGION_P is an optional output parameter.  If not-NULL, it is
970    filled with a pointer to the memory region of MEMADDR.  REG_LEN
971    returns LEN trimmed to the end of the region.  This is how much the
972    caller can continue requesting, if the access is permitted.  A
973    single xfer request must not straddle memory region boundaries.  */
974
975 static int
976 memory_xfer_check_region (gdb_byte *readbuf, const gdb_byte *writebuf,
977                           ULONGEST memaddr, ULONGEST len, ULONGEST *reg_len,
978                           struct mem_region **region_p)
979 {
980   struct mem_region *region;
981
982   region = lookup_mem_region (memaddr);
983
984   if (region_p != NULL)
985     *region_p = region;
986
987   switch (region->attrib.mode)
988     {
989     case MEM_RO:
990       if (writebuf != NULL)
991         return 0;
992       break;
993
994     case MEM_WO:
995       if (readbuf != NULL)
996         return 0;
997       break;
998
999     case MEM_FLASH:
1000       /* We only support writing to flash during "load" for now.  */
1001       if (writebuf != NULL)
1002         error (_("Writing to flash memory forbidden in this context"));
1003       break;
1004
1005     case MEM_NONE:
1006       return 0;
1007     }
1008
1009   /* region->hi == 0 means there's no upper bound.  */
1010   if (memaddr + len < region->hi || region->hi == 0)
1011     *reg_len = len;
1012   else
1013     *reg_len = region->hi - memaddr;
1014
1015   return 1;
1016 }
1017
1018 /* Read memory from more than one valid target.  A core file, for
1019    instance, could have some of memory but delegate other bits to
1020    the target below it.  So, we must manually try all targets.  */
1021
1022 enum target_xfer_status
1023 raw_memory_xfer_partial (struct target_ops *ops, gdb_byte *readbuf,
1024                          const gdb_byte *writebuf, ULONGEST memaddr, LONGEST len,
1025                          ULONGEST *xfered_len)
1026 {
1027   enum target_xfer_status res;
1028
1029   do
1030     {
1031       res = ops->xfer_partial (TARGET_OBJECT_MEMORY, NULL,
1032                                readbuf, writebuf, memaddr, len,
1033                                xfered_len);
1034       if (res == TARGET_XFER_OK)
1035         break;
1036
1037       /* Stop if the target reports that the memory is not available.  */
1038       if (res == TARGET_XFER_UNAVAILABLE)
1039         break;
1040
1041       /* We want to continue past core files to executables, but not
1042          past a running target's memory.  */
1043       if (ops->has_all_memory ())
1044         break;
1045
1046       ops = ops->beneath ();
1047     }
1048   while (ops != NULL);
1049
1050   /* The cache works at the raw memory level.  Make sure the cache
1051      gets updated with raw contents no matter what kind of memory
1052      object was originally being written.  Note we do write-through
1053      first, so that if it fails, we don't write to the cache contents
1054      that never made it to the target.  */
1055   if (writebuf != NULL
1056       && inferior_ptid != null_ptid
1057       && target_dcache_init_p ()
1058       && (stack_cache_enabled_p () || code_cache_enabled_p ()))
1059     {
1060       DCACHE *dcache = target_dcache_get ();
1061
1062       /* Note that writing to an area of memory which wasn't present
1063          in the cache doesn't cause it to be loaded in.  */
1064       dcache_update (dcache, res, memaddr, writebuf, *xfered_len);
1065     }
1066
1067   return res;
1068 }
1069
1070 /* Perform a partial memory transfer.
1071    For docs see target.h, to_xfer_partial.  */
1072
1073 static enum target_xfer_status
1074 memory_xfer_partial_1 (struct target_ops *ops, enum target_object object,
1075                        gdb_byte *readbuf, const gdb_byte *writebuf, ULONGEST memaddr,
1076                        ULONGEST len, ULONGEST *xfered_len)
1077 {
1078   enum target_xfer_status res;
1079   ULONGEST reg_len;
1080   struct mem_region *region;
1081   struct inferior *inf;
1082
1083   /* For accesses to unmapped overlay sections, read directly from
1084      files.  Must do this first, as MEMADDR may need adjustment.  */
1085   if (readbuf != NULL && overlay_debugging)
1086     {
1087       struct obj_section *section = find_pc_overlay (memaddr);
1088
1089       if (pc_in_unmapped_range (memaddr, section))
1090         {
1091           struct target_section_table *table
1092             = target_get_section_table (ops);
1093           const char *section_name = section->the_bfd_section->name;
1094
1095           memaddr = overlay_mapped_address (memaddr, section);
1096           return section_table_xfer_memory_partial (readbuf, writebuf,
1097                                                     memaddr, len, xfered_len,
1098                                                     table->sections,
1099                                                     table->sections_end,
1100                                                     section_name);
1101         }
1102     }
1103
1104   /* Try the executable files, if "trust-readonly-sections" is set.  */
1105   if (readbuf != NULL && trust_readonly)
1106     {
1107       struct target_section *secp;
1108       struct target_section_table *table;
1109
1110       secp = target_section_by_addr (ops, memaddr);
1111       if (secp != NULL
1112           && (bfd_get_section_flags (secp->the_bfd_section->owner,
1113                                      secp->the_bfd_section)
1114               & SEC_READONLY))
1115         {
1116           table = target_get_section_table (ops);
1117           return section_table_xfer_memory_partial (readbuf, writebuf,
1118                                                     memaddr, len, xfered_len,
1119                                                     table->sections,
1120                                                     table->sections_end,
1121                                                     NULL);
1122         }
1123     }
1124
1125   /* Try GDB's internal data cache.  */
1126
1127   if (!memory_xfer_check_region (readbuf, writebuf, memaddr, len, &reg_len,
1128                                  &region))
1129     return TARGET_XFER_E_IO;
1130
1131   if (inferior_ptid != null_ptid)
1132     inf = current_inferior ();
1133   else
1134     inf = NULL;
1135
1136   if (inf != NULL
1137       && readbuf != NULL
1138       /* The dcache reads whole cache lines; that doesn't play well
1139          with reading from a trace buffer, because reading outside of
1140          the collected memory range fails.  */
1141       && get_traceframe_number () == -1
1142       && (region->attrib.cache
1143           || (stack_cache_enabled_p () && object == TARGET_OBJECT_STACK_MEMORY)
1144           || (code_cache_enabled_p () && object == TARGET_OBJECT_CODE_MEMORY)))
1145     {
1146       DCACHE *dcache = target_dcache_get_or_init ();
1147
1148       return dcache_read_memory_partial (ops, dcache, memaddr, readbuf,
1149                                          reg_len, xfered_len);
1150     }
1151
1152   /* If none of those methods found the memory we wanted, fall back
1153      to a target partial transfer.  Normally a single call to
1154      to_xfer_partial is enough; if it doesn't recognize an object
1155      it will call the to_xfer_partial of the next target down.
1156      But for memory this won't do.  Memory is the only target
1157      object which can be read from more than one valid target.
1158      A core file, for instance, could have some of memory but
1159      delegate other bits to the target below it.  So, we must
1160      manually try all targets.  */
1161
1162   res = raw_memory_xfer_partial (ops, readbuf, writebuf, memaddr, reg_len,
1163                                  xfered_len);
1164
1165   /* If we still haven't got anything, return the last error.  We
1166      give up.  */
1167   return res;
1168 }
1169
1170 /* Perform a partial memory transfer.  For docs see target.h,
1171    to_xfer_partial.  */
1172
1173 static enum target_xfer_status
1174 memory_xfer_partial (struct target_ops *ops, enum target_object object,
1175                      gdb_byte *readbuf, const gdb_byte *writebuf,
1176                      ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
1177 {
1178   enum target_xfer_status res;
1179
1180   /* Zero length requests are ok and require no work.  */
1181   if (len == 0)
1182     return TARGET_XFER_EOF;
1183
1184   memaddr = address_significant (target_gdbarch (), memaddr);
1185
1186   /* Fill in READBUF with breakpoint shadows, or WRITEBUF with
1187      breakpoint insns, thus hiding out from higher layers whether
1188      there are software breakpoints inserted in the code stream.  */
1189   if (readbuf != NULL)
1190     {
1191       res = memory_xfer_partial_1 (ops, object, readbuf, NULL, memaddr, len,
1192                                    xfered_len);
1193
1194       if (res == TARGET_XFER_OK && !show_memory_breakpoints)
1195         breakpoint_xfer_memory (readbuf, NULL, NULL, memaddr, *xfered_len);
1196     }
1197   else
1198     {
1199       /* A large write request is likely to be partially satisfied
1200          by memory_xfer_partial_1.  We will continually malloc
1201          and free a copy of the entire write request for breakpoint
1202          shadow handling even though we only end up writing a small
1203          subset of it.  Cap writes to a limit specified by the target
1204          to mitigate this.  */
1205       len = std::min (ops->get_memory_xfer_limit (), len);
1206
1207       gdb::byte_vector buf (writebuf, writebuf + len);
1208       breakpoint_xfer_memory (NULL, buf.data (), writebuf, memaddr, len);
1209       res = memory_xfer_partial_1 (ops, object, NULL, buf.data (), memaddr, len,
1210                                    xfered_len);
1211     }
1212
1213   return res;
1214 }
1215
1216 scoped_restore_tmpl<int>
1217 make_scoped_restore_show_memory_breakpoints (int show)
1218 {
1219   return make_scoped_restore (&show_memory_breakpoints, show);
1220 }
1221
1222 /* For docs see target.h, to_xfer_partial.  */
1223
1224 enum target_xfer_status
1225 target_xfer_partial (struct target_ops *ops,
1226                      enum target_object object, const char *annex,
1227                      gdb_byte *readbuf, const gdb_byte *writebuf,
1228                      ULONGEST offset, ULONGEST len,
1229                      ULONGEST *xfered_len)
1230 {
1231   enum target_xfer_status retval;
1232
1233   /* Transfer is done when LEN is zero.  */
1234   if (len == 0)
1235     return TARGET_XFER_EOF;
1236
1237   if (writebuf && !may_write_memory)
1238     error (_("Writing to memory is not allowed (addr %s, len %s)"),
1239            core_addr_to_string_nz (offset), plongest (len));
1240
1241   *xfered_len = 0;
1242
1243   /* If this is a memory transfer, let the memory-specific code
1244      have a look at it instead.  Memory transfers are more
1245      complicated.  */
1246   if (object == TARGET_OBJECT_MEMORY || object == TARGET_OBJECT_STACK_MEMORY
1247       || object == TARGET_OBJECT_CODE_MEMORY)
1248     retval = memory_xfer_partial (ops, object, readbuf,
1249                                   writebuf, offset, len, xfered_len);
1250   else if (object == TARGET_OBJECT_RAW_MEMORY)
1251     {
1252       /* Skip/avoid accessing the target if the memory region
1253          attributes block the access.  Check this here instead of in
1254          raw_memory_xfer_partial as otherwise we'd end up checking
1255          this twice in the case of the memory_xfer_partial path is
1256          taken; once before checking the dcache, and another in the
1257          tail call to raw_memory_xfer_partial.  */
1258       if (!memory_xfer_check_region (readbuf, writebuf, offset, len, &len,
1259                                      NULL))
1260         return TARGET_XFER_E_IO;
1261
1262       /* Request the normal memory object from other layers.  */
1263       retval = raw_memory_xfer_partial (ops, readbuf, writebuf, offset, len,
1264                                         xfered_len);
1265     }
1266   else
1267     retval = ops->xfer_partial (object, annex, readbuf,
1268                                 writebuf, offset, len, xfered_len);
1269
1270   if (targetdebug)
1271     {
1272       const unsigned char *myaddr = NULL;
1273
1274       fprintf_unfiltered (gdb_stdlog,
1275                           "%s:target_xfer_partial "
1276                           "(%d, %s, %s, %s, %s, %s) = %d, %s",
1277                           ops->shortname (),
1278                           (int) object,
1279                           (annex ? annex : "(null)"),
1280                           host_address_to_string (readbuf),
1281                           host_address_to_string (writebuf),
1282                           core_addr_to_string_nz (offset),
1283                           pulongest (len), retval,
1284                           pulongest (*xfered_len));
1285
1286       if (readbuf)
1287         myaddr = readbuf;
1288       if (writebuf)
1289         myaddr = writebuf;
1290       if (retval == TARGET_XFER_OK && myaddr != NULL)
1291         {
1292           int i;
1293
1294           fputs_unfiltered (", bytes =", gdb_stdlog);
1295           for (i = 0; i < *xfered_len; i++)
1296             {
1297               if ((((intptr_t) &(myaddr[i])) & 0xf) == 0)
1298                 {
1299                   if (targetdebug < 2 && i > 0)
1300                     {
1301                       fprintf_unfiltered (gdb_stdlog, " ...");
1302                       break;
1303                     }
1304                   fprintf_unfiltered (gdb_stdlog, "\n");
1305                 }
1306
1307               fprintf_unfiltered (gdb_stdlog, " %02x", myaddr[i] & 0xff);
1308             }
1309         }
1310
1311       fputc_unfiltered ('\n', gdb_stdlog);
1312     }
1313
1314   /* Check implementations of to_xfer_partial update *XFERED_LEN
1315      properly.  Do assertion after printing debug messages, so that we
1316      can find more clues on assertion failure from debugging messages.  */
1317   if (retval == TARGET_XFER_OK || retval == TARGET_XFER_UNAVAILABLE)
1318     gdb_assert (*xfered_len > 0);
1319
1320   return retval;
1321 }
1322
1323 /* Read LEN bytes of target memory at address MEMADDR, placing the
1324    results in GDB's memory at MYADDR.  Returns either 0 for success or
1325    -1 if any error occurs.
1326
1327    If an error occurs, no guarantee is made about the contents of the data at
1328    MYADDR.  In particular, the caller should not depend upon partial reads
1329    filling the buffer with good data.  There is no way for the caller to know
1330    how much good data might have been transfered anyway.  Callers that can
1331    deal with partial reads should call target_read (which will retry until
1332    it makes no progress, and then return how much was transferred).  */
1333
1334 int
1335 target_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1336 {
1337   if (target_read (current_top_target (), TARGET_OBJECT_MEMORY, NULL,
1338                    myaddr, memaddr, len) == len)
1339     return 0;
1340   else
1341     return -1;
1342 }
1343
1344 /* See target/target.h.  */
1345
1346 int
1347 target_read_uint32 (CORE_ADDR memaddr, uint32_t *result)
1348 {
1349   gdb_byte buf[4];
1350   int r;
1351
1352   r = target_read_memory (memaddr, buf, sizeof buf);
1353   if (r != 0)
1354     return r;
1355   *result = extract_unsigned_integer (buf, sizeof buf,
1356                                       gdbarch_byte_order (target_gdbarch ()));
1357   return 0;
1358 }
1359
1360 /* Like target_read_memory, but specify explicitly that this is a read
1361    from the target's raw memory.  That is, this read bypasses the
1362    dcache, breakpoint shadowing, etc.  */
1363
1364 int
1365 target_read_raw_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1366 {
1367   if (target_read (current_top_target (), TARGET_OBJECT_RAW_MEMORY, NULL,
1368                    myaddr, memaddr, len) == len)
1369     return 0;
1370   else
1371     return -1;
1372 }
1373
1374 /* Like target_read_memory, but specify explicitly that this is a read from
1375    the target's stack.  This may trigger different cache behavior.  */
1376
1377 int
1378 target_read_stack (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1379 {
1380   if (target_read (current_top_target (), TARGET_OBJECT_STACK_MEMORY, NULL,
1381                    myaddr, memaddr, len) == len)
1382     return 0;
1383   else
1384     return -1;
1385 }
1386
1387 /* Like target_read_memory, but specify explicitly that this is a read from
1388    the target's code.  This may trigger different cache behavior.  */
1389
1390 int
1391 target_read_code (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len)
1392 {
1393   if (target_read (current_top_target (), TARGET_OBJECT_CODE_MEMORY, NULL,
1394                    myaddr, memaddr, len) == len)
1395     return 0;
1396   else
1397     return -1;
1398 }
1399
1400 /* Write LEN bytes from MYADDR to target memory at address MEMADDR.
1401    Returns either 0 for success or -1 if any error occurs.  If an
1402    error occurs, no guarantee is made about how much data got written.
1403    Callers that can deal with partial writes should call
1404    target_write.  */
1405
1406 int
1407 target_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1408 {
1409   if (target_write (current_top_target (), TARGET_OBJECT_MEMORY, NULL,
1410                     myaddr, memaddr, len) == len)
1411     return 0;
1412   else
1413     return -1;
1414 }
1415
1416 /* Write LEN bytes from MYADDR to target raw memory at address
1417    MEMADDR.  Returns either 0 for success or -1 if any error occurs.
1418    If an error occurs, no guarantee is made about how much data got
1419    written.  Callers that can deal with partial writes should call
1420    target_write.  */
1421
1422 int
1423 target_write_raw_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, ssize_t len)
1424 {
1425   if (target_write (current_top_target (), TARGET_OBJECT_RAW_MEMORY, NULL,
1426                     myaddr, memaddr, len) == len)
1427     return 0;
1428   else
1429     return -1;
1430 }
1431
1432 /* Fetch the target's memory map.  */
1433
1434 std::vector<mem_region>
1435 target_memory_map (void)
1436 {
1437   std::vector<mem_region> result = current_top_target ()->memory_map ();
1438   if (result.empty ())
1439     return result;
1440
1441   std::sort (result.begin (), result.end ());
1442
1443   /* Check that regions do not overlap.  Simultaneously assign
1444      a numbering for the "mem" commands to use to refer to
1445      each region.  */
1446   mem_region *last_one = NULL;
1447   for (size_t ix = 0; ix < result.size (); ix++)
1448     {
1449       mem_region *this_one = &result[ix];
1450       this_one->number = ix;
1451
1452       if (last_one != NULL && last_one->hi > this_one->lo)
1453         {
1454           warning (_("Overlapping regions in memory map: ignoring"));
1455           return std::vector<mem_region> ();
1456         }
1457
1458       last_one = this_one;
1459     }
1460
1461   return result;
1462 }
1463
1464 void
1465 target_flash_erase (ULONGEST address, LONGEST length)
1466 {
1467   current_top_target ()->flash_erase (address, length);
1468 }
1469
1470 void
1471 target_flash_done (void)
1472 {
1473   current_top_target ()->flash_done ();
1474 }
1475
1476 static void
1477 show_trust_readonly (struct ui_file *file, int from_tty,
1478                      struct cmd_list_element *c, const char *value)
1479 {
1480   fprintf_filtered (file,
1481                     _("Mode for reading from readonly sections is %s.\n"),
1482                     value);
1483 }
1484
1485 /* Target vector read/write partial wrapper functions.  */
1486
1487 static enum target_xfer_status
1488 target_read_partial (struct target_ops *ops,
1489                      enum target_object object,
1490                      const char *annex, gdb_byte *buf,
1491                      ULONGEST offset, ULONGEST len,
1492                      ULONGEST *xfered_len)
1493 {
1494   return target_xfer_partial (ops, object, annex, buf, NULL, offset, len,
1495                               xfered_len);
1496 }
1497
1498 static enum target_xfer_status
1499 target_write_partial (struct target_ops *ops,
1500                       enum target_object object,
1501                       const char *annex, const gdb_byte *buf,
1502                       ULONGEST offset, LONGEST len, ULONGEST *xfered_len)
1503 {
1504   return target_xfer_partial (ops, object, annex, NULL, buf, offset, len,
1505                               xfered_len);
1506 }
1507
1508 /* Wrappers to perform the full transfer.  */
1509
1510 /* For docs on target_read see target.h.  */
1511
1512 LONGEST
1513 target_read (struct target_ops *ops,
1514              enum target_object object,
1515              const char *annex, gdb_byte *buf,
1516              ULONGEST offset, LONGEST len)
1517 {
1518   LONGEST xfered_total = 0;
1519   int unit_size = 1;
1520
1521   /* If we are reading from a memory object, find the length of an addressable
1522      unit for that architecture.  */
1523   if (object == TARGET_OBJECT_MEMORY
1524       || object == TARGET_OBJECT_STACK_MEMORY
1525       || object == TARGET_OBJECT_CODE_MEMORY
1526       || object == TARGET_OBJECT_RAW_MEMORY)
1527     unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
1528
1529   while (xfered_total < len)
1530     {
1531       ULONGEST xfered_partial;
1532       enum target_xfer_status status;
1533
1534       status = target_read_partial (ops, object, annex,
1535                                     buf + xfered_total * unit_size,
1536                                     offset + xfered_total, len - xfered_total,
1537                                     &xfered_partial);
1538
1539       /* Call an observer, notifying them of the xfer progress?  */
1540       if (status == TARGET_XFER_EOF)
1541         return xfered_total;
1542       else if (status == TARGET_XFER_OK)
1543         {
1544           xfered_total += xfered_partial;
1545           QUIT;
1546         }
1547       else
1548         return TARGET_XFER_E_IO;
1549
1550     }
1551   return len;
1552 }
1553
1554 /* Assuming that the entire [begin, end) range of memory cannot be
1555    read, try to read whatever subrange is possible to read.
1556
1557    The function returns, in RESULT, either zero or one memory block.
1558    If there's a readable subrange at the beginning, it is completely
1559    read and returned.  Any further readable subrange will not be read.
1560    Otherwise, if there's a readable subrange at the end, it will be
1561    completely read and returned.  Any readable subranges before it
1562    (obviously, not starting at the beginning), will be ignored.  In
1563    other cases -- either no readable subrange, or readable subrange(s)
1564    that is neither at the beginning, or end, nothing is returned.
1565
1566    The purpose of this function is to handle a read across a boundary
1567    of accessible memory in a case when memory map is not available.
1568    The above restrictions are fine for this case, but will give
1569    incorrect results if the memory is 'patchy'.  However, supporting
1570    'patchy' memory would require trying to read every single byte,
1571    and it seems unacceptable solution.  Explicit memory map is
1572    recommended for this case -- and target_read_memory_robust will
1573    take care of reading multiple ranges then.  */
1574
1575 static void
1576 read_whatever_is_readable (struct target_ops *ops,
1577                            const ULONGEST begin, const ULONGEST end,
1578                            int unit_size,
1579                            std::vector<memory_read_result> *result)
1580 {
1581   ULONGEST current_begin = begin;
1582   ULONGEST current_end = end;
1583   int forward;
1584   ULONGEST xfered_len;
1585
1586   /* If we previously failed to read 1 byte, nothing can be done here.  */
1587   if (end - begin <= 1)
1588     return;
1589
1590   gdb::unique_xmalloc_ptr<gdb_byte> buf ((gdb_byte *) xmalloc (end - begin));
1591
1592   /* Check that either first or the last byte is readable, and give up
1593      if not.  This heuristic is meant to permit reading accessible memory
1594      at the boundary of accessible region.  */
1595   if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
1596                            buf.get (), begin, 1, &xfered_len) == TARGET_XFER_OK)
1597     {
1598       forward = 1;
1599       ++current_begin;
1600     }
1601   else if (target_read_partial (ops, TARGET_OBJECT_MEMORY, NULL,
1602                                 buf.get () + (end - begin) - 1, end - 1, 1,
1603                                 &xfered_len) == TARGET_XFER_OK)
1604     {
1605       forward = 0;
1606       --current_end;
1607     }
1608   else
1609     return;
1610
1611   /* Loop invariant is that the [current_begin, current_end) was previously
1612      found to be not readable as a whole.
1613
1614      Note loop condition -- if the range has 1 byte, we can't divide the range
1615      so there's no point trying further.  */
1616   while (current_end - current_begin > 1)
1617     {
1618       ULONGEST first_half_begin, first_half_end;
1619       ULONGEST second_half_begin, second_half_end;
1620       LONGEST xfer;
1621       ULONGEST middle = current_begin + (current_end - current_begin) / 2;
1622
1623       if (forward)
1624         {
1625           first_half_begin = current_begin;
1626           first_half_end = middle;
1627           second_half_begin = middle;
1628           second_half_end = current_end;
1629         }
1630       else
1631         {
1632           first_half_begin = middle;
1633           first_half_end = current_end;
1634           second_half_begin = current_begin;
1635           second_half_end = middle;
1636         }
1637
1638       xfer = target_read (ops, TARGET_OBJECT_MEMORY, NULL,
1639                           buf.get () + (first_half_begin - begin) * unit_size,
1640                           first_half_begin,
1641                           first_half_end - first_half_begin);
1642
1643       if (xfer == first_half_end - first_half_begin)
1644         {
1645           /* This half reads up fine.  So, the error must be in the
1646              other half.  */
1647           current_begin = second_half_begin;
1648           current_end = second_half_end;
1649         }
1650       else
1651         {
1652           /* This half is not readable.  Because we've tried one byte, we
1653              know some part of this half if actually readable.  Go to the next
1654              iteration to divide again and try to read.
1655
1656              We don't handle the other half, because this function only tries
1657              to read a single readable subrange.  */
1658           current_begin = first_half_begin;
1659           current_end = first_half_end;
1660         }
1661     }
1662
1663   if (forward)
1664     {
1665       /* The [begin, current_begin) range has been read.  */
1666       result->emplace_back (begin, current_end, std::move (buf));
1667     }
1668   else
1669     {
1670       /* The [current_end, end) range has been read.  */
1671       LONGEST region_len = end - current_end;
1672
1673       gdb::unique_xmalloc_ptr<gdb_byte> data
1674         ((gdb_byte *) xmalloc (region_len * unit_size));
1675       memcpy (data.get (), buf.get () + (current_end - begin) * unit_size,
1676               region_len * unit_size);
1677       result->emplace_back (current_end, end, std::move (data));
1678     }
1679 }
1680
1681 std::vector<memory_read_result>
1682 read_memory_robust (struct target_ops *ops,
1683                     const ULONGEST offset, const LONGEST len)
1684 {
1685   std::vector<memory_read_result> result;
1686   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
1687
1688   LONGEST xfered_total = 0;
1689   while (xfered_total < len)
1690     {
1691       struct mem_region *region = lookup_mem_region (offset + xfered_total);
1692       LONGEST region_len;
1693
1694       /* If there is no explicit region, a fake one should be created.  */
1695       gdb_assert (region);
1696
1697       if (region->hi == 0)
1698         region_len = len - xfered_total;
1699       else
1700         region_len = region->hi - offset;
1701
1702       if (region->attrib.mode == MEM_NONE || region->attrib.mode == MEM_WO)
1703         {
1704           /* Cannot read this region.  Note that we can end up here only
1705              if the region is explicitly marked inaccessible, or
1706              'inaccessible-by-default' is in effect.  */
1707           xfered_total += region_len;
1708         }
1709       else
1710         {
1711           LONGEST to_read = std::min (len - xfered_total, region_len);
1712           gdb::unique_xmalloc_ptr<gdb_byte> buffer
1713             ((gdb_byte *) xmalloc (to_read * unit_size));
1714
1715           LONGEST xfered_partial =
1716               target_read (ops, TARGET_OBJECT_MEMORY, NULL, buffer.get (),
1717                            offset + xfered_total, to_read);
1718           /* Call an observer, notifying them of the xfer progress?  */
1719           if (xfered_partial <= 0)
1720             {
1721               /* Got an error reading full chunk.  See if maybe we can read
1722                  some subrange.  */
1723               read_whatever_is_readable (ops, offset + xfered_total,
1724                                          offset + xfered_total + to_read,
1725                                          unit_size, &result);
1726               xfered_total += to_read;
1727             }
1728           else
1729             {
1730               result.emplace_back (offset + xfered_total,
1731                                    offset + xfered_total + xfered_partial,
1732                                    std::move (buffer));
1733               xfered_total += xfered_partial;
1734             }
1735           QUIT;
1736         }
1737     }
1738
1739   return result;
1740 }
1741
1742
1743 /* An alternative to target_write with progress callbacks.  */
1744
1745 LONGEST
1746 target_write_with_progress (struct target_ops *ops,
1747                             enum target_object object,
1748                             const char *annex, const gdb_byte *buf,
1749                             ULONGEST offset, LONGEST len,
1750                             void (*progress) (ULONGEST, void *), void *baton)
1751 {
1752   LONGEST xfered_total = 0;
1753   int unit_size = 1;
1754
1755   /* If we are writing to a memory object, find the length of an addressable
1756      unit for that architecture.  */
1757   if (object == TARGET_OBJECT_MEMORY
1758       || object == TARGET_OBJECT_STACK_MEMORY
1759       || object == TARGET_OBJECT_CODE_MEMORY
1760       || object == TARGET_OBJECT_RAW_MEMORY)
1761     unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
1762
1763   /* Give the progress callback a chance to set up.  */
1764   if (progress)
1765     (*progress) (0, baton);
1766
1767   while (xfered_total < len)
1768     {
1769       ULONGEST xfered_partial;
1770       enum target_xfer_status status;
1771
1772       status = target_write_partial (ops, object, annex,
1773                                      buf + xfered_total * unit_size,
1774                                      offset + xfered_total, len - xfered_total,
1775                                      &xfered_partial);
1776
1777       if (status != TARGET_XFER_OK)
1778         return status == TARGET_XFER_EOF ? xfered_total : TARGET_XFER_E_IO;
1779
1780       if (progress)
1781         (*progress) (xfered_partial, baton);
1782
1783       xfered_total += xfered_partial;
1784       QUIT;
1785     }
1786   return len;
1787 }
1788
1789 /* For docs on target_write see target.h.  */
1790
1791 LONGEST
1792 target_write (struct target_ops *ops,
1793               enum target_object object,
1794               const char *annex, const gdb_byte *buf,
1795               ULONGEST offset, LONGEST len)
1796 {
1797   return target_write_with_progress (ops, object, annex, buf, offset, len,
1798                                      NULL, NULL);
1799 }
1800
1801 /* Help for target_read_alloc and target_read_stralloc.  See their comments
1802    for details.  */
1803
1804 template <typename T>
1805 gdb::optional<gdb::def_vector<T>>
1806 target_read_alloc_1 (struct target_ops *ops, enum target_object object,
1807                      const char *annex)
1808 {
1809   gdb::def_vector<T> buf;
1810   size_t buf_pos = 0;
1811   const int chunk = 4096;
1812
1813   /* This function does not have a length parameter; it reads the
1814      entire OBJECT).  Also, it doesn't support objects fetched partly
1815      from one target and partly from another (in a different stratum,
1816      e.g. a core file and an executable).  Both reasons make it
1817      unsuitable for reading memory.  */
1818   gdb_assert (object != TARGET_OBJECT_MEMORY);
1819
1820   /* Start by reading up to 4K at a time.  The target will throttle
1821      this number down if necessary.  */
1822   while (1)
1823     {
1824       ULONGEST xfered_len;
1825       enum target_xfer_status status;
1826
1827       buf.resize (buf_pos + chunk);
1828
1829       status = target_read_partial (ops, object, annex,
1830                                     (gdb_byte *) &buf[buf_pos],
1831                                     buf_pos, chunk,
1832                                     &xfered_len);
1833
1834       if (status == TARGET_XFER_EOF)
1835         {
1836           /* Read all there was.  */
1837           buf.resize (buf_pos);
1838           return buf;
1839         }
1840       else if (status != TARGET_XFER_OK)
1841         {
1842           /* An error occurred.  */
1843           return {};
1844         }
1845
1846       buf_pos += xfered_len;
1847
1848       QUIT;
1849     }
1850 }
1851
1852 /* See target.h  */
1853
1854 gdb::optional<gdb::byte_vector>
1855 target_read_alloc (struct target_ops *ops, enum target_object object,
1856                    const char *annex)
1857 {
1858   return target_read_alloc_1<gdb_byte> (ops, object, annex);
1859 }
1860
1861 /* See target.h.  */
1862
1863 gdb::optional<gdb::char_vector>
1864 target_read_stralloc (struct target_ops *ops, enum target_object object,
1865                       const char *annex)
1866 {
1867   gdb::optional<gdb::char_vector> buf
1868     = target_read_alloc_1<char> (ops, object, annex);
1869
1870   if (!buf)
1871     return {};
1872
1873   if (buf->back () != '\0')
1874     buf->push_back ('\0');
1875
1876   /* Check for embedded NUL bytes; but allow trailing NULs.  */
1877   for (auto it = std::find (buf->begin (), buf->end (), '\0');
1878        it != buf->end (); it++)
1879     if (*it != '\0')
1880       {
1881         warning (_("target object %d, annex %s, "
1882                    "contained unexpected null characters"),
1883                  (int) object, annex ? annex : "(none)");
1884         break;
1885       }
1886
1887   return buf;
1888 }
1889
1890 /* Memory transfer methods.  */
1891
1892 void
1893 get_target_memory (struct target_ops *ops, CORE_ADDR addr, gdb_byte *buf,
1894                    LONGEST len)
1895 {
1896   /* This method is used to read from an alternate, non-current
1897      target.  This read must bypass the overlay support (as symbols
1898      don't match this target), and GDB's internal cache (wrong cache
1899      for this target).  */
1900   if (target_read (ops, TARGET_OBJECT_RAW_MEMORY, NULL, buf, addr, len)
1901       != len)
1902     memory_error (TARGET_XFER_E_IO, addr);
1903 }
1904
1905 ULONGEST
1906 get_target_memory_unsigned (struct target_ops *ops, CORE_ADDR addr,
1907                             int len, enum bfd_endian byte_order)
1908 {
1909   gdb_byte buf[sizeof (ULONGEST)];
1910
1911   gdb_assert (len <= sizeof (buf));
1912   get_target_memory (ops, addr, buf, len);
1913   return extract_unsigned_integer (buf, len, byte_order);
1914 }
1915
1916 /* See target.h.  */
1917
1918 int
1919 target_insert_breakpoint (struct gdbarch *gdbarch,
1920                           struct bp_target_info *bp_tgt)
1921 {
1922   if (!may_insert_breakpoints)
1923     {
1924       warning (_("May not insert breakpoints"));
1925       return 1;
1926     }
1927
1928   return current_top_target ()->insert_breakpoint (gdbarch, bp_tgt);
1929 }
1930
1931 /* See target.h.  */
1932
1933 int
1934 target_remove_breakpoint (struct gdbarch *gdbarch,
1935                           struct bp_target_info *bp_tgt,
1936                           enum remove_bp_reason reason)
1937 {
1938   /* This is kind of a weird case to handle, but the permission might
1939      have been changed after breakpoints were inserted - in which case
1940      we should just take the user literally and assume that any
1941      breakpoints should be left in place.  */
1942   if (!may_insert_breakpoints)
1943     {
1944       warning (_("May not remove breakpoints"));
1945       return 1;
1946     }
1947
1948   return current_top_target ()->remove_breakpoint (gdbarch, bp_tgt, reason);
1949 }
1950
1951 static void
1952 info_target_command (const char *args, int from_tty)
1953 {
1954   int has_all_mem = 0;
1955
1956   if (symfile_objfile != NULL)
1957     printf_unfiltered (_("Symbols from \"%s\".\n"),
1958                        objfile_name (symfile_objfile));
1959
1960   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
1961     {
1962       if (!t->has_memory ())
1963         continue;
1964
1965       if ((int) (t->to_stratum) <= (int) dummy_stratum)
1966         continue;
1967       if (has_all_mem)
1968         printf_unfiltered (_("\tWhile running this, "
1969                              "GDB does not access memory from...\n"));
1970       printf_unfiltered ("%s:\n", t->longname ());
1971       t->files_info ();
1972       has_all_mem = t->has_all_memory ();
1973     }
1974 }
1975
1976 /* This function is called before any new inferior is created, e.g.
1977    by running a program, attaching, or connecting to a target.
1978    It cleans up any state from previous invocations which might
1979    change between runs.  This is a subset of what target_preopen
1980    resets (things which might change between targets).  */
1981
1982 void
1983 target_pre_inferior (int from_tty)
1984 {
1985   /* Clear out solib state.  Otherwise the solib state of the previous
1986      inferior might have survived and is entirely wrong for the new
1987      target.  This has been observed on GNU/Linux using glibc 2.3.  How
1988      to reproduce:
1989
1990      bash$ ./foo&
1991      [1] 4711
1992      bash$ ./foo&
1993      [1] 4712
1994      bash$ gdb ./foo
1995      [...]
1996      (gdb) attach 4711
1997      (gdb) detach
1998      (gdb) attach 4712
1999      Cannot access memory at address 0xdeadbeef
2000   */
2001
2002   /* In some OSs, the shared library list is the same/global/shared
2003      across inferiors.  If code is shared between processes, so are
2004      memory regions and features.  */
2005   if (!gdbarch_has_global_solist (target_gdbarch ()))
2006     {
2007       no_shared_libraries (NULL, from_tty);
2008
2009       invalidate_target_mem_regions ();
2010
2011       target_clear_description ();
2012     }
2013
2014   /* attach_flag may be set if the previous process associated with
2015      the inferior was attached to.  */
2016   current_inferior ()->attach_flag = 0;
2017
2018   current_inferior ()->highest_thread_num = 0;
2019
2020   agent_capability_invalidate ();
2021 }
2022
2023 /* Callback for iterate_over_inferiors.  Gets rid of the given
2024    inferior.  */
2025
2026 static int
2027 dispose_inferior (struct inferior *inf, void *args)
2028 {
2029   /* Not all killed inferiors can, or will ever be, removed from the
2030      inferior list.  Killed inferiors clearly don't need to be killed
2031      again, so, we're done.  */
2032   if (inf->pid == 0)
2033     return 0;
2034
2035   thread_info *thread = any_thread_of_inferior (inf);
2036   if (thread != NULL)
2037     {
2038       switch_to_thread (thread);
2039
2040       /* Core inferiors actually should be detached, not killed.  */
2041       if (target_has_execution)
2042         target_kill ();
2043       else
2044         target_detach (inf, 0);
2045     }
2046
2047   return 0;
2048 }
2049
2050 /* This is to be called by the open routine before it does
2051    anything.  */
2052
2053 void
2054 target_preopen (int from_tty)
2055 {
2056   dont_repeat ();
2057
2058   if (have_inferiors ())
2059     {
2060       if (!from_tty
2061           || !have_live_inferiors ()
2062           || query (_("A program is being debugged already.  Kill it? ")))
2063         iterate_over_inferiors (dispose_inferior, NULL);
2064       else
2065         error (_("Program not killed."));
2066     }
2067
2068   /* Calling target_kill may remove the target from the stack.  But if
2069      it doesn't (which seems like a win for UDI), remove it now.  */
2070   /* Leave the exec target, though.  The user may be switching from a
2071      live process to a core of the same program.  */
2072   pop_all_targets_above (file_stratum);
2073
2074   target_pre_inferior (from_tty);
2075 }
2076
2077 /* See target.h.  */
2078
2079 void
2080 target_detach (inferior *inf, int from_tty)
2081 {
2082   /* As long as some to_detach implementations rely on the current_inferior
2083      (either directly, or indirectly, like through target_gdbarch or by
2084      reading memory), INF needs to be the current inferior.  When that
2085      requirement will become no longer true, then we can remove this
2086      assertion.  */
2087   gdb_assert (inf == current_inferior ());
2088
2089   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
2090     /* Don't remove global breakpoints here.  They're removed on
2091        disconnection from the target.  */
2092     ;
2093   else
2094     /* If we're in breakpoints-always-inserted mode, have to remove
2095        breakpoints before detaching.  */
2096     remove_breakpoints_inf (current_inferior ());
2097
2098   prepare_for_detach ();
2099
2100   current_top_target ()->detach (inf, from_tty);
2101 }
2102
2103 void
2104 target_disconnect (const char *args, int from_tty)
2105 {
2106   /* If we're in breakpoints-always-inserted mode or if breakpoints
2107      are global across processes, we have to remove them before
2108      disconnecting.  */
2109   remove_breakpoints ();
2110
2111   current_top_target ()->disconnect (args, from_tty);
2112 }
2113
2114 /* See target/target.h.  */
2115
2116 ptid_t
2117 target_wait (ptid_t ptid, struct target_waitstatus *status, int options)
2118 {
2119   return current_top_target ()->wait (ptid, status, options);
2120 }
2121
2122 /* See target.h.  */
2123
2124 ptid_t
2125 default_target_wait (struct target_ops *ops,
2126                      ptid_t ptid, struct target_waitstatus *status,
2127                      int options)
2128 {
2129   status->kind = TARGET_WAITKIND_IGNORE;
2130   return minus_one_ptid;
2131 }
2132
2133 const char *
2134 target_pid_to_str (ptid_t ptid)
2135 {
2136   return current_top_target ()->pid_to_str (ptid);
2137 }
2138
2139 const char *
2140 target_thread_name (struct thread_info *info)
2141 {
2142   return current_top_target ()->thread_name (info);
2143 }
2144
2145 struct thread_info *
2146 target_thread_handle_to_thread_info (const gdb_byte *thread_handle,
2147                                      int handle_len,
2148                                      struct inferior *inf)
2149 {
2150   return current_top_target ()->thread_handle_to_thread_info (thread_handle,
2151                                                      handle_len, inf);
2152 }
2153
2154 void
2155 target_resume (ptid_t ptid, int step, enum gdb_signal signal)
2156 {
2157   target_dcache_invalidate ();
2158
2159   current_top_target ()->resume (ptid, step, signal);
2160
2161   registers_changed_ptid (ptid);
2162   /* We only set the internal executing state here.  The user/frontend
2163      running state is set at a higher level.  This also clears the
2164      thread's stop_pc as side effect.  */
2165   set_executing (ptid, 1);
2166   clear_inline_frame_state (ptid);
2167 }
2168
2169 /* If true, target_commit_resume is a nop.  */
2170 static int defer_target_commit_resume;
2171
2172 /* See target.h.  */
2173
2174 void
2175 target_commit_resume (void)
2176 {
2177   if (defer_target_commit_resume)
2178     return;
2179
2180   current_top_target ()->commit_resume ();
2181 }
2182
2183 /* See target.h.  */
2184
2185 scoped_restore_tmpl<int>
2186 make_scoped_defer_target_commit_resume ()
2187 {
2188   return make_scoped_restore (&defer_target_commit_resume, 1);
2189 }
2190
2191 void
2192 target_pass_signals (int numsigs, unsigned char *pass_signals)
2193 {
2194   current_top_target ()->pass_signals (numsigs, pass_signals);
2195 }
2196
2197 void
2198 target_program_signals (int numsigs, unsigned char *program_signals)
2199 {
2200   current_top_target ()->program_signals (numsigs, program_signals);
2201 }
2202
2203 static int
2204 default_follow_fork (struct target_ops *self, int follow_child,
2205                      int detach_fork)
2206 {
2207   /* Some target returned a fork event, but did not know how to follow it.  */
2208   internal_error (__FILE__, __LINE__,
2209                   _("could not find a target to follow fork"));
2210 }
2211
2212 /* Look through the list of possible targets for a target that can
2213    follow forks.  */
2214
2215 int
2216 target_follow_fork (int follow_child, int detach_fork)
2217 {
2218   return current_top_target ()->follow_fork (follow_child, detach_fork);
2219 }
2220
2221 /* Target wrapper for follow exec hook.  */
2222
2223 void
2224 target_follow_exec (struct inferior *inf, char *execd_pathname)
2225 {
2226   current_top_target ()->follow_exec (inf, execd_pathname);
2227 }
2228
2229 static void
2230 default_mourn_inferior (struct target_ops *self)
2231 {
2232   internal_error (__FILE__, __LINE__,
2233                   _("could not find a target to follow mourn inferior"));
2234 }
2235
2236 void
2237 target_mourn_inferior (ptid_t ptid)
2238 {
2239   gdb_assert (ptid == inferior_ptid);
2240   current_top_target ()->mourn_inferior ();
2241
2242   /* We no longer need to keep handles on any of the object files.
2243      Make sure to release them to avoid unnecessarily locking any
2244      of them while we're not actually debugging.  */
2245   bfd_cache_close_all ();
2246 }
2247
2248 /* Look for a target which can describe architectural features, starting
2249    from TARGET.  If we find one, return its description.  */
2250
2251 const struct target_desc *
2252 target_read_description (struct target_ops *target)
2253 {
2254   return target->read_description ();
2255 }
2256
2257 /* This implements a basic search of memory, reading target memory and
2258    performing the search here (as opposed to performing the search in on the
2259    target side with, for example, gdbserver).  */
2260
2261 int
2262 simple_search_memory (struct target_ops *ops,
2263                       CORE_ADDR start_addr, ULONGEST search_space_len,
2264                       const gdb_byte *pattern, ULONGEST pattern_len,
2265                       CORE_ADDR *found_addrp)
2266 {
2267   /* NOTE: also defined in find.c testcase.  */
2268 #define SEARCH_CHUNK_SIZE 16000
2269   const unsigned chunk_size = SEARCH_CHUNK_SIZE;
2270   /* Buffer to hold memory contents for searching.  */
2271   unsigned search_buf_size;
2272
2273   search_buf_size = chunk_size + pattern_len - 1;
2274
2275   /* No point in trying to allocate a buffer larger than the search space.  */
2276   if (search_space_len < search_buf_size)
2277     search_buf_size = search_space_len;
2278
2279   gdb::byte_vector search_buf (search_buf_size);
2280
2281   /* Prime the search buffer.  */
2282
2283   if (target_read (ops, TARGET_OBJECT_MEMORY, NULL,
2284                    search_buf.data (), start_addr, search_buf_size)
2285       != search_buf_size)
2286     {
2287       warning (_("Unable to access %s bytes of target "
2288                  "memory at %s, halting search."),
2289                pulongest (search_buf_size), hex_string (start_addr));
2290       return -1;
2291     }
2292
2293   /* Perform the search.
2294
2295      The loop is kept simple by allocating [N + pattern-length - 1] bytes.
2296      When we've scanned N bytes we copy the trailing bytes to the start and
2297      read in another N bytes.  */
2298
2299   while (search_space_len >= pattern_len)
2300     {
2301       gdb_byte *found_ptr;
2302       unsigned nr_search_bytes
2303         = std::min (search_space_len, (ULONGEST) search_buf_size);
2304
2305       found_ptr = (gdb_byte *) memmem (search_buf.data (), nr_search_bytes,
2306                                        pattern, pattern_len);
2307
2308       if (found_ptr != NULL)
2309         {
2310           CORE_ADDR found_addr = start_addr + (found_ptr - search_buf.data ());
2311
2312           *found_addrp = found_addr;
2313           return 1;
2314         }
2315
2316       /* Not found in this chunk, skip to next chunk.  */
2317
2318       /* Don't let search_space_len wrap here, it's unsigned.  */
2319       if (search_space_len >= chunk_size)
2320         search_space_len -= chunk_size;
2321       else
2322         search_space_len = 0;
2323
2324       if (search_space_len >= pattern_len)
2325         {
2326           unsigned keep_len = search_buf_size - chunk_size;
2327           CORE_ADDR read_addr = start_addr + chunk_size + keep_len;
2328           int nr_to_read;
2329
2330           /* Copy the trailing part of the previous iteration to the front
2331              of the buffer for the next iteration.  */
2332           gdb_assert (keep_len == pattern_len - 1);
2333           memcpy (&search_buf[0], &search_buf[chunk_size], keep_len);
2334
2335           nr_to_read = std::min (search_space_len - keep_len,
2336                                  (ULONGEST) chunk_size);
2337
2338           if (target_read (ops, TARGET_OBJECT_MEMORY, NULL,
2339                            &search_buf[keep_len], read_addr,
2340                            nr_to_read) != nr_to_read)
2341             {
2342               warning (_("Unable to access %s bytes of target "
2343                          "memory at %s, halting search."),
2344                        plongest (nr_to_read),
2345                        hex_string (read_addr));
2346               return -1;
2347             }
2348
2349           start_addr += chunk_size;
2350         }
2351     }
2352
2353   /* Not found.  */
2354
2355   return 0;
2356 }
2357
2358 /* Default implementation of memory-searching.  */
2359
2360 static int
2361 default_search_memory (struct target_ops *self,
2362                        CORE_ADDR start_addr, ULONGEST search_space_len,
2363                        const gdb_byte *pattern, ULONGEST pattern_len,
2364                        CORE_ADDR *found_addrp)
2365 {
2366   /* Start over from the top of the target stack.  */
2367   return simple_search_memory (current_top_target (),
2368                                start_addr, search_space_len,
2369                                pattern, pattern_len, found_addrp);
2370 }
2371
2372 /* Search SEARCH_SPACE_LEN bytes beginning at START_ADDR for the
2373    sequence of bytes in PATTERN with length PATTERN_LEN.
2374
2375    The result is 1 if found, 0 if not found, and -1 if there was an error
2376    requiring halting of the search (e.g. memory read error).
2377    If the pattern is found the address is recorded in FOUND_ADDRP.  */
2378
2379 int
2380 target_search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
2381                       const gdb_byte *pattern, ULONGEST pattern_len,
2382                       CORE_ADDR *found_addrp)
2383 {
2384   return current_top_target ()->search_memory (start_addr, search_space_len,
2385                                       pattern, pattern_len, found_addrp);
2386 }
2387
2388 /* Look through the currently pushed targets.  If none of them will
2389    be able to restart the currently running process, issue an error
2390    message.  */
2391
2392 void
2393 target_require_runnable (void)
2394 {
2395   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
2396     {
2397       /* If this target knows how to create a new program, then
2398          assume we will still be able to after killing the current
2399          one.  Either killing and mourning will not pop T, or else
2400          find_default_run_target will find it again.  */
2401       if (t->can_create_inferior ())
2402         return;
2403
2404       /* Do not worry about targets at certain strata that can not
2405          create inferiors.  Assume they will be pushed again if
2406          necessary, and continue to the process_stratum.  */
2407       if (t->to_stratum > process_stratum)
2408         continue;
2409
2410       error (_("The \"%s\" target does not support \"run\".  "
2411                "Try \"help target\" or \"continue\"."),
2412              t->shortname ());
2413     }
2414
2415   /* This function is only called if the target is running.  In that
2416      case there should have been a process_stratum target and it
2417      should either know how to create inferiors, or not...  */
2418   internal_error (__FILE__, __LINE__, _("No targets found"));
2419 }
2420
2421 /* Whether GDB is allowed to fall back to the default run target for
2422    "run", "attach", etc. when no target is connected yet.  */
2423 static int auto_connect_native_target = 1;
2424
2425 static void
2426 show_auto_connect_native_target (struct ui_file *file, int from_tty,
2427                                  struct cmd_list_element *c, const char *value)
2428 {
2429   fprintf_filtered (file,
2430                     _("Whether GDB may automatically connect to the "
2431                       "native target is %s.\n"),
2432                     value);
2433 }
2434
2435 /* A pointer to the target that can respond to "run" or "attach".
2436    Native targets are always singletons and instantiated early at GDB
2437    startup.  */
2438 static target_ops *the_native_target;
2439
2440 /* See target.h.  */
2441
2442 void
2443 set_native_target (target_ops *target)
2444 {
2445   if (the_native_target != NULL)
2446     internal_error (__FILE__, __LINE__,
2447                     _("native target already set (\"%s\")."),
2448                     the_native_target->longname ());
2449
2450   the_native_target = target;
2451 }
2452
2453 /* See target.h.  */
2454
2455 target_ops *
2456 get_native_target ()
2457 {
2458   return the_native_target;
2459 }
2460
2461 /* Look through the list of possible targets for a target that can
2462    execute a run or attach command without any other data.  This is
2463    used to locate the default process stratum.
2464
2465    If DO_MESG is not NULL, the result is always valid (error() is
2466    called for errors); else, return NULL on error.  */
2467
2468 static struct target_ops *
2469 find_default_run_target (const char *do_mesg)
2470 {
2471   if (auto_connect_native_target && the_native_target != NULL)
2472     return the_native_target;
2473
2474   if (do_mesg != NULL)
2475     error (_("Don't know how to %s.  Try \"help target\"."), do_mesg);
2476   return NULL;
2477 }
2478
2479 /* See target.h.  */
2480
2481 struct target_ops *
2482 find_attach_target (void)
2483 {
2484   /* If a target on the current stack can attach, use it.  */
2485   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
2486     {
2487       if (t->can_attach ())
2488         return t;
2489     }
2490
2491   /* Otherwise, use the default run target for attaching.  */
2492   return find_default_run_target ("attach");
2493 }
2494
2495 /* See target.h.  */
2496
2497 struct target_ops *
2498 find_run_target (void)
2499 {
2500   /* If a target on the current stack can run, use it.  */
2501   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
2502     {
2503       if (t->can_create_inferior ())
2504         return t;
2505     }
2506
2507   /* Otherwise, use the default run target.  */
2508   return find_default_run_target ("run");
2509 }
2510
2511 bool
2512 target_ops::info_proc (const char *args, enum info_proc_what what)
2513 {
2514   return false;
2515 }
2516
2517 /* Implement the "info proc" command.  */
2518
2519 int
2520 target_info_proc (const char *args, enum info_proc_what what)
2521 {
2522   struct target_ops *t;
2523
2524   /* If we're already connected to something that can get us OS
2525      related data, use it.  Otherwise, try using the native
2526      target.  */
2527   t = find_target_at (process_stratum);
2528   if (t == NULL)
2529     t = find_default_run_target (NULL);
2530
2531   for (; t != NULL; t = t->beneath ())
2532     {
2533       if (t->info_proc (args, what))
2534         {
2535           if (targetdebug)
2536             fprintf_unfiltered (gdb_stdlog,
2537                                 "target_info_proc (\"%s\", %d)\n", args, what);
2538
2539           return 1;
2540         }
2541     }
2542
2543   return 0;
2544 }
2545
2546 static int
2547 find_default_supports_disable_randomization (struct target_ops *self)
2548 {
2549   struct target_ops *t;
2550
2551   t = find_default_run_target (NULL);
2552   if (t != NULL)
2553     return t->supports_disable_randomization ();
2554   return 0;
2555 }
2556
2557 int
2558 target_supports_disable_randomization (void)
2559 {
2560   return current_top_target ()->supports_disable_randomization ();
2561 }
2562
2563 /* See target/target.h.  */
2564
2565 int
2566 target_supports_multi_process (void)
2567 {
2568   return current_top_target ()->supports_multi_process ();
2569 }
2570
2571 /* See target.h.  */
2572
2573 gdb::optional<gdb::char_vector>
2574 target_get_osdata (const char *type)
2575 {
2576   struct target_ops *t;
2577
2578   /* If we're already connected to something that can get us OS
2579      related data, use it.  Otherwise, try using the native
2580      target.  */
2581   t = find_target_at (process_stratum);
2582   if (t == NULL)
2583     t = find_default_run_target ("get OS data");
2584
2585   if (!t)
2586     return {};
2587
2588   return target_read_stralloc (t, TARGET_OBJECT_OSDATA, type);
2589 }
2590
2591 static struct address_space *
2592 default_thread_address_space (struct target_ops *self, ptid_t ptid)
2593 {
2594   struct inferior *inf;
2595
2596   /* Fall-back to the "main" address space of the inferior.  */
2597   inf = find_inferior_ptid (ptid);
2598
2599   if (inf == NULL || inf->aspace == NULL)
2600     internal_error (__FILE__, __LINE__,
2601                     _("Can't determine the current "
2602                       "address space of thread %s\n"),
2603                     target_pid_to_str (ptid));
2604
2605   return inf->aspace;
2606 }
2607
2608 /* Determine the current address space of thread PTID.  */
2609
2610 struct address_space *
2611 target_thread_address_space (ptid_t ptid)
2612 {
2613   struct address_space *aspace;
2614
2615   aspace = current_top_target ()->thread_address_space (ptid);
2616   gdb_assert (aspace != NULL);
2617
2618   return aspace;
2619 }
2620
2621 /* See target.h.  */
2622
2623 target_ops *
2624 target_ops::beneath () const
2625 {
2626   return g_target_stack.find_beneath (this);
2627 }
2628
2629 void
2630 target_ops::close ()
2631 {
2632 }
2633
2634 bool
2635 target_ops::can_attach ()
2636 {
2637   return 0;
2638 }
2639
2640 void
2641 target_ops::attach (const char *, int)
2642 {
2643   gdb_assert_not_reached ("target_ops::attach called");
2644 }
2645
2646 bool
2647 target_ops::can_create_inferior ()
2648 {
2649   return 0;
2650 }
2651
2652 void
2653 target_ops::create_inferior (const char *, const std::string &,
2654                              char **, int)
2655 {
2656   gdb_assert_not_reached ("target_ops::create_inferior called");
2657 }
2658
2659 bool
2660 target_ops::can_run ()
2661 {
2662   return false;
2663 }
2664
2665 int
2666 target_can_run ()
2667 {
2668   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
2669     {
2670       if (t->can_run ())
2671         return 1;
2672     }
2673
2674   return 0;
2675 }
2676
2677 /* Target file operations.  */
2678
2679 static struct target_ops *
2680 default_fileio_target (void)
2681 {
2682   struct target_ops *t;
2683
2684   /* If we're already connected to something that can perform
2685      file I/O, use it. Otherwise, try using the native target.  */
2686   t = find_target_at (process_stratum);
2687   if (t != NULL)
2688     return t;
2689   return find_default_run_target ("file I/O");
2690 }
2691
2692 /* File handle for target file operations.  */
2693
2694 struct fileio_fh_t
2695 {
2696   /* The target on which this file is open.  NULL if the target is
2697      meanwhile closed while the handle is open.  */
2698   target_ops *target;
2699
2700   /* The file descriptor on the target.  */
2701   int target_fd;
2702
2703   /* Check whether this fileio_fh_t represents a closed file.  */
2704   bool is_closed ()
2705   {
2706     return target_fd < 0;
2707   }
2708 };
2709
2710 /* Vector of currently open file handles.  The value returned by
2711    target_fileio_open and passed as the FD argument to other
2712    target_fileio_* functions is an index into this vector.  This
2713    vector's entries are never freed; instead, files are marked as
2714    closed, and the handle becomes available for reuse.  */
2715 static std::vector<fileio_fh_t> fileio_fhandles;
2716
2717 /* Index into fileio_fhandles of the lowest handle that might be
2718    closed.  This permits handle reuse without searching the whole
2719    list each time a new file is opened.  */
2720 static int lowest_closed_fd;
2721
2722 /* Invalidate the target associated with open handles that were open
2723    on target TARG, since we're about to close (and maybe destroy) the
2724    target.  The handles remain open from the client's perspective, but
2725    trying to do anything with them other than closing them will fail
2726    with EIO.  */
2727
2728 static void
2729 fileio_handles_invalidate_target (target_ops *targ)
2730 {
2731   for (fileio_fh_t &fh : fileio_fhandles)
2732     if (fh.target == targ)
2733       fh.target = NULL;
2734 }
2735
2736 /* Acquire a target fileio file descriptor.  */
2737
2738 static int
2739 acquire_fileio_fd (target_ops *target, int target_fd)
2740 {
2741   /* Search for closed handles to reuse.  */
2742   for (; lowest_closed_fd < fileio_fhandles.size (); lowest_closed_fd++)
2743     {
2744       fileio_fh_t &fh = fileio_fhandles[lowest_closed_fd];
2745
2746       if (fh.is_closed ())
2747         break;
2748     }
2749
2750   /* Push a new handle if no closed handles were found.  */
2751   if (lowest_closed_fd == fileio_fhandles.size ())
2752     fileio_fhandles.push_back (fileio_fh_t {target, target_fd});
2753   else
2754     fileio_fhandles[lowest_closed_fd] = {target, target_fd};
2755
2756   /* Should no longer be marked closed.  */
2757   gdb_assert (!fileio_fhandles[lowest_closed_fd].is_closed ());
2758
2759   /* Return its index, and start the next lookup at
2760      the next index.  */
2761   return lowest_closed_fd++;
2762 }
2763
2764 /* Release a target fileio file descriptor.  */
2765
2766 static void
2767 release_fileio_fd (int fd, fileio_fh_t *fh)
2768 {
2769   fh->target_fd = -1;
2770   lowest_closed_fd = std::min (lowest_closed_fd, fd);
2771 }
2772
2773 /* Return a pointer to the fileio_fhandle_t corresponding to FD.  */
2774
2775 static fileio_fh_t *
2776 fileio_fd_to_fh (int fd)
2777 {
2778   return &fileio_fhandles[fd];
2779 }
2780
2781
2782 /* Default implementations of file i/o methods.  We don't want these
2783    to delegate automatically, because we need to know which target
2784    supported the method, in order to call it directly from within
2785    pread/pwrite, etc.  */
2786
2787 int
2788 target_ops::fileio_open (struct inferior *inf, const char *filename,
2789                          int flags, int mode, int warn_if_slow,
2790                          int *target_errno)
2791 {
2792   *target_errno = FILEIO_ENOSYS;
2793   return -1;
2794 }
2795
2796 int
2797 target_ops::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
2798                            ULONGEST offset, int *target_errno)
2799 {
2800   *target_errno = FILEIO_ENOSYS;
2801   return -1;
2802 }
2803
2804 int
2805 target_ops::fileio_pread (int fd, gdb_byte *read_buf, int len,
2806                           ULONGEST offset, int *target_errno)
2807 {
2808   *target_errno = FILEIO_ENOSYS;
2809   return -1;
2810 }
2811
2812 int
2813 target_ops::fileio_fstat (int fd, struct stat *sb, int *target_errno)
2814 {
2815   *target_errno = FILEIO_ENOSYS;
2816   return -1;
2817 }
2818
2819 int
2820 target_ops::fileio_close (int fd, int *target_errno)
2821 {
2822   *target_errno = FILEIO_ENOSYS;
2823   return -1;
2824 }
2825
2826 int
2827 target_ops::fileio_unlink (struct inferior *inf, const char *filename,
2828                            int *target_errno)
2829 {
2830   *target_errno = FILEIO_ENOSYS;
2831   return -1;
2832 }
2833
2834 gdb::optional<std::string>
2835 target_ops::fileio_readlink (struct inferior *inf, const char *filename,
2836                              int *target_errno)
2837 {
2838   *target_errno = FILEIO_ENOSYS;
2839   return {};
2840 }
2841
2842 /* Helper for target_fileio_open and
2843    target_fileio_open_warn_if_slow.  */
2844
2845 static int
2846 target_fileio_open_1 (struct inferior *inf, const char *filename,
2847                       int flags, int mode, int warn_if_slow,
2848                       int *target_errno)
2849 {
2850   for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
2851     {
2852       int fd = t->fileio_open (inf, filename, flags, mode,
2853                                warn_if_slow, target_errno);
2854
2855       if (fd == -1 && *target_errno == FILEIO_ENOSYS)
2856         continue;
2857
2858       if (fd < 0)
2859         fd = -1;
2860       else
2861         fd = acquire_fileio_fd (t, fd);
2862
2863       if (targetdebug)
2864         fprintf_unfiltered (gdb_stdlog,
2865                                 "target_fileio_open (%d,%s,0x%x,0%o,%d)"
2866                                 " = %d (%d)\n",
2867                                 inf == NULL ? 0 : inf->num,
2868                                 filename, flags, mode,
2869                                 warn_if_slow, fd,
2870                                 fd != -1 ? 0 : *target_errno);
2871       return fd;
2872     }
2873
2874   *target_errno = FILEIO_ENOSYS;
2875   return -1;
2876 }
2877
2878 /* See target.h.  */
2879
2880 int
2881 target_fileio_open (struct inferior *inf, const char *filename,
2882                     int flags, int mode, int *target_errno)
2883 {
2884   return target_fileio_open_1 (inf, filename, flags, mode, 0,
2885                                target_errno);
2886 }
2887
2888 /* See target.h.  */
2889
2890 int
2891 target_fileio_open_warn_if_slow (struct inferior *inf,
2892                                  const char *filename,
2893                                  int flags, int mode, int *target_errno)
2894 {
2895   return target_fileio_open_1 (inf, filename, flags, mode, 1,
2896                                target_errno);
2897 }
2898
2899 /* See target.h.  */
2900
2901 int
2902 target_fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
2903                       ULONGEST offset, int *target_errno)
2904 {
2905   fileio_fh_t *fh = fileio_fd_to_fh (fd);
2906   int ret = -1;
2907
2908   if (fh->is_closed ())
2909     *target_errno = EBADF;
2910   else if (fh->target == NULL)
2911     *target_errno = EIO;
2912   else
2913     ret = fh->target->fileio_pwrite (fh->target_fd, write_buf,
2914                                      len, offset, target_errno);
2915
2916   if (targetdebug)
2917     fprintf_unfiltered (gdb_stdlog,
2918                         "target_fileio_pwrite (%d,...,%d,%s) "
2919                         "= %d (%d)\n",
2920                         fd, len, pulongest (offset),
2921                         ret, ret != -1 ? 0 : *target_errno);
2922   return ret;
2923 }
2924
2925 /* See target.h.  */
2926
2927 int
2928 target_fileio_pread (int fd, gdb_byte *read_buf, int len,
2929                      ULONGEST offset, int *target_errno)
2930 {
2931   fileio_fh_t *fh = fileio_fd_to_fh (fd);
2932   int ret = -1;
2933
2934   if (fh->is_closed ())
2935     *target_errno = EBADF;
2936   else if (fh->target == NULL)
2937     *target_errno = EIO;
2938   else
2939     ret = fh->target->fileio_pread (fh->target_fd, read_buf,
2940                                     len, offset, target_errno);
2941
2942   if (targetdebug)
2943     fprintf_unfiltered (gdb_stdlog,
2944                         "target_fileio_pread (%d,...,%d,%s) "
2945                         "= %d (%d)\n",
2946                         fd, len, pulongest (offset),
2947                         ret, ret != -1 ? 0 : *target_errno);
2948   return ret;
2949 }
2950
2951 /* See target.h.  */
2952
2953 int
2954 target_fileio_fstat (int fd, struct stat *sb, int *target_errno)
2955 {
2956   fileio_fh_t *fh = fileio_fd_to_fh (fd);
2957   int ret = -1;
2958
2959   if (fh->is_closed ())
2960     *target_errno = EBADF;
2961   else if (fh->target == NULL)
2962     *target_errno = EIO;
2963   else
2964     ret = fh->target->fileio_fstat (fh->target_fd, sb, target_errno);
2965
2966   if (targetdebug)
2967     fprintf_unfiltered (gdb_stdlog,
2968                         "target_fileio_fstat (%d) = %d (%d)\n",
2969                         fd, ret, ret != -1 ? 0 : *target_errno);
2970   return ret;
2971 }
2972
2973 /* See target.h.  */
2974
2975 int
2976 target_fileio_close (int fd, int *target_errno)
2977 {
2978   fileio_fh_t *fh = fileio_fd_to_fh (fd);
2979   int ret = -1;
2980
2981   if (fh->is_closed ())
2982     *target_errno = EBADF;
2983   else
2984     {
2985       if (fh->target != NULL)
2986         ret = fh->target->fileio_close (fh->target_fd,
2987                                         target_errno);
2988       else
2989         ret = 0;
2990       release_fileio_fd (fd, fh);
2991     }
2992
2993   if (targetdebug)
2994     fprintf_unfiltered (gdb_stdlog,
2995                         "target_fileio_close (%d) = %d (%d)\n",
2996                         fd, ret, ret != -1 ? 0 : *target_errno);
2997   return ret;
2998 }
2999
3000 /* See target.h.  */
3001
3002 int
3003 target_fileio_unlink (struct inferior *inf, const char *filename,
3004                       int *target_errno)
3005 {
3006   for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3007     {
3008       int ret = t->fileio_unlink (inf, filename, target_errno);
3009
3010       if (ret == -1 && *target_errno == FILEIO_ENOSYS)
3011         continue;
3012
3013       if (targetdebug)
3014         fprintf_unfiltered (gdb_stdlog,
3015                             "target_fileio_unlink (%d,%s)"
3016                             " = %d (%d)\n",
3017                             inf == NULL ? 0 : inf->num, filename,
3018                             ret, ret != -1 ? 0 : *target_errno);
3019       return ret;
3020     }
3021
3022   *target_errno = FILEIO_ENOSYS;
3023   return -1;
3024 }
3025
3026 /* See target.h.  */
3027
3028 gdb::optional<std::string>
3029 target_fileio_readlink (struct inferior *inf, const char *filename,
3030                         int *target_errno)
3031 {
3032   for (target_ops *t = default_fileio_target (); t != NULL; t = t->beneath ())
3033     {
3034       gdb::optional<std::string> ret
3035         = t->fileio_readlink (inf, filename, target_errno);
3036
3037       if (!ret.has_value () && *target_errno == FILEIO_ENOSYS)
3038         continue;
3039
3040       if (targetdebug)
3041         fprintf_unfiltered (gdb_stdlog,
3042                             "target_fileio_readlink (%d,%s)"
3043                             " = %s (%d)\n",
3044                             inf == NULL ? 0 : inf->num,
3045                             filename, ret ? ret->c_str () : "(nil)",
3046                             ret ? 0 : *target_errno);
3047       return ret;
3048     }
3049
3050   *target_errno = FILEIO_ENOSYS;
3051   return {};
3052 }
3053
3054 /* Like scoped_fd, but specific to target fileio.  */
3055
3056 class scoped_target_fd
3057 {
3058 public:
3059   explicit scoped_target_fd (int fd) noexcept
3060     : m_fd (fd)
3061   {
3062   }
3063
3064   ~scoped_target_fd ()
3065   {
3066     if (m_fd >= 0)
3067       {
3068         int target_errno;
3069
3070         target_fileio_close (m_fd, &target_errno);
3071       }
3072   }
3073
3074   DISABLE_COPY_AND_ASSIGN (scoped_target_fd);
3075
3076   int get () const noexcept
3077   {
3078     return m_fd;
3079   }
3080
3081 private:
3082   int m_fd;
3083 };
3084
3085 /* Read target file FILENAME, in the filesystem as seen by INF.  If
3086    INF is NULL, use the filesystem seen by the debugger (GDB or, for
3087    remote targets, the remote stub).  Store the result in *BUF_P and
3088    return the size of the transferred data.  PADDING additional bytes
3089    are available in *BUF_P.  This is a helper function for
3090    target_fileio_read_alloc; see the declaration of that function for
3091    more information.  */
3092
3093 static LONGEST
3094 target_fileio_read_alloc_1 (struct inferior *inf, const char *filename,
3095                             gdb_byte **buf_p, int padding)
3096 {
3097   size_t buf_alloc, buf_pos;
3098   gdb_byte *buf;
3099   LONGEST n;
3100   int target_errno;
3101
3102   scoped_target_fd fd (target_fileio_open (inf, filename, FILEIO_O_RDONLY,
3103                                            0700, &target_errno));
3104   if (fd.get () == -1)
3105     return -1;
3106
3107   /* Start by reading up to 4K at a time.  The target will throttle
3108      this number down if necessary.  */
3109   buf_alloc = 4096;
3110   buf = (gdb_byte *) xmalloc (buf_alloc);
3111   buf_pos = 0;
3112   while (1)
3113     {
3114       n = target_fileio_pread (fd.get (), &buf[buf_pos],
3115                                buf_alloc - buf_pos - padding, buf_pos,
3116                                &target_errno);
3117       if (n < 0)
3118         {
3119           /* An error occurred.  */
3120           xfree (buf);
3121           return -1;
3122         }
3123       else if (n == 0)
3124         {
3125           /* Read all there was.  */
3126           if (buf_pos == 0)
3127             xfree (buf);
3128           else
3129             *buf_p = buf;
3130           return buf_pos;
3131         }
3132
3133       buf_pos += n;
3134
3135       /* If the buffer is filling up, expand it.  */
3136       if (buf_alloc < buf_pos * 2)
3137         {
3138           buf_alloc *= 2;
3139           buf = (gdb_byte *) xrealloc (buf, buf_alloc);
3140         }
3141
3142       QUIT;
3143     }
3144 }
3145
3146 /* See target.h.  */
3147
3148 LONGEST
3149 target_fileio_read_alloc (struct inferior *inf, const char *filename,
3150                           gdb_byte **buf_p)
3151 {
3152   return target_fileio_read_alloc_1 (inf, filename, buf_p, 0);
3153 }
3154
3155 /* See target.h.  */
3156
3157 gdb::unique_xmalloc_ptr<char> 
3158 target_fileio_read_stralloc (struct inferior *inf, const char *filename)
3159 {
3160   gdb_byte *buffer;
3161   char *bufstr;
3162   LONGEST i, transferred;
3163
3164   transferred = target_fileio_read_alloc_1 (inf, filename, &buffer, 1);
3165   bufstr = (char *) buffer;
3166
3167   if (transferred < 0)
3168     return gdb::unique_xmalloc_ptr<char> (nullptr);
3169
3170   if (transferred == 0)
3171     return gdb::unique_xmalloc_ptr<char> (xstrdup (""));
3172
3173   bufstr[transferred] = 0;
3174
3175   /* Check for embedded NUL bytes; but allow trailing NULs.  */
3176   for (i = strlen (bufstr); i < transferred; i++)
3177     if (bufstr[i] != 0)
3178       {
3179         warning (_("target file %s "
3180                    "contained unexpected null characters"),
3181                  filename);
3182         break;
3183       }
3184
3185   return gdb::unique_xmalloc_ptr<char> (bufstr);
3186 }
3187
3188
3189 static int
3190 default_region_ok_for_hw_watchpoint (struct target_ops *self,
3191                                      CORE_ADDR addr, int len)
3192 {
3193   return (len <= gdbarch_ptr_bit (target_gdbarch ()) / TARGET_CHAR_BIT);
3194 }
3195
3196 static int
3197 default_watchpoint_addr_within_range (struct target_ops *target,
3198                                       CORE_ADDR addr,
3199                                       CORE_ADDR start, int length)
3200 {
3201   return addr >= start && addr < start + length;
3202 }
3203
3204 static struct gdbarch *
3205 default_thread_architecture (struct target_ops *ops, ptid_t ptid)
3206 {
3207   inferior *inf = find_inferior_ptid (ptid);
3208   gdb_assert (inf != NULL);
3209   return inf->gdbarch;
3210 }
3211
3212 /* See target.h.  */
3213
3214 target_ops *
3215 target_stack::find_beneath (const target_ops *t) const
3216 {
3217   /* Look for a non-empty slot at stratum levels beneath T's.  */
3218   for (int stratum = t->to_stratum - 1; stratum >= 0; --stratum)
3219     if (m_stack[stratum] != NULL)
3220       return m_stack[stratum];
3221
3222   return NULL;
3223 }
3224
3225 /* See target.h.  */
3226
3227 struct target_ops *
3228 find_target_at (enum strata stratum)
3229 {
3230   return g_target_stack.at (stratum);
3231 }
3232
3233 \f
3234
3235 /* See target.h  */
3236
3237 void
3238 target_announce_detach (int from_tty)
3239 {
3240   pid_t pid;
3241   const char *exec_file;
3242
3243   if (!from_tty)
3244     return;
3245
3246   exec_file = get_exec_file (0);
3247   if (exec_file == NULL)
3248     exec_file = "";
3249
3250   pid = inferior_ptid.pid ();
3251   printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
3252                      target_pid_to_str (ptid_t (pid)));
3253   gdb_flush (gdb_stdout);
3254 }
3255
3256 /* The inferior process has died.  Long live the inferior!  */
3257
3258 void
3259 generic_mourn_inferior (void)
3260 {
3261   inferior *inf = current_inferior ();
3262
3263   inferior_ptid = null_ptid;
3264
3265   /* Mark breakpoints uninserted in case something tries to delete a
3266      breakpoint while we delete the inferior's threads (which would
3267      fail, since the inferior is long gone).  */
3268   mark_breakpoints_out ();
3269
3270   if (inf->pid != 0)
3271     exit_inferior (inf);
3272
3273   /* Note this wipes step-resume breakpoints, so needs to be done
3274      after exit_inferior, which ends up referencing the step-resume
3275      breakpoints through clear_thread_inferior_resources.  */
3276   breakpoint_init_inferior (inf_exited);
3277
3278   registers_changed ();
3279
3280   reopen_exec_file ();
3281   reinit_frame_cache ();
3282
3283   if (deprecated_detach_hook)
3284     deprecated_detach_hook ();
3285 }
3286 \f
3287 /* Convert a normal process ID to a string.  Returns the string in a
3288    static buffer.  */
3289
3290 const char *
3291 normal_pid_to_str (ptid_t ptid)
3292 {
3293   static char buf[32];
3294
3295   xsnprintf (buf, sizeof buf, "process %d", ptid.pid ());
3296   return buf;
3297 }
3298
3299 static const char *
3300 default_pid_to_str (struct target_ops *ops, ptid_t ptid)
3301 {
3302   return normal_pid_to_str (ptid);
3303 }
3304
3305 /* Error-catcher for target_find_memory_regions.  */
3306 static int
3307 dummy_find_memory_regions (struct target_ops *self,
3308                            find_memory_region_ftype ignore1, void *ignore2)
3309 {
3310   error (_("Command not implemented for this target."));
3311   return 0;
3312 }
3313
3314 /* Error-catcher for target_make_corefile_notes.  */
3315 static char *
3316 dummy_make_corefile_notes (struct target_ops *self,
3317                            bfd *ignore1, int *ignore2)
3318 {
3319   error (_("Command not implemented for this target."));
3320   return NULL;
3321 }
3322
3323 #include "target-delegates.c"
3324
3325
3326 static const target_info dummy_target_info = {
3327   "None",
3328   N_("None"),
3329   ""
3330 };
3331
3332 dummy_target::dummy_target ()
3333 {
3334   to_stratum = dummy_stratum;
3335 }
3336
3337 debug_target::debug_target ()
3338 {
3339   to_stratum = debug_stratum;
3340 }
3341
3342 const target_info &
3343 dummy_target::info () const
3344 {
3345   return dummy_target_info;
3346 }
3347
3348 const target_info &
3349 debug_target::info () const
3350 {
3351   return beneath ()->info ();
3352 }
3353
3354 \f
3355
3356 void
3357 target_close (struct target_ops *targ)
3358 {
3359   gdb_assert (!target_is_pushed (targ));
3360
3361   fileio_handles_invalidate_target (targ);
3362
3363   targ->close ();
3364
3365   if (targetdebug)
3366     fprintf_unfiltered (gdb_stdlog, "target_close ()\n");
3367 }
3368
3369 int
3370 target_thread_alive (ptid_t ptid)
3371 {
3372   return current_top_target ()->thread_alive (ptid);
3373 }
3374
3375 void
3376 target_update_thread_list (void)
3377 {
3378   current_top_target ()->update_thread_list ();
3379 }
3380
3381 void
3382 target_stop (ptid_t ptid)
3383 {
3384   if (!may_stop)
3385     {
3386       warning (_("May not interrupt or stop the target, ignoring attempt"));
3387       return;
3388     }
3389
3390   current_top_target ()->stop (ptid);
3391 }
3392
3393 void
3394 target_interrupt ()
3395 {
3396   if (!may_stop)
3397     {
3398       warning (_("May not interrupt or stop the target, ignoring attempt"));
3399       return;
3400     }
3401
3402   current_top_target ()->interrupt ();
3403 }
3404
3405 /* See target.h.  */
3406
3407 void
3408 target_pass_ctrlc (void)
3409 {
3410   current_top_target ()->pass_ctrlc ();
3411 }
3412
3413 /* See target.h.  */
3414
3415 void
3416 default_target_pass_ctrlc (struct target_ops *ops)
3417 {
3418   target_interrupt ();
3419 }
3420
3421 /* See target/target.h.  */
3422
3423 void
3424 target_stop_and_wait (ptid_t ptid)
3425 {
3426   struct target_waitstatus status;
3427   int was_non_stop = non_stop;
3428
3429   non_stop = 1;
3430   target_stop (ptid);
3431
3432   memset (&status, 0, sizeof (status));
3433   target_wait (ptid, &status, 0);
3434
3435   non_stop = was_non_stop;
3436 }
3437
3438 /* See target/target.h.  */
3439
3440 void
3441 target_continue_no_signal (ptid_t ptid)
3442 {
3443   target_resume (ptid, 0, GDB_SIGNAL_0);
3444 }
3445
3446 /* See target/target.h.  */
3447
3448 void
3449 target_continue (ptid_t ptid, enum gdb_signal signal)
3450 {
3451   target_resume (ptid, 0, signal);
3452 }
3453
3454 /* Concatenate ELEM to LIST, a comma-separated list.  */
3455
3456 static void
3457 str_comma_list_concat_elem (std::string *list, const char *elem)
3458 {
3459   if (!list->empty ())
3460     list->append (", ");
3461
3462   list->append (elem);
3463 }
3464
3465 /* Helper for target_options_to_string.  If OPT is present in
3466    TARGET_OPTIONS, append the OPT_STR (string version of OPT) in RET.
3467    OPT is removed from TARGET_OPTIONS.  */
3468
3469 static void
3470 do_option (int *target_options, std::string *ret,
3471            int opt, const char *opt_str)
3472 {
3473   if ((*target_options & opt) != 0)
3474     {
3475       str_comma_list_concat_elem (ret, opt_str);
3476       *target_options &= ~opt;
3477     }
3478 }
3479
3480 /* See target.h.  */
3481
3482 std::string
3483 target_options_to_string (int target_options)
3484 {
3485   std::string ret;
3486
3487 #define DO_TARG_OPTION(OPT) \
3488   do_option (&target_options, &ret, OPT, #OPT)
3489
3490   DO_TARG_OPTION (TARGET_WNOHANG);
3491
3492   if (target_options != 0)
3493     str_comma_list_concat_elem (&ret, "unknown???");
3494
3495   return ret;
3496 }
3497
3498 void
3499 target_fetch_registers (struct regcache *regcache, int regno)
3500 {
3501   current_top_target ()->fetch_registers (regcache, regno);
3502   if (targetdebug)
3503     regcache->debug_print_register ("target_fetch_registers", regno);
3504 }
3505
3506 void
3507 target_store_registers (struct regcache *regcache, int regno)
3508 {
3509   if (!may_write_registers)
3510     error (_("Writing to registers is not allowed (regno %d)"), regno);
3511
3512   current_top_target ()->store_registers (regcache, regno);
3513   if (targetdebug)
3514     {
3515       regcache->debug_print_register ("target_store_registers", regno);
3516     }
3517 }
3518
3519 int
3520 target_core_of_thread (ptid_t ptid)
3521 {
3522   return current_top_target ()->core_of_thread (ptid);
3523 }
3524
3525 int
3526 simple_verify_memory (struct target_ops *ops,
3527                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
3528 {
3529   LONGEST total_xfered = 0;
3530
3531   while (total_xfered < size)
3532     {
3533       ULONGEST xfered_len;
3534       enum target_xfer_status status;
3535       gdb_byte buf[1024];
3536       ULONGEST howmuch = std::min<ULONGEST> (sizeof (buf), size - total_xfered);
3537
3538       status = target_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
3539                                     buf, NULL, lma + total_xfered, howmuch,
3540                                     &xfered_len);
3541       if (status == TARGET_XFER_OK
3542           && memcmp (data + total_xfered, buf, xfered_len) == 0)
3543         {
3544           total_xfered += xfered_len;
3545           QUIT;
3546         }
3547       else
3548         return 0;
3549     }
3550   return 1;
3551 }
3552
3553 /* Default implementation of memory verification.  */
3554
3555 static int
3556 default_verify_memory (struct target_ops *self,
3557                        const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
3558 {
3559   /* Start over from the top of the target stack.  */
3560   return simple_verify_memory (current_top_target (),
3561                                data, memaddr, size);
3562 }
3563
3564 int
3565 target_verify_memory (const gdb_byte *data, CORE_ADDR memaddr, ULONGEST size)
3566 {
3567   return current_top_target ()->verify_memory (data, memaddr, size);
3568 }
3569
3570 /* The documentation for this function is in its prototype declaration in
3571    target.h.  */
3572
3573 int
3574 target_insert_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
3575                                enum target_hw_bp_type rw)
3576 {
3577   return current_top_target ()->insert_mask_watchpoint (addr, mask, rw);
3578 }
3579
3580 /* The documentation for this function is in its prototype declaration in
3581    target.h.  */
3582
3583 int
3584 target_remove_mask_watchpoint (CORE_ADDR addr, CORE_ADDR mask,
3585                                enum target_hw_bp_type rw)
3586 {
3587   return current_top_target ()->remove_mask_watchpoint (addr, mask, rw);
3588 }
3589
3590 /* The documentation for this function is in its prototype declaration
3591    in target.h.  */
3592
3593 int
3594 target_masked_watch_num_registers (CORE_ADDR addr, CORE_ADDR mask)
3595 {
3596   return current_top_target ()->masked_watch_num_registers (addr, mask);
3597 }
3598
3599 /* The documentation for this function is in its prototype declaration
3600    in target.h.  */
3601
3602 int
3603 target_ranged_break_num_registers (void)
3604 {
3605   return current_top_target ()->ranged_break_num_registers ();
3606 }
3607
3608 /* See target.h.  */
3609
3610 struct btrace_target_info *
3611 target_enable_btrace (ptid_t ptid, const struct btrace_config *conf)
3612 {
3613   return current_top_target ()->enable_btrace (ptid, conf);
3614 }
3615
3616 /* See target.h.  */
3617
3618 void
3619 target_disable_btrace (struct btrace_target_info *btinfo)
3620 {
3621   current_top_target ()->disable_btrace (btinfo);
3622 }
3623
3624 /* See target.h.  */
3625
3626 void
3627 target_teardown_btrace (struct btrace_target_info *btinfo)
3628 {
3629   current_top_target ()->teardown_btrace (btinfo);
3630 }
3631
3632 /* See target.h.  */
3633
3634 enum btrace_error
3635 target_read_btrace (struct btrace_data *btrace,
3636                     struct btrace_target_info *btinfo,
3637                     enum btrace_read_type type)
3638 {
3639   return current_top_target ()->read_btrace (btrace, btinfo, type);
3640 }
3641
3642 /* See target.h.  */
3643
3644 const struct btrace_config *
3645 target_btrace_conf (const struct btrace_target_info *btinfo)
3646 {
3647   return current_top_target ()->btrace_conf (btinfo);
3648 }
3649
3650 /* See target.h.  */
3651
3652 void
3653 target_stop_recording (void)
3654 {
3655   current_top_target ()->stop_recording ();
3656 }
3657
3658 /* See target.h.  */
3659
3660 void
3661 target_save_record (const char *filename)
3662 {
3663   current_top_target ()->save_record (filename);
3664 }
3665
3666 /* See target.h.  */
3667
3668 int
3669 target_supports_delete_record ()
3670 {
3671   return current_top_target ()->supports_delete_record ();
3672 }
3673
3674 /* See target.h.  */
3675
3676 void
3677 target_delete_record (void)
3678 {
3679   current_top_target ()->delete_record ();
3680 }
3681
3682 /* See target.h.  */
3683
3684 enum record_method
3685 target_record_method (ptid_t ptid)
3686 {
3687   return current_top_target ()->record_method (ptid);
3688 }
3689
3690 /* See target.h.  */
3691
3692 int
3693 target_record_is_replaying (ptid_t ptid)
3694 {
3695   return current_top_target ()->record_is_replaying (ptid);
3696 }
3697
3698 /* See target.h.  */
3699
3700 int
3701 target_record_will_replay (ptid_t ptid, int dir)
3702 {
3703   return current_top_target ()->record_will_replay (ptid, dir);
3704 }
3705
3706 /* See target.h.  */
3707
3708 void
3709 target_record_stop_replaying (void)
3710 {
3711   current_top_target ()->record_stop_replaying ();
3712 }
3713
3714 /* See target.h.  */
3715
3716 void
3717 target_goto_record_begin (void)
3718 {
3719   current_top_target ()->goto_record_begin ();
3720 }
3721
3722 /* See target.h.  */
3723
3724 void
3725 target_goto_record_end (void)
3726 {
3727   current_top_target ()->goto_record_end ();
3728 }
3729
3730 /* See target.h.  */
3731
3732 void
3733 target_goto_record (ULONGEST insn)
3734 {
3735   current_top_target ()->goto_record (insn);
3736 }
3737
3738 /* See target.h.  */
3739
3740 void
3741 target_insn_history (int size, gdb_disassembly_flags flags)
3742 {
3743   current_top_target ()->insn_history (size, flags);
3744 }
3745
3746 /* See target.h.  */
3747
3748 void
3749 target_insn_history_from (ULONGEST from, int size,
3750                           gdb_disassembly_flags flags)
3751 {
3752   current_top_target ()->insn_history_from (from, size, flags);
3753 }
3754
3755 /* See target.h.  */
3756
3757 void
3758 target_insn_history_range (ULONGEST begin, ULONGEST end,
3759                            gdb_disassembly_flags flags)
3760 {
3761   current_top_target ()->insn_history_range (begin, end, flags);
3762 }
3763
3764 /* See target.h.  */
3765
3766 void
3767 target_call_history (int size, record_print_flags flags)
3768 {
3769   current_top_target ()->call_history (size, flags);
3770 }
3771
3772 /* See target.h.  */
3773
3774 void
3775 target_call_history_from (ULONGEST begin, int size, record_print_flags flags)
3776 {
3777   current_top_target ()->call_history_from (begin, size, flags);
3778 }
3779
3780 /* See target.h.  */
3781
3782 void
3783 target_call_history_range (ULONGEST begin, ULONGEST end, record_print_flags flags)
3784 {
3785   current_top_target ()->call_history_range (begin, end, flags);
3786 }
3787
3788 /* See target.h.  */
3789
3790 const struct frame_unwind *
3791 target_get_unwinder (void)
3792 {
3793   return current_top_target ()->get_unwinder ();
3794 }
3795
3796 /* See target.h.  */
3797
3798 const struct frame_unwind *
3799 target_get_tailcall_unwinder (void)
3800 {
3801   return current_top_target ()->get_tailcall_unwinder ();
3802 }
3803
3804 /* See target.h.  */
3805
3806 void
3807 target_prepare_to_generate_core (void)
3808 {
3809   current_top_target ()->prepare_to_generate_core ();
3810 }
3811
3812 /* See target.h.  */
3813
3814 void
3815 target_done_generating_core (void)
3816 {
3817   current_top_target ()->done_generating_core ();
3818 }
3819
3820 \f
3821
3822 static char targ_desc[] =
3823 "Names of targets and files being debugged.\nShows the entire \
3824 stack of targets currently in use (including the exec-file,\n\
3825 core-file, and process, if any), as well as the symbol file name.";
3826
3827 static void
3828 default_rcmd (struct target_ops *self, const char *command,
3829               struct ui_file *output)
3830 {
3831   error (_("\"monitor\" command not supported by this target."));
3832 }
3833
3834 static void
3835 do_monitor_command (const char *cmd, int from_tty)
3836 {
3837   target_rcmd (cmd, gdb_stdtarg);
3838 }
3839
3840 /* Erases all the memory regions marked as flash.  CMD and FROM_TTY are
3841    ignored.  */
3842
3843 void
3844 flash_erase_command (const char *cmd, int from_tty)
3845 {
3846   /* Used to communicate termination of flash operations to the target.  */
3847   bool found_flash_region = false;
3848   struct gdbarch *gdbarch = target_gdbarch ();
3849
3850   std::vector<mem_region> mem_regions = target_memory_map ();
3851
3852   /* Iterate over all memory regions.  */
3853   for (const mem_region &m : mem_regions)
3854     {
3855       /* Is this a flash memory region?  */
3856       if (m.attrib.mode == MEM_FLASH)
3857         {
3858           found_flash_region = true;
3859           target_flash_erase (m.lo, m.hi - m.lo);
3860
3861           ui_out_emit_tuple tuple_emitter (current_uiout, "erased-regions");
3862
3863           current_uiout->message (_("Erasing flash memory region at address "));
3864           current_uiout->field_fmt ("address", "%s", paddress (gdbarch, m.lo));
3865           current_uiout->message (", size = ");
3866           current_uiout->field_fmt ("size", "%s", hex_string (m.hi - m.lo));
3867           current_uiout->message ("\n");
3868         }
3869     }
3870
3871   /* Did we do any flash operations?  If so, we need to finalize them.  */
3872   if (found_flash_region)
3873     target_flash_done ();
3874   else
3875     current_uiout->message (_("No flash memory regions found.\n"));
3876 }
3877
3878 /* Print the name of each layers of our target stack.  */
3879
3880 static void
3881 maintenance_print_target_stack (const char *cmd, int from_tty)
3882 {
3883   printf_filtered (_("The current target stack is:\n"));
3884
3885   for (target_ops *t = current_top_target (); t != NULL; t = t->beneath ())
3886     {
3887       if (t->to_stratum == debug_stratum)
3888         continue;
3889       printf_filtered ("  - %s (%s)\n", t->shortname (), t->longname ());
3890     }
3891 }
3892
3893 /* See target.h.  */
3894
3895 void
3896 target_async (int enable)
3897 {
3898   infrun_async (enable);
3899   current_top_target ()->async (enable);
3900 }
3901
3902 /* See target.h.  */
3903
3904 void
3905 target_thread_events (int enable)
3906 {
3907   current_top_target ()->thread_events (enable);
3908 }
3909
3910 /* Controls if targets can report that they can/are async.  This is
3911    just for maintainers to use when debugging gdb.  */
3912 int target_async_permitted = 1;
3913
3914 /* The set command writes to this variable.  If the inferior is
3915    executing, target_async_permitted is *not* updated.  */
3916 static int target_async_permitted_1 = 1;
3917
3918 static void
3919 maint_set_target_async_command (const char *args, int from_tty,
3920                                 struct cmd_list_element *c)
3921 {
3922   if (have_live_inferiors ())
3923     {
3924       target_async_permitted_1 = target_async_permitted;
3925       error (_("Cannot change this setting while the inferior is running."));
3926     }
3927
3928   target_async_permitted = target_async_permitted_1;
3929 }
3930
3931 static void
3932 maint_show_target_async_command (struct ui_file *file, int from_tty,
3933                                  struct cmd_list_element *c,
3934                                  const char *value)
3935 {
3936   fprintf_filtered (file,
3937                     _("Controlling the inferior in "
3938                       "asynchronous mode is %s.\n"), value);
3939 }
3940
3941 /* Return true if the target operates in non-stop mode even with "set
3942    non-stop off".  */
3943
3944 static int
3945 target_always_non_stop_p (void)
3946 {
3947   return current_top_target ()->always_non_stop_p ();
3948 }
3949
3950 /* See target.h.  */
3951
3952 int
3953 target_is_non_stop_p (void)
3954 {
3955   return (non_stop
3956           || target_non_stop_enabled == AUTO_BOOLEAN_TRUE
3957           || (target_non_stop_enabled == AUTO_BOOLEAN_AUTO
3958               && target_always_non_stop_p ()));
3959 }
3960
3961 /* Controls if targets can report that they always run in non-stop
3962    mode.  This is just for maintainers to use when debugging gdb.  */
3963 enum auto_boolean target_non_stop_enabled = AUTO_BOOLEAN_AUTO;
3964
3965 /* The set command writes to this variable.  If the inferior is
3966    executing, target_non_stop_enabled is *not* updated.  */
3967 static enum auto_boolean target_non_stop_enabled_1 = AUTO_BOOLEAN_AUTO;
3968
3969 /* Implementation of "maint set target-non-stop".  */
3970
3971 static void
3972 maint_set_target_non_stop_command (const char *args, int from_tty,
3973                                    struct cmd_list_element *c)
3974 {
3975   if (have_live_inferiors ())
3976     {
3977       target_non_stop_enabled_1 = target_non_stop_enabled;
3978       error (_("Cannot change this setting while the inferior is running."));
3979     }
3980
3981   target_non_stop_enabled = target_non_stop_enabled_1;
3982 }
3983
3984 /* Implementation of "maint show target-non-stop".  */
3985
3986 static void
3987 maint_show_target_non_stop_command (struct ui_file *file, int from_tty,
3988                                     struct cmd_list_element *c,
3989                                     const char *value)
3990 {
3991   if (target_non_stop_enabled == AUTO_BOOLEAN_AUTO)
3992     fprintf_filtered (file,
3993                       _("Whether the target is always in non-stop mode "
3994                         "is %s (currently %s).\n"), value,
3995                       target_always_non_stop_p () ? "on" : "off");
3996   else
3997     fprintf_filtered (file,
3998                       _("Whether the target is always in non-stop mode "
3999                         "is %s.\n"), value);
4000 }
4001
4002 /* Temporary copies of permission settings.  */
4003
4004 static int may_write_registers_1 = 1;
4005 static int may_write_memory_1 = 1;
4006 static int may_insert_breakpoints_1 = 1;
4007 static int may_insert_tracepoints_1 = 1;
4008 static int may_insert_fast_tracepoints_1 = 1;
4009 static int may_stop_1 = 1;
4010
4011 /* Make the user-set values match the real values again.  */
4012
4013 void
4014 update_target_permissions (void)
4015 {
4016   may_write_registers_1 = may_write_registers;
4017   may_write_memory_1 = may_write_memory;
4018   may_insert_breakpoints_1 = may_insert_breakpoints;
4019   may_insert_tracepoints_1 = may_insert_tracepoints;
4020   may_insert_fast_tracepoints_1 = may_insert_fast_tracepoints;
4021   may_stop_1 = may_stop;
4022 }
4023
4024 /* The one function handles (most of) the permission flags in the same
4025    way.  */
4026
4027 static void
4028 set_target_permissions (const char *args, int from_tty,
4029                         struct cmd_list_element *c)
4030 {
4031   if (target_has_execution)
4032     {
4033       update_target_permissions ();
4034       error (_("Cannot change this setting while the inferior is running."));
4035     }
4036
4037   /* Make the real values match the user-changed values.  */
4038   may_write_registers = may_write_registers_1;
4039   may_insert_breakpoints = may_insert_breakpoints_1;
4040   may_insert_tracepoints = may_insert_tracepoints_1;
4041   may_insert_fast_tracepoints = may_insert_fast_tracepoints_1;
4042   may_stop = may_stop_1;
4043   update_observer_mode ();
4044 }
4045
4046 /* Set memory write permission independently of observer mode.  */
4047
4048 static void
4049 set_write_memory_permission (const char *args, int from_tty,
4050                         struct cmd_list_element *c)
4051 {
4052   /* Make the real values match the user-changed values.  */
4053   may_write_memory = may_write_memory_1;
4054   update_observer_mode ();
4055 }
4056
4057 void
4058 initialize_targets (void)
4059 {
4060   the_dummy_target = new dummy_target ();
4061   push_target (the_dummy_target);
4062
4063   the_debug_target = new debug_target ();
4064
4065   add_info ("target", info_target_command, targ_desc);
4066   add_info ("files", info_target_command, targ_desc);
4067
4068   add_setshow_zuinteger_cmd ("target", class_maintenance, &targetdebug, _("\
4069 Set target debugging."), _("\
4070 Show target debugging."), _("\
4071 When non-zero, target debugging is enabled.  Higher numbers are more\n\
4072 verbose."),
4073                              set_targetdebug,
4074                              show_targetdebug,
4075                              &setdebuglist, &showdebuglist);
4076
4077   add_setshow_boolean_cmd ("trust-readonly-sections", class_support,
4078                            &trust_readonly, _("\
4079 Set mode for reading from readonly sections."), _("\
4080 Show mode for reading from readonly sections."), _("\
4081 When this mode is on, memory reads from readonly sections (such as .text)\n\
4082 will be read from the object file instead of from the target.  This will\n\
4083 result in significant performance improvement for remote targets."),
4084                            NULL,
4085                            show_trust_readonly,
4086                            &setlist, &showlist);
4087
4088   add_com ("monitor", class_obscure, do_monitor_command,
4089            _("Send a command to the remote monitor (remote targets only)."));
4090
4091   add_cmd ("target-stack", class_maintenance, maintenance_print_target_stack,
4092            _("Print the name of each layer of the internal target stack."),
4093            &maintenanceprintlist);
4094
4095   add_setshow_boolean_cmd ("target-async", no_class,
4096                            &target_async_permitted_1, _("\
4097 Set whether gdb controls the inferior in asynchronous mode."), _("\
4098 Show whether gdb controls the inferior in asynchronous mode."), _("\
4099 Tells gdb whether to control the inferior in asynchronous mode."),
4100                            maint_set_target_async_command,
4101                            maint_show_target_async_command,
4102                            &maintenance_set_cmdlist,
4103                            &maintenance_show_cmdlist);
4104
4105   add_setshow_auto_boolean_cmd ("target-non-stop", no_class,
4106                                 &target_non_stop_enabled_1, _("\
4107 Set whether gdb always controls the inferior in non-stop mode."), _("\
4108 Show whether gdb always controls the inferior in non-stop mode."), _("\
4109 Tells gdb whether to control the inferior in non-stop mode."),
4110                            maint_set_target_non_stop_command,
4111                            maint_show_target_non_stop_command,
4112                            &maintenance_set_cmdlist,
4113                            &maintenance_show_cmdlist);
4114
4115   add_setshow_boolean_cmd ("may-write-registers", class_support,
4116                            &may_write_registers_1, _("\
4117 Set permission to write into registers."), _("\
4118 Show permission to write into registers."), _("\
4119 When this permission is on, GDB may write into the target's registers.\n\
4120 Otherwise, any sort of write attempt will result in an error."),
4121                            set_target_permissions, NULL,
4122                            &setlist, &showlist);
4123
4124   add_setshow_boolean_cmd ("may-write-memory", class_support,
4125                            &may_write_memory_1, _("\
4126 Set permission to write into target memory."), _("\
4127 Show permission to write into target memory."), _("\
4128 When this permission is on, GDB may write into the target's memory.\n\
4129 Otherwise, any sort of write attempt will result in an error."),
4130                            set_write_memory_permission, NULL,
4131                            &setlist, &showlist);
4132
4133   add_setshow_boolean_cmd ("may-insert-breakpoints", class_support,
4134                            &may_insert_breakpoints_1, _("\
4135 Set permission to insert breakpoints in the target."), _("\
4136 Show permission to insert breakpoints in the target."), _("\
4137 When this permission is on, GDB may insert breakpoints in the program.\n\
4138 Otherwise, any sort of insertion attempt will result in an error."),
4139                            set_target_permissions, NULL,
4140                            &setlist, &showlist);
4141
4142   add_setshow_boolean_cmd ("may-insert-tracepoints", class_support,
4143                            &may_insert_tracepoints_1, _("\
4144 Set permission to insert tracepoints in the target."), _("\
4145 Show permission to insert tracepoints in the target."), _("\
4146 When this permission is on, GDB may insert tracepoints in the program.\n\
4147 Otherwise, any sort of insertion attempt will result in an error."),
4148                            set_target_permissions, NULL,
4149                            &setlist, &showlist);
4150
4151   add_setshow_boolean_cmd ("may-insert-fast-tracepoints", class_support,
4152                            &may_insert_fast_tracepoints_1, _("\
4153 Set permission to insert fast tracepoints in the target."), _("\
4154 Show permission to insert fast tracepoints in the target."), _("\
4155 When this permission is on, GDB may insert fast tracepoints.\n\
4156 Otherwise, any sort of insertion attempt will result in an error."),
4157                            set_target_permissions, NULL,
4158                            &setlist, &showlist);
4159
4160   add_setshow_boolean_cmd ("may-interrupt", class_support,
4161                            &may_stop_1, _("\
4162 Set permission to interrupt or signal the target."), _("\
4163 Show permission to interrupt or signal the target."), _("\
4164 When this permission is on, GDB may interrupt/stop the target's execution.\n\
4165 Otherwise, any attempt to interrupt or stop will be ignored."),
4166                            set_target_permissions, NULL,
4167                            &setlist, &showlist);
4168
4169   add_com ("flash-erase", no_class, flash_erase_command,
4170            _("Erase all flash memory regions."));
4171
4172   add_setshow_boolean_cmd ("auto-connect-native-target", class_support,
4173                            &auto_connect_native_target, _("\
4174 Set whether GDB may automatically connect to the native target."), _("\
4175 Show whether GDB may automatically connect to the native target."), _("\
4176 When on, and GDB is not connected to a target yet, GDB\n\
4177 attempts \"run\" and other commands with the native target."),
4178                            NULL, show_auto_connect_native_target,
4179                            &setlist, &showlist);
4180 }