2009-10-16 Hui Zhu <teawater@gmail.com>
[external/binutils.git] / gdb / gcore.c
1 /* Generate a core file for the inferior process.
2
3    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "elf-bfd.h"
23 #include "infcall.h"
24 #include "inferior.h"
25 #include "gdbcore.h"
26 #include "objfiles.h"
27 #include "symfile.h"
28 #include "arch-utils.h"
29 #include "completer.h"
30 #include "gcore.h"
31 #include "cli/cli-decode.h"
32 #include "gdb_assert.h"
33 #include <fcntl.h>
34 #include "regcache.h"
35 #include "regset.h"
36
37 /* The largest amount of memory to read from the target at once.  We
38    must throttle it to limit the amount of memory used by GDB during
39    generate-core-file for programs with large resident data.  */
40 #define MAX_COPY_BYTES (1024 * 1024)
41
42 static const char *default_gcore_target (void);
43 static enum bfd_architecture default_gcore_arch (void);
44 static unsigned long default_gcore_mach (void);
45 static int gcore_memory_sections (bfd *);
46
47 /* create_gcore_bfd -- helper for gcore_command (exported).
48    Open a new bfd core file for output, and return the handle.  */
49
50 bfd *
51 create_gcore_bfd (char *filename)
52 {
53   bfd *obfd = bfd_openw (filename, default_gcore_target ());
54   if (!obfd)
55     error (_("Failed to open '%s' for output."), filename);
56   bfd_set_format (obfd, bfd_core);
57   bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ());
58   return obfd;
59 }
60
61 /* write_gcore_file -- helper for gcore_command (exported).
62    Compose and write the corefile data to the core file.  */
63
64
65 void
66 write_gcore_file (bfd *obfd)
67 {
68   void *note_data = NULL;
69   int note_size = 0;
70   asection *note_sec = NULL;
71
72   /* An external target method must build the notes section.  */
73   note_data = target_make_corefile_notes (obfd, &note_size);
74
75   /* Create the note section.  */
76   if (note_data != NULL && note_size != 0)
77     {
78       note_sec = bfd_make_section_anyway_with_flags (obfd, "note0",
79                                                      SEC_HAS_CONTENTS
80                                                      | SEC_READONLY
81                                                      | SEC_ALLOC);
82       if (note_sec == NULL)
83         error (_("Failed to create 'note' section for corefile: %s"),
84                bfd_errmsg (bfd_get_error ()));
85
86       bfd_set_section_vma (obfd, note_sec, 0);
87       bfd_set_section_alignment (obfd, note_sec, 0);
88       bfd_set_section_size (obfd, note_sec, note_size);
89     }
90
91   /* Now create the memory/load sections.  */
92   if (gcore_memory_sections (obfd) == 0)
93     error (_("gcore: failed to get corefile memory sections from target."));
94
95   /* Write out the contents of the note section.  */
96   if (note_data != NULL && note_size != 0)
97     {
98       if (!bfd_set_section_contents (obfd, note_sec, note_data, 0, note_size))
99         warning (_("writing note section (%s)"), 
100                  bfd_errmsg (bfd_get_error ()));
101     }
102 }
103
104 /* gcore_command -- implements the 'gcore' command.
105    Generate a core file from the inferior process.  */
106
107 static void
108 gcore_command (char *args, int from_tty)
109 {
110   struct cleanup *old_chain;
111   char *corefilename, corefilename_buffer[40];
112   bfd *obfd;
113
114   /* No use generating a corefile without a target process.  */
115   if (!target_has_execution)
116     noprocess ();
117
118   if (args && *args)
119     corefilename = args;
120   else
121     {
122       /* Default corefile name is "core.PID".  */
123       sprintf (corefilename_buffer, "core.%d", PIDGET (inferior_ptid));
124       corefilename = corefilename_buffer;
125     }
126
127   if (info_verbose)
128     fprintf_filtered (gdb_stdout,
129                       "Opening corefile '%s' for output.\n", corefilename);
130
131   /* Open the output file.  */
132   obfd = create_gcore_bfd (corefilename);
133
134   /* Need a cleanup that will close the file (FIXME: delete it?).  */
135   old_chain = make_cleanup_bfd_close (obfd);
136
137   /* Call worker function.  */
138   write_gcore_file (obfd);
139
140   /* Succeeded.  */
141   fprintf_filtered (gdb_stdout, "Saved corefile %s\n", corefilename);
142
143   /* Clean-ups will close the output file and free malloc memory.  */
144   do_cleanups (old_chain);
145   return;
146 }
147
148 static unsigned long
149 default_gcore_mach (void)
150 {
151 #if 1   /* See if this even matters...  */
152   return 0;
153 #else
154
155   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch);
156
157   if (bfdarch != NULL)
158     return bfdarch->mach;
159   if (exec_bfd == NULL)
160     error (_("Can't find default bfd machine type (need execfile)."));
161
162   return bfd_get_mach (exec_bfd);
163 #endif /* 1 */
164 }
165
166 static enum bfd_architecture
167 default_gcore_arch (void)
168 {
169   const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch);
170
171   if (bfdarch != NULL)
172     return bfdarch->arch;
173   if (exec_bfd == NULL)
174     error (_("Can't find bfd architecture for corefile (need execfile)."));
175
176   return bfd_get_arch (exec_bfd);
177 }
178
179 static const char *
180 default_gcore_target (void)
181 {
182   /* The gdbarch may define a target to use for core files.  */
183   if (gdbarch_gcore_bfd_target_p (target_gdbarch))
184     return gdbarch_gcore_bfd_target (target_gdbarch);
185
186   /* Otherwise, try to fall back to the exec_bfd target.  This will probably
187      not work for non-ELF targets.  */
188   if (exec_bfd == NULL)
189     return NULL;
190   else
191     return bfd_get_target (exec_bfd);
192 }
193
194 /* Derive a reasonable stack segment by unwinding the target stack,
195    and store its limits in *BOTTOM and *TOP.  Return non-zero if
196    successful.  */
197
198 static int
199 derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
200 {
201   struct frame_info *fi, *tmp_fi;
202
203   gdb_assert (bottom);
204   gdb_assert (top);
205
206   /* Can't succeed without stack and registers.  */
207   if (!target_has_stack || !target_has_registers)
208     return 0;
209
210   /* Can't succeed without current frame.  */
211   fi = get_current_frame ();
212   if (fi == NULL)
213     return 0;
214
215   /* Save frame pointer of TOS frame.  */
216   *top = get_frame_base (fi);
217   /* If current stack pointer is more "inner", use that instead.  */
218   if (gdbarch_inner_than (get_frame_arch (fi), get_frame_sp (fi), *top))
219     *top = get_frame_sp (fi);
220
221   /* Find prev-most frame.  */
222   while ((tmp_fi = get_prev_frame (fi)) != NULL)
223     fi = tmp_fi;
224
225   /* Save frame pointer of prev-most frame.  */
226   *bottom = get_frame_base (fi);
227
228   /* Now canonicalize their order, so that BOTTOM is a lower address
229      (as opposed to a lower stack frame).  */
230   if (*bottom > *top)
231     {
232       bfd_vma tmp_vma;
233
234       tmp_vma = *top;
235       *top = *bottom;
236       *bottom = tmp_vma;
237     }
238
239   return 1;
240 }
241
242 /* call_target_sbrk --
243    helper function for derive_heap_segment.  */
244
245 static bfd_vma
246 call_target_sbrk (int sbrk_arg)
247 {
248   struct objfile *sbrk_objf;
249   struct gdbarch *gdbarch;
250   bfd_vma top_of_heap;
251   struct value *target_sbrk_arg;
252   struct value *sbrk_fn, *ret;
253   bfd_vma tmp;
254
255   if (lookup_minimal_symbol ("sbrk", NULL, NULL) != NULL)
256     {
257       sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
258       if (sbrk_fn == NULL)
259         return (bfd_vma) 0;
260     }
261   else if (lookup_minimal_symbol ("_sbrk", NULL, NULL) != NULL)
262     {
263       sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
264       if (sbrk_fn == NULL)
265         return (bfd_vma) 0;
266     }
267   else
268     return (bfd_vma) 0;
269
270   gdbarch = get_objfile_arch (sbrk_objf);
271   target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int, 
272                                         sbrk_arg);
273   gdb_assert (target_sbrk_arg);
274   ret = call_function_by_hand (sbrk_fn, 1, &target_sbrk_arg);
275   if (ret == NULL)
276     return (bfd_vma) 0;
277
278   tmp = value_as_long (ret);
279   if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
280     return (bfd_vma) 0;
281
282   top_of_heap = tmp;
283   return top_of_heap;
284 }
285
286 /* Derive a reasonable heap segment for ABFD by looking at sbrk and
287    the static data sections.  Store its limits in *BOTTOM and *TOP.
288    Return non-zero if successful.  */
289
290 static int
291 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
292 {
293   struct gdbarch *gdbarch;
294   bfd_vma top_of_data_memory = 0;
295   bfd_vma top_of_heap = 0;
296   bfd_size_type sec_size;
297   bfd_vma sec_vaddr;
298   asection *sec;
299
300   gdb_assert (bottom);
301   gdb_assert (top);
302
303   /* This function depends on being able to call a function in the
304      inferior.  */
305   if (!target_has_execution)
306     return 0;
307
308   /* The following code assumes that the link map is arranged as
309      follows (low to high addresses):
310
311      ---------------------------------
312      | text sections                 |
313      ---------------------------------
314      | data sections (including bss) |
315      ---------------------------------
316      | heap                          |
317      --------------------------------- */
318
319   for (sec = abfd->sections; sec; sec = sec->next)
320     {
321       if (bfd_get_section_flags (abfd, sec) & SEC_DATA
322           || strcmp (".bss", bfd_section_name (abfd, sec)) == 0)
323         {
324           sec_vaddr = bfd_get_section_vma (abfd, sec);
325           sec_size = bfd_get_section_size (sec);
326           if (sec_vaddr + sec_size > top_of_data_memory)
327             top_of_data_memory = sec_vaddr + sec_size;
328         }
329     }
330
331   top_of_heap = call_target_sbrk (0);
332   if (top_of_heap == (bfd_vma) 0)
333     return 0;
334
335   /* Return results.  */
336   if (top_of_heap > top_of_data_memory)
337     {
338       *bottom = top_of_data_memory;
339       *top = top_of_heap;
340       return 1;
341     }
342
343   /* No additional heap space needs to be saved.  */
344   return 0;
345 }
346
347 static void
348 make_output_phdrs (bfd *obfd, asection *osec, void *ignored)
349 {
350   int p_flags = 0;
351   int p_type = 0;
352
353   /* FIXME: these constants may only be applicable for ELF.  */
354   if (strncmp (bfd_section_name (obfd, osec), "load", 4) == 0)
355     p_type = PT_LOAD;
356   else if (strncmp (bfd_section_name (obfd, osec), "note", 4) == 0)
357     p_type = PT_NOTE;
358   else
359     p_type = PT_NULL;
360
361   p_flags |= PF_R;      /* Segment is readable.  */
362   if (!(bfd_get_section_flags (obfd, osec) & SEC_READONLY))
363     p_flags |= PF_W;    /* Segment is writable.  */
364   if (bfd_get_section_flags (obfd, osec) & SEC_CODE)
365     p_flags |= PF_X;    /* Segment is executable.  */
366
367   bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
368 }
369
370 static int
371 gcore_create_callback (CORE_ADDR vaddr, unsigned long size,
372                        int read, int write, int exec, void *data)
373 {
374   bfd *obfd = data;
375   asection *osec;
376   flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
377
378   /* If the memory segment has no permissions set, ignore it, otherwise
379      when we later try to access it for read/write, we'll get an error
380      or jam the kernel.  */
381   if (read == 0 && write == 0 && exec == 0)
382     {
383       if (info_verbose)
384         {
385           fprintf_filtered (gdb_stdout, "Ignore segment, %s bytes at %s\n",
386                             plongest (size), paddress (target_gdbarch, vaddr));
387         }
388
389       return 0;
390     }
391
392   if (write == 0)
393     {
394       /* See if this region of memory lies inside a known file on disk.
395          If so, we can avoid copying its contents by clearing SEC_LOAD.  */
396       struct objfile *objfile;
397       struct obj_section *objsec;
398
399       ALL_OBJSECTIONS (objfile, objsec)
400         {
401           bfd *abfd = objfile->obfd;
402           asection *asec = objsec->the_bfd_section;
403           bfd_vma align = (bfd_vma) 1 << bfd_get_section_alignment (abfd,
404                                                                     asec);
405           bfd_vma start = obj_section_addr (objsec) & -align;
406           bfd_vma end = (obj_section_endaddr (objsec) + align - 1) & -align;
407           /* Match if either the entire memory region lies inside the
408              section (i.e. a mapping covering some pages of a large
409              segment) or the entire section lies inside the memory region
410              (i.e. a mapping covering multiple small sections).
411
412              This BFD was synthesized from reading target memory,
413              we don't want to omit that.  */
414           if (((vaddr >= start && vaddr + size <= end)
415                || (start >= vaddr && end <= vaddr + size))
416               && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
417             {
418               flags &= ~SEC_LOAD;
419               flags |= SEC_NEVER_LOAD;
420               goto keep;        /* break out of two nested for loops */
421             }
422         }
423
424     keep:
425       flags |= SEC_READONLY;
426     }
427
428   if (exec)
429     flags |= SEC_CODE;
430   else
431     flags |= SEC_DATA;
432
433   osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
434   if (osec == NULL)
435     {
436       warning (_("Couldn't make gcore segment: %s"),
437                bfd_errmsg (bfd_get_error ()));
438       return 1;
439     }
440
441   if (info_verbose)
442     {
443       fprintf_filtered (gdb_stdout, "Save segment, %s bytes at %s\n",
444                         plongest (size), paddress (target_gdbarch, vaddr));
445     }
446
447   bfd_set_section_size (obfd, osec, size);
448   bfd_set_section_vma (obfd, osec, vaddr);
449   bfd_section_lma (obfd, osec) = 0; /* ??? bfd_set_section_lma?  */
450   return 0;
451 }
452
453 static int
454 objfile_find_memory_regions (int (*func) (CORE_ADDR, unsigned long,
455                                           int, int, int, void *),
456                              void *obfd)
457 {
458   /* Use objfile data to create memory sections.  */
459   struct objfile *objfile;
460   struct obj_section *objsec;
461   bfd_vma temp_bottom, temp_top;
462
463   /* Call callback function for each objfile section.  */
464   ALL_OBJSECTIONS (objfile, objsec)
465     {
466       bfd *ibfd = objfile->obfd;
467       asection *isec = objsec->the_bfd_section;
468       flagword flags = bfd_get_section_flags (ibfd, isec);
469       int ret;
470
471       if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
472         {
473           int size = bfd_section_size (ibfd, isec);
474           int ret;
475
476           ret = (*func) (obj_section_addr (objsec), bfd_section_size (ibfd, isec),
477                          1, /* All sections will be readable.  */
478                          (flags & SEC_READONLY) == 0, /* Writable.  */
479                          (flags & SEC_CODE) != 0, /* Executable.  */
480                          obfd);
481           if (ret != 0)
482             return ret;
483         }
484     }
485
486   /* Make a stack segment.  */
487   if (derive_stack_segment (&temp_bottom, &temp_top))
488     (*func) (temp_bottom, temp_top - temp_bottom,
489              1, /* Stack section will be readable.  */
490              1, /* Stack section will be writable.  */
491              0, /* Stack section will not be executable.  */
492              obfd);
493
494   /* Make a heap segment. */
495   if (derive_heap_segment (exec_bfd, &temp_bottom, &temp_top))
496     (*func) (temp_bottom, temp_top - temp_bottom,
497              1, /* Heap section will be readable.  */
498              1, /* Heap section will be writable.  */
499              0, /* Heap section will not be executable.  */
500              obfd);
501
502   return 0;
503 }
504
505 static void
506 gcore_copy_callback (bfd *obfd, asection *osec, void *ignored)
507 {
508   bfd_size_type size, total_size = bfd_section_size (obfd, osec);
509   file_ptr offset = 0;
510   struct cleanup *old_chain = NULL;
511   void *memhunk;
512
513   /* Read-only sections are marked; we don't have to copy their contents.  */
514   if ((bfd_get_section_flags (obfd, osec) & SEC_LOAD) == 0)
515     return;
516
517   /* Only interested in "load" sections.  */
518   if (strncmp ("load", bfd_section_name (obfd, osec), 4) != 0)
519     return;
520
521   size = min (total_size, MAX_COPY_BYTES);
522   memhunk = xmalloc (size);
523   /* ??? This is crap since xmalloc should never return NULL.  */
524   if (memhunk == NULL)
525     error (_("Not enough memory to create corefile."));
526   old_chain = make_cleanup (xfree, memhunk);
527
528   while (total_size > 0)
529     {
530       if (size > total_size)
531         size = total_size;
532
533       if (target_read_memory (bfd_section_vma (obfd, osec) + offset,
534                               memhunk, size) != 0)
535         {
536           warning (_("Memory read failed for corefile section, %s bytes at %s."),
537                    plongest (size),
538                    paddress (target_gdbarch, bfd_section_vma (obfd, osec)));
539           break;
540         }
541       if (!bfd_set_section_contents (obfd, osec, memhunk, offset, size))
542         {
543           warning (_("Failed to write corefile contents (%s)."),
544                    bfd_errmsg (bfd_get_error ()));
545           break;
546         }
547
548       total_size -= size;
549       offset += size;
550     }
551
552   do_cleanups (old_chain);      /* Frees MEMHUNK.  */
553 }
554
555 static int
556 gcore_memory_sections (bfd *obfd)
557 {
558   if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
559     return 0;                   /* FIXME: error return/msg?  */
560
561   /* Record phdrs for section-to-segment mapping.  */
562   bfd_map_over_sections (obfd, make_output_phdrs, NULL);
563
564   /* Copy memory region contents.  */
565   bfd_map_over_sections (obfd, gcore_copy_callback, NULL);
566
567   return 1;
568 }
569
570 /* Provide a prototype to silence -Wmissing-prototypes.  */
571 extern initialize_file_ftype _initialize_gcore;
572
573 void
574 _initialize_gcore (void)
575 {
576   add_com ("generate-core-file", class_files, gcore_command, _("\
577 Save a core file with the current state of the debugged process.\n\
578 Argument is optional filename.  Default filename is 'core.<process_id>'."));
579
580   add_com_alias ("gcore", "generate-core-file", class_files, 1);
581   exec_set_find_memory_regions (objfile_find_memory_regions);
582 }