1/* Core dump and executable file functions below target vector, for GDB.
2
3   Copyright 1986, 1987, 1989, 1991, 1992, 1993, 1994, 1995, 1996,
4   1997, 1998, 1999, 2000, 2001, 2003, 2004 Free Software Foundation,
5   Inc.
6
7   This file is part of GDB.
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19   You should have received a copy of the GNU General Public License
20   along with this program; if not, write to the Free Software
21   Foundation, Inc., 59 Temple Place - Suite 330,
22   Boston, MA 02111-1307, USA.  */
23
24#include "defs.h"
25#include "arch-utils.h"
26#include "gdb_string.h"
27#include <errno.h>
28#include <signal.h>
29#include <fcntl.h>
30#ifdef HAVE_SYS_FILE_H
31#include <sys/file.h>		/* needed for F_OK and friends */
32#endif
33#include "frame.h"		/* required by inferior.h */
34#include "inferior.h"
35#include "symtab.h"
36#include "command.h"
37#include "bfd.h"
38#include "target.h"
39#include "gdbcore.h"
40#include "gdbthread.h"
41#include "regcache.h"
42#include "regset.h"
43#include "symfile.h"
44#include "exec.h"
45#include "readline/readline.h"
46
47#include "gdb_assert.h"
48
49#ifndef O_BINARY
50#define O_BINARY 0
51#endif
52
53/* List of all available core_fns.  On gdb startup, each core file register
54   reader calls add_core_fns() to register information on each core format it
55   is prepared to read. */
56
57static struct core_fns *core_file_fns = NULL;
58
59/* The core_fns for a core file handler that is prepared to read the core
60   file currently open on core_bfd. */
61
62static struct core_fns *core_vec = NULL;
63
64/* FIXME: kettenis/20031023: Eventually this variable should
65   disappear.  */
66
67struct gdbarch *core_gdbarch = NULL;
68
69static void core_files_info (struct target_ops *);
70
71#ifdef SOLIB_ADD
72static int solib_add_stub (void *);
73#endif
74
75static struct core_fns *sniff_core_bfd (bfd *);
76
77static int gdb_check_format (bfd *);
78
79static void core_open (char *, int);
80
81static void core_detach (char *, int);
82
83static void core_close (int);
84
85static void core_close_cleanup (void *ignore);
86
87static void get_core_registers (int);
88
89static void add_to_thread_list (bfd *, asection *, void *);
90
91static int ignore (CORE_ADDR, char *);
92
93static int core_file_thread_alive (ptid_t tid);
94
95static void init_core_ops (void);
96
97void _initialize_corelow (void);
98
99struct target_ops core_ops;
100
101/* Link a new core_fns into the global core_file_fns list.  Called on gdb
102   startup by the _initialize routine in each core file register reader, to
103   register information about each format the the reader is prepared to
104   handle. */
105
106void
107add_core_fns (struct core_fns *cf)
108{
109  cf->next = core_file_fns;
110  core_file_fns = cf;
111}
112
113/* The default function that core file handlers can use to examine a
114   core file BFD and decide whether or not to accept the job of
115   reading the core file. */
116
117int
118default_core_sniffer (struct core_fns *our_fns, bfd *abfd)
119{
120  int result;
121
122  result = (bfd_get_flavour (abfd) == our_fns -> core_flavour);
123  return (result);
124}
125
126/* Walk through the list of core functions to find a set that can
127   handle the core file open on ABFD.  Default to the first one in the
128   list if nothing matches.  Returns pointer to set that is
129   selected. */
130
131static struct core_fns *
132sniff_core_bfd (bfd *abfd)
133{
134  struct core_fns *cf;
135  struct core_fns *yummy = NULL;
136  int matches = 0;;
137
138  /* Don't sniff if we have support for register sets in CORE_GDBARCH.  */
139  if (core_gdbarch && gdbarch_regset_from_core_section_p (core_gdbarch))
140    return NULL;
141
142  for (cf = core_file_fns; cf != NULL; cf = cf->next)
143    {
144      if (cf->core_sniffer (cf, abfd))
145	{
146	  yummy = cf;
147	  matches++;
148	}
149    }
150  if (matches > 1)
151    {
152      warning ("\"%s\": ambiguous core format, %d handlers match",
153	       bfd_get_filename (abfd), matches);
154    }
155  else if (matches == 0)
156    {
157      warning ("\"%s\": no core file handler recognizes format, using default",
158	       bfd_get_filename (abfd));
159    }
160  if (yummy == NULL)
161    {
162      yummy = core_file_fns;
163    }
164  return (yummy);
165}
166
167/* The default is to reject every core file format we see.  Either
168   BFD has to recognize it, or we have to provide a function in the
169   core file handler that recognizes it. */
170
171int
172default_check_format (bfd *abfd)
173{
174  return (0);
175}
176
177/* Attempt to recognize core file formats that BFD rejects. */
178
179static int
180gdb_check_format (bfd *abfd)
181{
182  struct core_fns *cf;
183
184  for (cf = core_file_fns; cf != NULL; cf = cf->next)
185    {
186      if (cf->check_format (abfd))
187	{
188	  return (1);
189	}
190    }
191  return (0);
192}
193
194/* Discard all vestiges of any previous core file and mark data and stack
195   spaces as empty.  */
196
197static void
198core_close (int quitting)
199{
200  char *name;
201
202  if (core_bfd)
203    {
204      inferior_ptid = null_ptid;	/* Avoid confusion from thread stuff */
205
206      /* Clear out solib state while the bfd is still open. See
207         comments in clear_solib in solib.c. */
208#ifdef CLEAR_SOLIB
209      CLEAR_SOLIB ();
210#endif
211
212      name = bfd_get_filename (core_bfd);
213      if (!bfd_close (core_bfd))
214	warning ("cannot close \"%s\": %s",
215		 name, bfd_errmsg (bfd_get_error ()));
216      xfree (name);
217      core_bfd = NULL;
218      if (core_ops.to_sections)
219	{
220	  xfree (core_ops.to_sections);
221	  core_ops.to_sections = NULL;
222	  core_ops.to_sections_end = NULL;
223	}
224    }
225  core_vec = NULL;
226  core_gdbarch = NULL;
227}
228
229static void
230core_close_cleanup (void *ignore)
231{
232  core_close (0/*ignored*/);
233}
234
235#ifdef SOLIB_ADD
236/* Stub function for catch_errors around shared library hacking.  FROM_TTYP
237   is really an int * which points to from_tty.  */
238
239static int
240solib_add_stub (void *from_ttyp)
241{
242  SOLIB_ADD (NULL, *(int *) from_ttyp, &current_target, auto_solib_add);
243  re_enable_breakpoints_in_shlibs ();
244  return 0;
245}
246#endif /* SOLIB_ADD */
247
248/* Look for sections whose names start with `.reg/' so that we can extract the
249   list of threads in a core file.  */
250
251static void
252add_to_thread_list (bfd *abfd, asection *asect, void *reg_sect_arg)
253{
254  int thread_id;
255  asection *reg_sect = (asection *) reg_sect_arg;
256
257  if (strncmp (bfd_section_name (abfd, asect), ".reg/", 5) != 0)
258    return;
259
260  thread_id = atoi (bfd_section_name (abfd, asect) + 5);
261
262  add_thread (pid_to_ptid (thread_id));
263
264/* Warning, Will Robinson, looking at BFD private data! */
265
266  if (reg_sect != NULL
267      && asect->filepos == reg_sect->filepos)	/* Did we find .reg? */
268    inferior_ptid = pid_to_ptid (thread_id);	/* Yes, make it current */
269}
270
271/* This routine opens and sets up the core file bfd.  */
272
273static void
274core_open (char *filename, int from_tty)
275{
276  const char *p;
277  int siggy;
278  struct cleanup *old_chain;
279  char *temp;
280  bfd *temp_bfd;
281  int ontop;
282  int scratch_chan;
283
284  target_preopen (from_tty);
285  if (!filename)
286    {
287      error (core_bfd ?
288	     "No core file specified.  (Use `detach' to stop debugging a core file.)"
289	     : "No core file specified.");
290    }
291
292  filename = tilde_expand (filename);
293  if (filename[0] != '/')
294    {
295      temp = concat (current_directory, "/", filename, NULL);
296      xfree (filename);
297      filename = temp;
298    }
299
300  old_chain = make_cleanup (xfree, filename);
301
302  scratch_chan = open (filename, O_BINARY | ( write_files ? O_RDWR : O_RDONLY ), 0);
303  if (scratch_chan < 0)
304    perror_with_name (filename);
305
306  temp_bfd = bfd_fdopenr (filename, gnutarget, scratch_chan);
307  if (temp_bfd == NULL)
308    perror_with_name (filename);
309
310  if (!bfd_check_format (temp_bfd, bfd_core) &&
311      !gdb_check_format (temp_bfd))
312    {
313      /* Do it after the err msg */
314      /* FIXME: should be checking for errors from bfd_close (for one thing,
315         on error it does not free all the storage associated with the
316         bfd).  */
317      make_cleanup_bfd_close (temp_bfd);
318      error ("\"%s\" is not a core dump: %s",
319	     filename, bfd_errmsg (bfd_get_error ()));
320    }
321
322  /* Looks semi-reasonable.  Toss the old core file and work on the new.  */
323
324  discard_cleanups (old_chain);	/* Don't free filename any more */
325  unpush_target (&core_ops);
326  core_bfd = temp_bfd;
327  old_chain = make_cleanup (core_close_cleanup, 0 /*ignore*/);
328
329  /* FIXME: kettenis/20031023: This is very dangerous.  The
330     CORE_GDBARCH that results from this call may very well be
331     different from CURRENT_GDBARCH.  However, its methods may only
332     work if it is selected as the current architecture, because they
333     rely on swapped data (see gdbarch.c).  We should get rid of that
334     swapped data.  */
335  core_gdbarch = gdbarch_from_bfd (core_bfd);
336
337  /* Find a suitable core file handler to munch on core_bfd */
338  core_vec = sniff_core_bfd (core_bfd);
339
340  validate_files ();
341
342  /* Find the data section */
343  if (build_section_table (core_bfd, &core_ops.to_sections,
344			   &core_ops.to_sections_end))
345    error ("\"%s\": Can't find sections: %s",
346	   bfd_get_filename (core_bfd), bfd_errmsg (bfd_get_error ()));
347
348  /* If we have no exec file, try to set the architecture from the
349     core file.  We don't do this unconditionally since an exec file
350     typically contains more information that helps us determine the
351     architecture than a core file.  */
352  if (!exec_bfd)
353    set_gdbarch_from_file (core_bfd);
354
355  ontop = !push_target (&core_ops);
356  discard_cleanups (old_chain);
357
358  p = bfd_core_file_failing_command (core_bfd);
359  if (p)
360    printf_filtered ("Core was generated by `%s'.\n", p);
361
362  siggy = bfd_core_file_failing_signal (core_bfd);
363  if (siggy > 0)
364    /* NOTE: target_signal_from_host() converts a target signal value
365       into gdb's internal signal value.  Unfortunately gdb's internal
366       value is called ``target_signal'' and this function got the
367       name ..._from_host(). */
368    printf_filtered ("Program terminated with signal %d, %s.\n", siggy,
369		     target_signal_to_string (target_signal_from_host (siggy)));
370
371  /* Build up thread list from BFD sections. */
372
373  init_thread_list ();
374  bfd_map_over_sections (core_bfd, add_to_thread_list,
375			 bfd_get_section_by_name (core_bfd, ".reg"));
376
377  if (ontop)
378    {
379      /* Fetch all registers from core file.  */
380      target_fetch_registers (-1);
381
382      /* Add symbols and section mappings for any shared libraries.  */
383#ifdef SOLIB_ADD
384      catch_errors (solib_add_stub, &from_tty, (char *) 0,
385		    RETURN_MASK_ALL);
386#endif
387
388      /* Now, set up the frame cache, and print the top of stack.  */
389      flush_cached_frames ();
390      select_frame (get_current_frame ());
391      print_stack_frame (deprecated_selected_frame,
392			 frame_relative_level (deprecated_selected_frame), 1);
393    }
394  else
395    {
396      warning (
397		"you won't be able to access this core file until you terminate\n\
398your %s; do ``info files''", target_longname);
399    }
400}
401
402static void
403core_detach (char *args, int from_tty)
404{
405  if (args)
406    error ("Too many arguments");
407  unpush_target (&core_ops);
408  reinit_frame_cache ();
409  if (from_tty)
410    printf_filtered ("No core file now.\n");
411}
412
413
414/* Try to retrieve registers from a section in core_bfd, and supply
415   them to core_vec->core_read_registers, as the register set numbered
416   WHICH.
417
418   If inferior_ptid is zero, do the single-threaded thing: look for a
419   section named NAME.  If inferior_ptid is non-zero, do the
420   multi-threaded thing: look for a section named "NAME/PID", where
421   PID is the shortest ASCII decimal representation of inferior_ptid.
422
423   HUMAN_NAME is a human-readable name for the kind of registers the
424   NAME section contains, for use in error messages.
425
426   If REQUIRED is non-zero, print an error if the core file doesn't
427   have a section by the appropriate name.  Otherwise, just do nothing.  */
428
429static void
430get_core_register_section (char *name,
431			   int which,
432			   char *human_name,
433			   int required)
434{
435  static char *section_name = NULL;
436  struct bfd_section *section;
437  bfd_size_type size;
438  char *contents;
439
440  xfree (section_name);
441  if (PIDGET (inferior_ptid))
442    section_name = xstrprintf ("%s/%d", name, PIDGET (inferior_ptid));
443  else
444    section_name = xstrdup (name);
445
446  section = bfd_get_section_by_name (core_bfd, section_name);
447  if (! section)
448    {
449      if (required)
450	warning ("Couldn't find %s registers in core file.\n", human_name);
451      return;
452    }
453
454  size = bfd_section_size (core_bfd, section);
455  contents = alloca (size);
456  if (! bfd_get_section_contents (core_bfd, section, contents,
457				  (file_ptr) 0, size))
458    {
459      warning ("Couldn't read %s registers from `%s' section in core file.\n",
460	       human_name, name);
461      return;
462    }
463
464  if (core_gdbarch && gdbarch_regset_from_core_section_p (core_gdbarch))
465    {
466      const struct regset *regset;
467
468      regset = gdbarch_regset_from_core_section (core_gdbarch, name, size);
469      if (regset == NULL)
470	{
471	  if (required)
472	    warning ("Couldn't recognize %s registers in core file.\n",
473		     human_name);
474	  return;
475	}
476
477      regset->supply_regset (regset, current_regcache, -1, contents, size);
478      return;
479    }
480
481  gdb_assert (core_vec);
482  core_vec->core_read_registers (contents, size, which,
483				 ((CORE_ADDR)
484				  bfd_section_vma (core_bfd, section)));
485}
486
487
488/* Get the registers out of a core file.  This is the machine-
489   independent part.  Fetch_core_registers is the machine-dependent
490   part, typically implemented in the xm-file for each architecture.  */
491
492/* We just get all the registers, so we don't use regno.  */
493
494static void
495get_core_registers (int regno)
496{
497  int status;
498
499  if (!(core_gdbarch && gdbarch_regset_from_core_section_p (core_gdbarch))
500      && (core_vec == NULL || core_vec->core_read_registers == NULL))
501    {
502      fprintf_filtered (gdb_stderr,
503		     "Can't fetch registers from this type of core file\n");
504      return;
505    }
506
507  get_core_register_section (".reg", 0, "general-purpose", 1);
508  get_core_register_section (".reg2", 2, "floating-point", 0);
509  get_core_register_section (".reg-xfp", 3, "extended floating-point", 0);
510
511  deprecated_registers_fetched ();
512}
513
514static void
515core_files_info (struct target_ops *t)
516{
517  print_section_info (t, core_bfd);
518}
519
520static LONGEST
521core_xfer_partial (struct target_ops *ops, enum target_object object,
522		   const char *annex, void *readbuf,
523		   const void *writebuf, ULONGEST offset, LONGEST len)
524{
525  switch (object)
526    {
527    case TARGET_OBJECT_MEMORY:
528      if (readbuf)
529	return (*ops->to_xfer_memory) (offset, readbuf, len, 0/*read*/,
530				       NULL, ops);
531      if (writebuf)
532	return (*ops->to_xfer_memory) (offset, writebuf, len, 1/*write*/,
533				       NULL, ops);
534      return -1;
535
536    case TARGET_OBJECT_AUXV:
537      if (readbuf)
538	{
539	  /* When the aux vector is stored in core file, BFD
540	     represents this with a fake section called ".auxv".  */
541
542	  struct bfd_section *section;
543	  bfd_size_type size;
544	  char *contents;
545
546	  section = bfd_get_section_by_name (core_bfd, ".auxv");
547	  if (section == NULL)
548	    return -1;
549
550	  size = bfd_section_size (core_bfd, section);
551	  if (offset >= size)
552	    return 0;
553	  size -= offset;
554	  if (size > len)
555	    size = len;
556	  if (size > 0 &&
557	      ! bfd_get_section_contents (core_bfd, section, readbuf,
558					  (file_ptr) offset, size))
559	    {
560	      warning ("Couldn't read NT_AUXV note in core file.");
561	      return -1;
562	    }
563
564	  return size;
565	}
566      return -1;
567
568    case TARGET_OBJECT_DIRTY:
569      {
570	ULONGEST addr;
571	addr = *(ULONGEST*)annex + offset;
572	if (readbuf)
573	  return (*ops->to_xfer_memory) (addr, readbuf, len, 0/*read*/,
574					 NULL, ops);
575	if (writebuf)
576	  return (*ops->to_xfer_memory) (addr, writebuf, len, 1/*write*/,
577					 NULL, ops);
578	return -1;
579      }
580
581    default:
582      if (ops->beneath != NULL)
583	return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
584					      readbuf, writebuf, offset, len);
585      return -1;
586    }
587}
588
589
590/* If mourn is being called in all the right places, this could be say
591   `gdb internal error' (since generic_mourn calls breakpoint_init_inferior).  */
592
593static int
594ignore (CORE_ADDR addr, char *contents)
595{
596  return 0;
597}
598
599
600/* Okay, let's be honest: threads gleaned from a core file aren't
601   exactly lively, are they?  On the other hand, if we don't claim
602   that each & every one is alive, then we don't get any of them
603   to appear in an "info thread" command, which is quite a useful
604   behaviour.
605 */
606static int
607core_file_thread_alive (ptid_t tid)
608{
609  return 1;
610}
611
612/* Fill in core_ops with its defined operations and properties.  */
613
614static void
615init_core_ops (void)
616{
617  core_ops.to_shortname = "core";
618  core_ops.to_longname = "Local core dump file";
619  core_ops.to_doc =
620    "Use a core file as a target.  Specify the filename of the core file.";
621  core_ops.to_open = core_open;
622  core_ops.to_close = core_close;
623  core_ops.to_attach = find_default_attach;
624  core_ops.to_detach = core_detach;
625  core_ops.to_fetch_registers = get_core_registers;
626  core_ops.to_xfer_partial = core_xfer_partial;
627  core_ops.to_xfer_memory = xfer_memory;
628  core_ops.to_files_info = core_files_info;
629  core_ops.to_insert_breakpoint = ignore;
630  core_ops.to_remove_breakpoint = ignore;
631  core_ops.to_create_inferior = find_default_create_inferior;
632  core_ops.to_thread_alive = core_file_thread_alive;
633  core_ops.to_stratum = core_stratum;
634  core_ops.to_has_memory = 1;
635  core_ops.to_has_stack = 1;
636  core_ops.to_has_registers = 1;
637  core_ops.to_magic = OPS_MAGIC;
638}
639
640/* non-zero if we should not do the add_target call in
641   _initialize_corelow; not initialized (i.e., bss) so that
642   the target can initialize it (i.e., data) if appropriate.
643   This needs to be set at compile time because we don't know
644   for sure whether the target's initialize routine is called
645   before us or after us. */
646int coreops_suppress_target;
647
648void
649_initialize_corelow (void)
650{
651  init_core_ops ();
652
653  if (!coreops_suppress_target)
654    add_target (&core_ops);
655}
656