GDB (API)
/home/stan/gdb/src/gdb/gcore.c
Go to the documentation of this file.
00001 /* Generate a core file for the inferior process.
00002 
00003    Copyright (C) 2001-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 #include "defs.h"
00021 #include "elf-bfd.h"
00022 #include "infcall.h"
00023 #include "inferior.h"
00024 #include "gdbcore.h"
00025 #include "objfiles.h"
00026 #include "solib.h"
00027 #include "symfile.h"
00028 #include "arch-utils.h"
00029 #include "completer.h"
00030 #include "gcore.h"
00031 #include "cli/cli-decode.h"
00032 #include "gdb_assert.h"
00033 #include <fcntl.h>
00034 #include "regcache.h"
00035 #include "regset.h"
00036 #include "gdb_bfd.h"
00037 #include "readline/tilde.h"
00038 
00039 /* The largest amount of memory to read from the target at once.  We
00040    must throttle it to limit the amount of memory used by GDB during
00041    generate-core-file for programs with large resident data.  */
00042 #define MAX_COPY_BYTES (1024 * 1024)
00043 
00044 static const char *default_gcore_target (void);
00045 static enum bfd_architecture default_gcore_arch (void);
00046 static unsigned long default_gcore_mach (void);
00047 static int gcore_memory_sections (bfd *);
00048 
00049 /* create_gcore_bfd -- helper for gcore_command (exported).
00050    Open a new bfd core file for output, and return the handle.  */
00051 
00052 bfd *
00053 create_gcore_bfd (const char *filename)
00054 {
00055   bfd *obfd = gdb_bfd_openw (filename, default_gcore_target ());
00056 
00057   if (!obfd)
00058     error (_("Failed to open '%s' for output."), filename);
00059   bfd_set_format (obfd, bfd_core);
00060   bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ());
00061   return obfd;
00062 }
00063 
00064 /* write_gcore_file -- helper for gcore_command (exported).
00065    Compose and write the corefile data to the core file.  */
00066 
00067 
00068 void
00069 write_gcore_file (bfd *obfd)
00070 {
00071   void *note_data = NULL;
00072   int note_size = 0;
00073   asection *note_sec = NULL;
00074 
00075   /* An external target method must build the notes section.  */
00076   /* FIXME: uweigand/2011-10-06: All architectures that support core file
00077      generation should be converted to gdbarch_make_corefile_notes; at that
00078      point, the target vector method can be removed.  */
00079   if (!gdbarch_make_corefile_notes_p (target_gdbarch ()))
00080     note_data = target_make_corefile_notes (obfd, &note_size);
00081   else
00082     note_data = gdbarch_make_corefile_notes (target_gdbarch (), obfd, &note_size);
00083 
00084   if (note_data == NULL || note_size == 0)
00085     error (_("Target does not support core file generation."));
00086 
00087   /* Create the note section.  */
00088   note_sec = bfd_make_section_anyway_with_flags (obfd, "note0",
00089                                                  SEC_HAS_CONTENTS
00090                                                  | SEC_READONLY
00091                                                  | SEC_ALLOC);
00092   if (note_sec == NULL)
00093     error (_("Failed to create 'note' section for corefile: %s"),
00094            bfd_errmsg (bfd_get_error ()));
00095 
00096   bfd_set_section_vma (obfd, note_sec, 0);
00097   bfd_set_section_alignment (obfd, note_sec, 0);
00098   bfd_set_section_size (obfd, note_sec, note_size);
00099 
00100   /* Now create the memory/load sections.  */
00101   if (gcore_memory_sections (obfd) == 0)
00102     error (_("gcore: failed to get corefile memory sections from target."));
00103 
00104   /* Write out the contents of the note section.  */
00105   if (!bfd_set_section_contents (obfd, note_sec, note_data, 0, note_size))
00106     warning (_("writing note section (%s)"), bfd_errmsg (bfd_get_error ()));
00107 }
00108 
00109 static void
00110 do_bfd_delete_cleanup (void *arg)
00111 {
00112   bfd *obfd = arg;
00113   const char *filename = obfd->filename;
00114 
00115   gdb_bfd_unref (arg);
00116   unlink (filename);
00117 }
00118 
00119 /* gcore_command -- implements the 'gcore' command.
00120    Generate a core file from the inferior process.  */
00121 
00122 static void
00123 gcore_command (char *args, int from_tty)
00124 {
00125   struct cleanup *filename_chain;
00126   struct cleanup *bfd_chain;
00127   char *corefilename;
00128   bfd *obfd;
00129 
00130   /* No use generating a corefile without a target process.  */
00131   if (!target_has_execution)
00132     noprocess ();
00133 
00134   if (args && *args)
00135     corefilename = tilde_expand (args);
00136   else
00137     {
00138       /* Default corefile name is "core.PID".  */
00139       corefilename = xstrprintf ("core.%d", ptid_get_pid (inferior_ptid));
00140     }
00141   filename_chain = make_cleanup (xfree, corefilename);
00142 
00143   if (info_verbose)
00144     fprintf_filtered (gdb_stdout,
00145                       "Opening corefile '%s' for output.\n", corefilename);
00146 
00147   /* Open the output file.  */
00148   obfd = create_gcore_bfd (corefilename);
00149 
00150   /* Need a cleanup that will close and delete the file.  */
00151   bfd_chain = make_cleanup (do_bfd_delete_cleanup, obfd);
00152 
00153   /* Call worker function.  */
00154   write_gcore_file (obfd);
00155 
00156   /* Succeeded.  */
00157   discard_cleanups (bfd_chain);
00158   gdb_bfd_unref (obfd);
00159 
00160   fprintf_filtered (gdb_stdout, "Saved corefile %s\n", corefilename);
00161   do_cleanups (filename_chain);
00162 }
00163 
00164 static unsigned long
00165 default_gcore_mach (void)
00166 {
00167 #if 1   /* See if this even matters...  */
00168   return 0;
00169 #else
00170 
00171   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch ());
00172 
00173   if (bfdarch != NULL)
00174     return bfdarch->mach;
00175   if (exec_bfd == NULL)
00176     error (_("Can't find default bfd machine type (need execfile)."));
00177 
00178   return bfd_get_mach (exec_bfd);
00179 #endif /* 1 */
00180 }
00181 
00182 static enum bfd_architecture
00183 default_gcore_arch (void)
00184 {
00185   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch ());
00186 
00187   if (bfdarch != NULL)
00188     return bfdarch->arch;
00189   if (exec_bfd == NULL)
00190     error (_("Can't find bfd architecture for corefile (need execfile)."));
00191 
00192   return bfd_get_arch (exec_bfd);
00193 }
00194 
00195 static const char *
00196 default_gcore_target (void)
00197 {
00198   /* The gdbarch may define a target to use for core files.  */
00199   if (gdbarch_gcore_bfd_target_p (target_gdbarch ()))
00200     return gdbarch_gcore_bfd_target (target_gdbarch ());
00201 
00202   /* Otherwise, try to fall back to the exec_bfd target.  This will probably
00203      not work for non-ELF targets.  */
00204   if (exec_bfd == NULL)
00205     return NULL;
00206   else
00207     return bfd_get_target (exec_bfd);
00208 }
00209 
00210 /* Derive a reasonable stack segment by unwinding the target stack,
00211    and store its limits in *BOTTOM and *TOP.  Return non-zero if
00212    successful.  */
00213 
00214 static int
00215 derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
00216 {
00217   struct frame_info *fi, *tmp_fi;
00218 
00219   gdb_assert (bottom);
00220   gdb_assert (top);
00221 
00222   /* Can't succeed without stack and registers.  */
00223   if (!target_has_stack || !target_has_registers)
00224     return 0;
00225 
00226   /* Can't succeed without current frame.  */
00227   fi = get_current_frame ();
00228   if (fi == NULL)
00229     return 0;
00230 
00231   /* Save frame pointer of TOS frame.  */
00232   *top = get_frame_base (fi);
00233   /* If current stack pointer is more "inner", use that instead.  */
00234   if (gdbarch_inner_than (get_frame_arch (fi), get_frame_sp (fi), *top))
00235     *top = get_frame_sp (fi);
00236 
00237   /* Find prev-most frame.  */
00238   while ((tmp_fi = get_prev_frame (fi)) != NULL)
00239     fi = tmp_fi;
00240 
00241   /* Save frame pointer of prev-most frame.  */
00242   *bottom = get_frame_base (fi);
00243 
00244   /* Now canonicalize their order, so that BOTTOM is a lower address
00245      (as opposed to a lower stack frame).  */
00246   if (*bottom > *top)
00247     {
00248       bfd_vma tmp_vma;
00249 
00250       tmp_vma = *top;
00251       *top = *bottom;
00252       *bottom = tmp_vma;
00253     }
00254 
00255   return 1;
00256 }
00257 
00258 /* call_target_sbrk --
00259    helper function for derive_heap_segment.  */
00260 
00261 static bfd_vma
00262 call_target_sbrk (int sbrk_arg)
00263 {
00264   struct objfile *sbrk_objf;
00265   struct gdbarch *gdbarch;
00266   bfd_vma top_of_heap;
00267   struct value *target_sbrk_arg;
00268   struct value *sbrk_fn, *ret;
00269   bfd_vma tmp;
00270 
00271   if (lookup_minimal_symbol ("sbrk", NULL, NULL) != NULL)
00272     {
00273       sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
00274       if (sbrk_fn == NULL)
00275         return (bfd_vma) 0;
00276     }
00277   else if (lookup_minimal_symbol ("_sbrk", NULL, NULL) != NULL)
00278     {
00279       sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
00280       if (sbrk_fn == NULL)
00281         return (bfd_vma) 0;
00282     }
00283   else
00284     return (bfd_vma) 0;
00285 
00286   gdbarch = get_objfile_arch (sbrk_objf);
00287   target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int, 
00288                                         sbrk_arg);
00289   gdb_assert (target_sbrk_arg);
00290   ret = call_function_by_hand (sbrk_fn, 1, &target_sbrk_arg);
00291   if (ret == NULL)
00292     return (bfd_vma) 0;
00293 
00294   tmp = value_as_long (ret);
00295   if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
00296     return (bfd_vma) 0;
00297 
00298   top_of_heap = tmp;
00299   return top_of_heap;
00300 }
00301 
00302 /* Derive a reasonable heap segment for ABFD by looking at sbrk and
00303    the static data sections.  Store its limits in *BOTTOM and *TOP.
00304    Return non-zero if successful.  */
00305 
00306 static int
00307 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
00308 {
00309   bfd_vma top_of_data_memory = 0;
00310   bfd_vma top_of_heap = 0;
00311   bfd_size_type sec_size;
00312   bfd_vma sec_vaddr;
00313   asection *sec;
00314 
00315   gdb_assert (bottom);
00316   gdb_assert (top);
00317 
00318   /* This function depends on being able to call a function in the
00319      inferior.  */
00320   if (!target_has_execution)
00321     return 0;
00322 
00323   /* The following code assumes that the link map is arranged as
00324      follows (low to high addresses):
00325 
00326      ---------------------------------
00327      | text sections                 |
00328      ---------------------------------
00329      | data sections (including bss) |
00330      ---------------------------------
00331      | heap                          |
00332      --------------------------------- */
00333 
00334   for (sec = abfd->sections; sec; sec = sec->next)
00335     {
00336       if (bfd_get_section_flags (abfd, sec) & SEC_DATA
00337           || strcmp (".bss", bfd_section_name (abfd, sec)) == 0)
00338         {
00339           sec_vaddr = bfd_get_section_vma (abfd, sec);
00340           sec_size = bfd_get_section_size (sec);
00341           if (sec_vaddr + sec_size > top_of_data_memory)
00342             top_of_data_memory = sec_vaddr + sec_size;
00343         }
00344     }
00345 
00346   top_of_heap = call_target_sbrk (0);
00347   if (top_of_heap == (bfd_vma) 0)
00348     return 0;
00349 
00350   /* Return results.  */
00351   if (top_of_heap > top_of_data_memory)
00352     {
00353       *bottom = top_of_data_memory;
00354       *top = top_of_heap;
00355       return 1;
00356     }
00357 
00358   /* No additional heap space needs to be saved.  */
00359   return 0;
00360 }
00361 
00362 static void
00363 make_output_phdrs (bfd *obfd, asection *osec, void *ignored)
00364 {
00365   int p_flags = 0;
00366   int p_type = 0;
00367 
00368   /* FIXME: these constants may only be applicable for ELF.  */
00369   if (strncmp (bfd_section_name (obfd, osec), "load", 4) == 0)
00370     p_type = PT_LOAD;
00371   else if (strncmp (bfd_section_name (obfd, osec), "note", 4) == 0)
00372     p_type = PT_NOTE;
00373   else
00374     p_type = PT_NULL;
00375 
00376   p_flags |= PF_R;      /* Segment is readable.  */
00377   if (!(bfd_get_section_flags (obfd, osec) & SEC_READONLY))
00378     p_flags |= PF_W;    /* Segment is writable.  */
00379   if (bfd_get_section_flags (obfd, osec) & SEC_CODE)
00380     p_flags |= PF_X;    /* Segment is executable.  */
00381 
00382   bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
00383 }
00384 
00385 /* find_memory_region_ftype implementation.  DATA is 'bfd *' for the core file
00386    GDB is creating.  */
00387 
00388 static int
00389 gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read,
00390                        int write, int exec, int modified, void *data)
00391 {
00392   bfd *obfd = data;
00393   asection *osec;
00394   flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
00395 
00396   /* If the memory segment has no permissions set, ignore it, otherwise
00397      when we later try to access it for read/write, we'll get an error
00398      or jam the kernel.  */
00399   if (read == 0 && write == 0 && exec == 0 && modified == 0)
00400     {
00401       if (info_verbose)
00402         {
00403           fprintf_filtered (gdb_stdout, "Ignore segment, %s bytes at %s\n",
00404                             plongest (size), paddress (target_gdbarch (), vaddr));
00405         }
00406 
00407       return 0;
00408     }
00409 
00410   if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
00411     {
00412       /* See if this region of memory lies inside a known file on disk.
00413          If so, we can avoid copying its contents by clearing SEC_LOAD.  */
00414       struct objfile *objfile;
00415       struct obj_section *objsec;
00416 
00417       ALL_OBJSECTIONS (objfile, objsec)
00418         {
00419           bfd *abfd = objfile->obfd;
00420           asection *asec = objsec->the_bfd_section;
00421           bfd_vma align = (bfd_vma) 1 << bfd_get_section_alignment (abfd,
00422                                                                     asec);
00423           bfd_vma start = obj_section_addr (objsec) & -align;
00424           bfd_vma end = (obj_section_endaddr (objsec) + align - 1) & -align;
00425 
00426           /* Match if either the entire memory region lies inside the
00427              section (i.e. a mapping covering some pages of a large
00428              segment) or the entire section lies inside the memory region
00429              (i.e. a mapping covering multiple small sections).
00430 
00431              This BFD was synthesized from reading target memory,
00432              we don't want to omit that.  */
00433           if (objfile->separate_debug_objfile_backlink == NULL
00434               && ((vaddr >= start && vaddr + size <= end)
00435                   || (start >= vaddr && end <= vaddr + size))
00436               && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
00437             {
00438               flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
00439               goto keep;        /* Break out of two nested for loops.  */
00440             }
00441         }
00442 
00443     keep:;
00444     }
00445 
00446   if (write == 0)
00447     flags |= SEC_READONLY;
00448 
00449   if (exec)
00450     flags |= SEC_CODE;
00451   else
00452     flags |= SEC_DATA;
00453 
00454   osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
00455   if (osec == NULL)
00456     {
00457       warning (_("Couldn't make gcore segment: %s"),
00458                bfd_errmsg (bfd_get_error ()));
00459       return 1;
00460     }
00461 
00462   if (info_verbose)
00463     {
00464       fprintf_filtered (gdb_stdout, "Save segment, %s bytes at %s\n",
00465                         plongest (size), paddress (target_gdbarch (), vaddr));
00466     }
00467 
00468   bfd_set_section_size (obfd, osec, size);
00469   bfd_set_section_vma (obfd, osec, vaddr);
00470   bfd_section_lma (obfd, osec) = 0; /* ??? bfd_set_section_lma?  */
00471   return 0;
00472 }
00473 
00474 static int
00475 objfile_find_memory_regions (find_memory_region_ftype func, void *obfd)
00476 {
00477   /* Use objfile data to create memory sections.  */
00478   struct objfile *objfile;
00479   struct obj_section *objsec;
00480   bfd_vma temp_bottom, temp_top;
00481 
00482   /* Call callback function for each objfile section.  */
00483   ALL_OBJSECTIONS (objfile, objsec)
00484     {
00485       bfd *ibfd = objfile->obfd;
00486       asection *isec = objsec->the_bfd_section;
00487       flagword flags = bfd_get_section_flags (ibfd, isec);
00488 
00489       /* Separate debug info files are irrelevant for gcore.  */
00490       if (objfile->separate_debug_objfile_backlink != NULL)
00491         continue;
00492 
00493       if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
00494         {
00495           int size = bfd_section_size (ibfd, isec);
00496           int ret;
00497 
00498           ret = (*func) (obj_section_addr (objsec), size, 
00499                          1, /* All sections will be readable.  */
00500                          (flags & SEC_READONLY) == 0, /* Writable.  */
00501                          (flags & SEC_CODE) != 0, /* Executable.  */
00502                          1, /* MODIFIED is unknown, pass it as true.  */
00503                          obfd);
00504           if (ret != 0)
00505             return ret;
00506         }
00507     }
00508 
00509   /* Make a stack segment.  */
00510   if (derive_stack_segment (&temp_bottom, &temp_top))
00511     (*func) (temp_bottom, temp_top - temp_bottom,
00512              1, /* Stack section will be readable.  */
00513              1, /* Stack section will be writable.  */
00514              0, /* Stack section will not be executable.  */
00515              1, /* Stack section will be modified.  */
00516              obfd);
00517 
00518   /* Make a heap segment.  */
00519   if (derive_heap_segment (exec_bfd, &temp_bottom, &temp_top))
00520     (*func) (temp_bottom, temp_top - temp_bottom,
00521              1, /* Heap section will be readable.  */
00522              1, /* Heap section will be writable.  */
00523              0, /* Heap section will not be executable.  */
00524              1, /* Heap section will be modified.  */
00525              obfd);
00526 
00527   return 0;
00528 }
00529 
00530 static void
00531 gcore_copy_callback (bfd *obfd, asection *osec, void *ignored)
00532 {
00533   bfd_size_type size, total_size = bfd_section_size (obfd, osec);
00534   file_ptr offset = 0;
00535   struct cleanup *old_chain = NULL;
00536   void *memhunk;
00537 
00538   /* Read-only sections are marked; we don't have to copy their contents.  */
00539   if ((bfd_get_section_flags (obfd, osec) & SEC_LOAD) == 0)
00540     return;
00541 
00542   /* Only interested in "load" sections.  */
00543   if (strncmp ("load", bfd_section_name (obfd, osec), 4) != 0)
00544     return;
00545 
00546   size = min (total_size, MAX_COPY_BYTES);
00547   memhunk = xmalloc (size);
00548   old_chain = make_cleanup (xfree, memhunk);
00549 
00550   while (total_size > 0)
00551     {
00552       if (size > total_size)
00553         size = total_size;
00554 
00555       if (target_read_memory (bfd_section_vma (obfd, osec) + offset,
00556                               memhunk, size) != 0)
00557         {
00558           warning (_("Memory read failed for corefile "
00559                      "section, %s bytes at %s."),
00560                    plongest (size),
00561                    paddress (target_gdbarch (), bfd_section_vma (obfd, osec)));
00562           break;
00563         }
00564       if (!bfd_set_section_contents (obfd, osec, memhunk, offset, size))
00565         {
00566           warning (_("Failed to write corefile contents (%s)."),
00567                    bfd_errmsg (bfd_get_error ()));
00568           break;
00569         }
00570 
00571       total_size -= size;
00572       offset += size;
00573     }
00574 
00575   do_cleanups (old_chain);      /* Frees MEMHUNK.  */
00576 }
00577 
00578 static int
00579 gcore_memory_sections (bfd *obfd)
00580 {
00581   /* Try gdbarch method first, then fall back to target method.  */
00582   if (!gdbarch_find_memory_regions_p (target_gdbarch ())
00583       || gdbarch_find_memory_regions (target_gdbarch (),
00584                                       gcore_create_callback, obfd) != 0)
00585     {
00586       if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
00587         return 0;                       /* FIXME: error return/msg?  */
00588     }
00589 
00590   /* Record phdrs for section-to-segment mapping.  */
00591   bfd_map_over_sections (obfd, make_output_phdrs, NULL);
00592 
00593   /* Copy memory region contents.  */
00594   bfd_map_over_sections (obfd, gcore_copy_callback, NULL);
00595 
00596   return 1;
00597 }
00598 
00599 /* Provide a prototype to silence -Wmissing-prototypes.  */
00600 extern initialize_file_ftype _initialize_gcore;
00601 
00602 void
00603 _initialize_gcore (void)
00604 {
00605   add_com ("generate-core-file", class_files, gcore_command, _("\
00606 Save a core file with the current state of the debugged process.\n\
00607 Argument is optional filename.  Default filename is 'core.<process_id>'."));
00608 
00609   add_com_alias ("gcore", "generate-core-file", class_files, 1);
00610   exec_set_find_memory_regions (objfile_find_memory_regions);
00611 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines