gdb/gcore.c - gdb

Functions defined

Macros defined

Source code

  1. /* Generate a core file for the inferior process.

  2.    Copyright (C) 2001-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "elf-bfd.h"
  16. #include "infcall.h"
  17. #include "inferior.h"
  18. #include "gdbcore.h"
  19. #include "objfiles.h"
  20. #include "solib.h"
  21. #include "symfile.h"
  22. #include "arch-utils.h"
  23. #include "completer.h"
  24. #include "gcore.h"
  25. #include "cli/cli-decode.h"
  26. #include <fcntl.h>
  27. #include "regcache.h"
  28. #include "regset.h"
  29. #include "gdb_bfd.h"
  30. #include "readline/tilde.h"

  31. /* The largest amount of memory to read from the target at once.  We
  32.    must throttle it to limit the amount of memory used by GDB during
  33.    generate-core-file for programs with large resident data.  */
  34. #define MAX_COPY_BYTES (1024 * 1024)

  35. static const char *default_gcore_target (void);
  36. static enum bfd_architecture default_gcore_arch (void);
  37. static unsigned long default_gcore_mach (void);
  38. static int gcore_memory_sections (bfd *);

  39. /* create_gcore_bfd -- helper for gcore_command (exported).
  40.    Open a new bfd core file for output, and return the handle.  */

  41. bfd *
  42. create_gcore_bfd (const char *filename)
  43. {
  44.   bfd *obfd = gdb_bfd_openw (filename, default_gcore_target ());

  45.   if (!obfd)
  46.     error (_("Failed to open '%s' for output."), filename);
  47.   bfd_set_format (obfd, bfd_core);
  48.   bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ());
  49.   return obfd;
  50. }

  51. /* write_gcore_file_1 -- do the actual work of write_gcore_file.  */

  52. static void
  53. write_gcore_file_1 (bfd *obfd)
  54. {
  55.   struct cleanup *cleanup;
  56.   void *note_data = NULL;
  57.   int note_size = 0;
  58.   asection *note_sec = NULL;

  59.   /* An external target method must build the notes section.  */
  60.   /* FIXME: uweigand/2011-10-06: All architectures that support core file
  61.      generation should be converted to gdbarch_make_corefile_notes; at that
  62.      point, the target vector method can be removed.  */
  63.   if (!gdbarch_make_corefile_notes_p (target_gdbarch ()))
  64.     note_data = target_make_corefile_notes (obfd, &note_size);
  65.   else
  66.     note_data = gdbarch_make_corefile_notes (target_gdbarch (), obfd, &note_size);

  67.   cleanup = make_cleanup (xfree, note_data);

  68.   if (note_data == NULL || note_size == 0)
  69.     error (_("Target does not support core file generation."));

  70.   /* Create the note section.  */
  71.   note_sec = bfd_make_section_anyway_with_flags (obfd, "note0",
  72.                                                  SEC_HAS_CONTENTS
  73.                                                  | SEC_READONLY
  74.                                                  | SEC_ALLOC);
  75.   if (note_sec == NULL)
  76.     error (_("Failed to create 'note' section for corefile: %s"),
  77.            bfd_errmsg (bfd_get_error ()));

  78.   bfd_set_section_vma (obfd, note_sec, 0);
  79.   bfd_set_section_alignment (obfd, note_sec, 0);
  80.   bfd_set_section_size (obfd, note_sec, note_size);

  81.   /* Now create the memory/load sections.  */
  82.   if (gcore_memory_sections (obfd) == 0)
  83.     error (_("gcore: failed to get corefile memory sections from target."));

  84.   /* Write out the contents of the note section.  */
  85.   if (!bfd_set_section_contents (obfd, note_sec, note_data, 0, note_size))
  86.     warning (_("writing note section (%s)"), bfd_errmsg (bfd_get_error ()));

  87.   do_cleanups (cleanup);
  88. }

  89. /* write_gcore_file -- helper for gcore_command (exported).
  90.    Compose and write the corefile data to the core file.  */

  91. void
  92. write_gcore_file (bfd *obfd)
  93. {
  94.   volatile struct gdb_exception except;

  95.   target_prepare_to_generate_core ();

  96.   TRY_CATCH (except, RETURN_MASK_ALL)
  97.     write_gcore_file_1 (obfd);

  98.   target_done_generating_core ();

  99.   if (except.reason < 0)
  100.     throw_exception (except);
  101. }

  102. static void
  103. do_bfd_delete_cleanup (void *arg)
  104. {
  105.   bfd *obfd = arg;
  106.   const char *filename = obfd->filename;

  107.   gdb_bfd_unref (arg);
  108.   unlink (filename);
  109. }

  110. /* gcore_command -- implements the 'gcore' command.
  111.    Generate a core file from the inferior process.  */

  112. static void
  113. gcore_command (char *args, int from_tty)
  114. {
  115.   struct cleanup *filename_chain;
  116.   struct cleanup *bfd_chain;
  117.   char *corefilename;
  118.   bfd *obfd;

  119.   /* No use generating a corefile without a target process.  */
  120.   if (!target_has_execution)
  121.     noprocess ();

  122.   if (args && *args)
  123.     corefilename = tilde_expand (args);
  124.   else
  125.     {
  126.       /* Default corefile name is "core.PID".  */
  127.       corefilename = xstrprintf ("core.%d", ptid_get_pid (inferior_ptid));
  128.     }
  129.   filename_chain = make_cleanup (xfree, corefilename);

  130.   if (info_verbose)
  131.     fprintf_filtered (gdb_stdout,
  132.                       "Opening corefile '%s' for output.\n", corefilename);

  133.   /* Open the output file.  */
  134.   obfd = create_gcore_bfd (corefilename);

  135.   /* Need a cleanup that will close and delete the file.  */
  136.   bfd_chain = make_cleanup (do_bfd_delete_cleanup, obfd);

  137.   /* Call worker function.  */
  138.   write_gcore_file (obfd);

  139.   /* Succeeded.  */
  140.   discard_cleanups (bfd_chain);
  141.   gdb_bfd_unref (obfd);

  142.   fprintf_filtered (gdb_stdout, "Saved corefile %s\n", corefilename);
  143.   do_cleanups (filename_chain);
  144. }

  145. static unsigned long
  146. default_gcore_mach (void)
  147. {
  148. #if 1        /* See if this even matters...  */
  149.   return 0;
  150. #else

  151.   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch ());

  152.   if (bfdarch != NULL)
  153.     return bfdarch->mach;
  154.   if (exec_bfd == NULL)
  155.     error (_("Can't find default bfd machine type (need execfile)."));

  156.   return bfd_get_mach (exec_bfd);
  157. #endif /* 1 */
  158. }

  159. static enum bfd_architecture
  160. default_gcore_arch (void)
  161. {
  162.   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch ());

  163.   if (bfdarch != NULL)
  164.     return bfdarch->arch;
  165.   if (exec_bfd == NULL)
  166.     error (_("Can't find bfd architecture for corefile (need execfile)."));

  167.   return bfd_get_arch (exec_bfd);
  168. }

  169. static const char *
  170. default_gcore_target (void)
  171. {
  172.   /* The gdbarch may define a target to use for core files.  */
  173.   if (gdbarch_gcore_bfd_target_p (target_gdbarch ()))
  174.     return gdbarch_gcore_bfd_target (target_gdbarch ());

  175.   /* Otherwise, try to fall back to the exec_bfd target.  This will probably
  176.      not work for non-ELF targets.  */
  177.   if (exec_bfd == NULL)
  178.     return NULL;
  179.   else
  180.     return bfd_get_target (exec_bfd);
  181. }

  182. /* Derive a reasonable stack segment by unwinding the target stack,
  183.    and store its limits in *BOTTOM and *TOP.  Return non-zero if
  184.    successful.  */

  185. static int
  186. derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
  187. {
  188.   struct frame_info *fi, *tmp_fi;

  189.   gdb_assert (bottom);
  190.   gdb_assert (top);

  191.   /* Can't succeed without stack and registers.  */
  192.   if (!target_has_stack || !target_has_registers)
  193.     return 0;

  194.   /* Can't succeed without current frame.  */
  195.   fi = get_current_frame ();
  196.   if (fi == NULL)
  197.     return 0;

  198.   /* Save frame pointer of TOS frame.  */
  199.   *top = get_frame_base (fi);
  200.   /* If current stack pointer is more "inner", use that instead.  */
  201.   if (gdbarch_inner_than (get_frame_arch (fi), get_frame_sp (fi), *top))
  202.     *top = get_frame_sp (fi);

  203.   /* Find prev-most frame.  */
  204.   while ((tmp_fi = get_prev_frame (fi)) != NULL)
  205.     fi = tmp_fi;

  206.   /* Save frame pointer of prev-most frame.  */
  207.   *bottom = get_frame_base (fi);

  208.   /* Now canonicalize their order, so that BOTTOM is a lower address
  209.      (as opposed to a lower stack frame).  */
  210.   if (*bottom > *top)
  211.     {
  212.       bfd_vma tmp_vma;

  213.       tmp_vma = *top;
  214.       *top = *bottom;
  215.       *bottom = tmp_vma;
  216.     }

  217.   return 1;
  218. }

  219. /* call_target_sbrk --
  220.    helper function for derive_heap_segment.  */

  221. static bfd_vma
  222. call_target_sbrk (int sbrk_arg)
  223. {
  224.   struct objfile *sbrk_objf;
  225.   struct gdbarch *gdbarch;
  226.   bfd_vma top_of_heap;
  227.   struct value *target_sbrk_arg;
  228.   struct value *sbrk_fn, *ret;
  229.   bfd_vma tmp;

  230.   if (lookup_minimal_symbol ("sbrk", NULL, NULL).minsym != NULL)
  231.     {
  232.       sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
  233.       if (sbrk_fn == NULL)
  234.         return (bfd_vma) 0;
  235.     }
  236.   else if (lookup_minimal_symbol ("_sbrk", NULL, NULL).minsym != NULL)
  237.     {
  238.       sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
  239.       if (sbrk_fn == NULL)
  240.         return (bfd_vma) 0;
  241.     }
  242.   else
  243.     return (bfd_vma) 0;

  244.   gdbarch = get_objfile_arch (sbrk_objf);
  245.   target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int,
  246.                                         sbrk_arg);
  247.   gdb_assert (target_sbrk_arg);
  248.   ret = call_function_by_hand (sbrk_fn, 1, &target_sbrk_arg);
  249.   if (ret == NULL)
  250.     return (bfd_vma) 0;

  251.   tmp = value_as_long (ret);
  252.   if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
  253.     return (bfd_vma) 0;

  254.   top_of_heap = tmp;
  255.   return top_of_heap;
  256. }

  257. /* Derive a reasonable heap segment for ABFD by looking at sbrk and
  258.    the static data sections.  Store its limits in *BOTTOM and *TOP.
  259.    Return non-zero if successful.  */

  260. static int
  261. derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
  262. {
  263.   bfd_vma top_of_data_memory = 0;
  264.   bfd_vma top_of_heap = 0;
  265.   bfd_size_type sec_size;
  266.   bfd_vma sec_vaddr;
  267.   asection *sec;

  268.   gdb_assert (bottom);
  269.   gdb_assert (top);

  270.   /* This function depends on being able to call a function in the
  271.      inferior.  */
  272.   if (!target_has_execution)
  273.     return 0;

  274.   /* The following code assumes that the link map is arranged as
  275.      follows (low to high addresses):

  276.      ---------------------------------
  277.      | text sections                 |
  278.      ---------------------------------
  279.      | data sections (including bss) |
  280.      ---------------------------------
  281.      | heap                          |
  282.      --------------------------------- */

  283.   for (sec = abfd->sections; sec; sec = sec->next)
  284.     {
  285.       if (bfd_get_section_flags (abfd, sec) & SEC_DATA
  286.           || strcmp (".bss", bfd_section_name (abfd, sec)) == 0)
  287.         {
  288.           sec_vaddr = bfd_get_section_vma (abfd, sec);
  289.           sec_size = bfd_get_section_size (sec);
  290.           if (sec_vaddr + sec_size > top_of_data_memory)
  291.             top_of_data_memory = sec_vaddr + sec_size;
  292.         }
  293.     }

  294.   top_of_heap = call_target_sbrk (0);
  295.   if (top_of_heap == (bfd_vma) 0)
  296.     return 0;

  297.   /* Return results.  */
  298.   if (top_of_heap > top_of_data_memory)
  299.     {
  300.       *bottom = top_of_data_memory;
  301.       *top = top_of_heap;
  302.       return 1;
  303.     }

  304.   /* No additional heap space needs to be saved.  */
  305.   return 0;
  306. }

  307. static void
  308. make_output_phdrs (bfd *obfd, asection *osec, void *ignored)
  309. {
  310.   int p_flags = 0;
  311.   int p_type = 0;

  312.   /* FIXME: these constants may only be applicable for ELF.  */
  313.   if (strncmp (bfd_section_name (obfd, osec), "load", 4) == 0)
  314.     p_type = PT_LOAD;
  315.   else if (strncmp (bfd_section_name (obfd, osec), "note", 4) == 0)
  316.     p_type = PT_NOTE;
  317.   else
  318.     p_type = PT_NULL;

  319.   p_flags |= PF_R;        /* Segment is readable.  */
  320.   if (!(bfd_get_section_flags (obfd, osec) & SEC_READONLY))
  321.     p_flags |= PF_W;        /* Segment is writable.  */
  322.   if (bfd_get_section_flags (obfd, osec) & SEC_CODE)
  323.     p_flags |= PF_X;        /* Segment is executable.  */

  324.   bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
  325. }

  326. /* find_memory_region_ftype implementation.  DATA is 'bfd *' for the core file
  327.    GDB is creating.  */

  328. static int
  329. gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read,
  330.                        int write, int exec, int modified, void *data)
  331. {
  332.   bfd *obfd = data;
  333.   asection *osec;
  334.   flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;

  335.   /* If the memory segment has no permissions set, ignore it, otherwise
  336.      when we later try to access it for read/write, we'll get an error
  337.      or jam the kernel.  */
  338.   if (read == 0 && write == 0 && exec == 0 && modified == 0)
  339.     {
  340.       if (info_verbose)
  341.         {
  342.           fprintf_filtered (gdb_stdout, "Ignore segment, %s bytes at %s\n",
  343.                             plongest (size), paddress (target_gdbarch (), vaddr));
  344.         }

  345.       return 0;
  346.     }

  347.   if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
  348.     {
  349.       /* See if this region of memory lies inside a known file on disk.
  350.          If so, we can avoid copying its contents by clearing SEC_LOAD.  */
  351.       struct objfile *objfile;
  352.       struct obj_section *objsec;

  353.       ALL_OBJSECTIONS (objfile, objsec)
  354.         {
  355.           bfd *abfd = objfile->obfd;
  356.           asection *asec = objsec->the_bfd_section;
  357.           bfd_vma align = (bfd_vma) 1 << bfd_get_section_alignment (abfd,
  358.                                                                     asec);
  359.           bfd_vma start = obj_section_addr (objsec) & -align;
  360.           bfd_vma end = (obj_section_endaddr (objsec) + align - 1) & -align;

  361.           /* Match if either the entire memory region lies inside the
  362.              section (i.e. a mapping covering some pages of a large
  363.              segment) or the entire section lies inside the memory region
  364.              (i.e. a mapping covering multiple small sections).

  365.              This BFD was synthesized from reading target memory,
  366.              we don't want to omit that.  */
  367.           if (objfile->separate_debug_objfile_backlink == NULL
  368.               && ((vaddr >= start && vaddr + size <= end)
  369.                   || (start >= vaddr && end <= vaddr + size))
  370.               && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
  371.             {
  372.               flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
  373.               goto keep;        /* Break out of two nested for loops.  */
  374.             }
  375.         }

  376.     keep:;
  377.     }

  378.   if (write == 0)
  379.     flags |= SEC_READONLY;

  380.   if (exec)
  381.     flags |= SEC_CODE;
  382.   else
  383.     flags |= SEC_DATA;

  384.   osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
  385.   if (osec == NULL)
  386.     {
  387.       warning (_("Couldn't make gcore segment: %s"),
  388.                bfd_errmsg (bfd_get_error ()));
  389.       return 1;
  390.     }

  391.   if (info_verbose)
  392.     {
  393.       fprintf_filtered (gdb_stdout, "Save segment, %s bytes at %s\n",
  394.                         plongest (size), paddress (target_gdbarch (), vaddr));
  395.     }

  396.   bfd_set_section_size (obfd, osec, size);
  397.   bfd_set_section_vma (obfd, osec, vaddr);
  398.   bfd_section_lma (obfd, osec) = 0; /* ??? bfd_set_section_lma?  */
  399.   return 0;
  400. }

  401. int
  402. objfile_find_memory_regions (struct target_ops *self,
  403.                              find_memory_region_ftype func, void *obfd)
  404. {
  405.   /* Use objfile data to create memory sections.  */
  406.   struct objfile *objfile;
  407.   struct obj_section *objsec;
  408.   bfd_vma temp_bottom, temp_top;

  409.   /* Call callback function for each objfile section.  */
  410.   ALL_OBJSECTIONS (objfile, objsec)
  411.     {
  412.       bfd *ibfd = objfile->obfd;
  413.       asection *isec = objsec->the_bfd_section;
  414.       flagword flags = bfd_get_section_flags (ibfd, isec);

  415.       /* Separate debug info files are irrelevant for gcore.  */
  416.       if (objfile->separate_debug_objfile_backlink != NULL)
  417.         continue;

  418.       if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
  419.         {
  420.           int size = bfd_section_size (ibfd, isec);
  421.           int ret;

  422.           ret = (*func) (obj_section_addr (objsec), size,
  423.                          1, /* All sections will be readable.  */
  424.                          (flags & SEC_READONLY) == 0, /* Writable.  */
  425.                          (flags & SEC_CODE) != 0, /* Executable.  */
  426.                          1, /* MODIFIED is unknown, pass it as true.  */
  427.                          obfd);
  428.           if (ret != 0)
  429.             return ret;
  430.         }
  431.     }

  432.   /* Make a stack segment.  */
  433.   if (derive_stack_segment (&temp_bottom, &temp_top))
  434.     (*func) (temp_bottom, temp_top - temp_bottom,
  435.              1, /* Stack section will be readable.  */
  436.              1, /* Stack section will be writable.  */
  437.              0, /* Stack section will not be executable.  */
  438.              1, /* Stack section will be modified.  */
  439.              obfd);

  440.   /* Make a heap segment.  */
  441.   if (derive_heap_segment (exec_bfd, &temp_bottom, &temp_top))
  442.     (*func) (temp_bottom, temp_top - temp_bottom,
  443.              1, /* Heap section will be readable.  */
  444.              1, /* Heap section will be writable.  */
  445.              0, /* Heap section will not be executable.  */
  446.              1, /* Heap section will be modified.  */
  447.              obfd);

  448.   return 0;
  449. }

  450. static void
  451. gcore_copy_callback (bfd *obfd, asection *osec, void *ignored)
  452. {
  453.   bfd_size_type size, total_size = bfd_section_size (obfd, osec);
  454.   file_ptr offset = 0;
  455.   struct cleanup *old_chain = NULL;
  456.   void *memhunk;

  457.   /* Read-only sections are marked; we don't have to copy their contents.  */
  458.   if ((bfd_get_section_flags (obfd, osec) & SEC_LOAD) == 0)
  459.     return;

  460.   /* Only interested in "load" sections.  */
  461.   if (strncmp ("load", bfd_section_name (obfd, osec), 4) != 0)
  462.     return;

  463.   size = min (total_size, MAX_COPY_BYTES);
  464.   memhunk = xmalloc (size);
  465.   old_chain = make_cleanup (xfree, memhunk);

  466.   while (total_size > 0)
  467.     {
  468.       if (size > total_size)
  469.         size = total_size;

  470.       if (target_read_memory (bfd_section_vma (obfd, osec) + offset,
  471.                               memhunk, size) != 0)
  472.         {
  473.           warning (_("Memory read failed for corefile "
  474.                      "section, %s bytes at %s."),
  475.                    plongest (size),
  476.                    paddress (target_gdbarch (), bfd_section_vma (obfd, osec)));
  477.           break;
  478.         }
  479.       if (!bfd_set_section_contents (obfd, osec, memhunk, offset, size))
  480.         {
  481.           warning (_("Failed to write corefile contents (%s)."),
  482.                    bfd_errmsg (bfd_get_error ()));
  483.           break;
  484.         }

  485.       total_size -= size;
  486.       offset += size;
  487.     }

  488.   do_cleanups (old_chain);        /* Frees MEMHUNK.  */
  489. }

  490. static int
  491. gcore_memory_sections (bfd *obfd)
  492. {
  493.   /* Try gdbarch method first, then fall back to target method.  */
  494.   if (!gdbarch_find_memory_regions_p (target_gdbarch ())
  495.       || gdbarch_find_memory_regions (target_gdbarch (),
  496.                                       gcore_create_callback, obfd) != 0)
  497.     {
  498.       if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
  499.         return 0;                        /* FIXME: error return/msg?  */
  500.     }

  501.   /* Record phdrs for section-to-segment mapping.  */
  502.   bfd_map_over_sections (obfd, make_output_phdrs, NULL);

  503.   /* Copy memory region contents.  */
  504.   bfd_map_over_sections (obfd, gcore_copy_callback, NULL);

  505.   return 1;
  506. }

  507. /* Provide a prototype to silence -Wmissing-prototypes.  */
  508. extern initialize_file_ftype _initialize_gcore;

  509. void
  510. _initialize_gcore (void)
  511. {
  512.   add_com ("generate-core-file", class_files, gcore_command, _("\
  513. Save a core file with the current state of the debugged process.\n\
  514. Argument is optional filename.  Default filename is 'core.<process_id>'."));

  515.   add_com_alias ("gcore", "generate-core-file", class_files, 1);
  516. }