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