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