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