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