1 /* Generate a core file for the inferior process.
2 
3    Copyright (C) 2001-2024 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 3 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, see <http://www.gnu.org/licenses/>.  */
19 
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"
40 
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
51 
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)
56 
57 static const char *default_gcore_target (void);
58 static enum bfd_architecture default_gcore_arch (void);
59 static int gcore_memory_sections (bfd *);
60 
61 /* create_gcore_bfd -- helper for gcore_command (exported).
62    Open a new bfd core file for output, and return the handle.  */
63 
64 gdb_bfd_ref_ptr
create_gcore_bfd(const char * filename)65 create_gcore_bfd (const char *filename)
66 {
67   gdb_bfd_ref_ptr obfd (gdb_bfd_openw (filename, default_gcore_target ()));
68 
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;
74 }
75 
76 /* write_gcore_file_1 -- do the actual work of write_gcore_file.  */
77 
78 static void
write_gcore_file_1(bfd * obfd)79 write_gcore_file_1 (bfd *obfd)
80 {
81   gdb::unique_xmalloc_ptr<char> note_data;
82   int note_size = 0;
83   asection *note_sec = NULL;
84   gdbarch *arch = current_inferior ()->arch ();
85 
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);
94 
95   if (note_data == NULL || note_size == 0)
96     error (_("Target does not support core file generation."));
97 
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 ()));
106 
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);
110 
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."));
119 
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 ()));
124 }
125 
126 /* write_gcore_file -- helper for gcore_command (exported).
127    Compose and write the corefile data to the core file.  */
128 
129 void
write_gcore_file(bfd * obfd)130 write_gcore_file (bfd *obfd)
131 {
132   target_prepare_to_generate_core ();
133   SCOPE_EXIT { target_done_generating_core (); };
134   write_gcore_file_1 (obfd);
135 }
136 
137 /* gcore_command -- implements the 'gcore' command.
138    Generate a core file from the inferior process.  */
139 
140 static void
gcore_command(const char * args,int from_tty)141 gcore_command (const char *args, int from_tty)
142 {
143   gdb::unique_xmalloc_ptr<char> corefilename;
144 
145   /* No use generating a corefile without a target process.  */
146   if (!target_has_execution ())
147     noprocess ();
148 
149   if (args && *args)
150     corefilename.reset (tilde_expand (args));
151   else
152     {
153       /* Default corefile name is "core.PID".  */
154       corefilename = xstrprintf ("core.%d", inferior_ptid.pid ());
155     }
156 
157   if (info_verbose)
158     gdb_printf ("Opening corefile '%s' for output.\n",
159                     corefilename.get ());
160 
161   if (target_supports_dumpcore ())
162     target_dumpcore (corefilename.get ());
163   else
164     {
165       /* Open the output file.  */
166       gdb_bfd_ref_ptr obfd (create_gcore_bfd (corefilename.get ()));
167 
168       /* Arrange to unlink the file on failure.  */
169       gdb::unlinker unlink_file (corefilename.get ());
170 
171       /* Call worker function.  */
172       write_gcore_file (obfd.get ());
173 
174       /* Succeeded.  */
175       unlink_file.keep ();
176     }
177 
178   gdb_printf ("Saved corefile %s\n", corefilename.get ());
179 }
180 
181 static enum bfd_architecture
default_gcore_arch(void)182 default_gcore_arch (void)
183 {
184   const bfd_arch_info *bfdarch
185     = gdbarch_bfd_arch_info (current_inferior ()->arch ());
186 
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)."));
191 
192   return bfd_get_arch (current_program_space->exec_bfd ());
193 }
194 
195 static const char *
default_gcore_target(void)196 default_gcore_target (void)
197 {
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);
202 
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 ());
209 }
210 
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.  */
214 
215 static int
derive_stack_segment(bfd_vma * bottom,bfd_vma * top)216 derive_stack_segment (bfd_vma *bottom, bfd_vma *top)
217 {
218   frame_info_ptr fi, tmp_fi;
219 
220   gdb_assert (bottom);
221   gdb_assert (top);
222 
223   /* Can't succeed without stack and registers.  */
224   if (!target_has_stack () || !target_has_registers ())
225     return 0;
226 
227   /* Can't succeed without current frame.  */
228   fi = get_current_frame ();
229   if (fi == NULL)
230     return 0;
231 
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);
237 
238   /* Find prev-most frame.  */
239   while ((tmp_fi = get_prev_frame (fi)) != NULL)
240     fi = tmp_fi;
241 
242   /* Save frame pointer of prev-most frame.  */
243   *bottom = get_frame_base (fi);
244 
245   /* Now canonicalize their order, so that BOTTOM is a lower address
246      (as opposed to a lower stack frame).  */
247   if (*bottom > *top)
248     {
249       bfd_vma tmp_vma;
250 
251       tmp_vma = *top;
252       *top = *bottom;
253       *bottom = tmp_vma;
254     }
255 
256   return 1;
257 }
258 
259 /* call_target_sbrk --
260    helper function for derive_heap_segment.  */
261 
262 static bfd_vma
call_target_sbrk(int sbrk_arg)263 call_target_sbrk (int sbrk_arg)
264 {
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;
271 
272   if (lookup_minimal_symbol ("sbrk", NULL, NULL).minsym != NULL)
273     {
274       sbrk_fn = find_function_in_inferior ("sbrk", &sbrk_objf);
275       if (sbrk_fn == NULL)
276           return (bfd_vma) 0;
277     }
278   else if (lookup_minimal_symbol ("_sbrk", NULL, NULL).minsym != NULL)
279     {
280       sbrk_fn = find_function_in_inferior ("_sbrk", &sbrk_objf);
281       if (sbrk_fn == NULL)
282           return (bfd_vma) 0;
283     }
284   else
285     return (bfd_vma) 0;
286 
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;
294 
295   tmp = value_as_long (ret);
296   if ((LONGEST) tmp <= 0 || (LONGEST) tmp == 0xffffffff)
297     return (bfd_vma) 0;
298 
299   top_of_heap = tmp;
300   return top_of_heap;
301 }
302 
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.  */
306 
307 static int
derive_heap_segment(bfd * abfd,bfd_vma * bottom,bfd_vma * top)308 derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top)
309 {
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;
315 
316   gdb_assert (bottom);
317   gdb_assert (top);
318 
319   /* This function depends on being able to call a function in the
320      inferior.  */
321   if (!target_has_execution ())
322     return 0;
323 
324   /* The following code assumes that the link map is arranged as
325      follows (low to high addresses):
326 
327      ---------------------------------
328      | text sections                 |
329      ---------------------------------
330      | data sections (including bss) |
331      ---------------------------------
332      | heap                          |
333      --------------------------------- */
334 
335   for (sec = abfd->sections; sec; sec = sec->next)
336     {
337       if (bfd_section_flags (sec) & SEC_DATA
338             || strcmp (".bss", bfd_section_name (sec)) == 0)
339           {
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;
344           }
345     }
346 
347   top_of_heap = call_target_sbrk (0);
348   if (top_of_heap == (bfd_vma) 0)
349     return 0;
350 
351   /* Return results.  */
352   if (top_of_heap > top_of_data_memory)
353     {
354       *bottom = top_of_data_memory;
355       *top = top_of_heap;
356       return 1;
357     }
358 
359   /* No additional heap space needs to be saved.  */
360   return 0;
361 }
362 
363 static void
make_output_phdrs(bfd * obfd,asection * osec)364 make_output_phdrs (bfd *obfd, asection *osec)
365 {
366   int p_flags = 0;
367   int p_type = 0;
368 
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;
374 
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;
382 
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.  */
388 
389   bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec);
390 }
391 
392 /* find_memory_region_ftype implementation.
393 
394    MEMORY_TAGGED is true if the memory region contains memory tags, false
395    otherwise.
396 
397    DATA is 'bfd *' for the core file GDB is creating.  */
398 
399 static int
gcore_create_callback(CORE_ADDR vaddr,unsigned long size,int read,int write,int exec,int modified,bool memory_tagged,void * data)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)
403 {
404   bfd *obfd = (bfd *) data;
405   asection *osec;
406   flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD;
407 
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)
412     {
413       if (info_verbose)
414           gdb_printf ("Ignore segment, %s bytes at %s\n",
415                         plongest (size), paddress (current_inferior ()->arch (),
416                         vaddr));
417 
418       return 0;
419     }
420 
421   if (write == 0 && modified == 0 && !solib_keep_data_in_core (vaddr, size))
422     {
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.  */
425 
426       for (objfile *objfile : current_program_space->objfiles ())
427           for (obj_section *objsec : objfile->sections ())
428             {
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;
434 
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).
439 
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))
446                 {
447                     flags &= ~(SEC_LOAD | SEC_HAS_CONTENTS);
448                     goto keep;          /* Break out of two nested for loops.  */
449                 }
450             }
451 
452     keep:;
453     }
454 
455   if (write == 0)
456     flags |= SEC_READONLY;
457 
458   if (exec)
459     flags |= SEC_CODE;
460   else
461     flags |= SEC_DATA;
462 
463   osec = bfd_make_section_anyway_with_flags (obfd, "load", flags);
464   if (osec == NULL)
465     {
466       warning (_("Couldn't make gcore segment: %s"),
467                  bfd_errmsg (bfd_get_error ()));
468       return 1;
469     }
470 
471   if (info_verbose)
472     gdb_printf ("Save segment, %s bytes at %s\n",
473                     plongest (size), paddress (current_inferior ()->arch (),
474                     vaddr));
475 
476   bfd_set_section_size (osec, size);
477   bfd_set_section_vma (osec, vaddr);
478   bfd_set_section_lma (osec, 0);
479   return 0;
480 }
481 
482 /* gdbarch_find_memory_region callback for creating a memory tag section.
483 
484    MEMORY_TAGGED is true if the memory region contains memory tags, false
485    otherwise.
486 
487    DATA is 'bfd *' for the core file GDB is creating.  */
488 
489 static int
gcore_create_memtag_section_callback(CORE_ADDR vaddr,unsigned long size,int read,int write,int exec,int modified,bool memory_tagged,void * data)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)
494 {
495   /* Are there memory tags in this particular memory map entry?  */
496   if (!memory_tagged)
497     return 0;
498 
499   bfd *obfd = (bfd *) data;
500 
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);
507 
508   if (memtag_section == nullptr)
509     {
510       warning (_("Couldn't make gcore memory tag segment: %s"),
511                  bfd_errmsg (bfd_get_error ()));
512       return 1;
513     }
514 
515   if (info_verbose)
516     {
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));
521     }
522 
523   return 0;
524 }
525 
526 int
objfile_find_memory_regions(struct target_ops * self,find_memory_region_ftype func,void * obfd)527 objfile_find_memory_regions (struct target_ops *self,
528                                    find_memory_region_ftype func, void *obfd)
529 {
530   /* Use objfile data to create memory sections.  */
531   bfd_vma temp_bottom = 0, temp_top = 0;
532 
533   /* Call callback function for each objfile section.  */
534   for (objfile *objfile : current_program_space->objfiles ())
535     for (obj_section *objsec : objfile->sections ())
536       {
537           asection *isec = objsec->the_bfd_section;
538           flagword flags = bfd_section_flags (isec);
539 
540           /* Separate debug info files are irrelevant for gcore.  */
541           if (objfile->separate_debug_objfile_backlink != NULL)
542             continue;
543 
544           if ((flags & SEC_ALLOC) || (flags & SEC_LOAD))
545             {
546               int size = bfd_section_size (isec);
547               int ret;
548 
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;
558             }
559       }
560 
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);
570 
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);
581 
582   return 0;
583 }
584 
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.  */
588 
589 static size_t
get_all_zero_block_size(const gdb_byte * data,size_t size)590 get_all_zero_block_size (const gdb_byte *data, size_t size)
591 {
592   size = std::min (size, (size_t) SPARSE_BLOCK_SIZE);
593 
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;
603 }
604 
605 /* Basically a named-elements pair, used as return type of
606    find_next_all_zero_block.  */
607 
608 struct offset_and_size
609 {
610   size_t offset;
611   size_t size;
612 };
613 
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.  */
617 
618 static offset_and_size
find_next_all_zero_block(const gdb_byte * data,size_t offset,size_t size)619 find_next_all_zero_block (const gdb_byte *data, size_t offset, size_t size)
620 {
621   for (; offset < size; offset += SPARSE_BLOCK_SIZE)
622     {
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};
627     }
628   return {0, 0};
629 }
630 
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.  */
635 
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)
642 {
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.)  */
649 
650   if (size == 0)
651     return true;
652 
653   size_t data_offset = 0;
654 
655   if (!skip_align)
656     {
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.  */
661 
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)
667           {
668             gdb_byte dummy = 0;
669 
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;
674 
675             gdb_assert (obfd->output_has_begun);
676           }
677 
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;
681 
682       /* Do we need to align?  */
683       if (aligned_offset_remainder != 0)
684           {
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;
689 
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);
694 
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;
700 
701             /* Skip over what we've written, and proceed with
702                assumes-aligned logic.  */
703             data_offset += align_write_size;
704           }
705     }
706 
707   while (data_offset < size)
708     {
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)
712           {
713             /* Skip writing all-zero blocks.  */
714             data_offset += all_zero_block_size;
715             continue;
716           }
717 
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.  */
720 
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);
728 
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;
733 
734       data_offset = next_data_offset;
735 
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;
741     }
742 
743   return true;
744 }
745 
746 static void
gcore_copy_callback(bfd * obfd,asection * osec)747 gcore_copy_callback (bfd *obfd, asection *osec)
748 {
749   bfd_size_type size, total_size = bfd_section_size (osec);
750   file_ptr offset = 0;
751 
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;
755 
756   /* Only interested in "load" sections.  */
757   if (!startswith (bfd_section_name (osec), "load"))
758     return;
759 
760   size = std::min (total_size, (bfd_size_type) MAX_COPY_BYTES);
761   gdb::byte_vector memhunk (size);
762 
763   while (total_size > 0)
764     {
765       if (size > total_size)
766           size = total_size;
767 
768       if (target_read_memory (bfd_section_vma (osec) + offset,
769                                     memhunk.data (), size) != 0)
770           {
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;
777           }
778 
779       if (!sparse_bfd_set_section_contents (obfd, osec, memhunk.data (),
780                                                       offset, size))
781           {
782             warning (_("Failed to write corefile contents (%s)."),
783                        bfd_errmsg (bfd_get_error ()));
784             break;
785           }
786 
787       total_size -= size;
788       offset += size;
789     }
790 }
791 
792 /* Callback to copy contents to a particular memory tag section.  */
793 
794 static void
gcore_copy_memtag_section_callback(bfd * obfd,asection * osec)795 gcore_copy_memtag_section_callback (bfd *obfd, asection *osec)
796 {
797   /* We are only interested in "memtag" sections.  */
798   if (!startswith (bfd_section_name (osec), "memtag"))
799     return;
800 
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."));
804 }
805 
806 static int
gcore_memory_sections(bfd * obfd)807 gcore_memory_sections (bfd *obfd)
808 {
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)
813     {
814       if (target_find_memory_regions (gcore_create_callback, obfd) != 0)
815           return 0;                     /* FIXME: error return/msg?  */
816     }
817 
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)
822     {
823       if (target_find_memory_regions (gcore_create_memtag_section_callback,
824                                               obfd) != 0)
825           return 0;
826     }
827 
828   /* Record phdrs for section-to-segment mapping.  */
829   for (asection *sect : gdb_bfd_sections (obfd))
830     make_output_phdrs (obfd, sect);
831 
832   /* Copy memory region and memory tag contents.  */
833   for (asection *sect : gdb_bfd_sections (obfd))
834     {
835       gcore_copy_callback (obfd, sect);
836       gcore_copy_memtag_section_callback (obfd, sect);
837     }
838 
839   return 1;
840 }
841 
842 /* See gcore.h.  */
843 
844 thread_info *
gcore_find_signalled_thread()845 gcore_find_signalled_thread ()
846 {
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;
851 
852   for (thread_info *thr : current_inferior ()->non_exited_threads ())
853     if (thr->stop_signal () != GDB_SIGNAL_0)
854       return thr;
855 
856   /* Default to the current thread, unless it has exited.  */
857   if (curr_thr->state != THREAD_EXITED)
858     return curr_thr;
859 
860   return nullptr;
861 }
862 
863 void _initialize_gcore ();
864 void
_initialize_gcore()865 _initialize_gcore ()
866 {
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'."));
872 
873   add_com_alias ("gcore", generate_core_file_cmd, class_files, 1);
874 }
875