Fix building Loongarch BFD with a 32-bit compiler
[binutils-gdb.git] / gdb / gcore.c
blob007966212a793beeb51100f6eab915a09d7191c2
1 /* Generate a core file for the inferior process.
3 Copyright (C) 2001-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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 3 of the License, or
10 (at your option) any later version.
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.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "elf-bfd.h"
21 #include "infcall.h"
22 #include "inferior.h"
23 #include "gdbcore.h"
24 #include "objfiles.h"
25 #include "solib.h"
26 #include "symfile.h"
27 #include "arch-utils.h"
28 #include "completer.h"
29 #include "gcore.h"
30 #include "cli/cli-decode.h"
31 #include <fcntl.h>
32 #include "regcache.h"
33 #include "regset.h"
34 #include "gdb_bfd.h"
35 #include "readline/tilde.h"
36 #include <algorithm>
37 #include "gdbsupport/gdb_unlinker.h"
38 #include "gdbsupport/byte-vector.h"
39 #include "gdbsupport/scope-exit.h"
41 /* To generate sparse cores, we look at the data to write in chunks of
42 this size when considering whether to skip the write. Only if we
43 have a full block of this size with all zeros do we skip writing
44 it. A simpler algorithm that would try to skip all zeros would
45 result in potentially many more write/lseek syscalls, as normal
46 data is typically sprinkled with many small holes of zeros. Also,
47 it's much more efficient to memcmp a block of data against an
48 all-zero buffer than to check each and every data byte against zero
49 one by one. */
50 #define SPARSE_BLOCK_SIZE 0x1000
52 /* The largest amount of memory to read from the target at once. We
53 must throttle it to limit the amount of memory used by GDB during
54 generate-core-file for programs with large resident data. */
55 #define MAX_COPY_BYTES (256 * SPARSE_BLOCK_SIZE)
57 static const char *default_gcore_target (void);
58 static enum bfd_architecture default_gcore_arch (void);
59 static int gcore_memory_sections (bfd *);
61 /* create_gcore_bfd -- helper for gcore_command (exported).
62 Open a new bfd core file for output, and return the handle. */
64 gdb_bfd_ref_ptr
65 create_gcore_bfd (const char *filename)
67 gdb_bfd_ref_ptr obfd (gdb_bfd_openw (filename, default_gcore_target ()));
69 if (obfd == NULL)
70 error (_("Failed to open '%s' for output."), filename);
71 bfd_set_format (obfd.get (), bfd_core);
72 bfd_set_arch_mach (obfd.get (), default_gcore_arch (), 0);
73 return obfd;
76 /* write_gcore_file_1 -- do the actual work of write_gcore_file. */
78 static void
79 write_gcore_file_1 (bfd *obfd)
81 gdb::unique_xmalloc_ptr<char> note_data;
82 int note_size = 0;
83 asection *note_sec = NULL;
84 gdbarch *arch = current_inferior ()->arch ();
86 /* An external target method must build the notes section. */
87 /* FIXME: uweigand/2011-10-06: All architectures that support core file
88 generation should be converted to gdbarch_make_corefile_notes; at that
89 point, the target vector method can be removed. */
90 if (!gdbarch_make_corefile_notes_p (arch))
91 note_data = target_make_corefile_notes (obfd, &note_size);
92 else
93 note_data = gdbarch_make_corefile_notes (arch, obfd, &note_size);
95 if (note_data == NULL || note_size == 0)
96 error (_("Target does not support core file generation."));
98 /* Create the note section. */
99 note_sec = bfd_make_section_anyway_with_flags (obfd, "note0",
100 SEC_HAS_CONTENTS
101 | SEC_READONLY
102 | SEC_ALLOC);
103 if (note_sec == NULL)
104 error (_("Failed to create 'note' section for corefile: %s"),
105 bfd_errmsg (bfd_get_error ()));
107 bfd_set_section_vma (note_sec, 0);
108 bfd_set_section_alignment (note_sec, 0);
109 bfd_set_section_size (note_sec, note_size);
111 /* Now create the memory/load sections. Note
112 gcore_memory_sections's sparse logic is assuming that we'll
113 always write something afterwards, which we do: just below, we
114 write the note section. So there's no need for an ftruncate-like
115 call to grow the file to the right size if the last memory
116 sections were zeros and we skipped writing them. */
117 if (gcore_memory_sections (obfd) == 0)
118 error (_("gcore: failed to get corefile memory sections from target."));
120 /* Write out the contents of the note section. */
121 if (!bfd_set_section_contents (obfd, note_sec, note_data.get (), 0,
122 note_size))
123 warning (_("writing note section (%s)"), bfd_errmsg (bfd_get_error ()));
126 /* write_gcore_file -- helper for gcore_command (exported).
127 Compose and write the corefile data to the core file. */
129 void
130 write_gcore_file (bfd *obfd)
132 target_prepare_to_generate_core ();
133 SCOPE_EXIT { target_done_generating_core (); };
134 write_gcore_file_1 (obfd);
137 /* gcore_command -- implements the 'gcore' command.
138 Generate a core file from the inferior process. */
140 static void
141 gcore_command (const char *args, int from_tty)
143 gdb::unique_xmalloc_ptr<char> corefilename;
145 /* No use generating a corefile without a target process. */
146 if (!target_has_execution ())
147 noprocess ();
149 if (args && *args)
150 corefilename.reset (tilde_expand (args));
151 else
153 /* Default corefile name is "core.PID". */
154 corefilename = xstrprintf ("core.%d", inferior_ptid.pid ());
157 if (info_verbose)
158 gdb_printf ("Opening corefile '%s' for output.\n",
159 corefilename.get ());
161 if (target_supports_dumpcore ())
162 target_dumpcore (corefilename.get ());
163 else
165 /* Open the output file. */
166 gdb_bfd_ref_ptr obfd (create_gcore_bfd (corefilename.get ()));
168 /* Arrange to unlink the file on failure. */
169 gdb::unlinker unlink_file (corefilename.get ());
171 /* Call worker function. */
172 write_gcore_file (obfd.get ());
174 /* Succeeded. */
175 unlink_file.keep ();
178 gdb_printf ("Saved corefile %s\n", corefilename.get ());
181 static enum bfd_architecture
182 default_gcore_arch (void)
184 const bfd_arch_info *bfdarch
185 = gdbarch_bfd_arch_info (current_inferior ()->arch ());
187 if (bfdarch != NULL)
188 return bfdarch->arch;
189 if (current_program_space->exec_bfd () == NULL)
190 error (_("Can't find bfd architecture for corefile (need execfile)."));
192 return bfd_get_arch (current_program_space->exec_bfd ());
195 static const char *
196 default_gcore_target (void)
198 gdbarch *arch = current_inferior ()->arch ();
199 /* The gdbarch may define a target to use for core files. */
200 if (gdbarch_gcore_bfd_target_p (arch))
201 return gdbarch_gcore_bfd_target (arch);
203 /* Otherwise, try to fall back to the exec target. This will probably
204 not work for non-ELF targets. */
205 if (current_program_space->exec_bfd () == NULL)
206 return NULL;
207 else
208 return bfd_get_target (current_program_space->exec_bfd ());
211 /* Derive a reasonable stack segment by unwinding the target stack,
212 and store its limits in *BOTTOM and *TOP. Return non-zero if
213 successful. */
215 static int
216 derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
218 frame_info_ptr fi, tmp_fi;
220 gdb_assert (bottom);
221 gdb_assert (top);
223 /* Can't succeed without stack and registers. */
224 if (!target_has_stack () || !target_has_registers ())
225 return 0;
227 /* Can't succeed without current frame. */
228 fi = get_current_frame ();
229 if (fi == NULL)
230 return 0;
232 /* Save frame pointer of TOS frame. */
233 *top = get_frame_base (fi);
234 /* If current stack pointer is more "inner", use that instead. */
235 if (gdbarch_inner_than (get_frame_arch (fi), get_frame_sp (fi), *top))
236 *top = get_frame_sp (fi);
238 /* Find prev-most frame. */
239 while ((tmp_fi = get_prev_frame (fi)) != NULL)
240 fi = tmp_fi;
242 /* Save frame pointer of prev-most frame. */
243 *bottom = get_frame_base (fi);
245 /* Now canonicalize their order, so that BOTTOM is a lower address
246 (as opposed to a lower stack frame). */
247 if (*bottom > *top)
249 bfd_vma tmp_vma;
251 tmp_vma = *top;
252 *top = *bottom;
253 *bottom = tmp_vma;
256 return 1;
259 /* call_target_sbrk --
260 helper function for derive_heap_segment. */
262 static bfd_vma
263 call_target_sbrk (int sbrk_arg)
265 struct objfile *sbrk_objf;
266 struct gdbarch *gdbarch;
267 bfd_vma top_of_heap;
268 struct value *target_sbrk_arg;
269 struct value *sbrk_fn, *ret;
270 bfd_vma tmp;
272 if (lookup_minimal_symbol ("sbrk", NULL, NULL).minsym != NULL)
274 sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
275 if (sbrk_fn == NULL)
276 return (bfd_vma) 0;
278 else if (lookup_minimal_symbol ("_sbrk", NULL, NULL).minsym != NULL)
280 sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
281 if (sbrk_fn == NULL)
282 return (bfd_vma) 0;
284 else
285 return (bfd_vma) 0;
287 gdbarch = sbrk_objf->arch ();
288 target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int,
289 sbrk_arg);
290 gdb_assert (target_sbrk_arg);
291 ret = call_function_by_hand (sbrk_fn, NULL, target_sbrk_arg);
292 if (ret == NULL)
293 return (bfd_vma) 0;
295 tmp = value_as_long (ret);
296 if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
297 return (bfd_vma) 0;
299 top_of_heap = tmp;
300 return top_of_heap;
303 /* Derive a reasonable heap segment for ABFD by looking at sbrk and
304 the static data sections. Store its limits in *BOTTOM and *TOP.
305 Return non-zero if successful. */
307 static int
308 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
310 bfd_vma top_of_data_memory = 0;
311 bfd_vma top_of_heap = 0;
312 bfd_size_type sec_size;
313 bfd_vma sec_vaddr;
314 asection *sec;
316 gdb_assert (bottom);
317 gdb_assert (top);
319 /* This function depends on being able to call a function in the
320 inferior. */
321 if (!target_has_execution ())
322 return 0;
324 /* The following code assumes that the link map is arranged as
325 follows (low to high addresses):
327 ---------------------------------
328 | text sections |
329 ---------------------------------
330 | data sections (including bss) |
331 ---------------------------------
332 | heap |
333 --------------------------------- */
335 for (sec = abfd->sections; sec; sec = sec->next)
337 if (bfd_section_flags (sec) & SEC_DATA
338 || strcmp (".bss", bfd_section_name (sec)) == 0)
340 sec_vaddr = bfd_section_vma (sec);
341 sec_size = bfd_section_size (sec);
342 if (sec_vaddr + sec_size > top_of_data_memory)
343 top_of_data_memory = sec_vaddr + sec_size;
347 top_of_heap = call_target_sbrk (0);
348 if (top_of_heap == (bfd_vma) 0)
349 return 0;
351 /* Return results. */
352 if (top_of_heap > top_of_data_memory)
354 *bottom = top_of_data_memory;
355 *top = top_of_heap;
356 return 1;
359 /* No additional heap space needs to be saved. */
360 return 0;
363 static void
364 make_output_phdrs (bfd *obfd, asection *osec)
366 int p_flags = 0;
367 int p_type = 0;
369 /* Memory tag segments have already been handled by the architecture, as
370 those contain arch-specific information. If we have one of those, just
371 return. */
372 if (startswith (bfd_section_name (osec), "memtag"))
373 return;
375 /* FIXME: these constants may only be applicable for ELF. */
376 if (startswith (bfd_section_name (osec), "load"))
377 p_type = PT_LOAD;
378 else if (startswith (bfd_section_name (osec), "note"))
379 p_type = PT_NOTE;
380 else
381 p_type = PT_NULL;
383 p_flags |= PF_R; /* Segment is readable. */
384 if (!(bfd_section_flags (osec) & SEC_READONLY))
385 p_flags |= PF_W; /* Segment is writable. */
386 if (bfd_section_flags (osec) & SEC_CODE)
387 p_flags |= PF_X; /* Segment is executable. */
389 bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
392 /* find_memory_region_ftype implementation.
394 MEMORY_TAGGED is true if the memory region contains memory tags, false
395 otherwise.
397 DATA is 'bfd *' for the core file GDB is creating. */
399 static int
400 gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read,
401 int write, int exec, int modified, bool memory_tagged,
402 void *data)
404 bfd *obfd = (bfd *) data;
405 asection *osec;
406 flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
408 /* If the memory segment has no permissions set, ignore it, otherwise
409 when we later try to access it for read/write, we'll get an error
410 or jam the kernel. */
411 if (read == 0 && write == 0 && exec == 0 && modified == 0)
413 if (info_verbose)
414 gdb_printf ("Ignore segment, %s bytes at %s\n",
415 plongest (size), paddress (current_inferior ()->arch (),
416 vaddr));
418 return 0;
421 if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
423 /* See if this region of memory lies inside a known file on disk.
424 If so, we can avoid copying its contents by clearing SEC_LOAD. */
426 for (objfile *objfile : current_program_space->objfiles ())
427 for (obj_section *objsec : objfile->sections ())
429 bfd *abfd = objfile->obfd.get ();
430 asection *asec = objsec->the_bfd_section;
431 bfd_vma align = (bfd_vma) 1 << bfd_section_alignment (asec);
432 bfd_vma start = objsec->addr () & -align;
433 bfd_vma end = (objsec->endaddr () + align - 1) & -align;
435 /* Match if either the entire memory region lies inside the
436 section (i.e. a mapping covering some pages of a large
437 segment) or the entire section lies inside the memory region
438 (i.e. a mapping covering multiple small sections).
440 This BFD was synthesized from reading target memory,
441 we don't want to omit that. */
442 if (objfile->separate_debug_objfile_backlink == NULL
443 && ((vaddr >= start && vaddr + size <= end)
444 || (start >= vaddr && end <= vaddr + size))
445 && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
447 flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
448 goto keep; /* Break out of two nested for loops. */
452 keep:;
455 if (write == 0)
456 flags |= SEC_READONLY;
458 if (exec)
459 flags |= SEC_CODE;
460 else
461 flags |= SEC_DATA;
463 osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
464 if (osec == NULL)
466 warning (_("Couldn't make gcore segment: %s"),
467 bfd_errmsg (bfd_get_error ()));
468 return 1;
471 if (info_verbose)
472 gdb_printf ("Save segment, %s bytes at %s\n",
473 plongest (size), paddress (current_inferior ()->arch (),
474 vaddr));
476 bfd_set_section_size (osec, size);
477 bfd_set_section_vma (osec, vaddr);
478 bfd_set_section_lma (osec, 0);
479 return 0;
482 /* gdbarch_find_memory_region callback for creating a memory tag section.
484 MEMORY_TAGGED is true if the memory region contains memory tags, false
485 otherwise.
487 DATA is 'bfd *' for the core file GDB is creating. */
489 static int
490 gcore_create_memtag_section_callback (CORE_ADDR vaddr, unsigned long size,
491 int read, int write, int exec,
492 int modified, bool memory_tagged,
493 void *data)
495 /* Are there memory tags in this particular memory map entry? */
496 if (!memory_tagged)
497 return 0;
499 bfd *obfd = (bfd *) data;
501 /* Ask the architecture to create a memory tag section for this particular
502 memory map entry. It will be populated with contents later, as we can't
503 start writing the contents before we have all the sections sorted out. */
504 gdbarch *arch = current_inferior ()->arch ();
505 asection *memtag_section
506 = gdbarch_create_memtag_section (arch, obfd, vaddr, size);
508 if (memtag_section == nullptr)
510 warning (_("Couldn't make gcore memory tag segment: %s"),
511 bfd_errmsg (bfd_get_error ()));
512 return 1;
515 if (info_verbose)
517 gdb_printf (gdb_stdout, "Saved memory tag segment, %s bytes "
518 "at %s\n",
519 plongest (bfd_section_size (memtag_section)),
520 paddress (arch, vaddr));
523 return 0;
527 objfile_find_memory_regions (struct target_ops *self,
528 find_memory_region_ftype func, void *obfd)
530 /* Use objfile data to create memory sections. */
531 bfd_vma temp_bottom, temp_top;
533 /* Call callback function for each objfile section. */
534 for (objfile *objfile : current_program_space->objfiles ())
535 for (obj_section *objsec : objfile->sections ())
537 asection *isec = objsec->the_bfd_section;
538 flagword flags = bfd_section_flags (isec);
540 /* Separate debug info files are irrelevant for gcore. */
541 if (objfile->separate_debug_objfile_backlink != NULL)
542 continue;
544 if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
546 int size = bfd_section_size (isec);
547 int ret;
549 ret = (*func) (objsec->addr (), size,
550 1, /* All sections will be readable. */
551 (flags & SEC_READONLY) == 0, /* Writable. */
552 (flags & SEC_CODE) != 0, /* Executable. */
553 1, /* MODIFIED is unknown, pass it as true. */
554 false, /* No memory tags in the object file. */
555 obfd);
556 if (ret != 0)
557 return ret;
561 /* Make a stack segment. */
562 if (derive_stack_segment (&temp_bottom, &temp_top))
563 (*func) (temp_bottom, temp_top - temp_bottom,
564 1, /* Stack section will be readable. */
565 1, /* Stack section will be writable. */
566 0, /* Stack section will not be executable. */
567 1, /* Stack section will be modified. */
568 false, /* No memory tags in the object file. */
569 obfd);
571 /* Make a heap segment. */
572 if (derive_heap_segment (current_program_space->exec_bfd (), &temp_bottom,
573 &temp_top))
574 (*func) (temp_bottom, temp_top - temp_bottom,
575 1, /* Heap section will be readable. */
576 1, /* Heap section will be writable. */
577 0, /* Heap section will not be executable. */
578 1, /* Heap section will be modified. */
579 false, /* No memory tags in the object file. */
580 obfd);
582 return 0;
585 /* Check if we have a block full of zeros at DATA within the [DATA,
586 DATA+SIZE) buffer. Returns the size of the all-zero block found.
587 Returns at most the minimum between SIZE and SPARSE_BLOCK_SIZE. */
589 static size_t
590 get_all_zero_block_size (const gdb_byte *data, size_t size)
592 size = std::min (size, (size_t) SPARSE_BLOCK_SIZE);
594 /* A memcmp of a whole block is much faster than a simple for loop.
595 This makes a big difference, as with a for loop, this code would
596 dominate the performance and result in doubling the time to
597 generate a core, at the time of writing. With an optimized
598 memcmp, this doesn't even show up in the perf trace. */
599 static const gdb_byte all_zero_block[SPARSE_BLOCK_SIZE] = {};
600 if (memcmp (data, all_zero_block, size) == 0)
601 return size;
602 return 0;
605 /* Basically a named-elements pair, used as return type of
606 find_next_all_zero_block. */
608 struct offset_and_size
610 size_t offset;
611 size_t size;
614 /* Find the next all-zero block at DATA+OFFSET within the [DATA,
615 DATA+SIZE) buffer. Returns the offset and the size of the all-zero
616 block if found, or zero if not found. */
618 static offset_and_size
619 find_next_all_zero_block (const gdb_byte *data, size_t offset, size_t size)
621 for (; offset < size; offset += SPARSE_BLOCK_SIZE)
623 size_t zero_block_size
624 = get_all_zero_block_size (data + offset, size - offset);
625 if (zero_block_size != 0)
626 return {offset, zero_block_size};
628 return {0, 0};
631 /* Wrapper around bfd_set_section_contents that avoids writing
632 all-zero blocks to disk, so we create a sparse core file.
633 SKIP_ALIGN is a recursion helper -- if true, we'll skip aligning
634 the file position to SPARSE_BLOCK_SIZE. */
636 static bool
637 sparse_bfd_set_section_contents (bfd *obfd, asection *osec,
638 const gdb_byte *data,
639 size_t sec_offset,
640 size_t size,
641 bool skip_align = false)
643 /* Note, we don't have to have special handling for the case of the
644 last memory region ending with zeros, because our caller always
645 writes out the note section after the memory/load sections. If
646 it didn't, we'd have to seek+write the last byte to make the file
647 size correct. (Or add an ftruncate abstraction to bfd and call
648 that.) */
650 if (size == 0)
651 return true;
653 size_t data_offset = 0;
655 if (!skip_align)
657 /* Align the all-zero block search with SPARSE_BLOCK_SIZE, to
658 better align with filesystem blocks. If we find we're
659 misaligned, then write/skip the bytes needed to make us
660 aligned. We do that with (one level) recursion. */
662 /* We need to know the section's file offset on disk. We can
663 only look at it after the bfd's 'output_has_begun' flag has
664 been set, as bfd hasn't computed the file offsets
665 otherwise. */
666 if (!obfd->output_has_begun)
668 gdb_byte dummy = 0;
670 /* A write forces BFD to compute the bfd's section file
671 positions. Zero size works for that too. */
672 if (!bfd_set_section_contents (obfd, osec, &dummy, 0, 0))
673 return false;
675 gdb_assert (obfd->output_has_begun);
678 /* How much after the last aligned offset are we writing at. */
679 size_t aligned_offset_remainder
680 = (osec->filepos + sec_offset) % SPARSE_BLOCK_SIZE;
682 /* Do we need to align? */
683 if (aligned_offset_remainder != 0)
685 /* How much we need to advance in order to find the next
686 SPARSE_BLOCK_SIZE filepos-aligned block. */
687 size_t distance_to_next_aligned
688 = SPARSE_BLOCK_SIZE - aligned_offset_remainder;
690 /* How much we'll actually write in the recursion call. The
691 caller may want us to write fewer bytes than
692 DISTANCE_TO_NEXT_ALIGNED. */
693 size_t align_write_size = std::min (size, distance_to_next_aligned);
695 /* Recurse, skipping the alignment code. */
696 if (!sparse_bfd_set_section_contents (obfd, osec, data,
697 sec_offset,
698 align_write_size, true))
699 return false;
701 /* Skip over what we've written, and proceed with
702 assumes-aligned logic. */
703 data_offset += align_write_size;
707 while (data_offset < size)
709 size_t all_zero_block_size
710 = get_all_zero_block_size (data + data_offset, size - data_offset);
711 if (all_zero_block_size != 0)
713 /* Skip writing all-zero blocks. */
714 data_offset += all_zero_block_size;
715 continue;
718 /* We have some non-zero data to write to file. Find the next
719 all-zero block within the data, and only write up to it. */
721 offset_and_size next_all_zero_block
722 = find_next_all_zero_block (data,
723 data_offset + SPARSE_BLOCK_SIZE,
724 size);
725 size_t next_data_offset = (next_all_zero_block.offset == 0
726 ? size
727 : next_all_zero_block.offset);
729 if (!bfd_set_section_contents (obfd, osec, data + data_offset,
730 sec_offset + data_offset,
731 next_data_offset - data_offset))
732 return false;
734 data_offset = next_data_offset;
736 /* If we already know we have an all-zero block at the next
737 offset, we can skip calling get_all_zero_block_size for
738 it again. */
739 if (next_all_zero_block.offset != 0)
740 data_offset += next_all_zero_block.size;
743 return true;
746 static void
747 gcore_copy_callback (bfd *obfd, asection *osec)
749 bfd_size_type size, total_size = bfd_section_size (osec);
750 file_ptr offset = 0;
752 /* Read-only sections are marked; we don't have to copy their contents. */
753 if ((bfd_section_flags (osec) & SEC_LOAD) == 0)
754 return;
756 /* Only interested in "load" sections. */
757 if (!startswith (bfd_section_name (osec), "load"))
758 return;
760 size = std::min (total_size, (bfd_size_type) MAX_COPY_BYTES);
761 gdb::byte_vector memhunk (size);
763 while (total_size > 0)
765 if (size > total_size)
766 size = total_size;
768 if (target_read_memory (bfd_section_vma (osec) + offset,
769 memhunk.data (), size) != 0)
771 warning (_("Memory read failed for corefile "
772 "section, %s bytes at %s."),
773 plongest (size),
774 paddress (current_inferior ()->arch (),
775 bfd_section_vma (osec)));
776 break;
779 if (!sparse_bfd_set_section_contents (obfd, osec, memhunk.data (),
780 offset, size))
782 warning (_("Failed to write corefile contents (%s)."),
783 bfd_errmsg (bfd_get_error ()));
784 break;
787 total_size -= size;
788 offset += size;
792 /* Callback to copy contents to a particular memory tag section. */
794 static void
795 gcore_copy_memtag_section_callback (bfd *obfd, asection *osec)
797 /* We are only interested in "memtag" sections. */
798 if (!startswith (bfd_section_name (osec), "memtag"))
799 return;
801 /* Fill the section with memory tag contents. */
802 if (!gdbarch_fill_memtag_section (current_inferior ()->arch (), osec))
803 error (_("Failed to fill memory tag section for core file."));
806 static int
807 gcore_memory_sections (bfd *obfd)
809 /* Try gdbarch method first, then fall back to target method. */
810 gdbarch *arch = current_inferior ()->arch ();
811 if (!gdbarch_find_memory_regions_p (arch)
812 || gdbarch_find_memory_regions (arch, gcore_create_callback, obfd) != 0)
814 if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
815 return 0; /* FIXME: error return/msg? */
818 /* Take care of dumping memory tags, if there are any. */
819 if (!gdbarch_find_memory_regions_p (arch)
820 || gdbarch_find_memory_regions (arch, gcore_create_memtag_section_callback,
821 obfd) != 0)
823 if (target_find_memory_regions (gcore_create_memtag_section_callback,
824 obfd) != 0)
825 return 0;
828 /* Record phdrs for section-to-segment mapping. */
829 for (asection *sect : gdb_bfd_sections (obfd))
830 make_output_phdrs (obfd, sect);
832 /* Copy memory region and memory tag contents. */
833 for (asection *sect : gdb_bfd_sections (obfd))
835 gcore_copy_callback (obfd, sect);
836 gcore_copy_memtag_section_callback (obfd, sect);
839 return 1;
842 /* See gcore.h. */
844 thread_info *
845 gcore_find_signalled_thread ()
847 thread_info *curr_thr = inferior_thread ();
848 if (curr_thr->state != THREAD_EXITED
849 && curr_thr->stop_signal () != GDB_SIGNAL_0)
850 return curr_thr;
852 for (thread_info *thr : current_inferior ()->non_exited_threads ())
853 if (thr->stop_signal () != GDB_SIGNAL_0)
854 return thr;
856 /* Default to the current thread, unless it has exited. */
857 if (curr_thr->state != THREAD_EXITED)
858 return curr_thr;
860 return nullptr;
863 void _initialize_gcore ();
864 void
865 _initialize_gcore ()
867 cmd_list_element *generate_core_file_cmd
868 = add_com ("generate-core-file", class_files, gcore_command, _("\
869 Save a core file with the current state of the debugged process.\n\
870 Usage: generate-core-file [FILENAME]\n\
871 Argument is optional filename. Default filename is 'core.PROCESS_ID'."));
873 add_com_alias ("gcore", generate_core_file_cmd, class_files, 1);