RISC-V: Don't report warnings when linking different privileged spec objects.
[binutils-gdb.git] / gdb / gcore.c
blob969a8543ba29da69e9f0128f62939d6250108c90
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 (current_program_space, "sbrk").minsym != nullptr)
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 (current_program_space, "_sbrk").minsym
279 != nullptr)
281 sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
282 if (sbrk_fn == NULL)
283 return (bfd_vma) 0;
285 else
286 return (bfd_vma) 0;
288 gdbarch = sbrk_objf->arch ();
289 target_sbrk_arg = value_from_longest (builtin_type (gdbarch)->builtin_int,
290 sbrk_arg);
291 gdb_assert (target_sbrk_arg);
292 ret = call_function_by_hand (sbrk_fn, NULL, target_sbrk_arg);
293 if (ret == NULL)
294 return (bfd_vma) 0;
296 tmp = value_as_long (ret);
297 if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
298 return (bfd_vma) 0;
300 top_of_heap = tmp;
301 return top_of_heap;
304 /* Derive a reasonable heap segment for ABFD by looking at sbrk and
305 the static data sections. Store its limits in *BOTTOM and *TOP.
306 Return non-zero if successful. */
308 static int
309 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
311 bfd_vma top_of_data_memory = 0;
312 bfd_vma top_of_heap = 0;
313 bfd_size_type sec_size;
314 bfd_vma sec_vaddr;
315 asection *sec;
317 gdb_assert (bottom);
318 gdb_assert (top);
320 /* This function depends on being able to call a function in the
321 inferior. */
322 if (!target_has_execution ())
323 return 0;
325 /* The following code assumes that the link map is arranged as
326 follows (low to high addresses):
328 ---------------------------------
329 | text sections |
330 ---------------------------------
331 | data sections (including bss) |
332 ---------------------------------
333 | heap |
334 --------------------------------- */
336 for (sec = abfd->sections; sec; sec = sec->next)
338 if (bfd_section_flags (sec) & SEC_DATA
339 || strcmp (".bss", bfd_section_name (sec)) == 0)
341 sec_vaddr = bfd_section_vma (sec);
342 sec_size = bfd_section_size (sec);
343 if (sec_vaddr + sec_size > top_of_data_memory)
344 top_of_data_memory = sec_vaddr + sec_size;
348 top_of_heap = call_target_sbrk (0);
349 if (top_of_heap == (bfd_vma) 0)
350 return 0;
352 /* Return results. */
353 if (top_of_heap > top_of_data_memory)
355 *bottom = top_of_data_memory;
356 *top = top_of_heap;
357 return 1;
360 /* No additional heap space needs to be saved. */
361 return 0;
364 static void
365 make_output_phdrs (bfd *obfd, asection *osec)
367 int p_flags = 0;
368 int p_type = 0;
370 /* Memory tag segments have already been handled by the architecture, as
371 those contain arch-specific information. If we have one of those, just
372 return. */
373 if (startswith (bfd_section_name (osec), "memtag"))
374 return;
376 /* FIXME: these constants may only be applicable for ELF. */
377 if (startswith (bfd_section_name (osec), "load"))
378 p_type = PT_LOAD;
379 else if (startswith (bfd_section_name (osec), "note"))
380 p_type = PT_NOTE;
381 else
382 p_type = PT_NULL;
384 p_flags |= PF_R; /* Segment is readable. */
385 if (!(bfd_section_flags (osec) & SEC_READONLY))
386 p_flags |= PF_W; /* Segment is writable. */
387 if (bfd_section_flags (osec) & SEC_CODE)
388 p_flags |= PF_X; /* Segment is executable. */
390 bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
393 /* find_memory_region_ftype implementation.
395 MEMORY_TAGGED is true if the memory region contains memory tags, false
396 otherwise.
398 DATA is 'bfd *' for the core file GDB is creating. */
400 static int
401 gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read,
402 int write, int exec, int modified, bool memory_tagged,
403 void *data)
405 bfd *obfd = (bfd *) data;
406 asection *osec;
407 flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
409 /* If the memory segment has no permissions set, ignore it, otherwise
410 when we later try to access it for read/write, we'll get an error
411 or jam the kernel. */
412 if (read == 0 && write == 0 && exec == 0 && modified == 0)
414 if (info_verbose)
415 gdb_printf ("Ignore segment, %s bytes at %s\n",
416 plongest (size), paddress (current_inferior ()->arch (),
417 vaddr));
419 return 0;
422 if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
424 /* See if this region of memory lies inside a known file on disk.
425 If so, we can avoid copying its contents by clearing SEC_LOAD. */
427 for (objfile *objfile : current_program_space->objfiles ())
428 for (obj_section *objsec : objfile->sections ())
430 bfd *abfd = objfile->obfd.get ();
431 asection *asec = objsec->the_bfd_section;
432 bfd_vma align = (bfd_vma) 1 << bfd_section_alignment (asec);
433 bfd_vma start = objsec->addr () & -align;
434 bfd_vma end = (objsec->endaddr () + align - 1) & -align;
436 /* Match if either the entire memory region lies inside the
437 section (i.e. a mapping covering some pages of a large
438 segment) or the entire section lies inside the memory region
439 (i.e. a mapping covering multiple small sections).
441 This BFD was synthesized from reading target memory,
442 we don't want to omit that. */
443 if (objfile->separate_debug_objfile_backlink == NULL
444 && ((vaddr >= start && vaddr + size <= end)
445 || (start >= vaddr && end <= vaddr + size))
446 && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY))
448 flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
449 goto keep; /* Break out of two nested for loops. */
453 keep:;
456 if (write == 0)
457 flags |= SEC_READONLY;
459 if (exec)
460 flags |= SEC_CODE;
461 else
462 flags |= SEC_DATA;
464 osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
465 if (osec == NULL)
467 warning (_("Couldn't make gcore segment: %s"),
468 bfd_errmsg (bfd_get_error ()));
469 return 1;
472 if (info_verbose)
473 gdb_printf ("Save segment, %s bytes at %s\n",
474 plongest (size), paddress (current_inferior ()->arch (),
475 vaddr));
477 bfd_set_section_size (osec, size);
478 bfd_set_section_vma (osec, vaddr);
479 bfd_set_section_lma (osec, 0);
480 return 0;
483 /* gdbarch_find_memory_region callback for creating a memory tag section.
485 MEMORY_TAGGED is true if the memory region contains memory tags, false
486 otherwise.
488 DATA is 'bfd *' for the core file GDB is creating. */
490 static int
491 gcore_create_memtag_section_callback (CORE_ADDR vaddr, unsigned long size,
492 int read, int write, int exec,
493 int modified, bool memory_tagged,
494 void *data)
496 /* Are there memory tags in this particular memory map entry? */
497 if (!memory_tagged)
498 return 0;
500 bfd *obfd = (bfd *) data;
502 /* Ask the architecture to create a memory tag section for this particular
503 memory map entry. It will be populated with contents later, as we can't
504 start writing the contents before we have all the sections sorted out. */
505 gdbarch *arch = current_inferior ()->arch ();
506 asection *memtag_section
507 = gdbarch_create_memtag_section (arch, obfd, vaddr, size);
509 if (memtag_section == nullptr)
511 warning (_("Couldn't make gcore memory tag segment: %s"),
512 bfd_errmsg (bfd_get_error ()));
513 return 1;
516 if (info_verbose)
518 gdb_printf (gdb_stdout, "Saved memory tag segment, %s bytes "
519 "at %s\n",
520 plongest (bfd_section_size (memtag_section)),
521 paddress (arch, vaddr));
524 return 0;
528 objfile_find_memory_regions (struct target_ops *self,
529 find_memory_region_ftype func, void *obfd)
531 /* Use objfile data to create memory sections. */
532 bfd_vma temp_bottom = 0, temp_top = 0;
534 /* Call callback function for each objfile section. */
535 for (objfile *objfile : current_program_space->objfiles ())
536 for (obj_section *objsec : objfile->sections ())
538 asection *isec = objsec->the_bfd_section;
539 flagword flags = bfd_section_flags (isec);
541 /* Separate debug info files are irrelevant for gcore. */
542 if (objfile->separate_debug_objfile_backlink != NULL)
543 continue;
545 if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
547 int size = bfd_section_size (isec);
548 int ret;
550 ret = (*func) (objsec->addr (), size,
551 1, /* All sections will be readable. */
552 (flags & SEC_READONLY) == 0, /* Writable. */
553 (flags & SEC_CODE) != 0, /* Executable. */
554 1, /* MODIFIED is unknown, pass it as true. */
555 false, /* No memory tags in the object file. */
556 obfd);
557 if (ret != 0)
558 return ret;
562 /* Make a stack segment. */
563 if (derive_stack_segment (&temp_bottom, &temp_top))
564 (*func) (temp_bottom, temp_top - temp_bottom,
565 1, /* Stack section will be readable. */
566 1, /* Stack section will be writable. */
567 0, /* Stack section will not be executable. */
568 1, /* Stack section will be modified. */
569 false, /* No memory tags in the object file. */
570 obfd);
572 /* Make a heap segment. */
573 if (derive_heap_segment (current_program_space->exec_bfd (), &temp_bottom,
574 &temp_top))
575 (*func) (temp_bottom, temp_top - temp_bottom,
576 1, /* Heap section will be readable. */
577 1, /* Heap section will be writable. */
578 0, /* Heap section will not be executable. */
579 1, /* Heap section will be modified. */
580 false, /* No memory tags in the object file. */
581 obfd);
583 return 0;
586 /* Check if we have a block full of zeros at DATA within the [DATA,
587 DATA+SIZE) buffer. Returns the size of the all-zero block found.
588 Returns at most the minimum between SIZE and SPARSE_BLOCK_SIZE. */
590 static size_t
591 get_all_zero_block_size (const gdb_byte *data, size_t size)
593 size = std::min (size, (size_t) SPARSE_BLOCK_SIZE);
595 /* A memcmp of a whole block is much faster than a simple for loop.
596 This makes a big difference, as with a for loop, this code would
597 dominate the performance and result in doubling the time to
598 generate a core, at the time of writing. With an optimized
599 memcmp, this doesn't even show up in the perf trace. */
600 static const gdb_byte all_zero_block[SPARSE_BLOCK_SIZE] = {};
601 if (memcmp (data, all_zero_block, size) == 0)
602 return size;
603 return 0;
606 /* Basically a named-elements pair, used as return type of
607 find_next_all_zero_block. */
609 struct offset_and_size
611 size_t offset;
612 size_t size;
615 /* Find the next all-zero block at DATA+OFFSET within the [DATA,
616 DATA+SIZE) buffer. Returns the offset and the size of the all-zero
617 block if found, or zero if not found. */
619 static offset_and_size
620 find_next_all_zero_block (const gdb_byte *data, size_t offset, size_t size)
622 for (; offset < size; offset += SPARSE_BLOCK_SIZE)
624 size_t zero_block_size
625 = get_all_zero_block_size (data + offset, size - offset);
626 if (zero_block_size != 0)
627 return {offset, zero_block_size};
629 return {0, 0};
632 /* Wrapper around bfd_set_section_contents that avoids writing
633 all-zero blocks to disk, so we create a sparse core file.
634 SKIP_ALIGN is a recursion helper -- if true, we'll skip aligning
635 the file position to SPARSE_BLOCK_SIZE. */
637 static bool
638 sparse_bfd_set_section_contents (bfd *obfd, asection *osec,
639 const gdb_byte *data,
640 size_t sec_offset,
641 size_t size,
642 bool skip_align = false)
644 /* Note, we don't have to have special handling for the case of the
645 last memory region ending with zeros, because our caller always
646 writes out the note section after the memory/load sections. If
647 it didn't, we'd have to seek+write the last byte to make the file
648 size correct. (Or add an ftruncate abstraction to bfd and call
649 that.) */
651 if (size == 0)
652 return true;
654 size_t data_offset = 0;
656 if (!skip_align)
658 /* Align the all-zero block search with SPARSE_BLOCK_SIZE, to
659 better align with filesystem blocks. If we find we're
660 misaligned, then write/skip the bytes needed to make us
661 aligned. We do that with (one level) recursion. */
663 /* We need to know the section's file offset on disk. We can
664 only look at it after the bfd's 'output_has_begun' flag has
665 been set, as bfd hasn't computed the file offsets
666 otherwise. */
667 if (!obfd->output_has_begun)
669 gdb_byte dummy = 0;
671 /* A write forces BFD to compute the bfd's section file
672 positions. Zero size works for that too. */
673 if (!bfd_set_section_contents (obfd, osec, &dummy, 0, 0))
674 return false;
676 gdb_assert (obfd->output_has_begun);
679 /* How much after the last aligned offset are we writing at. */
680 size_t aligned_offset_remainder
681 = (osec->filepos + sec_offset) % SPARSE_BLOCK_SIZE;
683 /* Do we need to align? */
684 if (aligned_offset_remainder != 0)
686 /* How much we need to advance in order to find the next
687 SPARSE_BLOCK_SIZE filepos-aligned block. */
688 size_t distance_to_next_aligned
689 = SPARSE_BLOCK_SIZE - aligned_offset_remainder;
691 /* How much we'll actually write in the recursion call. The
692 caller may want us to write fewer bytes than
693 DISTANCE_TO_NEXT_ALIGNED. */
694 size_t align_write_size = std::min (size, distance_to_next_aligned);
696 /* Recurse, skipping the alignment code. */
697 if (!sparse_bfd_set_section_contents (obfd, osec, data,
698 sec_offset,
699 align_write_size, true))
700 return false;
702 /* Skip over what we've written, and proceed with
703 assumes-aligned logic. */
704 data_offset += align_write_size;
708 while (data_offset < size)
710 size_t all_zero_block_size
711 = get_all_zero_block_size (data + data_offset, size - data_offset);
712 if (all_zero_block_size != 0)
714 /* Skip writing all-zero blocks. */
715 data_offset += all_zero_block_size;
716 continue;
719 /* We have some non-zero data to write to file. Find the next
720 all-zero block within the data, and only write up to it. */
722 offset_and_size next_all_zero_block
723 = find_next_all_zero_block (data,
724 data_offset + SPARSE_BLOCK_SIZE,
725 size);
726 size_t next_data_offset = (next_all_zero_block.offset == 0
727 ? size
728 : next_all_zero_block.offset);
730 if (!bfd_set_section_contents (obfd, osec, data + data_offset,
731 sec_offset + data_offset,
732 next_data_offset - data_offset))
733 return false;
735 data_offset = next_data_offset;
737 /* If we already know we have an all-zero block at the next
738 offset, we can skip calling get_all_zero_block_size for
739 it again. */
740 if (next_all_zero_block.offset != 0)
741 data_offset += next_all_zero_block.size;
744 return true;
747 static void
748 gcore_copy_callback (bfd *obfd, asection *osec)
750 bfd_size_type size, total_size = bfd_section_size (osec);
751 file_ptr offset = 0;
753 /* Read-only sections are marked; we don't have to copy their contents. */
754 if ((bfd_section_flags (osec) & SEC_LOAD) == 0)
755 return;
757 /* Only interested in "load" sections. */
758 if (!startswith (bfd_section_name (osec), "load"))
759 return;
761 size = std::min (total_size, (bfd_size_type) MAX_COPY_BYTES);
762 gdb::byte_vector memhunk (size);
764 while (total_size > 0)
766 if (size > total_size)
767 size = total_size;
769 if (target_read_memory (bfd_section_vma (osec) + offset,
770 memhunk.data (), size) != 0)
772 warning (_("Memory read failed for corefile "
773 "section, %s bytes at %s."),
774 plongest (size),
775 paddress (current_inferior ()->arch (),
776 bfd_section_vma (osec)));
777 break;
780 if (!sparse_bfd_set_section_contents (obfd, osec, memhunk.data (),
781 offset, size))
783 warning (_("Failed to write corefile contents (%s)."),
784 bfd_errmsg (bfd_get_error ()));
785 break;
788 total_size -= size;
789 offset += size;
793 /* Callback to copy contents to a particular memory tag section. */
795 static void
796 gcore_copy_memtag_section_callback (bfd *obfd, asection *osec)
798 /* We are only interested in "memtag" sections. */
799 if (!startswith (bfd_section_name (osec), "memtag"))
800 return;
802 /* Fill the section with memory tag contents. */
803 if (!gdbarch_fill_memtag_section (current_inferior ()->arch (), osec))
804 error (_("Failed to fill memory tag section for core file."));
807 static int
808 gcore_memory_sections (bfd *obfd)
810 /* Try gdbarch method first, then fall back to target method. */
811 gdbarch *arch = current_inferior ()->arch ();
812 if (!gdbarch_find_memory_regions_p (arch)
813 || gdbarch_find_memory_regions (arch, gcore_create_callback, obfd) != 0)
815 if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
816 return 0; /* FIXME: error return/msg? */
819 /* Take care of dumping memory tags, if there are any. */
820 if (!gdbarch_find_memory_regions_p (arch)
821 || gdbarch_find_memory_regions (arch, gcore_create_memtag_section_callback,
822 obfd) != 0)
824 if (target_find_memory_regions (gcore_create_memtag_section_callback,
825 obfd) != 0)
826 return 0;
829 /* Record phdrs for section-to-segment mapping. */
830 for (asection *sect : gdb_bfd_sections (obfd))
831 make_output_phdrs (obfd, sect);
833 /* Copy memory region and memory tag contents. */
834 for (asection *sect : gdb_bfd_sections (obfd))
836 gcore_copy_callback (obfd, sect);
837 gcore_copy_memtag_section_callback (obfd, sect);
840 return 1;
843 /* See gcore.h. */
845 thread_info *
846 gcore_find_signalled_thread ()
848 thread_info *curr_thr = inferior_thread ();
849 if (curr_thr->state != THREAD_EXITED
850 && curr_thr->stop_signal () != GDB_SIGNAL_0)
851 return curr_thr;
853 for (thread_info *thr : current_inferior ()->non_exited_threads ())
854 if (thr->stop_signal () != GDB_SIGNAL_0)
855 return thr;
857 /* Default to the current thread, unless it has exited. */
858 if (curr_thr->state != THREAD_EXITED)
859 return curr_thr;
861 return nullptr;
864 void _initialize_gcore ();
865 void
866 _initialize_gcore ()
868 cmd_list_element *generate_core_file_cmd
869 = add_com ("generate-core-file", class_files, gcore_command, _("\
870 Save a core file with the current state of the debugged process.\n\
871 Usage: generate-core-file [FILENAME]\n\
872 Argument is optional filename. Default filename is 'core.PROCESS_ID'."));
874 add_com_alias ("gcore", generate_core_file_cmd, class_files, 1);