2002-01-10 Michael Snyder <msnyder@redhat.com>
[external/binutils.git] / gdb / gcore.c
1 /* Generate a core file for the inferior process.
2    Copyright 2001, 2002 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "cli/cli-decode.h"
23 #include "inferior.h"
24 #include "gdbcore.h"
25 #include "elf-bfd.h"
26 #include <sys/procfs.h>
27 #include "symfile.h"
28 #include "objfiles.h"
29
30 static char                  *default_gcore_target (void);
31 static enum bfd_architecture  default_gcore_arch (void);
32 static unsigned long          default_gcore_mach (void);
33 static int                    gcore_memory_sections (bfd *);
34
35 /* Function: gcore_command
36    Generate a core file from the inferior process.  */
37
38 static void
39 gcore_command (char *args, int from_tty)
40 {
41   struct cleanup *old_chain;
42   char *corefilename, corefilename_buffer[40];
43   asection *note_sec;
44   bfd *obfd;
45   void *note_data = NULL;
46   int note_size = 0;
47
48   /* No use generating a corefile without a target process.  */
49   if (!(target_has_execution))
50     noprocess ();
51
52   if (args && *args)
53     corefilename = args;
54   else
55     {
56       /* Default corefile name is "core.PID".  */
57       sprintf (corefilename_buffer, "core.%d", PIDGET (inferior_ptid));
58       corefilename = corefilename_buffer;
59     }
60
61   if (info_verbose)
62     fprintf_filtered (gdb_stdout, 
63                       "Opening corefile '%s' for output.\n", corefilename);
64
65   /* Open the output file. */
66   if (!(obfd = bfd_openw (corefilename, NULL /*default_gcore_target ()*/)))
67     {
68       error ("Failed to open '%s' for output.", corefilename);
69     }
70
71   /* Need a cleanup that will close the file (FIXME: delete it?). */
72   old_chain = make_cleanup_bfd_close (obfd);
73
74   bfd_set_format (obfd, bfd_core);
75   bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ());
76
77   /* An external target method must build the notes section. */
78   note_data = (char *) target_make_corefile_notes (obfd, &note_size);
79
80   /* Create the note section. */
81   if (note_data != NULL && note_size != 0)
82     {
83       if ((note_sec = bfd_make_section_anyway (obfd, "note0")) == NULL)
84         error ("Failed to create 'note' section for corefile: %s", 
85                bfd_errmsg (bfd_get_error ()));
86
87       bfd_set_section_vma (obfd, note_sec, 0);
88       bfd_set_section_flags (obfd, note_sec, 
89                              SEC_HAS_CONTENTS | SEC_READONLY | SEC_ALLOC);
90       bfd_set_section_alignment (obfd, note_sec, 0);
91       bfd_set_section_size (obfd, note_sec, note_size);
92     }
93
94   /* Now create the memory/load sections. */
95   if (gcore_memory_sections (obfd) == 0)
96     error ("gcore: failed to get corefile memory sections from target.");
97
98   /* Write out the contents of the note section. */
99   if (note_data != NULL && note_size != 0)
100     {
101       if (!bfd_set_section_contents (obfd, note_sec, note_data, 0, note_size))
102         {
103           warning ("writing note section (%s)", 
104                    bfd_errmsg (bfd_get_error ()));
105         }
106     }
107
108   /* Succeeded. */
109   fprintf_filtered (gdb_stdout, 
110                     "Saved corefile %s\n", corefilename);
111
112   /* Clean-ups will close the output file and free malloc memory. */
113   do_cleanups (old_chain);
114   return;
115 }
116
117 static unsigned long
118 default_gcore_mach (void)
119 {
120 #ifdef TARGET_ARCHITECTURE
121   const struct bfd_arch_info * bfdarch = TARGET_ARCHITECTURE;
122
123   if (bfdarch != NULL)
124     return bfdarch->mach;
125 #endif
126   if (exec_bfd == NULL)
127     error ("Can't find default bfd machine type (need execfile).");
128
129   return bfd_get_mach (exec_bfd);
130 }
131
132 static enum bfd_architecture
133 default_gcore_arch (void)
134 {
135 #ifdef TARGET_ARCHITECTURE
136   const struct bfd_arch_info * bfdarch = TARGET_ARCHITECTURE;
137
138   if (bfdarch != NULL)
139     return bfdarch->arch;
140 #endif
141   if (exec_bfd == NULL)
142     error ("Can't find bfd architecture for corefile (need execfile).");
143
144   return bfd_get_arch (exec_bfd);
145 }
146
147 static char *
148 default_gcore_target (void)
149 {
150   /* FIXME -- this may only work for ELF targets.  */
151   if (exec_bfd == NULL)
152     error ("Can't find default bfd target for corefile (need execfile).");
153
154   return bfd_get_target (exec_bfd);
155 }
156
157 /*
158  * Default method for stack segment (preemptable by target).
159  */
160
161 static int (*override_derive_stack_segment) (bfd_vma *, bfd_vma *);
162
163 extern void
164 preempt_derive_stack_segment (int (*override_func) (bfd_vma *, bfd_vma *))
165 {
166   override_derive_stack_segment = override_func;
167 }
168
169 /* Function: default_derive_stack_segment
170    Derive a reasonable stack segment by unwinding the target stack. 
171    
172    Returns 0 for failure, 1 for success.  */
173
174 static int 
175 default_derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
176 {
177   bfd_vma tmp_vma;
178   struct frame_info *fi, *tmp_fi;
179
180   if (bottom == NULL || top == NULL)
181     return 0;   /* Paranoia. */
182
183   if (!target_has_stack || !target_has_registers)
184     return 0;   /* Can't succeed without stack and registers. */
185
186   if ((fi = get_current_frame ()) == NULL)
187     return 0;   /* Can't succeed without current frame. */
188
189   /* Save frame pointer of TOS frame. */
190   *top = fi->frame;
191   /* If current stack pointer is more "inner", use that instead. */
192   if (INNER_THAN (read_sp (), *top))
193     *top = read_sp ();
194
195   /* Find prev-most frame. */
196   while ((tmp_fi = get_prev_frame (fi)) != NULL)
197     fi = tmp_fi;
198
199   /* Save frame pointer of prev-most frame. */
200   *bottom = fi->frame;
201
202   /* Now canonicalize their order, so that 'bottom' is a lower address
203    (as opposed to a lower stack frame). */
204   if (*bottom > *top)
205     {
206       tmp_vma = *top;
207       *top = *bottom;
208       *bottom = tmp_vma;
209     }
210
211   return 1;     /* success */
212 }
213
214 static int
215 derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
216 {
217   if (override_derive_stack_segment)
218     return override_derive_stack_segment (bottom, top);
219   else
220     return default_derive_stack_segment (bottom, top);
221 }
222
223 /*
224  * Default method for heap segment (preemptable by target).
225  */
226
227 static int (*override_derive_heap_segment) (bfd *, bfd_vma *, bfd_vma *);
228
229 extern void
230 preempt_derive_heap_segment (int (*override_func) (bfd *, 
231                                                    bfd_vma *, bfd_vma *))
232 {
233   override_derive_heap_segment = override_func;
234 }
235
236 /* Function: default_derive_heap_segment
237    Derive a reasonable heap segment by looking at sbrk and
238    the static data sections.
239    
240    Returns 0 for failure, 1 for success.  */
241
242 static int 
243 default_derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
244 {
245   bfd_vma top_of_data_memory = 0;
246   bfd_vma top_of_heap = 0;
247   bfd_size_type sec_size;
248   struct value *zero, *sbrk;
249   bfd_vma sec_vaddr;
250   asection *sec;
251
252   if (bottom == NULL || top == NULL)
253     return 0;           /* Paranoia. */
254
255   if (!target_has_execution)
256     return 0;           /* This function depends on being able
257                            to call a function in the inferior.  */
258
259   /* Assumption: link map is arranged as follows (low to high addresses):
260      text sections
261      data sections (including bss)
262      heap
263   */
264
265   for (sec = abfd->sections; sec; sec = sec->next)
266     {
267       if (bfd_get_section_flags (abfd, sec) & SEC_DATA ||
268           strcmp (".bss", bfd_get_section_name (abfd, sec)) == 0)
269         {
270           sec_vaddr = bfd_get_section_vma (abfd, sec);
271           sec_size = bfd_get_section_size_before_reloc (sec);
272           if (sec_vaddr + sec_size > top_of_data_memory)
273             top_of_data_memory = sec_vaddr + sec_size;
274         }
275     }
276   /* Now get the top-of-heap by calling sbrk in the inferior.  */
277   if ((sbrk = find_function_in_inferior ("sbrk")) == NULL)
278     return 0;
279   if ((zero = value_from_longest (builtin_type_int, (LONGEST) 0)) == NULL)
280     return 0;
281   if ((sbrk = call_function_by_hand (sbrk, 1, &zero)) == NULL)
282     return 0;
283   top_of_heap = value_as_long (sbrk);
284
285   /* Return results. */
286   if (top_of_heap > top_of_data_memory)
287     {
288       *bottom = top_of_data_memory;
289       *top = top_of_heap;
290       return 1; /* success */
291     }
292   else
293     return 0;   /* No additional heap space needs to be saved. */
294 }
295
296 static int
297 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
298 {
299   if (override_derive_heap_segment)
300     return override_derive_heap_segment (abfd, bottom, top);
301   else
302     return default_derive_heap_segment (abfd, bottom, top);
303 }
304
305 /* ARGSUSED */
306 static void
307 make_output_phdrs (bfd *obfd, asection *osec, void *ignored)
308 {
309   int p_flags = 0;
310   int p_type;
311
312   /* FIXME: these constants may only be applicable for ELF.  */
313   if (strncmp (osec->name, "load", 4) == 0)
314     p_type = PT_LOAD;
315   else
316     p_type = PT_NOTE;
317
318   p_flags |= PF_R;      /* Segment is readable.  */
319   if (!(bfd_get_section_flags (obfd, osec) & SEC_READONLY))
320     p_flags |= PF_W;    /* Segment is writable.  */
321   if (bfd_get_section_flags (obfd, osec) & SEC_CODE)
322     p_flags |= PF_X;    /* Segment is executable.  */
323
324   bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 
325                    0, 0, 1, &osec);
326 }
327
328 static asection *
329 make_mem_sec (bfd *obfd, 
330               bfd_vma addr, 
331               bfd_size_type size, 
332               unsigned int flags, 
333               unsigned int alignment)
334 {
335   asection *osec;
336
337   if ((osec = bfd_make_section_anyway (obfd, "load")) == NULL)
338     {
339       warning ("Couldn't make gcore segment: %s",
340                bfd_errmsg (bfd_get_error ()));
341       return NULL;
342     }
343
344   if (info_verbose)
345     {
346       fprintf_filtered (gdb_stdout, 
347                         "Save segment, %ld bytes at 0x%s\n",
348                         size, paddr_nz (addr));
349     }
350
351   bfd_set_section_size (obfd, osec, size);
352   bfd_set_section_vma (obfd, osec, addr);
353   osec->lma = 0;        /* FIXME: there should be a macro for this! */
354   bfd_set_section_alignment (obfd, osec, alignment);
355   bfd_set_section_flags (obfd, osec, 
356                          flags | SEC_LOAD | SEC_ALLOC | SEC_HAS_CONTENTS);
357   return osec;
358 }
359
360 static int
361 gcore_create_callback (CORE_ADDR vaddr, 
362                        unsigned long size,
363                        int read, int write, int exec, 
364                        void *data)
365 {
366   flagword flags = 0;
367
368   if (write == 0)
369     {
370       flags |= SEC_READONLY;
371       /* Set size == zero for readonly sections. */
372       size = 0;
373     }
374   if (exec)
375     {
376       flags |= SEC_CODE;
377     }
378   else
379     {
380       flags |= SEC_DATA;
381     }
382
383   return ((make_mem_sec ((bfd *) data, vaddr, size, flags, 0)) == NULL);
384 }
385
386 static int
387 objfile_find_memory_regions (int (*func) (CORE_ADDR, 
388                                           unsigned long,
389                                           int, int, int,
390                                            void *), 
391                              void *obfd)
392 {
393   /* Use objfile data to create memory sections. */
394   struct objfile *objfile;
395   struct obj_section *objsec;
396   bfd_vma temp_bottom, temp_top;
397
398   /* Call callback function for each objfile section. */
399   ALL_OBJSECTIONS (objfile, objsec)
400     {
401       bfd *ibfd = objfile->obfd;
402       asection *isec = objsec->the_bfd_section;
403       flagword flags = bfd_get_section_flags (ibfd, isec);
404       int ret;
405
406       if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
407         {
408           int size = bfd_section_size (ibfd, isec);
409           int ret;
410
411           if ((ret = (*func) (objsec->addr, 
412                               bfd_section_size (ibfd, isec), 
413                               1, /* All sections will be readable.  */
414                               (flags & SEC_READONLY) == 0, /* writable */
415                               (flags & SEC_CODE) != 0, /* executable */
416                               obfd)) != 0)
417             return ret;
418         }
419     }
420
421   /* Make a stack segment. */
422   if (derive_stack_segment (&temp_bottom, &temp_top))
423     (*func) (temp_bottom, 
424              temp_top - temp_bottom, 
425              1, /* Stack section will be readable */
426              1, /* Stack section will be writable */
427              0, /* Stack section will not be executable */
428              obfd);
429
430   /* Make a heap segment. */
431   if (derive_heap_segment (exec_bfd, &temp_bottom, &temp_top))
432     (*func) (temp_bottom, 
433              temp_top - temp_bottom, 
434              1, /* Heap section will be readable */
435              1, /* Heap section will be writable */
436              0, /* Heap section will not be executable */
437              obfd);
438   return 0;
439 }
440
441 static void
442 gcore_copy_callback (bfd *obfd, asection *osec, void *ignored)
443 {
444   bfd_size_type size = bfd_section_size (obfd, osec);
445   struct cleanup *old_chain = NULL;
446   void *memhunk;
447
448   if (size == 0)
449     return;     /* Read-only sections are marked as zero-size.
450                    We don't have to copy their contents. */
451   if (strncmp ("load", bfd_get_section_name (obfd, osec), 4) != 0)
452     return;     /* Only interested in "load" sections. */
453
454   if ((memhunk = xmalloc (size)) == NULL)
455     error ("Not enough memory to create corefile.");
456   old_chain = make_cleanup (xfree, memhunk);
457
458   if (target_read_memory (bfd_section_vma (obfd, osec), 
459                           memhunk, size) != 0)
460     warning ("Memory read failed for corefile section, %ld bytes at 0x%s\n",
461              (long) size, paddr (bfd_section_vma (obfd, osec)));
462   if (!bfd_set_section_contents (obfd, osec, memhunk, 0, size))
463     warning ("Failed to write corefile contents (%s).", 
464              bfd_errmsg (bfd_get_error ()));
465
466   do_cleanups (old_chain);      /* frees the xmalloc buffer */
467 }
468
469 static int
470 gcore_memory_sections (bfd *obfd)
471 {
472   if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
473     return 0;   /* FIXME error return/msg? */
474
475   /* Record phdrs for section-to-segment mapping. */
476   bfd_map_over_sections (obfd, make_output_phdrs, NULL);
477
478   /* Copy memory region contents. */
479   bfd_map_over_sections (obfd, gcore_copy_callback, NULL);
480
481   return 1;     /* success */
482 }
483
484 void
485 _initialize_gcore (void)
486 {
487   add_com ("generate-core-file", class_files, gcore_command,
488            "Save a core file with the current state of the debugged process.\n\
489 Argument is optional filename.  Default filename is 'core.<process_id>'.");
490
491   add_com_alias ("gcore", "generate-core-file", class_files, 1);
492   exec_set_find_memory_regions (objfile_find_memory_regions);
493 }