gcore.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /* Generate a core file for the inferior process.
  2. Copyright (C) 2001-2022 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. #include <algorithm>
  32. #include "gdbsupport/gdb_unlinker.h"
  33. #include "gdbsupport/byte-vector.h"
  34. #include "gdbsupport/scope-exit.h"
  35. /* The largest amount of memory to read from the target at once. We
  36. must throttle it to limit the amount of memory used by GDB during
  37. generate-core-file for programs with large resident data. */
  38. #define MAX_COPY_BYTES (1024 * 1024)
  39. static const char *default_gcore_target (void);
  40. static enum bfd_architecture default_gcore_arch (void);
  41. static int gcore_memory_sections (bfd *);
  42. /* create_gcore_bfd -- helper for gcore_command (exported).
  43. Open a new bfd core file for output, and return the handle. */
  44. gdb_bfd_ref_ptr
  45. create_gcore_bfd (const char *filename)
  46. {
  47. gdb_bfd_ref_ptr obfd (gdb_bfd_openw (filename, default_gcore_target ()));
  48. if (obfd == NULL)
  49. error (_("Failed to open '%s' for output."), filename);
  50. bfd_set_format (obfd.get (), bfd_core);
  51. bfd_set_arch_mach (obfd.get (), default_gcore_arch (), 0);
  52. return obfd;
  53. }
  54. /* write_gcore_file_1 -- do the actual work of write_gcore_file. */
  55. static void
  56. write_gcore_file_1 (bfd *obfd)
  57. {
  58. gdb::unique_xmalloc_ptr<char> note_data;
  59. int note_size = 0;
  60. asection *note_sec = NULL;
  61. /* An external target method must build the notes section. */
  62. /* FIXME: uweigand/2011-10-06: All architectures that support core file
  63. generation should be converted to gdbarch_make_corefile_notes; at that
  64. point, the target vector method can be removed. */
  65. if (!gdbarch_make_corefile_notes_p (target_gdbarch ()))
  66. note_data = target_make_corefile_notes (obfd, &note_size);
  67. else
  68. note_data = gdbarch_make_corefile_notes (target_gdbarch (), obfd,
  69. &note_size);
  70. if (note_data == NULL || note_size == 0)
  71. error (_("Target does not support core file generation."));
  72. /* Create the note section. */
  73. note_sec = bfd_make_section_anyway_with_flags (obfd, "note0",
  74. SEC_HAS_CONTENTS
  75. | SEC_READONLY
  76. | SEC_ALLOC);
  77. if (note_sec == NULL)
  78. error (_("Failed to create 'note' section for corefile: %s"),
  79. bfd_errmsg (bfd_get_error ()));
  80. bfd_set_section_vma (note_sec, 0);
  81. bfd_set_section_alignment (note_sec, 0);
  82. bfd_set_section_size (note_sec, note_size);
  83. /* Now create the memory/load sections. */
  84. if (gcore_memory_sections (obfd) == 0)
  85. error (_("gcore: failed to get corefile memory sections from target."));
  86. /* Write out the contents of the note section. */
  87. if (!bfd_set_section_contents (obfd, note_sec, note_data.get (), 0,
  88. note_size))
  89. warning (_("writing note section (%s)"), bfd_errmsg (bfd_get_error ()));
  90. }
  91. /* write_gcore_file -- helper for gcore_command (exported).
  92. Compose and write the corefile data to the core file. */
  93. void
  94. write_gcore_file (bfd *obfd)
  95. {
  96. target_prepare_to_generate_core ();
  97. SCOPE_EXIT { target_done_generating_core (); };
  98. write_gcore_file_1 (obfd);
  99. }
  100. /* gcore_command -- implements the 'gcore' command.
  101. Generate a core file from the inferior process. */
  102. static void
  103. gcore_command (const char *args, int from_tty)
  104. {
  105. gdb::unique_xmalloc_ptr<char> corefilename;
  106. /* No use generating a corefile without a target process. */
  107. if (!target_has_execution ())
  108. noprocess ();
  109. if (args && *args)
  110. corefilename.reset (tilde_expand (args));
  111. else
  112. {
  113. /* Default corefile name is "core.PID". */
  114. corefilename = xstrprintf ("core.%d", inferior_ptid.pid ());
  115. }
  116. if (info_verbose)
  117. gdb_printf ("Opening corefile '%s' for output.\n",
  118. corefilename.get ());
  119. if (target_supports_dumpcore ())
  120. target_dumpcore (corefilename.get ());
  121. else
  122. {
  123. /* Open the output file. */
  124. gdb_bfd_ref_ptr obfd (create_gcore_bfd (corefilename.get ()));
  125. /* Arrange to unlink the file on failure. */
  126. gdb::unlinker unlink_file (corefilename.get ());
  127. /* Call worker function. */
  128. write_gcore_file (obfd.get ());
  129. /* Succeeded. */
  130. unlink_file.keep ();
  131. }
  132. gdb_printf ("Saved corefile %s\n", corefilename.get ());
  133. }
  134. static enum bfd_architecture
  135. default_gcore_arch (void)
  136. {
  137. const struct bfd_arch_info *bfdarch = gdbarch_bfd_arch_info (target_gdbarch ());
  138. if (bfdarch != NULL)
  139. return bfdarch->arch;
  140. if (current_program_space->exec_bfd () == NULL)
  141. error (_("Can't find bfd architecture for corefile (need execfile)."));
  142. return bfd_get_arch (current_program_space->exec_bfd ());
  143. }
  144. static const char *
  145. default_gcore_target (void)
  146. {
  147. /* The gdbarch may define a target to use for core files. */
  148. if (gdbarch_gcore_bfd_target_p (target_gdbarch ()))
  149. return gdbarch_gcore_bfd_target (target_gdbarch ());
  150. /* Otherwise, try to fall back to the exec target. This will probably
  151. not work for non-ELF targets. */
  152. if (current_program_space->exec_bfd () == NULL)
  153. return NULL;
  154. else
  155. return bfd_get_target (current_program_space->exec_bfd ());
  156. }
  157. /* Derive a reasonable stack segment by unwinding the target stack,
  158. and store its limits in *BOTTOM and *TOP. Return non-zero if
  159. successful. */
  160. static int
  161. derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
  162. {
  163. struct frame_info *fi, *tmp_fi;
  164. gdb_assert (bottom);
  165. gdb_assert (top);
  166. /* Can't succeed without stack and registers. */
  167. if (!target_has_stack () || !target_has_registers ())
  168. return 0;
  169. /* Can't succeed without current frame. */
  170. fi = get_current_frame ();
  171. if (fi == NULL)
  172. return 0;
  173. /* Save frame pointer of TOS frame. */
  174. *top = get_frame_base (fi);
  175. /* If current stack pointer is more "inner", use that instead. */
  176. if (gdbarch_inner_than (get_frame_arch (fi), get_frame_sp (fi), *top))
  177. *top = get_frame_sp (fi);
  178. /* Find prev-most frame. */
  179. while ((tmp_fi = get_prev_frame (fi)) != NULL)
  180. fi = tmp_fi;
  181. /* Save frame pointer of prev-most frame. */
  182. *bottom = get_frame_base (fi);
  183. /* Now canonicalize their order, so that BOTTOM is a lower address
  184. (as opposed to a lower stack frame). */
  185. if (*bottom > *top)
  186. {
  187. bfd_vma tmp_vma;
  188. tmp_vma = *top;
  189. *top = *bottom;
  190. *bottom = tmp_vma;
  191. }
  192. return 1;
  193. }
  194. /* call_target_sbrk --
  195. helper function for derive_heap_segment. */
  196. static bfd_vma
  197. call_target_sbrk (int sbrk_arg)
  198. {
  199. struct objfile *sbrk_objf;
  200. struct gdbarch *gdbarch;
  201. bfd_vma top_of_heap;
  202. struct value *target_sbrk_arg;
  203. struct value *sbrk_fn, *ret;
  204. bfd_vma tmp;
  205. if (lookup_minimal_symbol ("sbrk", NULL, NULL).minsym != NULL)
  206. {
  207. sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
  208. if (sbrk_fn == NULL)
  209. return (bfd_vma) 0;
  210. }
  211. else if (lookup_minimal_symbol ("_sbrk", NULL, NULL).minsym != NULL)
  212. {
  213. sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
  214. if (sbrk_fn == NULL)
  215. return (bfd_vma) 0;
  216. }
  217. else
  218. return (bfd_vma) 0;
  219. gdbarch = sbrk_objf->arch ();
  220. target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int,
  221. sbrk_arg);
  222. gdb_assert (target_sbrk_arg);
  223. ret = call_function_by_hand (sbrk_fn, NULL, target_sbrk_arg);
  224. if (ret == NULL)
  225. return (bfd_vma) 0;
  226. tmp = value_as_long (ret);
  227. if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
  228. return (bfd_vma) 0;
  229. top_of_heap = tmp;
  230. return top_of_heap;
  231. }
  232. /* Derive a reasonable heap segment for ABFD by looking at sbrk and
  233. the static data sections. Store its limits in *BOTTOM and *TOP.
  234. Return non-zero if successful. */
  235. static int
  236. derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
  237. {
  238. bfd_vma top_of_data_memory = 0;
  239. bfd_vma top_of_heap = 0;
  240. bfd_size_type sec_size;
  241. bfd_vma sec_vaddr;
  242. asection *sec;
  243. gdb_assert (bottom);
  244. gdb_assert (top);
  245. /* This function depends on being able to call a function in the
  246. inferior. */
  247. if (!target_has_execution ())
  248. return 0;
  249. /* The following code assumes that the link map is arranged as
  250. follows (low to high addresses):
  251. ---------------------------------
  252. | text sections |
  253. ---------------------------------
  254. | data sections (including bss) |
  255. ---------------------------------
  256. | heap |
  257. --------------------------------- */
  258. for (sec = abfd->sections; sec; sec = sec->next)
  259. {
  260. if (bfd_section_flags (sec) & SEC_DATA
  261. || strcmp (".bss", bfd_section_name (sec)) == 0)
  262. {
  263. sec_vaddr = bfd_section_vma (sec);
  264. sec_size = bfd_section_size (sec);
  265. if (sec_vaddr + sec_size > top_of_data_memory)
  266. top_of_data_memory = sec_vaddr + sec_size;
  267. }
  268. }
  269. top_of_heap = call_target_sbrk (0);
  270. if (top_of_heap == (bfd_vma) 0)
  271. return 0;
  272. /* Return results. */
  273. if (top_of_heap > top_of_data_memory)
  274. {
  275. *bottom = top_of_data_memory;
  276. *top = top_of_heap;
  277. return 1;
  278. }
  279. /* No additional heap space needs to be saved. */
  280. return 0;
  281. }
  282. static void
  283. make_output_phdrs (bfd *obfd, asection *osec)
  284. {
  285. int p_flags = 0;
  286. int p_type = 0;
  287. /* FIXME: these constants may only be applicable for ELF. */
  288. if (startswith (bfd_section_name (osec), "load"))
  289. p_type = PT_LOAD;
  290. else if (startswith (bfd_section_name (osec), "note"))
  291. p_type = PT_NOTE;
  292. else
  293. p_type = PT_NULL;
  294. p_flags |= PF_R; /* Segment is readable. */
  295. if (!(bfd_section_flags (osec) & SEC_READONLY))
  296. p_flags |= PF_W; /* Segment is writable. */
  297. if (bfd_section_flags (osec) & SEC_CODE)
  298. p_flags |= PF_X; /* Segment is executable. */
  299. bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
  300. }
  301. /* find_memory_region_ftype implementation. DATA is 'bfd *' for the core file
  302. GDB is creating. */
  303. static int
  304. gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read,
  305. int write, int exec, int modified, void *data)
  306. {
  307. bfd *obfd = (bfd *) data;
  308. asection *osec;
  309. flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
  310. /* If the memory segment has no permissions set, ignore it, otherwise
  311. when we later try to access it for read/write, we'll get an error
  312. or jam the kernel. */
  313. if (read == 0 && write == 0 && exec == 0 && modified == 0)
  314. {
  315. if (info_verbose)
  316. {
  317. gdb_printf ("Ignore segment, %s bytes at %s\n",
  318. plongest (size), paddress (target_gdbarch (), vaddr));
  319. }
  320. return 0;
  321. }
  322. if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
  323. {
  324. /* See if this region of memory lies inside a known file on disk.
  325. If so, we can avoid copying its contents by clearing SEC_LOAD. */
  326. struct obj_section *objsec;
  327. for (objfile *objfile : current_program_space->objfiles ())
  328. ALL_OBJFILE_OSECTIONS (objfile, objsec)
  329. {
  330. bfd *abfd = objfile->obfd;
  331. asection *asec = objsec->the_bfd_section;
  332. bfd_vma align = (bfd_vma) 1 << bfd_section_alignment (asec);
  333. bfd_vma start = objsec->addr () & -align;
  334. bfd_vma end = (objsec->endaddr () + align - 1) & -align;
  335. /* Match if either the entire memory region lies inside the
  336. section (i.e. a mapping covering some pages of a large
  337. segment) or the entire section lies inside the memory region
  338. (i.e. a mapping covering multiple small sections).
  339. This BFD was synthesized from reading target memory,
  340. we don't want to omit that. */
  341. if (objfile->separate_debug_objfile_backlink == NULL
  342. && ((vaddr >= start && vaddr + size <= end)
  343. || (start >= vaddr && end <= vaddr + size))
  344. && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
  345. {
  346. flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
  347. goto keep; /* Break out of two nested for loops. */
  348. }
  349. }
  350. keep:;
  351. }
  352. if (write == 0)
  353. flags |= SEC_READONLY;
  354. if (exec)
  355. flags |= SEC_CODE;
  356. else
  357. flags |= SEC_DATA;
  358. osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
  359. if (osec == NULL)
  360. {
  361. warning (_("Couldn't make gcore segment: %s"),
  362. bfd_errmsg (bfd_get_error ()));
  363. return 1;
  364. }
  365. if (info_verbose)
  366. {
  367. gdb_printf ("Save segment, %s bytes at %s\n",
  368. plongest (size), paddress (target_gdbarch (), vaddr));
  369. }
  370. bfd_set_section_size (osec, size);
  371. bfd_set_section_vma (osec, vaddr);
  372. bfd_set_section_lma (osec, 0);
  373. return 0;
  374. }
  375. int
  376. objfile_find_memory_regions (struct target_ops *self,
  377. find_memory_region_ftype func, void *obfd)
  378. {
  379. /* Use objfile data to create memory sections. */
  380. struct obj_section *objsec;
  381. bfd_vma temp_bottom, temp_top;
  382. /* Call callback function for each objfile section. */
  383. for (objfile *objfile : current_program_space->objfiles ())
  384. ALL_OBJFILE_OSECTIONS (objfile, objsec)
  385. {
  386. asection *isec = objsec->the_bfd_section;
  387. flagword flags = bfd_section_flags (isec);
  388. /* Separate debug info files are irrelevant for gcore. */
  389. if (objfile->separate_debug_objfile_backlink != NULL)
  390. continue;
  391. if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
  392. {
  393. int size = bfd_section_size (isec);
  394. int ret;
  395. ret = (*func) (objsec->addr (), size,
  396. 1, /* All sections will be readable. */
  397. (flags & SEC_READONLY) == 0, /* Writable. */
  398. (flags & SEC_CODE) != 0, /* Executable. */
  399. 1, /* MODIFIED is unknown, pass it as true. */
  400. obfd);
  401. if (ret != 0)
  402. return ret;
  403. }
  404. }
  405. /* Make a stack segment. */
  406. if (derive_stack_segment (&temp_bottom, &temp_top))
  407. (*func) (temp_bottom, temp_top - temp_bottom,
  408. 1, /* Stack section will be readable. */
  409. 1, /* Stack section will be writable. */
  410. 0, /* Stack section will not be executable. */
  411. 1, /* Stack section will be modified. */
  412. obfd);
  413. /* Make a heap segment. */
  414. if (derive_heap_segment (current_program_space->exec_bfd (), &temp_bottom,
  415. &temp_top))
  416. (*func) (temp_bottom, temp_top - temp_bottom,
  417. 1, /* Heap section will be readable. */
  418. 1, /* Heap section will be writable. */
  419. 0, /* Heap section will not be executable. */
  420. 1, /* Heap section will be modified. */
  421. obfd);
  422. return 0;
  423. }
  424. static void
  425. gcore_copy_callback (bfd *obfd, asection *osec)
  426. {
  427. bfd_size_type size, total_size = bfd_section_size (osec);
  428. file_ptr offset = 0;
  429. /* Read-only sections are marked; we don't have to copy their contents. */
  430. if ((bfd_section_flags (osec) & SEC_LOAD) == 0)
  431. return;
  432. /* Only interested in "load" sections. */
  433. if (!startswith (bfd_section_name (osec), "load"))
  434. return;
  435. size = std::min (total_size, (bfd_size_type) MAX_COPY_BYTES);
  436. gdb::byte_vector memhunk (size);
  437. while (total_size > 0)
  438. {
  439. if (size > total_size)
  440. size = total_size;
  441. if (target_read_memory (bfd_section_vma (osec) + offset,
  442. memhunk.data (), size) != 0)
  443. {
  444. warning (_("Memory read failed for corefile "
  445. "section, %s bytes at %s."),
  446. plongest (size),
  447. paddress (target_gdbarch (), bfd_section_vma (osec)));
  448. break;
  449. }
  450. if (!bfd_set_section_contents (obfd, osec, memhunk.data (),
  451. offset, size))
  452. {
  453. warning (_("Failed to write corefile contents (%s)."),
  454. bfd_errmsg (bfd_get_error ()));
  455. break;
  456. }
  457. total_size -= size;
  458. offset += size;
  459. }
  460. }
  461. static int
  462. gcore_memory_sections (bfd *obfd)
  463. {
  464. /* Try gdbarch method first, then fall back to target method. */
  465. if (!gdbarch_find_memory_regions_p (target_gdbarch ())
  466. || gdbarch_find_memory_regions (target_gdbarch (),
  467. gcore_create_callback, obfd) != 0)
  468. {
  469. if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
  470. return 0; /* FIXME: error return/msg? */
  471. }
  472. /* Record phdrs for section-to-segment mapping. */
  473. for (asection *sect : gdb_bfd_sections (obfd))
  474. make_output_phdrs (obfd, sect);
  475. /* Copy memory region contents. */
  476. for (asection *sect : gdb_bfd_sections (obfd))
  477. gcore_copy_callback (obfd, sect);
  478. return 1;
  479. }
  480. /* See gcore.h. */
  481. thread_info *
  482. gcore_find_signalled_thread ()
  483. {
  484. thread_info *curr_thr = inferior_thread ();
  485. if (curr_thr->state != THREAD_EXITED
  486. && curr_thr->stop_signal () != GDB_SIGNAL_0)
  487. return curr_thr;
  488. for (thread_info *thr : current_inferior ()->non_exited_threads ())
  489. if (thr->stop_signal () != GDB_SIGNAL_0)
  490. return thr;
  491. /* Default to the current thread, unless it has exited. */
  492. if (curr_thr->state != THREAD_EXITED)
  493. return curr_thr;
  494. return nullptr;
  495. }
  496. void _initialize_gcore ();
  497. void
  498. _initialize_gcore ()
  499. {
  500. cmd_list_element *generate_core_file_cmd
  501. = add_com ("generate-core-file", class_files, gcore_command, _("\
  502. Save a core file with the current state of the debugged process.\n\
  503. Usage: generate-core-file [FILENAME]\n\
  504. Argument is optional filename. Default filename is 'core.PROCESS_ID'."));
  505. add_com_alias ("gcore", generate_core_file_cmd, class_files, 1);
  506. }