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