OSDN Git Service

* target.c (memory_xfer_partial): Accesses to unmapped overlay
[pf3gnuchains/pf3gnuchains3x.git] / gdb / target.c
1 /* Select target systems and architectures at runtime for GDB.
2
3    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
5    Free Software Foundation, Inc.
6
7    Contributed by Cygnus Support.
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 51 Franklin Street, Fifth Floor,
24    Boston, MA 02110-1301, USA.  */
25
26 #include "defs.h"
27 #include <errno.h>
28 #include "gdb_string.h"
29 #include "target.h"
30 #include "gdbcmd.h"
31 #include "symtab.h"
32 #include "inferior.h"
33 #include "bfd.h"
34 #include "symfile.h"
35 #include "objfiles.h"
36 #include "gdb_wait.h"
37 #include "dcache.h"
38 #include <signal.h>
39 #include "regcache.h"
40 #include "gdb_assert.h"
41 #include "gdbcore.h"
42 #include "exceptions.h"
43 #include "target-descriptions.h"
44
45 static void target_info (char *, int);
46
47 static void maybe_kill_then_attach (char *, int);
48
49 static void kill_or_be_killed (int);
50
51 static void default_terminal_info (char *, int);
52
53 static int default_region_ok_for_hw_watchpoint (CORE_ADDR, int);
54
55 static int nosymbol (char *, CORE_ADDR *);
56
57 static void tcomplain (void) ATTR_NORETURN;
58
59 static int nomemory (CORE_ADDR, char *, int, int, struct target_ops *);
60
61 static int return_zero (void);
62
63 static int return_one (void);
64
65 static int return_minus_one (void);
66
67 void target_ignore (void);
68
69 static void target_command (char *, int);
70
71 static struct target_ops *find_default_run_target (char *);
72
73 static void nosupport_runtime (void);
74
75 static LONGEST default_xfer_partial (struct target_ops *ops,
76                                      enum target_object object,
77                                      const char *annex, gdb_byte *readbuf,
78                                      const gdb_byte *writebuf,
79                                      ULONGEST offset, LONGEST len);
80
81 static LONGEST current_xfer_partial (struct target_ops *ops,
82                                      enum target_object object,
83                                      const char *annex, gdb_byte *readbuf,
84                                      const gdb_byte *writebuf,
85                                      ULONGEST offset, LONGEST len);
86
87 static LONGEST target_xfer_partial (struct target_ops *ops,
88                                     enum target_object object,
89                                     const char *annex,
90                                     void *readbuf, const void *writebuf,
91                                     ULONGEST offset, LONGEST len);
92
93 static void init_dummy_target (void);
94
95 static struct target_ops debug_target;
96
97 static void debug_to_open (char *, int);
98
99 static void debug_to_close (int);
100
101 static void debug_to_attach (char *, int);
102
103 static void debug_to_detach (char *, int);
104
105 static void debug_to_resume (ptid_t, int, enum target_signal);
106
107 static ptid_t debug_to_wait (ptid_t, struct target_waitstatus *);
108
109 static void debug_to_fetch_registers (struct regcache *, int);
110
111 static void debug_to_store_registers (struct regcache *, int);
112
113 static void debug_to_prepare_to_store (struct regcache *);
114
115 static void debug_to_files_info (struct target_ops *);
116
117 static int debug_to_insert_breakpoint (struct bp_target_info *);
118
119 static int debug_to_remove_breakpoint (struct bp_target_info *);
120
121 static int debug_to_can_use_hw_breakpoint (int, int, int);
122
123 static int debug_to_insert_hw_breakpoint (struct bp_target_info *);
124
125 static int debug_to_remove_hw_breakpoint (struct bp_target_info *);
126
127 static int debug_to_insert_watchpoint (CORE_ADDR, int, int);
128
129 static int debug_to_remove_watchpoint (CORE_ADDR, int, int);
130
131 static int debug_to_stopped_by_watchpoint (void);
132
133 static int debug_to_stopped_data_address (struct target_ops *, CORE_ADDR *);
134
135 static int debug_to_region_ok_for_hw_watchpoint (CORE_ADDR, int);
136
137 static void debug_to_terminal_init (void);
138
139 static void debug_to_terminal_inferior (void);
140
141 static void debug_to_terminal_ours_for_output (void);
142
143 static void debug_to_terminal_save_ours (void);
144
145 static void debug_to_terminal_ours (void);
146
147 static void debug_to_terminal_info (char *, int);
148
149 static void debug_to_kill (void);
150
151 static void debug_to_load (char *, int);
152
153 static int debug_to_lookup_symbol (char *, CORE_ADDR *);
154
155 static void debug_to_mourn_inferior (void);
156
157 static int debug_to_can_run (void);
158
159 static void debug_to_notice_signals (ptid_t);
160
161 static int debug_to_thread_alive (ptid_t);
162
163 static void debug_to_stop (void);
164
165 /* NOTE: cagney/2004-09-29: Many targets reference this variable in
166    wierd and mysterious ways.  Putting the variable here lets those
167    wierd and mysterious ways keep building while they are being
168    converted to the inferior inheritance structure.  */
169 struct target_ops deprecated_child_ops;
170
171 /* Pointer to array of target architecture structures; the size of the
172    array; the current index into the array; the allocated size of the
173    array.  */
174 struct target_ops **target_structs;
175 unsigned target_struct_size;
176 unsigned target_struct_index;
177 unsigned target_struct_allocsize;
178 #define DEFAULT_ALLOCSIZE       10
179
180 /* The initial current target, so that there is always a semi-valid
181    current target.  */
182
183 static struct target_ops dummy_target;
184
185 /* Top of target stack.  */
186
187 static struct target_ops *target_stack;
188
189 /* The target structure we are currently using to talk to a process
190    or file or whatever "inferior" we have.  */
191
192 struct target_ops current_target;
193
194 /* Command list for target.  */
195
196 static struct cmd_list_element *targetlist = NULL;
197
198 /* Nonzero if we are debugging an attached outside process
199    rather than an inferior.  */
200
201 int attach_flag;
202
203 /* Nonzero if we should trust readonly sections from the
204    executable when reading memory.  */
205
206 static int trust_readonly = 0;
207
208 /* Non-zero if we want to see trace of target level stuff.  */
209
210 static int targetdebug = 0;
211 static void
212 show_targetdebug (struct ui_file *file, int from_tty,
213                   struct cmd_list_element *c, const char *value)
214 {
215   fprintf_filtered (file, _("Target debugging is %s.\n"), value);
216 }
217
218 static void setup_target_debug (void);
219
220 DCACHE *target_dcache;
221
222 /* The user just typed 'target' without the name of a target.  */
223
224 static void
225 target_command (char *arg, int from_tty)
226 {
227   fputs_filtered ("Argument required (target name).  Try `help target'\n",
228                   gdb_stdout);
229 }
230
231 /* Add a possible target architecture to the list.  */
232
233 void
234 add_target (struct target_ops *t)
235 {
236   /* Provide default values for all "must have" methods.  */
237   if (t->to_xfer_partial == NULL)
238     t->to_xfer_partial = default_xfer_partial;
239
240   if (!target_structs)
241     {
242       target_struct_allocsize = DEFAULT_ALLOCSIZE;
243       target_structs = (struct target_ops **) xmalloc
244         (target_struct_allocsize * sizeof (*target_structs));
245     }
246   if (target_struct_size >= target_struct_allocsize)
247     {
248       target_struct_allocsize *= 2;
249       target_structs = (struct target_ops **)
250         xrealloc ((char *) target_structs,
251                   target_struct_allocsize * sizeof (*target_structs));
252     }
253   target_structs[target_struct_size++] = t;
254
255   if (targetlist == NULL)
256     add_prefix_cmd ("target", class_run, target_command, _("\
257 Connect to a target machine or process.\n\
258 The first argument is the type or protocol of the target machine.\n\
259 Remaining arguments are interpreted by the target protocol.  For more\n\
260 information on the arguments for a particular protocol, type\n\
261 `help target ' followed by the protocol name."),
262                     &targetlist, "target ", 0, &cmdlist);
263   add_cmd (t->to_shortname, no_class, t->to_open, t->to_doc, &targetlist);
264 }
265
266 /* Stub functions */
267
268 void
269 target_ignore (void)
270 {
271 }
272
273 void
274 target_load (char *arg, int from_tty)
275 {
276   dcache_invalidate (target_dcache);
277   (*current_target.to_load) (arg, from_tty);
278 }
279
280 static int
281 nomemory (CORE_ADDR memaddr, char *myaddr, int len, int write,
282           struct target_ops *t)
283 {
284   errno = EIO;                  /* Can't read/write this location */
285   return 0;                     /* No bytes handled */
286 }
287
288 static void
289 tcomplain (void)
290 {
291   error (_("You can't do that when your target is `%s'"),
292          current_target.to_shortname);
293 }
294
295 void
296 noprocess (void)
297 {
298   error (_("You can't do that without a process to debug."));
299 }
300
301 static int
302 nosymbol (char *name, CORE_ADDR *addrp)
303 {
304   return 1;                     /* Symbol does not exist in target env */
305 }
306
307 static void
308 nosupport_runtime (void)
309 {
310   if (ptid_equal (inferior_ptid, null_ptid))
311     noprocess ();
312   else
313     error (_("No run-time support for this"));
314 }
315
316
317 static void
318 default_terminal_info (char *args, int from_tty)
319 {
320   printf_unfiltered (_("No saved terminal information.\n"));
321 }
322
323 /* This is the default target_create_inferior and target_attach function.
324    If the current target is executing, it asks whether to kill it off.
325    If this function returns without calling error(), it has killed off
326    the target, and the operation should be attempted.  */
327
328 static void
329 kill_or_be_killed (int from_tty)
330 {
331   if (target_has_execution)
332     {
333       printf_unfiltered (_("You are already running a program:\n"));
334       target_files_info ();
335       if (query ("Kill it? "))
336         {
337           target_kill ();
338           if (target_has_execution)
339             error (_("Killing the program did not help."));
340           return;
341         }
342       else
343         {
344           error (_("Program not killed."));
345         }
346     }
347   tcomplain ();
348 }
349
350 static void
351 maybe_kill_then_attach (char *args, int from_tty)
352 {
353   kill_or_be_killed (from_tty);
354   target_attach (args, from_tty);
355 }
356
357 static void
358 maybe_kill_then_create_inferior (char *exec, char *args, char **env,
359                                  int from_tty)
360 {
361   kill_or_be_killed (0);
362   target_create_inferior (exec, args, env, from_tty);
363 }
364
365 /* Go through the target stack from top to bottom, copying over zero
366    entries in current_target, then filling in still empty entries.  In
367    effect, we are doing class inheritance through the pushed target
368    vectors.
369
370    NOTE: cagney/2003-10-17: The problem with this inheritance, as it
371    is currently implemented, is that it discards any knowledge of
372    which target an inherited method originally belonged to.
373    Consequently, new new target methods should instead explicitly and
374    locally search the target stack for the target that can handle the
375    request.  */
376
377 static void
378 update_current_target (void)
379 {
380   struct target_ops *t;
381
382   /* First, reset current's contents.  */
383   memset (&current_target, 0, sizeof (current_target));
384
385 #define INHERIT(FIELD, TARGET) \
386       if (!current_target.FIELD) \
387         current_target.FIELD = (TARGET)->FIELD
388
389   for (t = target_stack; t; t = t->beneath)
390     {
391       INHERIT (to_shortname, t);
392       INHERIT (to_longname, t);
393       INHERIT (to_doc, t);
394       INHERIT (to_open, t);
395       INHERIT (to_close, t);
396       INHERIT (to_attach, t);
397       INHERIT (to_post_attach, t);
398       INHERIT (to_detach, t);
399       /* Do not inherit to_disconnect.  */
400       INHERIT (to_resume, t);
401       INHERIT (to_wait, t);
402       INHERIT (to_fetch_registers, t);
403       INHERIT (to_store_registers, t);
404       INHERIT (to_prepare_to_store, t);
405       INHERIT (deprecated_xfer_memory, t);
406       INHERIT (to_files_info, t);
407       INHERIT (to_insert_breakpoint, t);
408       INHERIT (to_remove_breakpoint, t);
409       INHERIT (to_can_use_hw_breakpoint, t);
410       INHERIT (to_insert_hw_breakpoint, t);
411       INHERIT (to_remove_hw_breakpoint, t);
412       INHERIT (to_insert_watchpoint, t);
413       INHERIT (to_remove_watchpoint, t);
414       INHERIT (to_stopped_data_address, t);
415       INHERIT (to_stopped_by_watchpoint, t);
416       INHERIT (to_have_steppable_watchpoint, t);
417       INHERIT (to_have_continuable_watchpoint, t);
418       INHERIT (to_region_ok_for_hw_watchpoint, t);
419       INHERIT (to_terminal_init, t);
420       INHERIT (to_terminal_inferior, t);
421       INHERIT (to_terminal_ours_for_output, t);
422       INHERIT (to_terminal_ours, t);
423       INHERIT (to_terminal_save_ours, t);
424       INHERIT (to_terminal_info, t);
425       INHERIT (to_kill, t);
426       INHERIT (to_load, t);
427       INHERIT (to_lookup_symbol, t);
428       INHERIT (to_create_inferior, t);
429       INHERIT (to_post_startup_inferior, t);
430       INHERIT (to_acknowledge_created_inferior, t);
431       INHERIT (to_insert_fork_catchpoint, t);
432       INHERIT (to_remove_fork_catchpoint, t);
433       INHERIT (to_insert_vfork_catchpoint, t);
434       INHERIT (to_remove_vfork_catchpoint, t);
435       /* Do not inherit to_follow_fork.  */
436       INHERIT (to_insert_exec_catchpoint, t);
437       INHERIT (to_remove_exec_catchpoint, t);
438       INHERIT (to_reported_exec_events_per_exec_call, t);
439       INHERIT (to_has_exited, t);
440       INHERIT (to_mourn_inferior, t);
441       INHERIT (to_can_run, t);
442       INHERIT (to_notice_signals, t);
443       INHERIT (to_thread_alive, t);
444       INHERIT (to_find_new_threads, t);
445       INHERIT (to_pid_to_str, t);
446       INHERIT (to_extra_thread_info, t);
447       INHERIT (to_stop, t);
448       /* Do not inherit to_xfer_partial.  */
449       INHERIT (to_rcmd, t);
450       INHERIT (to_enable_exception_callback, t);
451       INHERIT (to_get_current_exception_event, t);
452       INHERIT (to_pid_to_exec_file, t);
453       INHERIT (to_stratum, t);
454       INHERIT (to_has_all_memory, t);
455       INHERIT (to_has_memory, t);
456       INHERIT (to_has_stack, t);
457       INHERIT (to_has_registers, t);
458       INHERIT (to_has_execution, t);
459       INHERIT (to_has_thread_control, t);
460       INHERIT (to_sections, t);
461       INHERIT (to_sections_end, t);
462       INHERIT (to_can_async_p, t);
463       INHERIT (to_is_async_p, t);
464       INHERIT (to_async, t);
465       INHERIT (to_async_mask_value, t);
466       INHERIT (to_find_memory_regions, t);
467       INHERIT (to_make_corefile_notes, t);
468       INHERIT (to_get_thread_local_address, t);
469       /* Do not inherit to_read_description.  */
470       INHERIT (to_magic, t);
471       /* Do not inherit to_memory_map.  */
472       /* Do not inherit to_flash_erase.  */
473       /* Do not inherit to_flash_done.  */
474     }
475 #undef INHERIT
476
477   /* Clean up a target struct so it no longer has any zero pointers in
478      it.  Some entries are defaulted to a method that print an error,
479      others are hard-wired to a standard recursive default.  */
480
481 #define de_fault(field, value) \
482   if (!current_target.field)               \
483     current_target.field = value
484
485   de_fault (to_open,
486             (void (*) (char *, int))
487             tcomplain);
488   de_fault (to_close,
489             (void (*) (int))
490             target_ignore);
491   de_fault (to_attach,
492             maybe_kill_then_attach);
493   de_fault (to_post_attach,
494             (void (*) (int))
495             target_ignore);
496   de_fault (to_detach,
497             (void (*) (char *, int))
498             target_ignore);
499   de_fault (to_resume,
500             (void (*) (ptid_t, int, enum target_signal))
501             noprocess);
502   de_fault (to_wait,
503             (ptid_t (*) (ptid_t, struct target_waitstatus *))
504             noprocess);
505   de_fault (to_fetch_registers,
506             (void (*) (struct regcache *, int))
507             target_ignore);
508   de_fault (to_store_registers,
509             (void (*) (struct regcache *, int))
510             noprocess);
511   de_fault (to_prepare_to_store,
512             (void (*) (struct regcache *))
513             noprocess);
514   de_fault (deprecated_xfer_memory,
515             (int (*) (CORE_ADDR, gdb_byte *, int, int, struct mem_attrib *, struct target_ops *))
516             nomemory);
517   de_fault (to_files_info,
518             (void (*) (struct target_ops *))
519             target_ignore);
520   de_fault (to_insert_breakpoint,
521             memory_insert_breakpoint);
522   de_fault (to_remove_breakpoint,
523             memory_remove_breakpoint);
524   de_fault (to_can_use_hw_breakpoint,
525             (int (*) (int, int, int))
526             return_zero);
527   de_fault (to_insert_hw_breakpoint,
528             (int (*) (struct bp_target_info *))
529             return_minus_one);
530   de_fault (to_remove_hw_breakpoint,
531             (int (*) (struct bp_target_info *))
532             return_minus_one);
533   de_fault (to_insert_watchpoint,
534             (int (*) (CORE_ADDR, int, int))
535             return_minus_one);
536   de_fault (to_remove_watchpoint,
537             (int (*) (CORE_ADDR, int, int))
538             return_minus_one);
539   de_fault (to_stopped_by_watchpoint,
540             (int (*) (void))
541             return_zero);
542   de_fault (to_stopped_data_address,
543             (int (*) (struct target_ops *, CORE_ADDR *))
544             return_zero);
545   de_fault (to_region_ok_for_hw_watchpoint,
546             default_region_ok_for_hw_watchpoint);
547   de_fault (to_terminal_init,
548             (void (*) (void))
549             target_ignore);
550   de_fault (to_terminal_inferior,
551             (void (*) (void))
552             target_ignore);
553   de_fault (to_terminal_ours_for_output,
554             (void (*) (void))
555             target_ignore);
556   de_fault (to_terminal_ours,
557             (void (*) (void))
558             target_ignore);
559   de_fault (to_terminal_save_ours,
560             (void (*) (void))
561             target_ignore);
562   de_fault (to_terminal_info,
563             default_terminal_info);
564   de_fault (to_kill,
565             (void (*) (void))
566             noprocess);
567   de_fault (to_load,
568             (void (*) (char *, int))
569             tcomplain);
570   de_fault (to_lookup_symbol,
571             (int (*) (char *, CORE_ADDR *))
572             nosymbol);
573   de_fault (to_create_inferior,
574             maybe_kill_then_create_inferior);
575   de_fault (to_post_startup_inferior,
576             (void (*) (ptid_t))
577             target_ignore);
578   de_fault (to_acknowledge_created_inferior,
579             (void (*) (int))
580             target_ignore);
581   de_fault (to_insert_fork_catchpoint,
582             (void (*) (int))
583             tcomplain);
584   de_fault (to_remove_fork_catchpoint,
585             (int (*) (int))
586             tcomplain);
587   de_fault (to_insert_vfork_catchpoint,
588             (void (*) (int))
589             tcomplain);
590   de_fault (to_remove_vfork_catchpoint,
591             (int (*) (int))
592             tcomplain);
593   de_fault (to_insert_exec_catchpoint,
594             (void (*) (int))
595             tcomplain);
596   de_fault (to_remove_exec_catchpoint,
597             (int (*) (int))
598             tcomplain);
599   de_fault (to_reported_exec_events_per_exec_call,
600             (int (*) (void))
601             return_one);
602   de_fault (to_has_exited,
603             (int (*) (int, int, int *))
604             return_zero);
605   de_fault (to_mourn_inferior,
606             (void (*) (void))
607             noprocess);
608   de_fault (to_can_run,
609             return_zero);
610   de_fault (to_notice_signals,
611             (void (*) (ptid_t))
612             target_ignore);
613   de_fault (to_thread_alive,
614             (int (*) (ptid_t))
615             return_zero);
616   de_fault (to_find_new_threads,
617             (void (*) (void))
618             target_ignore);
619   de_fault (to_extra_thread_info,
620             (char *(*) (struct thread_info *))
621             return_zero);
622   de_fault (to_stop,
623             (void (*) (void))
624             target_ignore);
625   current_target.to_xfer_partial = current_xfer_partial;
626   de_fault (to_rcmd,
627             (void (*) (char *, struct ui_file *))
628             tcomplain);
629   de_fault (to_enable_exception_callback,
630             (struct symtab_and_line * (*) (enum exception_event_kind, int))
631             nosupport_runtime);
632   de_fault (to_get_current_exception_event,
633             (struct exception_event_record * (*) (void))
634             nosupport_runtime);
635   de_fault (to_pid_to_exec_file,
636             (char *(*) (int))
637             return_zero);
638   de_fault (to_can_async_p,
639             (int (*) (void))
640             return_zero);
641   de_fault (to_is_async_p,
642             (int (*) (void))
643             return_zero);
644   de_fault (to_async,
645             (void (*) (void (*) (enum inferior_event_type, void*), void*))
646             tcomplain);
647   current_target.to_read_description = NULL;
648 #undef de_fault
649
650   /* Finally, position the target-stack beneath the squashed
651      "current_target".  That way code looking for a non-inherited
652      target method can quickly and simply find it.  */
653   current_target.beneath = target_stack;
654 }
655
656 /* Mark OPS as a running target.  This reverses the effect
657    of target_mark_exited.  */
658
659 void
660 target_mark_running (struct target_ops *ops)
661 {
662   struct target_ops *t;
663
664   for (t = target_stack; t != NULL; t = t->beneath)
665     if (t == ops)
666       break;
667   if (t == NULL)
668     internal_error (__FILE__, __LINE__,
669                     "Attempted to mark unpushed target \"%s\" as running",
670                     ops->to_shortname);
671
672   ops->to_has_execution = 1;
673   ops->to_has_all_memory = 1;
674   ops->to_has_memory = 1;
675   ops->to_has_stack = 1;
676   ops->to_has_registers = 1;
677
678   update_current_target ();
679 }
680
681 /* Mark OPS as a non-running target.  This reverses the effect
682    of target_mark_running.  */
683
684 void
685 target_mark_exited (struct target_ops *ops)
686 {
687   struct target_ops *t;
688
689   for (t = target_stack; t != NULL; t = t->beneath)
690     if (t == ops)
691       break;
692   if (t == NULL)
693     internal_error (__FILE__, __LINE__,
694                     "Attempted to mark unpushed target \"%s\" as running",
695                     ops->to_shortname);
696
697   ops->to_has_execution = 0;
698   ops->to_has_all_memory = 0;
699   ops->to_has_memory = 0;
700   ops->to_has_stack = 0;
701   ops->to_has_registers = 0;
702
703   update_current_target ();
704 }
705
706 /* Push a new target type into the stack of the existing target accessors,
707    possibly superseding some of the existing accessors.
708
709    Result is zero if the pushed target ended up on top of the stack,
710    nonzero if at least one target is on top of it.
711
712    Rather than allow an empty stack, we always have the dummy target at
713    the bottom stratum, so we can call the function vectors without
714    checking them.  */
715
716 int
717 push_target (struct target_ops *t)
718 {
719   struct target_ops **cur;
720
721   /* Check magic number.  If wrong, it probably means someone changed
722      the struct definition, but not all the places that initialize one.  */
723   if (t->to_magic != OPS_MAGIC)
724     {
725       fprintf_unfiltered (gdb_stderr,
726                           "Magic number of %s target struct wrong\n",
727                           t->to_shortname);
728       internal_error (__FILE__, __LINE__, _("failed internal consistency check"));
729     }
730
731   /* Find the proper stratum to install this target in.  */
732   for (cur = &target_stack; (*cur) != NULL; cur = &(*cur)->beneath)
733     {
734       if ((int) (t->to_stratum) >= (int) (*cur)->to_stratum)
735         break;
736     }
737
738   /* If there's already targets at this stratum, remove them.  */
739   /* FIXME: cagney/2003-10-15: I think this should be popping all
740      targets to CUR, and not just those at this stratum level.  */
741   while ((*cur) != NULL && t->to_stratum == (*cur)->to_stratum)
742     {
743       /* There's already something at this stratum level.  Close it,
744          and un-hook it from the stack.  */
745       struct target_ops *tmp = (*cur);
746       (*cur) = (*cur)->beneath;
747       tmp->beneath = NULL;
748       target_close (tmp, 0);
749     }
750
751   /* We have removed all targets in our stratum, now add the new one.  */
752   t->beneath = (*cur);
753   (*cur) = t;
754
755   update_current_target ();
756
757   if (targetdebug)
758     setup_target_debug ();
759
760   /* Not on top?  */
761   return (t != target_stack);
762 }
763
764 /* Remove a target_ops vector from the stack, wherever it may be.
765    Return how many times it was removed (0 or 1).  */
766
767 int
768 unpush_target (struct target_ops *t)
769 {
770   struct target_ops **cur;
771   struct target_ops *tmp;
772
773   /* Look for the specified target.  Note that we assume that a target
774      can only occur once in the target stack. */
775
776   for (cur = &target_stack; (*cur) != NULL; cur = &(*cur)->beneath)
777     {
778       if ((*cur) == t)
779         break;
780     }
781
782   if ((*cur) == NULL)
783     return 0;                   /* Didn't find target_ops, quit now */
784
785   /* NOTE: cagney/2003-12-06: In '94 the close call was made
786      unconditional by moving it to before the above check that the
787      target was in the target stack (something about "Change the way
788      pushing and popping of targets work to support target overlays
789      and inheritance").  This doesn't make much sense - only open
790      targets should be closed.  */
791   target_close (t, 0);
792
793   /* Unchain the target */
794   tmp = (*cur);
795   (*cur) = (*cur)->beneath;
796   tmp->beneath = NULL;
797
798   update_current_target ();
799
800   return 1;
801 }
802
803 void
804 pop_target (void)
805 {
806   target_close (&current_target, 0);    /* Let it clean up */
807   if (unpush_target (target_stack) == 1)
808     return;
809
810   fprintf_unfiltered (gdb_stderr,
811                       "pop_target couldn't find target %s\n",
812                       current_target.to_shortname);
813   internal_error (__FILE__, __LINE__, _("failed internal consistency check"));
814 }
815
816 /* Using the objfile specified in BATON, find the address for the
817    current thread's thread-local storage with offset OFFSET.  */
818 CORE_ADDR
819 target_translate_tls_address (struct objfile *objfile, CORE_ADDR offset)
820 {
821   volatile CORE_ADDR addr = 0;
822
823   if (target_get_thread_local_address_p ()
824       && gdbarch_fetch_tls_load_module_address_p (current_gdbarch))
825     {
826       ptid_t ptid = inferior_ptid;
827       volatile struct gdb_exception ex;
828
829       TRY_CATCH (ex, RETURN_MASK_ALL)
830         {
831           CORE_ADDR lm_addr;
832           
833           /* Fetch the load module address for this objfile.  */
834           lm_addr = gdbarch_fetch_tls_load_module_address (current_gdbarch,
835                                                            objfile);
836           /* If it's 0, throw the appropriate exception.  */
837           if (lm_addr == 0)
838             throw_error (TLS_LOAD_MODULE_NOT_FOUND_ERROR,
839                          _("TLS load module not found"));
840
841           addr = target_get_thread_local_address (ptid, lm_addr, offset);
842         }
843       /* If an error occurred, print TLS related messages here.  Otherwise,
844          throw the error to some higher catcher.  */
845       if (ex.reason < 0)
846         {
847           int objfile_is_library = (objfile->flags & OBJF_SHARED);
848
849           switch (ex.error)
850             {
851             case TLS_NO_LIBRARY_SUPPORT_ERROR:
852               error (_("Cannot find thread-local variables in this thread library."));
853               break;
854             case TLS_LOAD_MODULE_NOT_FOUND_ERROR:
855               if (objfile_is_library)
856                 error (_("Cannot find shared library `%s' in dynamic"
857                          " linker's load module list"), objfile->name);
858               else
859                 error (_("Cannot find executable file `%s' in dynamic"
860                          " linker's load module list"), objfile->name);
861               break;
862             case TLS_NOT_ALLOCATED_YET_ERROR:
863               if (objfile_is_library)
864                 error (_("The inferior has not yet allocated storage for"
865                          " thread-local variables in\n"
866                          "the shared library `%s'\n"
867                          "for %s"),
868                        objfile->name, target_pid_to_str (ptid));
869               else
870                 error (_("The inferior has not yet allocated storage for"
871                          " thread-local variables in\n"
872                          "the executable `%s'\n"
873                          "for %s"),
874                        objfile->name, target_pid_to_str (ptid));
875               break;
876             case TLS_GENERIC_ERROR:
877               if (objfile_is_library)
878                 error (_("Cannot find thread-local storage for %s, "
879                          "shared library %s:\n%s"),
880                        target_pid_to_str (ptid),
881                        objfile->name, ex.message);
882               else
883                 error (_("Cannot find thread-local storage for %s, "
884                          "executable file %s:\n%s"),
885                        target_pid_to_str (ptid),
886                        objfile->name, ex.message);
887               break;
888             default:
889               throw_exception (ex);
890               break;
891             }
892         }
893     }
894   /* It wouldn't be wrong here to try a gdbarch method, too; finding
895      TLS is an ABI-specific thing.  But we don't do that yet.  */
896   else
897     error (_("Cannot find thread-local variables on this target"));
898
899   return addr;
900 }
901
902 #undef  MIN
903 #define MIN(A, B) (((A) <= (B)) ? (A) : (B))
904
905 /* target_read_string -- read a null terminated string, up to LEN bytes,
906    from MEMADDR in target.  Set *ERRNOP to the errno code, or 0 if successful.
907    Set *STRING to a pointer to malloc'd memory containing the data; the caller
908    is responsible for freeing it.  Return the number of bytes successfully
909    read.  */
910
911 int
912 target_read_string (CORE_ADDR memaddr, char **string, int len, int *errnop)
913 {
914   int tlen, origlen, offset, i;
915   gdb_byte buf[4];
916   int errcode = 0;
917   char *buffer;
918   int buffer_allocated;
919   char *bufptr;
920   unsigned int nbytes_read = 0;
921
922   /* Small for testing.  */
923   buffer_allocated = 4;
924   buffer = xmalloc (buffer_allocated);
925   bufptr = buffer;
926
927   origlen = len;
928
929   while (len > 0)
930     {
931       tlen = MIN (len, 4 - (memaddr & 3));
932       offset = memaddr & 3;
933
934       errcode = target_read_memory (memaddr & ~3, buf, sizeof buf);
935       if (errcode != 0)
936         {
937           /* The transfer request might have crossed the boundary to an
938              unallocated region of memory. Retry the transfer, requesting
939              a single byte.  */
940           tlen = 1;
941           offset = 0;
942           errcode = target_read_memory (memaddr, buf, 1);
943           if (errcode != 0)
944             goto done;
945         }
946
947       if (bufptr - buffer + tlen > buffer_allocated)
948         {
949           unsigned int bytes;
950           bytes = bufptr - buffer;
951           buffer_allocated *= 2;
952           buffer = xrealloc (buffer, buffer_allocated);
953           bufptr = buffer + bytes;
954         }
955
956       for (i = 0; i < tlen; i++)
957         {
958           *bufptr++ = buf[i + offset];
959           if (buf[i + offset] == '\000')
960             {
961               nbytes_read += i + 1;
962               goto done;
963             }
964         }
965
966       memaddr += tlen;
967       len -= tlen;
968       nbytes_read += tlen;
969     }
970 done:
971   if (errnop != NULL)
972     *errnop = errcode;
973   if (string != NULL)
974     *string = buffer;
975   return nbytes_read;
976 }
977
978 /* Find a section containing ADDR.  */
979 struct section_table *
980 target_section_by_addr (struct target_ops *target, CORE_ADDR addr)
981 {
982   struct section_table *secp;
983   for (secp = target->to_sections;
984        secp < target->to_sections_end;
985        secp++)
986     {
987       if (addr >= secp->addr && addr < secp->endaddr)
988         return secp;
989     }
990   return NULL;
991 }
992
993 /* Perform a partial memory transfer.  The arguments and return
994    value are just as for target_xfer_partial.  */
995
996 static LONGEST
997 memory_xfer_partial (struct target_ops *ops, void *readbuf, const void *writebuf,
998                      ULONGEST memaddr, LONGEST len)
999 {
1000   LONGEST res;
1001   int reg_len;
1002   struct mem_region *region;
1003
1004   /* Zero length requests are ok and require no work.  */
1005   if (len == 0)
1006     return 0;
1007
1008   /* Try the executable file, if "trust-readonly-sections" is set.  */
1009   if (readbuf != NULL && trust_readonly)
1010     {
1011       struct section_table *secp;
1012
1013       secp = target_section_by_addr (ops, memaddr);
1014       if (secp != NULL
1015           && (bfd_get_section_flags (secp->bfd, secp->the_bfd_section)
1016               & SEC_READONLY))
1017         return xfer_memory (memaddr, readbuf, len, 0, NULL, ops);
1018     }
1019
1020   /* Likewise for accesses to unmapped overlay sections.  */
1021   if (readbuf != NULL && overlay_debugging)
1022     {
1023       asection *section = find_pc_overlay (memaddr);
1024       if (pc_in_unmapped_range (memaddr, section))
1025         return xfer_memory (memaddr, readbuf, len, 0, NULL, ops);
1026     }
1027
1028   /* Try GDB's internal data cache.  */
1029   region = lookup_mem_region (memaddr);
1030   /* region->hi == 0 means there's no upper bound.  */
1031   if (memaddr + len < region->hi || region->hi == 0)
1032     reg_len = len;
1033   else
1034     reg_len = region->hi - memaddr;
1035
1036   switch (region->attrib.mode)
1037     {
1038     case MEM_RO:
1039       if (writebuf != NULL)
1040         return -1;
1041       break;
1042
1043     case MEM_WO:
1044       if (readbuf != NULL)
1045         return -1;
1046       break;
1047
1048     case MEM_FLASH:
1049       /* We only support writing to flash during "load" for now.  */
1050       if (writebuf != NULL)
1051         error (_("Writing to flash memory forbidden in this context"));
1052       break;
1053
1054     case MEM_NONE:
1055       return -1;
1056     }
1057
1058   if (region->attrib.cache)
1059     {
1060       /* FIXME drow/2006-08-09: This call discards OPS, so the raw
1061          memory request will start back at current_target.  */
1062       if (readbuf != NULL)
1063         res = dcache_xfer_memory (target_dcache, memaddr, readbuf,
1064                                   reg_len, 0);
1065       else
1066         /* FIXME drow/2006-08-09: If we're going to preserve const
1067            correctness dcache_xfer_memory should take readbuf and
1068            writebuf.  */
1069         res = dcache_xfer_memory (target_dcache, memaddr,
1070                                   (void *) writebuf,
1071                                   reg_len, 1);
1072       if (res <= 0)
1073         return -1;
1074       else
1075         return res;
1076     }
1077
1078   /* If none of those methods found the memory we wanted, fall back
1079      to a target partial transfer.  Normally a single call to
1080      to_xfer_partial is enough; if it doesn't recognize an object
1081      it will call the to_xfer_partial of the next target down.
1082      But for memory this won't do.  Memory is the only target
1083      object which can be read from more than one valid target.
1084      A core file, for instance, could have some of memory but
1085      delegate other bits to the target below it.  So, we must
1086      manually try all targets.  */
1087
1088   do
1089     {
1090       res = ops->to_xfer_partial (ops, TARGET_OBJECT_MEMORY, NULL,
1091                                   readbuf, writebuf, memaddr, reg_len);
1092       if (res > 0)
1093         return res;
1094
1095       /* We want to continue past core files to executables, but not
1096          past a running target's memory.  */
1097       if (ops->to_has_all_memory)
1098         return res;
1099
1100       ops = ops->beneath;
1101     }
1102   while (ops != NULL);
1103
1104   /* If we still haven't got anything, return the last error.  We
1105      give up.  */
1106   return res;
1107 }
1108
1109 static LONGEST
1110 target_xfer_partial (struct target_ops *ops,
1111                      enum target_object object, const char *annex,
1112                      void *readbuf, const void *writebuf,
1113                      ULONGEST offset, LONGEST len)
1114 {
1115   LONGEST retval;
1116
1117   gdb_assert (ops->to_xfer_partial != NULL);
1118
1119   /* If this is a memory transfer, let the memory-specific code
1120      have a look at it instead.  Memory transfers are more
1121      complicated.  */
1122   if (object == TARGET_OBJECT_MEMORY)
1123     retval = memory_xfer_partial (ops, readbuf, writebuf, offset, len);
1124   else
1125     {
1126       enum target_object raw_object = object;
1127
1128       /* If this is a raw memory transfer, request the normal
1129          memory object from other layers.  */
1130       if (raw_object == TARGET_OBJECT_RAW_MEMORY)
1131         raw_object = TARGET_OBJECT_MEMORY;
1132
1133       retval = ops->to_xfer_partial (ops, raw_object, annex, readbuf,
1134                                      writebuf, offset, len);
1135     }
1136
1137   if (targetdebug)
1138     {
1139       const unsigned char *myaddr = NULL;
1140
1141       fprintf_unfiltered (gdb_stdlog,
1142                           "%s:target_xfer_partial (%d, %s, 0x%lx,  0x%lx,  0x%s, %s) = %s",
1143                           ops->to_shortname,
1144                           (int) object,
1145                           (annex ? annex : "(null)"),
1146                           (long) readbuf, (long) writebuf,
1147                           paddr_nz (offset), paddr_d (len), paddr_d (retval));
1148
1149       if (readbuf)
1150         myaddr = readbuf;
1151       if (writebuf)
1152         myaddr = writebuf;
1153       if (retval > 0 && myaddr != NULL)
1154         {
1155           int i;
1156
1157           fputs_unfiltered (", bytes =", gdb_stdlog);
1158           for (i = 0; i < retval; i++)
1159             {
1160               if ((((long) &(myaddr[i])) & 0xf) == 0)
1161                 {
1162                   if (targetdebug < 2 && i > 0)
1163                     {
1164                       fprintf_unfiltered (gdb_stdlog, " ...");
1165                       break;
1166                     }
1167                   fprintf_unfiltered (gdb_stdlog, "\n");
1168                 }
1169
1170               fprintf_unfiltered (gdb_stdlog, " %02x", myaddr[i] & 0xff);
1171             }
1172         }
1173
1174       fputc_unfiltered ('\n', gdb_stdlog);
1175     }
1176   return retval;
1177 }
1178
1179 /* Read LEN bytes of target memory at address MEMADDR, placing the results in
1180    GDB's memory at MYADDR.  Returns either 0 for success or an errno value
1181    if any error occurs.
1182
1183    If an error occurs, no guarantee is made about the contents of the data at
1184    MYADDR.  In particular, the caller should not depend upon partial reads
1185    filling the buffer with good data.  There is no way for the caller to know
1186    how much good data might have been transfered anyway.  Callers that can
1187    deal with partial reads should call target_read (which will retry until
1188    it makes no progress, and then return how much was transferred). */
1189
1190 int
1191 target_read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
1192 {
1193   if (target_read (&current_target, TARGET_OBJECT_MEMORY, NULL,
1194                    myaddr, memaddr, len) == len)
1195     return 0;
1196   else
1197     return EIO;
1198 }
1199
1200 int
1201 target_write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
1202 {
1203   if (target_write (&current_target, TARGET_OBJECT_MEMORY, NULL,
1204                     myaddr, memaddr, len) == len)
1205     return 0;
1206   else
1207     return EIO;
1208 }
1209
1210 /* Fetch the target's memory map.  */
1211
1212 VEC(mem_region_s) *
1213 target_memory_map (void)
1214 {
1215   VEC(mem_region_s) *result;
1216   struct mem_region *last_one, *this_one;
1217   int ix;
1218   struct target_ops *t;
1219
1220   if (targetdebug)
1221     fprintf_unfiltered (gdb_stdlog, "target_memory_map ()\n");
1222
1223   for (t = current_target.beneath; t != NULL; t = t->beneath)
1224     if (t->to_memory_map != NULL)
1225       break;
1226
1227   if (t == NULL)
1228     return NULL;
1229
1230   result = t->to_memory_map (t);
1231   if (result == NULL)
1232     return NULL;
1233
1234   qsort (VEC_address (mem_region_s, result),
1235          VEC_length (mem_region_s, result),
1236          sizeof (struct mem_region), mem_region_cmp);
1237
1238   /* Check that regions do not overlap.  Simultaneously assign
1239      a numbering for the "mem" commands to use to refer to
1240      each region.  */
1241   last_one = NULL;
1242   for (ix = 0; VEC_iterate (mem_region_s, result, ix, this_one); ix++)
1243     {
1244       this_one->number = ix;
1245
1246       if (last_one && last_one->hi > this_one->lo)
1247         {
1248           warning (_("Overlapping regions in memory map: ignoring"));
1249           VEC_free (mem_region_s, result);
1250           return NULL;
1251         }
1252       last_one = this_one;
1253     }
1254
1255   return result;
1256 }
1257
1258 void
1259 target_flash_erase (ULONGEST address, LONGEST length)
1260 {
1261   struct target_ops *t;
1262
1263   for (t = current_target.beneath; t != NULL; t = t->beneath)
1264     if (t->to_flash_erase != NULL)
1265         {
1266           if (targetdebug)
1267             fprintf_unfiltered (gdb_stdlog, "target_flash_erase (%s, %s)\n",
1268                                 paddr (address), phex (length, 0));
1269           t->to_flash_erase (t, address, length);
1270           return;
1271         }
1272
1273   tcomplain ();
1274 }
1275
1276 void
1277 target_flash_done (void)
1278 {
1279   struct target_ops *t;
1280
1281   for (t = current_target.beneath; t != NULL; t = t->beneath)
1282     if (t->to_flash_done != NULL)
1283         {
1284           if (targetdebug)
1285             fprintf_unfiltered (gdb_stdlog, "target_flash_done\n");
1286           t->to_flash_done (t);
1287           return;
1288         }
1289
1290   tcomplain ();
1291 }
1292
1293 #ifndef target_stopped_data_address_p
1294 int
1295 target_stopped_data_address_p (struct target_ops *target)
1296 {
1297   if (target->to_stopped_data_address
1298       == (int (*) (struct target_ops *, CORE_ADDR *)) return_zero)
1299     return 0;
1300   if (target->to_stopped_data_address == debug_to_stopped_data_address
1301       && (debug_target.to_stopped_data_address
1302           == (int (*) (struct target_ops *, CORE_ADDR *)) return_zero))
1303     return 0;
1304   return 1;
1305 }
1306 #endif
1307
1308 static void
1309 show_trust_readonly (struct ui_file *file, int from_tty,
1310                      struct cmd_list_element *c, const char *value)
1311 {
1312   fprintf_filtered (file, _("\
1313 Mode for reading from readonly sections is %s.\n"),
1314                     value);
1315 }
1316
1317 /* More generic transfers.  */
1318
1319 static LONGEST
1320 default_xfer_partial (struct target_ops *ops, enum target_object object,
1321                       const char *annex, gdb_byte *readbuf,
1322                       const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1323 {
1324   if (object == TARGET_OBJECT_MEMORY
1325       && ops->deprecated_xfer_memory != NULL)
1326     /* If available, fall back to the target's
1327        "deprecated_xfer_memory" method.  */
1328     {
1329       int xfered = -1;
1330       errno = 0;
1331       if (writebuf != NULL)
1332         {
1333           void *buffer = xmalloc (len);
1334           struct cleanup *cleanup = make_cleanup (xfree, buffer);
1335           memcpy (buffer, writebuf, len);
1336           xfered = ops->deprecated_xfer_memory (offset, buffer, len,
1337                                                 1/*write*/, NULL, ops);
1338           do_cleanups (cleanup);
1339         }
1340       if (readbuf != NULL)
1341         xfered = ops->deprecated_xfer_memory (offset, readbuf, len, 0/*read*/,
1342                                               NULL, ops);
1343       if (xfered > 0)
1344         return xfered;
1345       else if (xfered == 0 && errno == 0)
1346         /* "deprecated_xfer_memory" uses 0, cross checked against
1347            ERRNO as one indication of an error.  */
1348         return 0;
1349       else
1350         return -1;
1351     }
1352   else if (ops->beneath != NULL)
1353     return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
1354                                           readbuf, writebuf, offset, len);
1355   else
1356     return -1;
1357 }
1358
1359 /* The xfer_partial handler for the topmost target.  Unlike the default,
1360    it does not need to handle memory specially; it just passes all
1361    requests down the stack.  */
1362
1363 static LONGEST
1364 current_xfer_partial (struct target_ops *ops, enum target_object object,
1365                       const char *annex, gdb_byte *readbuf,
1366                       const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
1367 {
1368   if (ops->beneath != NULL)
1369     return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
1370                                           readbuf, writebuf, offset, len);
1371   else
1372     return -1;
1373 }
1374
1375 /* Target vector read/write partial wrapper functions.
1376
1377    NOTE: cagney/2003-10-21: I wonder if having "to_xfer_partial
1378    (inbuf, outbuf)", instead of separate read/write methods, make life
1379    easier.  */
1380
1381 static LONGEST
1382 target_read_partial (struct target_ops *ops,
1383                      enum target_object object,
1384                      const char *annex, gdb_byte *buf,
1385                      ULONGEST offset, LONGEST len)
1386 {
1387   return target_xfer_partial (ops, object, annex, buf, NULL, offset, len);
1388 }
1389
1390 static LONGEST
1391 target_write_partial (struct target_ops *ops,
1392                       enum target_object object,
1393                       const char *annex, const gdb_byte *buf,
1394                       ULONGEST offset, LONGEST len)
1395 {
1396   return target_xfer_partial (ops, object, annex, NULL, buf, offset, len);
1397 }
1398
1399 /* Wrappers to perform the full transfer.  */
1400 LONGEST
1401 target_read (struct target_ops *ops,
1402              enum target_object object,
1403              const char *annex, gdb_byte *buf,
1404              ULONGEST offset, LONGEST len)
1405 {
1406   LONGEST xfered = 0;
1407   while (xfered < len)
1408     {
1409       LONGEST xfer = target_read_partial (ops, object, annex,
1410                                           (gdb_byte *) buf + xfered,
1411                                           offset + xfered, len - xfered);
1412       /* Call an observer, notifying them of the xfer progress?  */
1413       if (xfer == 0)
1414         return xfered;
1415       if (xfer < 0)
1416         return -1;
1417       xfered += xfer;
1418       QUIT;
1419     }
1420   return len;
1421 }
1422
1423 /* An alternative to target_write with progress callbacks.  */
1424
1425 LONGEST
1426 target_write_with_progress (struct target_ops *ops,
1427                             enum target_object object,
1428                             const char *annex, const gdb_byte *buf,
1429                             ULONGEST offset, LONGEST len,
1430                             void (*progress) (ULONGEST, void *), void *baton)
1431 {
1432   LONGEST xfered = 0;
1433
1434   /* Give the progress callback a chance to set up.  */
1435   if (progress)
1436     (*progress) (0, baton);
1437
1438   while (xfered < len)
1439     {
1440       LONGEST xfer = target_write_partial (ops, object, annex,
1441                                            (gdb_byte *) buf + xfered,
1442                                            offset + xfered, len - xfered);
1443
1444       if (xfer == 0)
1445         return xfered;
1446       if (xfer < 0)
1447         return -1;
1448
1449       if (progress)
1450         (*progress) (xfer, baton);
1451
1452       xfered += xfer;
1453       QUIT;
1454     }
1455   return len;
1456 }
1457
1458 LONGEST
1459 target_write (struct target_ops *ops,
1460               enum target_object object,
1461               const char *annex, const gdb_byte *buf,
1462               ULONGEST offset, LONGEST len)
1463 {
1464   return target_write_with_progress (ops, object, annex, buf, offset, len,
1465                                      NULL, NULL);
1466 }
1467
1468 /* Read OBJECT/ANNEX using OPS.  Store the result in *BUF_P and return
1469    the size of the transferred data.  PADDING additional bytes are
1470    available in *BUF_P.  This is a helper function for
1471    target_read_alloc; see the declaration of that function for more
1472    information.  */
1473
1474 static LONGEST
1475 target_read_alloc_1 (struct target_ops *ops, enum target_object object,
1476                      const char *annex, gdb_byte **buf_p, int padding)
1477 {
1478   size_t buf_alloc, buf_pos;
1479   gdb_byte *buf;
1480   LONGEST n;
1481
1482   /* This function does not have a length parameter; it reads the
1483      entire OBJECT).  Also, it doesn't support objects fetched partly
1484      from one target and partly from another (in a different stratum,
1485      e.g. a core file and an executable).  Both reasons make it
1486      unsuitable for reading memory.  */
1487   gdb_assert (object != TARGET_OBJECT_MEMORY);
1488
1489   /* Start by reading up to 4K at a time.  The target will throttle
1490      this number down if necessary.  */
1491   buf_alloc = 4096;
1492   buf = xmalloc (buf_alloc);
1493   buf_pos = 0;
1494   while (1)
1495     {
1496       n = target_read_partial (ops, object, annex, &buf[buf_pos],
1497                                buf_pos, buf_alloc - buf_pos - padding);
1498       if (n < 0)
1499         {
1500           /* An error occurred.  */
1501           xfree (buf);
1502           return -1;
1503         }
1504       else if (n == 0)
1505         {
1506           /* Read all there was.  */
1507           if (buf_pos == 0)
1508             xfree (buf);
1509           else
1510             *buf_p = buf;
1511           return buf_pos;
1512         }
1513
1514       buf_pos += n;
1515
1516       /* If the buffer is filling up, expand it.  */
1517       if (buf_alloc < buf_pos * 2)
1518         {
1519           buf_alloc *= 2;
1520           buf = xrealloc (buf, buf_alloc);
1521         }
1522
1523       QUIT;
1524     }
1525 }
1526
1527 /* Read OBJECT/ANNEX using OPS.  Store the result in *BUF_P and return
1528    the size of the transferred data.  See the declaration in "target.h"
1529    function for more information about the return value.  */
1530
1531 LONGEST
1532 target_read_alloc (struct target_ops *ops, enum target_object object,
1533                    const char *annex, gdb_byte **buf_p)
1534 {
1535   return target_read_alloc_1 (ops, object, annex, buf_p, 0);
1536 }
1537
1538 /* Read OBJECT/ANNEX using OPS.  The result is NUL-terminated and
1539    returned as a string, allocated using xmalloc.  If an error occurs
1540    or the transfer is unsupported, NULL is returned.  Empty objects
1541    are returned as allocated but empty strings.  A warning is issued
1542    if the result contains any embedded NUL bytes.  */
1543
1544 char *
1545 target_read_stralloc (struct target_ops *ops, enum target_object object,
1546                       const char *annex)
1547 {
1548   gdb_byte *buffer;
1549   LONGEST transferred;
1550
1551   transferred = target_read_alloc_1 (ops, object, annex, &buffer, 1);
1552
1553   if (transferred < 0)
1554     return NULL;
1555
1556   if (transferred == 0)
1557     return xstrdup ("");
1558
1559   buffer[transferred] = 0;
1560   if (strlen (buffer) < transferred)
1561     warning (_("target object %d, annex %s, "
1562                "contained unexpected null characters"),
1563              (int) object, annex ? annex : "(none)");
1564
1565   return (char *) buffer;
1566 }
1567
1568 /* Memory transfer methods.  */
1569
1570 void
1571 get_target_memory (struct target_ops *ops, CORE_ADDR addr, gdb_byte *buf,
1572                    LONGEST len)
1573 {
1574   if (target_read (ops, TARGET_OBJECT_MEMORY, NULL, buf, addr, len)
1575       != len)
1576     memory_error (EIO, addr);
1577 }
1578
1579 ULONGEST
1580 get_target_memory_unsigned (struct target_ops *ops,
1581                             CORE_ADDR addr, int len)
1582 {
1583   gdb_byte buf[sizeof (ULONGEST)];
1584
1585   gdb_assert (len <= sizeof (buf));
1586   get_target_memory (ops, addr, buf, len);
1587   return extract_unsigned_integer (buf, len);
1588 }
1589
1590 static void
1591 target_info (char *args, int from_tty)
1592 {
1593   struct target_ops *t;
1594   int has_all_mem = 0;
1595
1596   if (symfile_objfile != NULL)
1597     printf_unfiltered (_("Symbols from \"%s\".\n"), symfile_objfile->name);
1598
1599   for (t = target_stack; t != NULL; t = t->beneath)
1600     {
1601       if (!t->to_has_memory)
1602         continue;
1603
1604       if ((int) (t->to_stratum) <= (int) dummy_stratum)
1605         continue;
1606       if (has_all_mem)
1607         printf_unfiltered (_("\tWhile running this, GDB does not access memory from...\n"));
1608       printf_unfiltered ("%s:\n", t->to_longname);
1609       (t->to_files_info) (t);
1610       has_all_mem = t->to_has_all_memory;
1611     }
1612 }
1613
1614 /* This function is called before any new inferior is created, e.g.
1615    by running a program, attaching, or connecting to a target.
1616    It cleans up any state from previous invocations which might
1617    change between runs.  This is a subset of what target_preopen
1618    resets (things which might change between targets).  */
1619
1620 void
1621 target_pre_inferior (int from_tty)
1622 {
1623   invalidate_target_mem_regions ();
1624
1625   target_clear_description ();
1626 }
1627
1628 /* This is to be called by the open routine before it does
1629    anything.  */
1630
1631 void
1632 target_preopen (int from_tty)
1633 {
1634   dont_repeat ();
1635
1636   if (target_has_execution)
1637     {
1638       if (!from_tty
1639           || query (_("A program is being debugged already.  Kill it? ")))
1640         target_kill ();
1641       else
1642         error (_("Program not killed."));
1643     }
1644
1645   /* Calling target_kill may remove the target from the stack.  But if
1646      it doesn't (which seems like a win for UDI), remove it now.  */
1647
1648   if (target_has_execution)
1649     pop_target ();
1650
1651   target_pre_inferior (from_tty);
1652 }
1653
1654 /* Detach a target after doing deferred register stores.  */
1655
1656 void
1657 target_detach (char *args, int from_tty)
1658 {
1659   (current_target.to_detach) (args, from_tty);
1660 }
1661
1662 void
1663 target_disconnect (char *args, int from_tty)
1664 {
1665   struct target_ops *t;
1666
1667   for (t = current_target.beneath; t != NULL; t = t->beneath)
1668     if (t->to_disconnect != NULL)
1669         {
1670           if (targetdebug)
1671             fprintf_unfiltered (gdb_stdlog, "target_disconnect (%s, %d)\n",
1672                                 args, from_tty);
1673           t->to_disconnect (t, args, from_tty);
1674           return;
1675         }
1676
1677   tcomplain ();
1678 }
1679
1680 int
1681 target_async_mask (int mask)
1682 {
1683   int saved_async_masked_status = target_async_mask_value;
1684   target_async_mask_value = mask;
1685   return saved_async_masked_status;
1686 }
1687
1688 /* Look through the list of possible targets for a target that can
1689    follow forks.  */
1690
1691 int
1692 target_follow_fork (int follow_child)
1693 {
1694   struct target_ops *t;
1695
1696   for (t = current_target.beneath; t != NULL; t = t->beneath)
1697     {
1698       if (t->to_follow_fork != NULL)
1699         {
1700           int retval = t->to_follow_fork (t, follow_child);
1701           if (targetdebug)
1702             fprintf_unfiltered (gdb_stdlog, "target_follow_fork (%d) = %d\n",
1703                                 follow_child, retval);
1704           return retval;
1705         }
1706     }
1707
1708   /* Some target returned a fork event, but did not know how to follow it.  */
1709   internal_error (__FILE__, __LINE__,
1710                   "could not find a target to follow fork");
1711 }
1712
1713 /* Look for a target which can describe architectural features, starting
1714    from TARGET.  If we find one, return its description.  */
1715
1716 const struct target_desc *
1717 target_read_description (struct target_ops *target)
1718 {
1719   struct target_ops *t;
1720
1721   for (t = target; t != NULL; t = t->beneath)
1722     if (t->to_read_description != NULL)
1723       {
1724         const struct target_desc *tdesc;
1725
1726         tdesc = t->to_read_description (t);
1727         if (tdesc)
1728           return tdesc;
1729       }
1730
1731   return NULL;
1732 }
1733
1734 /* Look through the list of possible targets for a target that can
1735    execute a run or attach command without any other data.  This is
1736    used to locate the default process stratum.
1737
1738    Result is always valid (error() is called for errors).  */
1739
1740 static struct target_ops *
1741 find_default_run_target (char *do_mesg)
1742 {
1743   struct target_ops **t;
1744   struct target_ops *runable = NULL;
1745   int count;
1746
1747   count = 0;
1748
1749   for (t = target_structs; t < target_structs + target_struct_size;
1750        ++t)
1751     {
1752       if ((*t)->to_can_run && target_can_run (*t))
1753         {
1754           runable = *t;
1755           ++count;
1756         }
1757     }
1758
1759   if (count != 1)
1760     error (_("Don't know how to %s.  Try \"help target\"."), do_mesg);
1761
1762   return runable;
1763 }
1764
1765 void
1766 find_default_attach (char *args, int from_tty)
1767 {
1768   struct target_ops *t;
1769
1770   t = find_default_run_target ("attach");
1771   (t->to_attach) (args, from_tty);
1772   return;
1773 }
1774
1775 void
1776 find_default_create_inferior (char *exec_file, char *allargs, char **env,
1777                               int from_tty)
1778 {
1779   struct target_ops *t;
1780
1781   t = find_default_run_target ("run");
1782   (t->to_create_inferior) (exec_file, allargs, env, from_tty);
1783   return;
1784 }
1785
1786 static int
1787 default_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
1788 {
1789   return (len <= TYPE_LENGTH (builtin_type_void_data_ptr));
1790 }
1791
1792 static int
1793 return_zero (void)
1794 {
1795   return 0;
1796 }
1797
1798 static int
1799 return_one (void)
1800 {
1801   return 1;
1802 }
1803
1804 static int
1805 return_minus_one (void)
1806 {
1807   return -1;
1808 }
1809
1810 /*
1811  * Resize the to_sections pointer.  Also make sure that anyone that
1812  * was holding on to an old value of it gets updated.
1813  * Returns the old size.
1814  */
1815
1816 int
1817 target_resize_to_sections (struct target_ops *target, int num_added)
1818 {
1819   struct target_ops **t;
1820   struct section_table *old_value;
1821   int old_count;
1822
1823   old_value = target->to_sections;
1824
1825   if (target->to_sections)
1826     {
1827       old_count = target->to_sections_end - target->to_sections;
1828       target->to_sections = (struct section_table *)
1829         xrealloc ((char *) target->to_sections,
1830                   (sizeof (struct section_table)) * (num_added + old_count));
1831     }
1832   else
1833     {
1834       old_count = 0;
1835       target->to_sections = (struct section_table *)
1836         xmalloc ((sizeof (struct section_table)) * num_added);
1837     }
1838   target->to_sections_end = target->to_sections + (num_added + old_count);
1839
1840   /* Check to see if anyone else was pointing to this structure.
1841      If old_value was null, then no one was. */
1842
1843   if (old_value)
1844     {
1845       for (t = target_structs; t < target_structs + target_struct_size;
1846            ++t)
1847         {
1848           if ((*t)->to_sections == old_value)
1849             {
1850               (*t)->to_sections = target->to_sections;
1851               (*t)->to_sections_end = target->to_sections_end;
1852             }
1853         }
1854       /* There is a flattened view of the target stack in current_target,
1855          so its to_sections pointer might also need updating. */
1856       if (current_target.to_sections == old_value)
1857         {
1858           current_target.to_sections = target->to_sections;
1859           current_target.to_sections_end = target->to_sections_end;
1860         }
1861     }
1862
1863   return old_count;
1864
1865 }
1866
1867 /* Remove all target sections taken from ABFD.
1868
1869    Scan the current target stack for targets whose section tables
1870    refer to sections from BFD, and remove those sections.  We use this
1871    when we notice that the inferior has unloaded a shared object, for
1872    example.  */
1873 void
1874 remove_target_sections (bfd *abfd)
1875 {
1876   struct target_ops **t;
1877
1878   for (t = target_structs; t < target_structs + target_struct_size; t++)
1879     {
1880       struct section_table *src, *dest;
1881
1882       dest = (*t)->to_sections;
1883       for (src = (*t)->to_sections; src < (*t)->to_sections_end; src++)
1884         if (src->bfd != abfd)
1885           {
1886             /* Keep this section.  */
1887             if (dest < src) *dest = *src;
1888             dest++;
1889           }
1890
1891       /* If we've dropped any sections, resize the section table.  */
1892       if (dest < src)
1893         target_resize_to_sections (*t, dest - src);
1894     }
1895 }
1896
1897
1898
1899
1900 /* Find a single runnable target in the stack and return it.  If for
1901    some reason there is more than one, return NULL.  */
1902
1903 struct target_ops *
1904 find_run_target (void)
1905 {
1906   struct target_ops **t;
1907   struct target_ops *runable = NULL;
1908   int count;
1909
1910   count = 0;
1911
1912   for (t = target_structs; t < target_structs + target_struct_size; ++t)
1913     {
1914       if ((*t)->to_can_run && target_can_run (*t))
1915         {
1916           runable = *t;
1917           ++count;
1918         }
1919     }
1920
1921   return (count == 1 ? runable : NULL);
1922 }
1923
1924 /* Find a single core_stratum target in the list of targets and return it.
1925    If for some reason there is more than one, return NULL.  */
1926
1927 struct target_ops *
1928 find_core_target (void)
1929 {
1930   struct target_ops **t;
1931   struct target_ops *runable = NULL;
1932   int count;
1933
1934   count = 0;
1935
1936   for (t = target_structs; t < target_structs + target_struct_size;
1937        ++t)
1938     {
1939       if ((*t)->to_stratum == core_stratum)
1940         {
1941           runable = *t;
1942           ++count;
1943         }
1944     }
1945
1946   return (count == 1 ? runable : NULL);
1947 }
1948
1949 /*
1950  * Find the next target down the stack from the specified target.
1951  */
1952
1953 struct target_ops *
1954 find_target_beneath (struct target_ops *t)
1955 {
1956   return t->beneath;
1957 }
1958
1959 \f
1960 /* The inferior process has died.  Long live the inferior!  */
1961
1962 void
1963 generic_mourn_inferior (void)
1964 {
1965   extern int show_breakpoint_hit_counts;
1966
1967   inferior_ptid = null_ptid;
1968   attach_flag = 0;
1969   breakpoint_init_inferior (inf_exited);
1970   registers_changed ();
1971
1972   reopen_exec_file ();
1973   reinit_frame_cache ();
1974
1975   /* It is confusing to the user for ignore counts to stick around
1976      from previous runs of the inferior.  So clear them.  */
1977   /* However, it is more confusing for the ignore counts to disappear when
1978      using hit counts.  So don't clear them if we're counting hits.  */
1979   if (!show_breakpoint_hit_counts)
1980     breakpoint_clear_ignore_counts ();
1981
1982   if (deprecated_detach_hook)
1983     deprecated_detach_hook ();
1984 }
1985 \f
1986 /* Helper function for child_wait and the derivatives of child_wait.
1987    HOSTSTATUS is the waitstatus from wait() or the equivalent; store our
1988    translation of that in OURSTATUS.  */
1989 void
1990 store_waitstatus (struct target_waitstatus *ourstatus, int hoststatus)
1991 {
1992   if (WIFEXITED (hoststatus))
1993     {
1994       ourstatus->kind = TARGET_WAITKIND_EXITED;
1995       ourstatus->value.integer = WEXITSTATUS (hoststatus);
1996     }
1997   else if (!WIFSTOPPED (hoststatus))
1998     {
1999       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
2000       ourstatus->value.sig = target_signal_from_host (WTERMSIG (hoststatus));
2001     }
2002   else
2003     {
2004       ourstatus->kind = TARGET_WAITKIND_STOPPED;
2005       ourstatus->value.sig = target_signal_from_host (WSTOPSIG (hoststatus));
2006     }
2007 }
2008 \f
2009 /* Returns zero to leave the inferior alone, one to interrupt it.  */
2010 int (*target_activity_function) (void);
2011 int target_activity_fd;
2012 \f
2013 /* Convert a normal process ID to a string.  Returns the string in a
2014    static buffer.  */
2015
2016 char *
2017 normal_pid_to_str (ptid_t ptid)
2018 {
2019   static char buf[32];
2020
2021   xsnprintf (buf, sizeof buf, "process %d", ptid_get_pid (ptid));
2022   return buf;
2023 }
2024
2025 /* Error-catcher for target_find_memory_regions */
2026 static int dummy_find_memory_regions (int (*ignore1) (), void *ignore2)
2027 {
2028   error (_("No target."));
2029   return 0;
2030 }
2031
2032 /* Error-catcher for target_make_corefile_notes */
2033 static char * dummy_make_corefile_notes (bfd *ignore1, int *ignore2)
2034 {
2035   error (_("No target."));
2036   return NULL;
2037 }
2038
2039 /* Set up the handful of non-empty slots needed by the dummy target
2040    vector.  */
2041
2042 static void
2043 init_dummy_target (void)
2044 {
2045   dummy_target.to_shortname = "None";
2046   dummy_target.to_longname = "None";
2047   dummy_target.to_doc = "";
2048   dummy_target.to_attach = find_default_attach;
2049   dummy_target.to_create_inferior = find_default_create_inferior;
2050   dummy_target.to_pid_to_str = normal_pid_to_str;
2051   dummy_target.to_stratum = dummy_stratum;
2052   dummy_target.to_find_memory_regions = dummy_find_memory_regions;
2053   dummy_target.to_make_corefile_notes = dummy_make_corefile_notes;
2054   dummy_target.to_xfer_partial = default_xfer_partial;
2055   dummy_target.to_magic = OPS_MAGIC;
2056 }
2057 \f
2058 static void
2059 debug_to_open (char *args, int from_tty)
2060 {
2061   debug_target.to_open (args, from_tty);
2062
2063   fprintf_unfiltered (gdb_stdlog, "target_open (%s, %d)\n", args, from_tty);
2064 }
2065
2066 static void
2067 debug_to_close (int quitting)
2068 {
2069   target_close (&debug_target, quitting);
2070   fprintf_unfiltered (gdb_stdlog, "target_close (%d)\n", quitting);
2071 }
2072
2073 void
2074 target_close (struct target_ops *targ, int quitting)
2075 {
2076   if (targ->to_xclose != NULL)
2077     targ->to_xclose (targ, quitting);
2078   else if (targ->to_close != NULL)
2079     targ->to_close (quitting);
2080 }
2081
2082 static void
2083 debug_to_attach (char *args, int from_tty)
2084 {
2085   debug_target.to_attach (args, from_tty);
2086
2087   fprintf_unfiltered (gdb_stdlog, "target_attach (%s, %d)\n", args, from_tty);
2088 }
2089
2090
2091 static void
2092 debug_to_post_attach (int pid)
2093 {
2094   debug_target.to_post_attach (pid);
2095
2096   fprintf_unfiltered (gdb_stdlog, "target_post_attach (%d)\n", pid);
2097 }
2098
2099 static void
2100 debug_to_detach (char *args, int from_tty)
2101 {
2102   debug_target.to_detach (args, from_tty);
2103
2104   fprintf_unfiltered (gdb_stdlog, "target_detach (%s, %d)\n", args, from_tty);
2105 }
2106
2107 static void
2108 debug_to_resume (ptid_t ptid, int step, enum target_signal siggnal)
2109 {
2110   debug_target.to_resume (ptid, step, siggnal);
2111
2112   fprintf_unfiltered (gdb_stdlog, "target_resume (%d, %s, %s)\n", PIDGET (ptid),
2113                       step ? "step" : "continue",
2114                       target_signal_to_name (siggnal));
2115 }
2116
2117 static ptid_t
2118 debug_to_wait (ptid_t ptid, struct target_waitstatus *status)
2119 {
2120   ptid_t retval;
2121
2122   retval = debug_target.to_wait (ptid, status);
2123
2124   fprintf_unfiltered (gdb_stdlog,
2125                       "target_wait (%d, status) = %d,   ", PIDGET (ptid),
2126                       PIDGET (retval));
2127   fprintf_unfiltered (gdb_stdlog, "status->kind = ");
2128   switch (status->kind)
2129     {
2130     case TARGET_WAITKIND_EXITED:
2131       fprintf_unfiltered (gdb_stdlog, "exited, status = %d\n",
2132                           status->value.integer);
2133       break;
2134     case TARGET_WAITKIND_STOPPED:
2135       fprintf_unfiltered (gdb_stdlog, "stopped, signal = %s\n",
2136                           target_signal_to_name (status->value.sig));
2137       break;
2138     case TARGET_WAITKIND_SIGNALLED:
2139       fprintf_unfiltered (gdb_stdlog, "signalled, signal = %s\n",
2140                           target_signal_to_name (status->value.sig));
2141       break;
2142     case TARGET_WAITKIND_LOADED:
2143       fprintf_unfiltered (gdb_stdlog, "loaded\n");
2144       break;
2145     case TARGET_WAITKIND_FORKED:
2146       fprintf_unfiltered (gdb_stdlog, "forked\n");
2147       break;
2148     case TARGET_WAITKIND_VFORKED:
2149       fprintf_unfiltered (gdb_stdlog, "vforked\n");
2150       break;
2151     case TARGET_WAITKIND_EXECD:
2152       fprintf_unfiltered (gdb_stdlog, "execd\n");
2153       break;
2154     case TARGET_WAITKIND_SPURIOUS:
2155       fprintf_unfiltered (gdb_stdlog, "spurious\n");
2156       break;
2157     default:
2158       fprintf_unfiltered (gdb_stdlog, "unknown???\n");
2159       break;
2160     }
2161
2162   return retval;
2163 }
2164
2165 static void
2166 debug_print_register (const char * func,
2167                       struct regcache *regcache, int regno)
2168 {
2169   fprintf_unfiltered (gdb_stdlog, "%s ", func);
2170   if (regno >= 0 && regno < gdbarch_num_regs (current_gdbarch)
2171                             + gdbarch_num_pseudo_regs (current_gdbarch)
2172       && gdbarch_register_name (current_gdbarch, regno) != NULL
2173       && gdbarch_register_name (current_gdbarch, regno)[0] != '\0')
2174     fprintf_unfiltered (gdb_stdlog, "(%s)", gdbarch_register_name
2175                                               (current_gdbarch, regno));
2176   else
2177     fprintf_unfiltered (gdb_stdlog, "(%d)", regno);
2178   if (regno >= 0)
2179     {
2180       int i, size = register_size (current_gdbarch, regno);
2181       unsigned char buf[MAX_REGISTER_SIZE];
2182       regcache_cooked_read (regcache, regno, buf);
2183       fprintf_unfiltered (gdb_stdlog, " = ");
2184       for (i = 0; i < size; i++)
2185         {
2186           fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
2187         }
2188       if (size <= sizeof (LONGEST))
2189         {
2190           ULONGEST val = extract_unsigned_integer (buf, size);
2191           fprintf_unfiltered (gdb_stdlog, " 0x%s %s",
2192                               paddr_nz (val), paddr_d (val));
2193         }
2194     }
2195   fprintf_unfiltered (gdb_stdlog, "\n");
2196 }
2197
2198 static void
2199 debug_to_fetch_registers (struct regcache *regcache, int regno)
2200 {
2201   debug_target.to_fetch_registers (regcache, regno);
2202   debug_print_register ("target_fetch_registers", regcache, regno);
2203 }
2204
2205 static void
2206 debug_to_store_registers (struct regcache *regcache, int regno)
2207 {
2208   debug_target.to_store_registers (regcache, regno);
2209   debug_print_register ("target_store_registers", regcache, regno);
2210   fprintf_unfiltered (gdb_stdlog, "\n");
2211 }
2212
2213 static void
2214 debug_to_prepare_to_store (struct regcache *regcache)
2215 {
2216   debug_target.to_prepare_to_store (regcache);
2217
2218   fprintf_unfiltered (gdb_stdlog, "target_prepare_to_store ()\n");
2219 }
2220
2221 static int
2222 deprecated_debug_xfer_memory (CORE_ADDR memaddr, bfd_byte *myaddr, int len,
2223                               int write, struct mem_attrib *attrib,
2224                               struct target_ops *target)
2225 {
2226   int retval;
2227
2228   retval = debug_target.deprecated_xfer_memory (memaddr, myaddr, len, write,
2229                                                 attrib, target);
2230
2231   fprintf_unfiltered (gdb_stdlog,
2232                       "target_xfer_memory (0x%x, xxx, %d, %s, xxx) = %d",
2233                       (unsigned int) memaddr,   /* possable truncate long long */
2234                       len, write ? "write" : "read", retval);
2235
2236   if (retval > 0)
2237     {
2238       int i;
2239
2240       fputs_unfiltered (", bytes =", gdb_stdlog);
2241       for (i = 0; i < retval; i++)
2242         {
2243           if ((((long) &(myaddr[i])) & 0xf) == 0)
2244             {
2245               if (targetdebug < 2 && i > 0)
2246                 {
2247                   fprintf_unfiltered (gdb_stdlog, " ...");
2248                   break;
2249                 }
2250               fprintf_unfiltered (gdb_stdlog, "\n");
2251             }
2252
2253           fprintf_unfiltered (gdb_stdlog, " %02x", myaddr[i] & 0xff);
2254         }
2255     }
2256
2257   fputc_unfiltered ('\n', gdb_stdlog);
2258
2259   return retval;
2260 }
2261
2262 static void
2263 debug_to_files_info (struct target_ops *target)
2264 {
2265   debug_target.to_files_info (target);
2266
2267   fprintf_unfiltered (gdb_stdlog, "target_files_info (xxx)\n");
2268 }
2269
2270 static int
2271 debug_to_insert_breakpoint (struct bp_target_info *bp_tgt)
2272 {
2273   int retval;
2274
2275   retval = debug_target.to_insert_breakpoint (bp_tgt);
2276
2277   fprintf_unfiltered (gdb_stdlog,
2278                       "target_insert_breakpoint (0x%lx, xxx) = %ld\n",
2279                       (unsigned long) bp_tgt->placed_address,
2280                       (unsigned long) retval);
2281   return retval;
2282 }
2283
2284 static int
2285 debug_to_remove_breakpoint (struct bp_target_info *bp_tgt)
2286 {
2287   int retval;
2288
2289   retval = debug_target.to_remove_breakpoint (bp_tgt);
2290
2291   fprintf_unfiltered (gdb_stdlog,
2292                       "target_remove_breakpoint (0x%lx, xxx) = %ld\n",
2293                       (unsigned long) bp_tgt->placed_address,
2294                       (unsigned long) retval);
2295   return retval;
2296 }
2297
2298 static int
2299 debug_to_can_use_hw_breakpoint (int type, int cnt, int from_tty)
2300 {
2301   int retval;
2302
2303   retval = debug_target.to_can_use_hw_breakpoint (type, cnt, from_tty);
2304
2305   fprintf_unfiltered (gdb_stdlog,
2306                       "target_can_use_hw_breakpoint (%ld, %ld, %ld) = %ld\n",
2307                       (unsigned long) type,
2308                       (unsigned long) cnt,
2309                       (unsigned long) from_tty,
2310                       (unsigned long) retval);
2311   return retval;
2312 }
2313
2314 static int
2315 debug_to_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
2316 {
2317   CORE_ADDR retval;
2318
2319   retval = debug_target.to_region_ok_for_hw_watchpoint (addr, len);
2320
2321   fprintf_unfiltered (gdb_stdlog,
2322                       "TARGET_REGION_OK_FOR_HW_WATCHPOINT (%ld, %ld) = 0x%lx\n",
2323                       (unsigned long) addr,
2324                       (unsigned long) len,
2325                       (unsigned long) retval);
2326   return retval;
2327 }
2328
2329 static int
2330 debug_to_stopped_by_watchpoint (void)
2331 {
2332   int retval;
2333
2334   retval = debug_target.to_stopped_by_watchpoint ();
2335
2336   fprintf_unfiltered (gdb_stdlog,
2337                       "STOPPED_BY_WATCHPOINT () = %ld\n",
2338                       (unsigned long) retval);
2339   return retval;
2340 }
2341
2342 static int
2343 debug_to_stopped_data_address (struct target_ops *target, CORE_ADDR *addr)
2344 {
2345   int retval;
2346
2347   retval = debug_target.to_stopped_data_address (target, addr);
2348
2349   fprintf_unfiltered (gdb_stdlog,
2350                       "target_stopped_data_address ([0x%lx]) = %ld\n",
2351                       (unsigned long)*addr,
2352                       (unsigned long)retval);
2353   return retval;
2354 }
2355
2356 static int
2357 debug_to_insert_hw_breakpoint (struct bp_target_info *bp_tgt)
2358 {
2359   int retval;
2360
2361   retval = debug_target.to_insert_hw_breakpoint (bp_tgt);
2362
2363   fprintf_unfiltered (gdb_stdlog,
2364                       "target_insert_hw_breakpoint (0x%lx, xxx) = %ld\n",
2365                       (unsigned long) bp_tgt->placed_address,
2366                       (unsigned long) retval);
2367   return retval;
2368 }
2369
2370 static int
2371 debug_to_remove_hw_breakpoint (struct bp_target_info *bp_tgt)
2372 {
2373   int retval;
2374
2375   retval = debug_target.to_remove_hw_breakpoint (bp_tgt);
2376
2377   fprintf_unfiltered (gdb_stdlog,
2378                       "target_remove_hw_breakpoint (0x%lx, xxx) = %ld\n",
2379                       (unsigned long) bp_tgt->placed_address,
2380                       (unsigned long) retval);
2381   return retval;
2382 }
2383
2384 static int
2385 debug_to_insert_watchpoint (CORE_ADDR addr, int len, int type)
2386 {
2387   int retval;
2388
2389   retval = debug_target.to_insert_watchpoint (addr, len, type);
2390
2391   fprintf_unfiltered (gdb_stdlog,
2392                       "target_insert_watchpoint (0x%lx, %d, %d) = %ld\n",
2393                       (unsigned long) addr, len, type, (unsigned long) retval);
2394   return retval;
2395 }
2396
2397 static int
2398 debug_to_remove_watchpoint (CORE_ADDR addr, int len, int type)
2399 {
2400   int retval;
2401
2402   retval = debug_target.to_remove_watchpoint (addr, len, type);
2403
2404   fprintf_unfiltered (gdb_stdlog,
2405                       "target_remove_watchpoint (0x%lx, %d, %d) = %ld\n",
2406                       (unsigned long) addr, len, type, (unsigned long) retval);
2407   return retval;
2408 }
2409
2410 static void
2411 debug_to_terminal_init (void)
2412 {
2413   debug_target.to_terminal_init ();
2414
2415   fprintf_unfiltered (gdb_stdlog, "target_terminal_init ()\n");
2416 }
2417
2418 static void
2419 debug_to_terminal_inferior (void)
2420 {
2421   debug_target.to_terminal_inferior ();
2422
2423   fprintf_unfiltered (gdb_stdlog, "target_terminal_inferior ()\n");
2424 }
2425
2426 static void
2427 debug_to_terminal_ours_for_output (void)
2428 {
2429   debug_target.to_terminal_ours_for_output ();
2430
2431   fprintf_unfiltered (gdb_stdlog, "target_terminal_ours_for_output ()\n");
2432 }
2433
2434 static void
2435 debug_to_terminal_ours (void)
2436 {
2437   debug_target.to_terminal_ours ();
2438
2439   fprintf_unfiltered (gdb_stdlog, "target_terminal_ours ()\n");
2440 }
2441
2442 static void
2443 debug_to_terminal_save_ours (void)
2444 {
2445   debug_target.to_terminal_save_ours ();
2446
2447   fprintf_unfiltered (gdb_stdlog, "target_terminal_save_ours ()\n");
2448 }
2449
2450 static void
2451 debug_to_terminal_info (char *arg, int from_tty)
2452 {
2453   debug_target.to_terminal_info (arg, from_tty);
2454
2455   fprintf_unfiltered (gdb_stdlog, "target_terminal_info (%s, %d)\n", arg,
2456                       from_tty);
2457 }
2458
2459 static void
2460 debug_to_kill (void)
2461 {
2462   debug_target.to_kill ();
2463
2464   fprintf_unfiltered (gdb_stdlog, "target_kill ()\n");
2465 }
2466
2467 static void
2468 debug_to_load (char *args, int from_tty)
2469 {
2470   debug_target.to_load (args, from_tty);
2471
2472   fprintf_unfiltered (gdb_stdlog, "target_load (%s, %d)\n", args, from_tty);
2473 }
2474
2475 static int
2476 debug_to_lookup_symbol (char *name, CORE_ADDR *addrp)
2477 {
2478   int retval;
2479
2480   retval = debug_target.to_lookup_symbol (name, addrp);
2481
2482   fprintf_unfiltered (gdb_stdlog, "target_lookup_symbol (%s, xxx)\n", name);
2483
2484   return retval;
2485 }
2486
2487 static void
2488 debug_to_create_inferior (char *exec_file, char *args, char **env,
2489                           int from_tty)
2490 {
2491   debug_target.to_create_inferior (exec_file, args, env, from_tty);
2492
2493   fprintf_unfiltered (gdb_stdlog, "target_create_inferior (%s, %s, xxx, %d)\n",
2494                       exec_file, args, from_tty);
2495 }
2496
2497 static void
2498 debug_to_post_startup_inferior (ptid_t ptid)
2499 {
2500   debug_target.to_post_startup_inferior (ptid);
2501
2502   fprintf_unfiltered (gdb_stdlog, "target_post_startup_inferior (%d)\n",
2503                       PIDGET (ptid));
2504 }
2505
2506 static void
2507 debug_to_acknowledge_created_inferior (int pid)
2508 {
2509   debug_target.to_acknowledge_created_inferior (pid);
2510
2511   fprintf_unfiltered (gdb_stdlog, "target_acknowledge_created_inferior (%d)\n",
2512                       pid);
2513 }
2514
2515 static void
2516 debug_to_insert_fork_catchpoint (int pid)
2517 {
2518   debug_target.to_insert_fork_catchpoint (pid);
2519
2520   fprintf_unfiltered (gdb_stdlog, "target_insert_fork_catchpoint (%d)\n",
2521                       pid);
2522 }
2523
2524 static int
2525 debug_to_remove_fork_catchpoint (int pid)
2526 {
2527   int retval;
2528
2529   retval = debug_target.to_remove_fork_catchpoint (pid);
2530
2531   fprintf_unfiltered (gdb_stdlog, "target_remove_fork_catchpoint (%d) = %d\n",
2532                       pid, retval);
2533
2534   return retval;
2535 }
2536
2537 static void
2538 debug_to_insert_vfork_catchpoint (int pid)
2539 {
2540   debug_target.to_insert_vfork_catchpoint (pid);
2541
2542   fprintf_unfiltered (gdb_stdlog, "target_insert_vfork_catchpoint (%d)\n",
2543                       pid);
2544 }
2545
2546 static int
2547 debug_to_remove_vfork_catchpoint (int pid)
2548 {
2549   int retval;
2550
2551   retval = debug_target.to_remove_vfork_catchpoint (pid);
2552
2553   fprintf_unfiltered (gdb_stdlog, "target_remove_vfork_catchpoint (%d) = %d\n",
2554                       pid, retval);
2555
2556   return retval;
2557 }
2558
2559 static void
2560 debug_to_insert_exec_catchpoint (int pid)
2561 {
2562   debug_target.to_insert_exec_catchpoint (pid);
2563
2564   fprintf_unfiltered (gdb_stdlog, "target_insert_exec_catchpoint (%d)\n",
2565                       pid);
2566 }
2567
2568 static int
2569 debug_to_remove_exec_catchpoint (int pid)
2570 {
2571   int retval;
2572
2573   retval = debug_target.to_remove_exec_catchpoint (pid);
2574
2575   fprintf_unfiltered (gdb_stdlog, "target_remove_exec_catchpoint (%d) = %d\n",
2576                       pid, retval);
2577
2578   return retval;
2579 }
2580
2581 static int
2582 debug_to_reported_exec_events_per_exec_call (void)
2583 {
2584   int reported_exec_events;
2585
2586   reported_exec_events = debug_target.to_reported_exec_events_per_exec_call ();
2587
2588   fprintf_unfiltered (gdb_stdlog,
2589                       "target_reported_exec_events_per_exec_call () = %d\n",
2590                       reported_exec_events);
2591
2592   return reported_exec_events;
2593 }
2594
2595 static int
2596 debug_to_has_exited (int pid, int wait_status, int *exit_status)
2597 {
2598   int has_exited;
2599
2600   has_exited = debug_target.to_has_exited (pid, wait_status, exit_status);
2601
2602   fprintf_unfiltered (gdb_stdlog, "target_has_exited (%d, %d, %d) = %d\n",
2603                       pid, wait_status, *exit_status, has_exited);
2604
2605   return has_exited;
2606 }
2607
2608 static void
2609 debug_to_mourn_inferior (void)
2610 {
2611   debug_target.to_mourn_inferior ();
2612
2613   fprintf_unfiltered (gdb_stdlog, "target_mourn_inferior ()\n");
2614 }
2615
2616 static int
2617 debug_to_can_run (void)
2618 {
2619   int retval;
2620
2621   retval = debug_target.to_can_run ();
2622
2623   fprintf_unfiltered (gdb_stdlog, "target_can_run () = %d\n", retval);
2624
2625   return retval;
2626 }
2627
2628 static void
2629 debug_to_notice_signals (ptid_t ptid)
2630 {
2631   debug_target.to_notice_signals (ptid);
2632
2633   fprintf_unfiltered (gdb_stdlog, "target_notice_signals (%d)\n",
2634                       PIDGET (ptid));
2635 }
2636
2637 static int
2638 debug_to_thread_alive (ptid_t ptid)
2639 {
2640   int retval;
2641
2642   retval = debug_target.to_thread_alive (ptid);
2643
2644   fprintf_unfiltered (gdb_stdlog, "target_thread_alive (%d) = %d\n",
2645                       PIDGET (ptid), retval);
2646
2647   return retval;
2648 }
2649
2650 static void
2651 debug_to_find_new_threads (void)
2652 {
2653   debug_target.to_find_new_threads ();
2654
2655   fputs_unfiltered ("target_find_new_threads ()\n", gdb_stdlog);
2656 }
2657
2658 static void
2659 debug_to_stop (void)
2660 {
2661   debug_target.to_stop ();
2662
2663   fprintf_unfiltered (gdb_stdlog, "target_stop ()\n");
2664 }
2665
2666 static void
2667 debug_to_rcmd (char *command,
2668                struct ui_file *outbuf)
2669 {
2670   debug_target.to_rcmd (command, outbuf);
2671   fprintf_unfiltered (gdb_stdlog, "target_rcmd (%s, ...)\n", command);
2672 }
2673
2674 static struct symtab_and_line *
2675 debug_to_enable_exception_callback (enum exception_event_kind kind, int enable)
2676 {
2677   struct symtab_and_line *result;
2678   result = debug_target.to_enable_exception_callback (kind, enable);
2679   fprintf_unfiltered (gdb_stdlog,
2680                       "target get_exception_callback_sal (%d, %d)\n",
2681                       kind, enable);
2682   return result;
2683 }
2684
2685 static struct exception_event_record *
2686 debug_to_get_current_exception_event (void)
2687 {
2688   struct exception_event_record *result;
2689   result = debug_target.to_get_current_exception_event ();
2690   fprintf_unfiltered (gdb_stdlog, "target get_current_exception_event ()\n");
2691   return result;
2692 }
2693
2694 static char *
2695 debug_to_pid_to_exec_file (int pid)
2696 {
2697   char *exec_file;
2698
2699   exec_file = debug_target.to_pid_to_exec_file (pid);
2700
2701   fprintf_unfiltered (gdb_stdlog, "target_pid_to_exec_file (%d) = %s\n",
2702                       pid, exec_file);
2703
2704   return exec_file;
2705 }
2706
2707 static void
2708 setup_target_debug (void)
2709 {
2710   memcpy (&debug_target, &current_target, sizeof debug_target);
2711
2712   current_target.to_open = debug_to_open;
2713   current_target.to_close = debug_to_close;
2714   current_target.to_attach = debug_to_attach;
2715   current_target.to_post_attach = debug_to_post_attach;
2716   current_target.to_detach = debug_to_detach;
2717   current_target.to_resume = debug_to_resume;
2718   current_target.to_wait = debug_to_wait;
2719   current_target.to_fetch_registers = debug_to_fetch_registers;
2720   current_target.to_store_registers = debug_to_store_registers;
2721   current_target.to_prepare_to_store = debug_to_prepare_to_store;
2722   current_target.deprecated_xfer_memory = deprecated_debug_xfer_memory;
2723   current_target.to_files_info = debug_to_files_info;
2724   current_target.to_insert_breakpoint = debug_to_insert_breakpoint;
2725   current_target.to_remove_breakpoint = debug_to_remove_breakpoint;
2726   current_target.to_can_use_hw_breakpoint = debug_to_can_use_hw_breakpoint;
2727   current_target.to_insert_hw_breakpoint = debug_to_insert_hw_breakpoint;
2728   current_target.to_remove_hw_breakpoint = debug_to_remove_hw_breakpoint;
2729   current_target.to_insert_watchpoint = debug_to_insert_watchpoint;
2730   current_target.to_remove_watchpoint = debug_to_remove_watchpoint;
2731   current_target.to_stopped_by_watchpoint = debug_to_stopped_by_watchpoint;
2732   current_target.to_stopped_data_address = debug_to_stopped_data_address;
2733   current_target.to_region_ok_for_hw_watchpoint = debug_to_region_ok_for_hw_watchpoint;
2734   current_target.to_terminal_init = debug_to_terminal_init;
2735   current_target.to_terminal_inferior = debug_to_terminal_inferior;
2736   current_target.to_terminal_ours_for_output = debug_to_terminal_ours_for_output;
2737   current_target.to_terminal_ours = debug_to_terminal_ours;
2738   current_target.to_terminal_save_ours = debug_to_terminal_save_ours;
2739   current_target.to_terminal_info = debug_to_terminal_info;
2740   current_target.to_kill = debug_to_kill;
2741   current_target.to_load = debug_to_load;
2742   current_target.to_lookup_symbol = debug_to_lookup_symbol;
2743   current_target.to_create_inferior = debug_to_create_inferior;
2744   current_target.to_post_startup_inferior = debug_to_post_startup_inferior;
2745   current_target.to_acknowledge_created_inferior = debug_to_acknowledge_created_inferior;
2746   current_target.to_insert_fork_catchpoint = debug_to_insert_fork_catchpoint;
2747   current_target.to_remove_fork_catchpoint = debug_to_remove_fork_catchpoint;
2748   current_target.to_insert_vfork_catchpoint = debug_to_insert_vfork_catchpoint;
2749   current_target.to_remove_vfork_catchpoint = debug_to_remove_vfork_catchpoint;
2750   current_target.to_insert_exec_catchpoint = debug_to_insert_exec_catchpoint;
2751   current_target.to_remove_exec_catchpoint = debug_to_remove_exec_catchpoint;
2752   current_target.to_reported_exec_events_per_exec_call = debug_to_reported_exec_events_per_exec_call;
2753   current_target.to_has_exited = debug_to_has_exited;
2754   current_target.to_mourn_inferior = debug_to_mourn_inferior;
2755   current_target.to_can_run = debug_to_can_run;
2756   current_target.to_notice_signals = debug_to_notice_signals;
2757   current_target.to_thread_alive = debug_to_thread_alive;
2758   current_target.to_find_new_threads = debug_to_find_new_threads;
2759   current_target.to_stop = debug_to_stop;
2760   current_target.to_rcmd = debug_to_rcmd;
2761   current_target.to_enable_exception_callback = debug_to_enable_exception_callback;
2762   current_target.to_get_current_exception_event = debug_to_get_current_exception_event;
2763   current_target.to_pid_to_exec_file = debug_to_pid_to_exec_file;
2764 }
2765 \f
2766
2767 static char targ_desc[] =
2768 "Names of targets and files being debugged.\n\
2769 Shows the entire stack of targets currently in use (including the exec-file,\n\
2770 core-file, and process, if any), as well as the symbol file name.";
2771
2772 static void
2773 do_monitor_command (char *cmd,
2774                  int from_tty)
2775 {
2776   if ((current_target.to_rcmd
2777        == (void (*) (char *, struct ui_file *)) tcomplain)
2778       || (current_target.to_rcmd == debug_to_rcmd
2779           && (debug_target.to_rcmd
2780               == (void (*) (char *, struct ui_file *)) tcomplain)))
2781     error (_("\"monitor\" command not supported by this target."));
2782   target_rcmd (cmd, gdb_stdtarg);
2783 }
2784
2785 /* Print the name of each layers of our target stack.  */
2786
2787 static void
2788 maintenance_print_target_stack (char *cmd, int from_tty)
2789 {
2790   struct target_ops *t;
2791
2792   printf_filtered (_("The current target stack is:\n"));
2793
2794   for (t = target_stack; t != NULL; t = t->beneath)
2795     {
2796       printf_filtered ("  - %s (%s)\n", t->to_shortname, t->to_longname);
2797     }
2798 }
2799
2800 void
2801 initialize_targets (void)
2802 {
2803   init_dummy_target ();
2804   push_target (&dummy_target);
2805
2806   add_info ("target", target_info, targ_desc);
2807   add_info ("files", target_info, targ_desc);
2808
2809   add_setshow_zinteger_cmd ("target", class_maintenance, &targetdebug, _("\
2810 Set target debugging."), _("\
2811 Show target debugging."), _("\
2812 When non-zero, target debugging is enabled.  Higher numbers are more\n\
2813 verbose.  Changes do not take effect until the next \"run\" or \"target\"\n\
2814 command."),
2815                             NULL,
2816                             show_targetdebug,
2817                             &setdebuglist, &showdebuglist);
2818
2819   add_setshow_boolean_cmd ("trust-readonly-sections", class_support,
2820                            &trust_readonly, _("\
2821 Set mode for reading from readonly sections."), _("\
2822 Show mode for reading from readonly sections."), _("\
2823 When this mode is on, memory reads from readonly sections (such as .text)\n\
2824 will be read from the object file instead of from the target.  This will\n\
2825 result in significant performance improvement for remote targets."),
2826                            NULL,
2827                            show_trust_readonly,
2828                            &setlist, &showlist);
2829
2830   add_com ("monitor", class_obscure, do_monitor_command,
2831            _("Send a command to the remote monitor (remote targets only)."));
2832
2833   add_cmd ("target-stack", class_maintenance, maintenance_print_target_stack,
2834            _("Print the name of each layer of the internal target stack."),
2835            &maintenanceprintlist);
2836
2837   target_dcache = dcache_init ();
2838 }