]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/symfile.c
[gdb/build] Add GPL header comment to gdb/features/feature_to_c.awk
[thirdparty/binutils-gdb.git] / gdb / symfile.c
1 /* Generic symbol file reading for the GNU debugger, GDB.
2
3 Copyright (C) 1990-2024 Free Software Foundation, Inc.
4
5 Contributed by Cygnus Support, using pieces from other GDB modules.
6
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21
22 #include "arch-utils.h"
23 #include "cli/cli-cmds.h"
24 #include "extract-store-integer.h"
25 #include "symtab.h"
26 #include "gdbcore.h"
27 #include "frame.h"
28 #include "target.h"
29 #include "value.h"
30 #include "symfile.h"
31 #include "objfiles.h"
32 #include "source.h"
33 #include "breakpoint.h"
34 #include "language.h"
35 #include "complaints.h"
36 #include "inferior.h"
37 #include "regcache.h"
38 #include "filenames.h"
39 #include "gdbsupport/gdb_obstack.h"
40 #include "completer.h"
41 #include "readline/tilde.h"
42 #include "block.h"
43 #include "observable.h"
44 #include "exec.h"
45 #include "varobj.h"
46 #include "solib.h"
47 #include "stack.h"
48 #include "gdb_bfd.h"
49 #include "cli/cli-utils.h"
50 #include "gdbsupport/byte-vector.h"
51 #include "gdbsupport/pathstuff.h"
52 #include "gdbsupport/selftest.h"
53 #include "cli/cli-style.h"
54 #include "gdbsupport/forward-scope-exit.h"
55 #include "gdbsupport/buildargv.h"
56
57 #include <sys/types.h>
58 #include <fcntl.h>
59 #include <sys/stat.h>
60 #include <ctype.h>
61 #include <chrono>
62 #include <algorithm>
63
64 int (*deprecated_ui_load_progress_hook) (const char *section,
65 unsigned long num);
66 void (*deprecated_show_load_progress) (const char *section,
67 unsigned long section_sent,
68 unsigned long section_size,
69 unsigned long total_sent,
70 unsigned long total_size);
71 void (*deprecated_pre_add_symbol_hook) (const char *);
72 void (*deprecated_post_add_symbol_hook) (void);
73
74 using clear_symtab_users_cleanup
75 = FORWARD_SCOPE_EXIT (clear_symtab_users);
76
77 /* Global variables owned by this file. */
78
79 /* See symfile.h. */
80
81 int readnow_symbol_files;
82
83 /* See symfile.h. */
84
85 int readnever_symbol_files;
86
87 /* Functions this file defines. */
88
89 static void symbol_file_add_main_1 (const char *args, symfile_add_flags add_flags,
90 objfile_flags flags, CORE_ADDR reloff);
91
92 static const struct sym_fns *find_sym_fns (bfd *);
93
94 static void overlay_invalidate_all (void);
95
96 static void simple_free_overlay_table (void);
97
98 static void read_target_long_array (CORE_ADDR, unsigned int *, int, int,
99 enum bfd_endian);
100
101 static int simple_read_overlay_table (void);
102
103 static int simple_overlay_update_1 (struct obj_section *);
104
105 static void symfile_find_segment_sections (struct objfile *objfile);
106
107 /* List of all available sym_fns. On gdb startup, each object file reader
108 calls add_symtab_fns() to register information on each format it is
109 prepared to read. */
110
111 struct registered_sym_fns
112 {
113 registered_sym_fns (bfd_flavour sym_flavour_, const struct sym_fns *sym_fns_)
114 : sym_flavour (sym_flavour_), sym_fns (sym_fns_)
115 {}
116
117 /* BFD flavour that we handle. */
118 enum bfd_flavour sym_flavour;
119
120 /* The "vtable" of symbol functions. */
121 const struct sym_fns *sym_fns;
122 };
123
124 static std::vector<registered_sym_fns> symtab_fns;
125
126 /* Values for "set print symbol-loading". */
127
128 const char print_symbol_loading_off[] = "off";
129 const char print_symbol_loading_brief[] = "brief";
130 const char print_symbol_loading_full[] = "full";
131 static const char *print_symbol_loading_enums[] =
132 {
133 print_symbol_loading_off,
134 print_symbol_loading_brief,
135 print_symbol_loading_full,
136 NULL
137 };
138 static const char *print_symbol_loading = print_symbol_loading_full;
139
140 /* See symfile.h. */
141
142 bool auto_solib_add = true;
143 \f
144
145 /* Return non-zero if symbol-loading messages should be printed.
146 FROM_TTY is the standard from_tty argument to gdb commands.
147 If EXEC is non-zero the messages are for the executable.
148 Otherwise, messages are for shared libraries.
149 If FULL is non-zero then the caller is printing a detailed message.
150 E.g., the message includes the shared library name.
151 Otherwise, the caller is printing a brief "summary" message. */
152
153 int
154 print_symbol_loading_p (int from_tty, int exec, int full)
155 {
156 if (!from_tty && !info_verbose)
157 return 0;
158
159 if (exec)
160 {
161 /* We don't check FULL for executables, there are few such
162 messages, therefore brief == full. */
163 return print_symbol_loading != print_symbol_loading_off;
164 }
165 if (full)
166 return print_symbol_loading == print_symbol_loading_full;
167 return print_symbol_loading == print_symbol_loading_brief;
168 }
169
170 /* True if we are reading a symbol table. */
171
172 int currently_reading_symtab = 0;
173
174 /* Increment currently_reading_symtab and return a cleanup that can be
175 used to decrement it. */
176
177 scoped_restore_tmpl<int>
178 increment_reading_symtab (void)
179 {
180 gdb_assert (currently_reading_symtab >= 0);
181 return make_scoped_restore (&currently_reading_symtab,
182 currently_reading_symtab + 1);
183 }
184
185 /* Remember the lowest-addressed loadable section we've seen.
186
187 In case of equal vmas, the section with the largest size becomes the
188 lowest-addressed loadable section.
189
190 If the vmas and sizes are equal, the last section is considered the
191 lowest-addressed loadable section. */
192
193 static void
194 find_lowest_section (asection *sect, asection **lowest)
195 {
196 if (0 == (bfd_section_flags (sect) & (SEC_ALLOC | SEC_LOAD)))
197 return;
198 if (!*lowest)
199 *lowest = sect; /* First loadable section */
200 else if (bfd_section_vma (*lowest) > bfd_section_vma (sect))
201 *lowest = sect; /* A lower loadable section */
202 else if (bfd_section_vma (*lowest) == bfd_section_vma (sect)
203 && (bfd_section_size (*lowest) <= bfd_section_size (sect)))
204 *lowest = sect;
205 }
206
207 /* Build (allocate and populate) a section_addr_info struct from
208 an existing section table. */
209
210 section_addr_info
211 build_section_addr_info_from_section_table (const std::vector<target_section> &table)
212 {
213 section_addr_info sap;
214
215 for (const target_section &stp : table)
216 {
217 struct bfd_section *asect = stp.the_bfd_section;
218 bfd *abfd = asect->owner;
219
220 if (bfd_section_flags (asect) & (SEC_ALLOC | SEC_LOAD)
221 && sap.size () < table.size ())
222 sap.emplace_back (stp.addr,
223 bfd_section_name (asect),
224 gdb_bfd_section_index (abfd, asect));
225 }
226
227 return sap;
228 }
229
230 /* Create a section_addr_info from section offsets in ABFD. */
231
232 static section_addr_info
233 build_section_addr_info_from_bfd (bfd *abfd)
234 {
235 struct bfd_section *sec;
236
237 section_addr_info sap;
238 for (sec = abfd->sections; sec != NULL; sec = sec->next)
239 if (bfd_section_flags (sec) & (SEC_ALLOC | SEC_LOAD))
240 sap.emplace_back (bfd_section_vma (sec),
241 bfd_section_name (sec),
242 gdb_bfd_section_index (abfd, sec));
243
244 return sap;
245 }
246
247 /* Create a section_addr_info from section offsets in OBJFILE. */
248
249 section_addr_info
250 build_section_addr_info_from_objfile (const struct objfile *objfile)
251 {
252 int i;
253
254 /* Before reread_symbols gets rewritten it is not safe to call:
255 gdb_assert (objfile->num_sections == bfd_count_sections (objfile->obfd));
256 */
257 section_addr_info sap
258 = build_section_addr_info_from_bfd (objfile->obfd.get ());
259 for (i = 0; i < sap.size (); i++)
260 {
261 int sectindex = sap[i].sectindex;
262
263 sap[i].addr += objfile->section_offsets[sectindex];
264 }
265 return sap;
266 }
267
268 /* Initialize OBJFILE's sect_index_* members. */
269
270 static void
271 init_objfile_sect_indices (struct objfile *objfile)
272 {
273 asection *sect;
274 int i;
275
276 sect = bfd_get_section_by_name (objfile->obfd.get (), ".text");
277 if (sect)
278 objfile->sect_index_text = sect->index;
279
280 sect = bfd_get_section_by_name (objfile->obfd.get (), ".data");
281 if (sect)
282 objfile->sect_index_data = sect->index;
283
284 sect = bfd_get_section_by_name (objfile->obfd.get (), ".bss");
285 if (sect)
286 objfile->sect_index_bss = sect->index;
287
288 sect = bfd_get_section_by_name (objfile->obfd.get (), ".rodata");
289 if (sect)
290 objfile->sect_index_rodata = sect->index;
291
292 /* This is where things get really weird... We MUST have valid
293 indices for the various sect_index_* members or gdb will abort.
294 So if for example, there is no ".text" section, we have to
295 accommodate that. First, check for a file with the standard
296 one or two segments. */
297
298 symfile_find_segment_sections (objfile);
299
300 /* Except when explicitly adding symbol files at some address,
301 section_offsets contains nothing but zeros, so it doesn't matter
302 which slot in section_offsets the individual sect_index_* members
303 index into. So if they are all zero, it is safe to just point
304 all the currently uninitialized indices to the first slot. But
305 beware: if this is the main executable, it may be relocated
306 later, e.g. by the remote qOffsets packet, and then this will
307 be wrong! That's why we try segments first. */
308
309 for (i = 0; i < objfile->section_offsets.size (); i++)
310 {
311 if (objfile->section_offsets[i] != 0)
312 {
313 break;
314 }
315 }
316 if (i == objfile->section_offsets.size ())
317 {
318 if (objfile->sect_index_text == -1)
319 objfile->sect_index_text = 0;
320 if (objfile->sect_index_data == -1)
321 objfile->sect_index_data = 0;
322 if (objfile->sect_index_bss == -1)
323 objfile->sect_index_bss = 0;
324 if (objfile->sect_index_rodata == -1)
325 objfile->sect_index_rodata = 0;
326 }
327 }
328
329 /* Find a unique offset to use for loadable section SECT if
330 the user did not provide an offset. */
331
332 static void
333 place_section (bfd *abfd, asection *sect, section_offsets &offsets,
334 CORE_ADDR &lowest)
335 {
336 CORE_ADDR start_addr;
337 int done;
338 ULONGEST align = ((ULONGEST) 1) << bfd_section_alignment (sect);
339
340 /* We are only interested in allocated sections. */
341 if ((bfd_section_flags (sect) & SEC_ALLOC) == 0)
342 return;
343
344 /* If the user specified an offset, honor it. */
345 if (offsets[gdb_bfd_section_index (abfd, sect)] != 0)
346 return;
347
348 /* Otherwise, let's try to find a place for the section. */
349 start_addr = (lowest + align - 1) & -align;
350
351 do {
352 asection *cur_sec;
353
354 done = 1;
355
356 for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
357 {
358 int indx = cur_sec->index;
359
360 /* We don't need to compare against ourself. */
361 if (cur_sec == sect)
362 continue;
363
364 /* We can only conflict with allocated sections. */
365 if ((bfd_section_flags (cur_sec) & SEC_ALLOC) == 0)
366 continue;
367
368 /* If the section offset is 0, either the section has not been placed
369 yet, or it was the lowest section placed (in which case LOWEST
370 will be past its end). */
371 if (offsets[indx] == 0)
372 continue;
373
374 /* If this section would overlap us, then we must move up. */
375 if (start_addr + bfd_section_size (sect) > offsets[indx]
376 && start_addr < offsets[indx] + bfd_section_size (cur_sec))
377 {
378 start_addr = offsets[indx] + bfd_section_size (cur_sec);
379 start_addr = (start_addr + align - 1) & -align;
380 done = 0;
381 break;
382 }
383
384 /* Otherwise, we appear to be OK. So far. */
385 }
386 }
387 while (!done);
388
389 offsets[gdb_bfd_section_index (abfd, sect)] = start_addr;
390 lowest = start_addr + bfd_section_size (sect);
391 }
392
393 /* Store section_addr_info as prepared (made relative and with SECTINDEX
394 filled-in) by addr_info_make_relative into SECTION_OFFSETS. */
395
396 void
397 relative_addr_info_to_section_offsets (section_offsets &section_offsets,
398 const section_addr_info &addrs)
399 {
400 int i;
401
402 section_offsets.assign (section_offsets.size (), 0);
403
404 /* Now calculate offsets for section that were specified by the caller. */
405 for (i = 0; i < addrs.size (); i++)
406 {
407 const struct other_sections *osp;
408
409 osp = &addrs[i];
410 if (osp->sectindex == -1)
411 continue;
412
413 /* Record all sections in offsets. */
414 /* The section_offsets in the objfile are here filled in using
415 the BFD index. */
416 section_offsets[osp->sectindex] = osp->addr;
417 }
418 }
419
420 /* Transform section name S for a name comparison. prelink can split section
421 `.bss' into two sections `.dynbss' and `.bss' (in this order). Similarly
422 prelink can split `.sbss' into `.sdynbss' and `.sbss'. Use virtual address
423 of the new `.dynbss' (`.sdynbss') section as the adjacent new `.bss'
424 (`.sbss') section has invalid (increased) virtual address. */
425
426 static const char *
427 addr_section_name (const char *s)
428 {
429 if (strcmp (s, ".dynbss") == 0)
430 return ".bss";
431 if (strcmp (s, ".sdynbss") == 0)
432 return ".sbss";
433
434 return s;
435 }
436
437 /* std::sort comparator for addrs_section_sort. Sort entries in
438 ascending order by their (name, sectindex) pair. sectindex makes
439 the sort by name stable. */
440
441 static bool
442 addrs_section_compar (const struct other_sections *a,
443 const struct other_sections *b)
444 {
445 int retval;
446
447 retval = strcmp (addr_section_name (a->name.c_str ()),
448 addr_section_name (b->name.c_str ()));
449 if (retval != 0)
450 return retval < 0;
451
452 return a->sectindex < b->sectindex;
453 }
454
455 /* Provide sorted array of pointers to sections of ADDRS. */
456
457 static std::vector<const struct other_sections *>
458 addrs_section_sort (const section_addr_info &addrs)
459 {
460 int i;
461
462 std::vector<const struct other_sections *> array (addrs.size ());
463 for (i = 0; i < addrs.size (); i++)
464 array[i] = &addrs[i];
465
466 std::sort (array.begin (), array.end (), addrs_section_compar);
467
468 return array;
469 }
470
471 /* Relativize absolute addresses in ADDRS into offsets based on ABFD. Fill-in
472 also SECTINDEXes specific to ABFD there. This function can be used to
473 rebase ADDRS to start referencing different BFD than before. */
474
475 void
476 addr_info_make_relative (section_addr_info *addrs, bfd *abfd)
477 {
478 asection *lower_sect;
479 CORE_ADDR lower_offset;
480 int i;
481
482 /* Find lowest loadable section to be used as starting point for
483 contiguous sections. */
484 lower_sect = NULL;
485 for (asection *iter : gdb_bfd_sections (abfd))
486 find_lowest_section (iter, &lower_sect);
487 if (lower_sect == NULL)
488 {
489 warning (_("no loadable sections found in added symbol-file %s"),
490 bfd_get_filename (abfd));
491 lower_offset = 0;
492 }
493 else
494 lower_offset = bfd_section_vma (lower_sect);
495
496 /* Create ADDRS_TO_ABFD_ADDRS array to map the sections in ADDRS to sections
497 in ABFD. Section names are not unique - there can be multiple sections of
498 the same name. Also the sections of the same name do not have to be
499 adjacent to each other. Some sections may be present only in one of the
500 files. Even sections present in both files do not have to be in the same
501 order.
502
503 Use stable sort by name for the sections in both files. Then linearly
504 scan both lists matching as most of the entries as possible. */
505
506 std::vector<const struct other_sections *> addrs_sorted
507 = addrs_section_sort (*addrs);
508
509 section_addr_info abfd_addrs = build_section_addr_info_from_bfd (abfd);
510 std::vector<const struct other_sections *> abfd_addrs_sorted
511 = addrs_section_sort (abfd_addrs);
512
513 /* Now create ADDRS_TO_ABFD_ADDRS from ADDRS_SORTED and
514 ABFD_ADDRS_SORTED. */
515
516 std::vector<const struct other_sections *>
517 addrs_to_abfd_addrs (addrs->size (), nullptr);
518
519 std::vector<const struct other_sections *>::iterator abfd_sorted_iter
520 = abfd_addrs_sorted.begin ();
521 for (const other_sections *sect : addrs_sorted)
522 {
523 const char *sect_name = addr_section_name (sect->name.c_str ());
524
525 while (abfd_sorted_iter != abfd_addrs_sorted.end ()
526 && strcmp (addr_section_name ((*abfd_sorted_iter)->name.c_str ()),
527 sect_name) < 0)
528 abfd_sorted_iter++;
529
530 if (abfd_sorted_iter != abfd_addrs_sorted.end ()
531 && strcmp (addr_section_name ((*abfd_sorted_iter)->name.c_str ()),
532 sect_name) == 0)
533 {
534 int index_in_addrs;
535
536 /* Make the found item directly addressable from ADDRS. */
537 index_in_addrs = sect - addrs->data ();
538 gdb_assert (addrs_to_abfd_addrs[index_in_addrs] == NULL);
539 addrs_to_abfd_addrs[index_in_addrs] = *abfd_sorted_iter;
540
541 /* Never use the same ABFD entry twice. */
542 abfd_sorted_iter++;
543 }
544 }
545
546 /* Calculate offsets for the loadable sections.
547 FIXME! Sections must be in order of increasing loadable section
548 so that contiguous sections can use the lower-offset!!!
549
550 Adjust offsets if the segments are not contiguous.
551 If the section is contiguous, its offset should be set to
552 the offset of the highest loadable section lower than it
553 (the loadable section directly below it in memory).
554 this_offset = lower_offset = lower_addr - lower_orig_addr */
555
556 for (i = 0; i < addrs->size (); i++)
557 {
558 const struct other_sections *sect = addrs_to_abfd_addrs[i];
559
560 if (sect)
561 {
562 /* This is the index used by BFD. */
563 (*addrs)[i].sectindex = sect->sectindex;
564
565 if ((*addrs)[i].addr != 0)
566 {
567 (*addrs)[i].addr -= sect->addr;
568 lower_offset = (*addrs)[i].addr;
569 }
570 else
571 (*addrs)[i].addr = lower_offset;
572 }
573 else
574 {
575 /* addr_section_name transformation is not used for SECT_NAME. */
576 const std::string &sect_name = (*addrs)[i].name;
577
578 /* This section does not exist in ABFD, which is normally
579 unexpected and we want to issue a warning.
580
581 However, the ELF prelinker does create a few sections which are
582 marked in the main executable as loadable (they are loaded in
583 memory from the DYNAMIC segment) and yet are not present in
584 separate debug info files. This is fine, and should not cause
585 a warning. Shared libraries contain just the section
586 ".gnu.liblist" but it is not marked as loadable there. There is
587 no other way to identify them than by their name as the sections
588 created by prelink have no special flags.
589
590 For the sections `.bss' and `.sbss' see addr_section_name. */
591
592 if (!(sect_name == ".gnu.liblist"
593 || sect_name == ".gnu.conflict"
594 || (sect_name == ".bss"
595 && i > 0
596 && (*addrs)[i - 1].name == ".dynbss"
597 && addrs_to_abfd_addrs[i - 1] != NULL)
598 || (sect_name == ".sbss"
599 && i > 0
600 && (*addrs)[i - 1].name == ".sdynbss"
601 && addrs_to_abfd_addrs[i - 1] != NULL)))
602 warning (_("section %s not found in %s"), sect_name.c_str (),
603 bfd_get_filename (abfd));
604
605 (*addrs)[i].addr = 0;
606 (*addrs)[i].sectindex = -1;
607 }
608 }
609 }
610
611 /* Parse the user's idea of an offset for dynamic linking, into our idea
612 of how to represent it for fast symbol reading. This is the default
613 version of the sym_fns.sym_offsets function for symbol readers that
614 don't need to do anything special. It allocates a section_offsets table
615 for the objectfile OBJFILE and stuffs ADDR into all of the offsets. */
616
617 void
618 default_symfile_offsets (struct objfile *objfile,
619 const section_addr_info &addrs)
620 {
621 objfile->section_offsets.resize (gdb_bfd_count_sections (objfile->obfd.get ()));
622 relative_addr_info_to_section_offsets (objfile->section_offsets, addrs);
623
624 /* For relocatable files, all loadable sections will start at zero.
625 The zero is meaningless, so try to pick arbitrary addresses such
626 that no loadable sections overlap. This algorithm is quadratic,
627 but the number of sections in a single object file is generally
628 small. */
629 if ((bfd_get_file_flags (objfile->obfd.get ()) & (EXEC_P | DYNAMIC)) == 0)
630 {
631 bfd *abfd = objfile->obfd.get ();
632 asection *cur_sec;
633
634 for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
635 /* We do not expect this to happen; just skip this step if the
636 relocatable file has a section with an assigned VMA. */
637 if (bfd_section_vma (cur_sec) != 0)
638 break;
639
640 if (cur_sec == NULL)
641 {
642 section_offsets &offsets = objfile->section_offsets;
643
644 /* Pick non-overlapping offsets for sections the user did not
645 place explicitly. */
646 CORE_ADDR lowest = 0;
647 for (asection *sect : gdb_bfd_sections (objfile->obfd.get ()))
648 place_section (objfile->obfd.get (), sect, objfile->section_offsets,
649 lowest);
650
651 /* Correctly filling in the section offsets is not quite
652 enough. Relocatable files have two properties that
653 (most) shared objects do not:
654
655 - Their debug information will contain relocations. Some
656 shared libraries do also, but many do not, so this can not
657 be assumed.
658
659 - If there are multiple code sections they will be loaded
660 at different relative addresses in memory than they are
661 in the objfile, since all sections in the file will start
662 at address zero.
663
664 Because GDB has very limited ability to map from an
665 address in debug info to the correct code section,
666 it relies on adding SECT_OFF_TEXT to things which might be
667 code. If we clear all the section offsets, and set the
668 section VMAs instead, then symfile_relocate_debug_section
669 will return meaningful debug information pointing at the
670 correct sections.
671
672 GDB has too many different data structures for section
673 addresses - a bfd, objfile, and so_list all have section
674 tables, as does exec_ops. Some of these could probably
675 be eliminated. */
676
677 for (cur_sec = abfd->sections; cur_sec != NULL;
678 cur_sec = cur_sec->next)
679 {
680 if ((bfd_section_flags (cur_sec) & SEC_ALLOC) == 0)
681 continue;
682
683 bfd_set_section_vma (cur_sec, offsets[cur_sec->index]);
684 exec_set_section_address (bfd_get_filename (abfd),
685 cur_sec->index,
686 offsets[cur_sec->index]);
687 offsets[cur_sec->index] = 0;
688 }
689 }
690 }
691
692 /* Remember the bfd indexes for the .text, .data, .bss and
693 .rodata sections. */
694 init_objfile_sect_indices (objfile);
695 }
696
697 /* Divide the file into segments, which are individual relocatable units.
698 This is the default version of the sym_fns.sym_segments function for
699 symbol readers that do not have an explicit representation of segments.
700 It assumes that object files do not have segments, and fully linked
701 files have a single segment. */
702
703 symfile_segment_data_up
704 default_symfile_segments (bfd *abfd)
705 {
706 int num_sections, i;
707 asection *sect;
708 CORE_ADDR low, high;
709
710 /* Relocatable files contain enough information to position each
711 loadable section independently; they should not be relocated
712 in segments. */
713 if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) == 0)
714 return NULL;
715
716 /* Make sure there is at least one loadable section in the file. */
717 for (sect = abfd->sections; sect != NULL; sect = sect->next)
718 {
719 if ((bfd_section_flags (sect) & SEC_ALLOC) == 0)
720 continue;
721
722 break;
723 }
724 if (sect == NULL)
725 return NULL;
726
727 low = bfd_section_vma (sect);
728 high = low + bfd_section_size (sect);
729
730 symfile_segment_data_up data (new symfile_segment_data);
731
732 num_sections = bfd_count_sections (abfd);
733
734 /* All elements are initialized to 0 (map to no segment). */
735 data->segment_info.resize (num_sections);
736
737 for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
738 {
739 CORE_ADDR vma;
740
741 if ((bfd_section_flags (sect) & SEC_ALLOC) == 0)
742 continue;
743
744 vma = bfd_section_vma (sect);
745 if (vma < low)
746 low = vma;
747 if (vma + bfd_section_size (sect) > high)
748 high = vma + bfd_section_size (sect);
749
750 data->segment_info[i] = 1;
751 }
752
753 data->segments.emplace_back (low, high - low);
754
755 return data;
756 }
757
758 /* This is a convenience function to call sym_read for OBJFILE and
759 possibly force the partial symbols to be read. */
760
761 static void
762 read_symbols (struct objfile *objfile, symfile_add_flags add_flags)
763 {
764 (*objfile->sf->sym_read) (objfile, add_flags);
765 objfile->per_bfd->minsyms_read = true;
766
767 /* find_separate_debug_file_in_section should be called only if there is
768 single binary with no existing separate debug info file. */
769 if (!objfile->has_partial_symbols ()
770 && objfile->separate_debug_objfile == NULL
771 && objfile->separate_debug_objfile_backlink == NULL)
772 {
773 gdb_bfd_ref_ptr abfd (find_separate_debug_file_in_section (objfile));
774
775 if (abfd != NULL)
776 {
777 /* find_separate_debug_file_in_section uses the same filename for the
778 virtual section-as-bfd like the bfd filename containing the
779 section. Therefore use also non-canonical name form for the same
780 file containing the section. */
781 symbol_file_add_separate (abfd, bfd_get_filename (abfd.get ()),
782 add_flags | SYMFILE_NOT_FILENAME, objfile);
783 }
784 }
785 }
786
787 /* Initialize entry point information for this objfile. */
788
789 static void
790 init_entry_point_info (struct objfile *objfile)
791 {
792 struct entry_info *ei = &objfile->per_bfd->ei;
793
794 if (ei->initialized)
795 return;
796 ei->initialized = 1;
797
798 /* Save startup file's range of PC addresses to help blockframe.c
799 decide where the bottom of the stack is. */
800
801 if (bfd_get_file_flags (objfile->obfd.get ()) & EXEC_P)
802 {
803 /* Executable file -- record its entry point so we'll recognize
804 the startup file because it contains the entry point. */
805 ei->entry_point = bfd_get_start_address (objfile->obfd.get ());
806 ei->entry_point_p = 1;
807 }
808 else if (bfd_get_file_flags (objfile->obfd.get ()) & DYNAMIC
809 && bfd_get_start_address (objfile->obfd.get ()) != 0)
810 {
811 /* Some shared libraries may have entry points set and be
812 runnable. There's no clear way to indicate this, so just check
813 for values other than zero. */
814 ei->entry_point = bfd_get_start_address (objfile->obfd.get ());
815 ei->entry_point_p = 1;
816 }
817 else
818 {
819 /* Examination of non-executable.o files. Short-circuit this stuff. */
820 ei->entry_point_p = 0;
821 }
822
823 if (ei->entry_point_p)
824 {
825 CORE_ADDR entry_point = ei->entry_point;
826 int found;
827
828 /* Make certain that the address points at real code, and not a
829 function descriptor. */
830 entry_point = gdbarch_convert_from_func_ptr_addr
831 (objfile->arch (), entry_point, current_inferior ()->top_target ());
832
833 /* Remove any ISA markers, so that this matches entries in the
834 symbol table. */
835 ei->entry_point
836 = gdbarch_addr_bits_remove (objfile->arch (), entry_point);
837
838 found = 0;
839 for (obj_section *osect : objfile->sections ())
840 {
841 struct bfd_section *sect = osect->the_bfd_section;
842
843 if (entry_point >= bfd_section_vma (sect)
844 && entry_point < (bfd_section_vma (sect)
845 + bfd_section_size (sect)))
846 {
847 ei->the_bfd_section_index
848 = gdb_bfd_section_index (objfile->obfd.get (), sect);
849 found = 1;
850 break;
851 }
852 }
853
854 if (!found)
855 ei->the_bfd_section_index = SECT_OFF_TEXT (objfile);
856 }
857 }
858
859 /* Process a symbol file, as either the main file or as a dynamically
860 loaded file.
861
862 This function does not set the OBJFILE's entry-point info.
863
864 OBJFILE is where the symbols are to be read from.
865
866 ADDRS is the list of section load addresses. If the user has given
867 an 'add-symbol-file' command, then this is the list of offsets and
868 addresses he or she provided as arguments to the command; or, if
869 we're handling a shared library, these are the actual addresses the
870 sections are loaded at, according to the inferior's dynamic linker
871 (as gleaned by GDB's shared library code). We convert each address
872 into an offset from the section VMA's as it appears in the object
873 file, and then call the file's sym_offsets function to convert this
874 into a format-specific offset table --- a `section_offsets'.
875 The sectindex field is used to control the ordering of sections
876 with the same name. Upon return, it is updated to contain the
877 corresponding BFD section index, or -1 if the section was not found.
878
879 ADD_FLAGS encodes verbosity level, whether this is main symbol or
880 an extra symbol file such as dynamically loaded code, and whether
881 breakpoint reset should be deferred. */
882
883 static void
884 syms_from_objfile_1 (struct objfile *objfile,
885 section_addr_info *addrs,
886 symfile_add_flags add_flags)
887 {
888 section_addr_info local_addr;
889 const int mainline = add_flags & SYMFILE_MAINLINE;
890
891 objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd.get ()));
892 objfile->qf.clear ();
893
894 if (objfile->sf == NULL)
895 {
896 /* No symbols to load, but we still need to make sure
897 that the section_offsets table is allocated. */
898 int num_sections = gdb_bfd_count_sections (objfile->obfd.get ());
899
900 objfile->section_offsets.assign (num_sections, 0);
901 return;
902 }
903
904 /* Make sure that partially constructed symbol tables will be cleaned up
905 if an error occurs during symbol reading. */
906 std::optional<clear_symtab_users_cleanup> defer_clear_users;
907
908 objfile_up objfile_holder (objfile);
909
910 /* If ADDRS is NULL, put together a dummy address list.
911 We now establish the convention that an addr of zero means
912 no load address was specified. */
913 if (! addrs)
914 addrs = &local_addr;
915
916 if (mainline)
917 {
918 /* We will modify the main symbol table, make sure that all its users
919 will be cleaned up if an error occurs during symbol reading. */
920 defer_clear_users.emplace ((symfile_add_flag) 0);
921
922 /* Since no error yet, throw away the old symbol table. */
923
924 if (current_program_space->symfile_object_file != NULL)
925 {
926 current_program_space->symfile_object_file->unlink ();
927 gdb_assert (current_program_space->symfile_object_file == NULL);
928 }
929
930 /* Currently we keep symbols from the add-symbol-file command.
931 If the user wants to get rid of them, they should do "symbol-file"
932 without arguments first. Not sure this is the best behavior
933 (PR 2207). */
934
935 (*objfile->sf->sym_new_init) (objfile);
936 }
937
938 /* Convert addr into an offset rather than an absolute address.
939 We find the lowest address of a loaded segment in the objfile,
940 and assume that <addr> is where that got loaded.
941
942 We no longer warn if the lowest section is not a text segment (as
943 happens for the PA64 port. */
944 if (addrs->size () > 0)
945 addr_info_make_relative (addrs, objfile->obfd.get ());
946
947 /* Initialize symbol reading routines for this objfile, allow complaints to
948 appear for this new file, and record how verbose to be, then do the
949 initial symbol reading for this file. */
950
951 (*objfile->sf->sym_init) (objfile);
952 clear_complaints ();
953
954 (*objfile->sf->sym_offsets) (objfile, *addrs);
955
956 read_symbols (objfile, add_flags);
957
958 /* Discard cleanups as symbol reading was successful. */
959
960 objfile_holder.release ();
961 if (defer_clear_users)
962 defer_clear_users->release ();
963 }
964
965 /* Same as syms_from_objfile_1, but also initializes the objfile
966 entry-point info. */
967
968 static void
969 syms_from_objfile (struct objfile *objfile,
970 section_addr_info *addrs,
971 symfile_add_flags add_flags)
972 {
973 syms_from_objfile_1 (objfile, addrs, add_flags);
974 init_entry_point_info (objfile);
975 }
976
977 /* Perform required actions after either reading in the initial
978 symbols for a new objfile, or mapping in the symbols from a reusable
979 objfile. ADD_FLAGS is a bitmask of enum symfile_add_flags. */
980
981 static void
982 finish_new_objfile (struct objfile *objfile, symfile_add_flags add_flags)
983 {
984 /* If this is the main symbol file we have to clean up all users of the
985 old main symbol file. Otherwise it is sufficient to fixup all the
986 breakpoints that may have been redefined by this symbol file. */
987 if (add_flags & SYMFILE_MAINLINE)
988 {
989 /* OK, make it the "real" symbol file. */
990 current_program_space->symfile_object_file = objfile;
991
992 clear_symtab_users (add_flags);
993 }
994 else if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
995 {
996 breakpoint_re_set ();
997 }
998
999 /* We're done reading the symbol file; finish off complaints. */
1000 clear_complaints ();
1001 }
1002
1003 /* Process a symbol file, as either the main file or as a dynamically
1004 loaded file.
1005
1006 ABFD is a BFD already open on the file, as from symfile_bfd_open.
1007 A new reference is acquired by this function.
1008
1009 For NAME description see the objfile constructor.
1010
1011 ADD_FLAGS encodes verbosity, whether this is main symbol file or
1012 extra, such as dynamically loaded code, and what to do with breakpoints.
1013
1014 ADDRS is as described for syms_from_objfile_1, above.
1015 ADDRS is ignored when SYMFILE_MAINLINE bit is set in ADD_FLAGS.
1016
1017 PARENT is the original objfile if ABFD is a separate debug info file.
1018 Otherwise PARENT is NULL.
1019
1020 Upon success, returns a pointer to the objfile that was added.
1021 Upon failure, jumps back to command level (never returns). */
1022
1023 static struct objfile *
1024 symbol_file_add_with_addrs (const gdb_bfd_ref_ptr &abfd, const char *name,
1025 symfile_add_flags add_flags,
1026 section_addr_info *addrs,
1027 objfile_flags flags, struct objfile *parent)
1028 {
1029 struct objfile *objfile;
1030 const int from_tty = add_flags & SYMFILE_VERBOSE;
1031 const int mainline = add_flags & SYMFILE_MAINLINE;
1032 const int always_confirm = add_flags & SYMFILE_ALWAYS_CONFIRM;
1033 const int should_print = (print_symbol_loading_p (from_tty, mainline, 1)
1034 && (readnow_symbol_files
1035 || (add_flags & SYMFILE_NO_READ) == 0));
1036
1037 if (readnow_symbol_files)
1038 {
1039 flags |= OBJF_READNOW;
1040 add_flags &= ~SYMFILE_NO_READ;
1041 }
1042 else if (readnever_symbol_files
1043 || (parent != NULL && (parent->flags & OBJF_READNEVER)))
1044 {
1045 flags |= OBJF_READNEVER;
1046 add_flags |= SYMFILE_NO_READ;
1047 }
1048 if ((add_flags & SYMFILE_NOT_FILENAME) != 0)
1049 flags |= OBJF_NOT_FILENAME;
1050
1051 /* Give user a chance to burp if ALWAYS_CONFIRM or we'd be
1052 interactively wiping out any existing symbols. */
1053
1054 if (from_tty
1055 && (always_confirm
1056 || ((have_full_symbols () || have_partial_symbols ())
1057 && mainline))
1058 && !query (_("Load new symbol table from \"%s\"? "), name))
1059 error (_("Not confirmed."));
1060
1061 if (mainline)
1062 flags |= OBJF_MAINLINE;
1063 objfile = objfile::make (abfd, name, flags, parent);
1064
1065 /* We either created a new mapped symbol table, mapped an existing
1066 symbol table file which has not had initial symbol reading
1067 performed, or need to read an unmapped symbol table. */
1068 if (should_print)
1069 {
1070 if (deprecated_pre_add_symbol_hook)
1071 deprecated_pre_add_symbol_hook (name);
1072 else
1073 gdb_printf (_("Reading symbols from %ps...\n"),
1074 styled_string (file_name_style.style (), name));
1075 }
1076 syms_from_objfile (objfile, addrs, add_flags);
1077
1078 /* We now have at least a partial symbol table. Check to see if the
1079 user requested that all symbols be read on initial access via either
1080 the gdb startup command line or on a per symbol file basis. Expand
1081 all partial symbol tables for this objfile if so. */
1082
1083 if ((flags & OBJF_READNOW))
1084 {
1085 if (should_print)
1086 gdb_printf (_("Expanding full symbols from %ps...\n"),
1087 styled_string (file_name_style.style (), name));
1088
1089 objfile->expand_all_symtabs ();
1090 }
1091
1092 /* Note that we only print a message if we have no symbols and have
1093 no separate debug file. If there is a separate debug file which
1094 does not have symbols, we'll have emitted this message for that
1095 file, and so printing it twice is just redundant. */
1096 if (should_print && !objfile_has_symbols (objfile)
1097 && objfile->separate_debug_objfile == nullptr)
1098 gdb_printf (_("(No debugging symbols found in %ps)\n"),
1099 styled_string (file_name_style.style (), name));
1100
1101 if (should_print)
1102 {
1103 if (deprecated_post_add_symbol_hook)
1104 deprecated_post_add_symbol_hook ();
1105 }
1106
1107 /* We print some messages regardless of whether 'from_tty ||
1108 info_verbose' is true, so make sure they go out at the right
1109 time. */
1110 gdb_flush (gdb_stdout);
1111
1112 if (objfile->sf != nullptr)
1113 finish_new_objfile (objfile, add_flags);
1114
1115 gdb::observers::new_objfile.notify (objfile);
1116
1117 return objfile;
1118 }
1119
1120 /* Add BFD as a separate debug file for OBJFILE. For NAME description
1121 see the objfile constructor. */
1122
1123 void
1124 symbol_file_add_separate (const gdb_bfd_ref_ptr &bfd, const char *name,
1125 symfile_add_flags symfile_flags,
1126 struct objfile *objfile)
1127 {
1128 /* Create section_addr_info. We can't directly use offsets from OBJFILE
1129 because sections of BFD may not match sections of OBJFILE and because
1130 vma may have been modified by tools such as prelink. */
1131 section_addr_info sap = build_section_addr_info_from_objfile (objfile);
1132
1133 symbol_file_add_with_addrs
1134 (bfd, name, symfile_flags, &sap,
1135 objfile->flags & (OBJF_SHARED | OBJF_READNOW
1136 | OBJF_USERLOADED | OBJF_MAINLINE),
1137 objfile);
1138 }
1139
1140 /* Process the symbol file ABFD, as either the main file or as a
1141 dynamically loaded file.
1142 See symbol_file_add_with_addrs's comments for details. */
1143
1144 struct objfile *
1145 symbol_file_add_from_bfd (const gdb_bfd_ref_ptr &abfd, const char *name,
1146 symfile_add_flags add_flags,
1147 section_addr_info *addrs,
1148 objfile_flags flags, struct objfile *parent)
1149 {
1150 return symbol_file_add_with_addrs (abfd, name, add_flags, addrs, flags,
1151 parent);
1152 }
1153
1154 /* Process a symbol file, as either the main file or as a dynamically
1155 loaded file. See symbol_file_add_with_addrs's comments for details. */
1156
1157 struct objfile *
1158 symbol_file_add (const char *name, symfile_add_flags add_flags,
1159 section_addr_info *addrs, objfile_flags flags)
1160 {
1161 gdb_bfd_ref_ptr bfd (symfile_bfd_open (name));
1162
1163 return symbol_file_add_from_bfd (bfd, name, add_flags, addrs,
1164 flags, NULL);
1165 }
1166
1167 /* Call symbol_file_add() with default values and update whatever is
1168 affected by the loading of a new main().
1169 Used when the file is supplied in the gdb command line
1170 and by some targets with special loading requirements.
1171 The auxiliary function, symbol_file_add_main_1(), has the flags
1172 argument for the switches that can only be specified in the symbol_file
1173 command itself. */
1174
1175 void
1176 symbol_file_add_main (const char *args, symfile_add_flags add_flags)
1177 {
1178 symbol_file_add_main_1 (args, add_flags, 0, 0);
1179 }
1180
1181 static void
1182 symbol_file_add_main_1 (const char *args, symfile_add_flags add_flags,
1183 objfile_flags flags, CORE_ADDR reloff)
1184 {
1185 add_flags |= current_inferior ()->symfile_flags | SYMFILE_MAINLINE;
1186
1187 struct objfile *objfile = symbol_file_add (args, add_flags, NULL, flags);
1188 if (reloff != 0)
1189 objfile_rebase (objfile, reloff);
1190
1191 /* Getting new symbols may change our opinion about
1192 what is frameless. */
1193 reinit_frame_cache ();
1194
1195 if ((add_flags & SYMFILE_NO_READ) == 0)
1196 set_initial_language ();
1197 }
1198
1199 void
1200 symbol_file_clear (int from_tty)
1201 {
1202 if ((have_full_symbols () || have_partial_symbols ())
1203 && from_tty
1204 && (current_program_space->symfile_object_file
1205 ? !query (_("Discard symbol table from `%s'? "),
1206 objfile_name (current_program_space->symfile_object_file))
1207 : !query (_("Discard symbol table? "))))
1208 error (_("Not confirmed."));
1209
1210 /* solib descriptors may have handles to objfiles. Wipe them before their
1211 objfiles get stale by free_all_objfiles. */
1212 no_shared_libraries (NULL, from_tty);
1213
1214 current_program_space->free_all_objfiles ();
1215
1216 clear_symtab_users (0);
1217
1218 gdb_assert (current_program_space->symfile_object_file == NULL);
1219 if (from_tty)
1220 gdb_printf (_("No symbol file now.\n"));
1221 }
1222
1223 /* See symfile.h. */
1224
1225 bool separate_debug_file_debug = false;
1226
1227 static int
1228 separate_debug_file_exists (const std::string &name, unsigned long crc,
1229 struct objfile *parent_objfile,
1230 deferred_warnings *warnings)
1231 {
1232 SEPARATE_DEBUG_FILE_SCOPED_DEBUG_ENTER_EXIT;
1233
1234 unsigned long file_crc;
1235 int file_crc_p;
1236 struct stat parent_stat, abfd_stat;
1237 int verified_as_different;
1238
1239 /* Find a separate debug info file as if symbols would be present in
1240 PARENT_OBJFILE itself this function would not be called. .gnu_debuglink
1241 section can contain just the basename of PARENT_OBJFILE without any
1242 ".debug" suffix as "/usr/lib/debug/path/to/file" is a separate tree where
1243 the separate debug infos with the same basename can exist. */
1244
1245 if (filename_cmp (name.c_str (), objfile_name (parent_objfile)) == 0)
1246 return 0;
1247
1248 separate_debug_file_debug_printf ("Trying %s...", name.c_str ());
1249
1250 gdb_bfd_ref_ptr abfd (gdb_bfd_open (name.c_str (), gnutarget));
1251
1252 if (abfd == NULL)
1253 {
1254 separate_debug_file_debug_printf ("unable to open file");
1255 return 0;
1256 }
1257
1258 /* Verify symlinks were not the cause of filename_cmp name difference above.
1259
1260 Some operating systems, e.g. Windows, do not provide a meaningful
1261 st_ino; they always set it to zero. (Windows does provide a
1262 meaningful st_dev.) Files accessed from gdbservers that do not
1263 support the vFile:fstat packet will also have st_ino set to zero.
1264 Do not indicate a duplicate library in either case. While there
1265 is no guarantee that a system that provides meaningful inode
1266 numbers will never set st_ino to zero, this is merely an
1267 optimization, so we do not need to worry about false negatives. */
1268
1269 if (bfd_stat (abfd.get (), &abfd_stat) == 0
1270 && abfd_stat.st_ino != 0
1271 && bfd_stat (parent_objfile->obfd.get (), &parent_stat) == 0)
1272 {
1273 if (abfd_stat.st_dev == parent_stat.st_dev
1274 && abfd_stat.st_ino == parent_stat.st_ino)
1275 {
1276 separate_debug_file_debug_printf ("same file as the objfile");
1277 return 0;
1278 }
1279 verified_as_different = 1;
1280 }
1281 else
1282 verified_as_different = 0;
1283
1284 file_crc_p = gdb_bfd_crc (abfd.get (), &file_crc);
1285
1286 if (!file_crc_p)
1287 {
1288 separate_debug_file_debug_printf ("error computing CRC");
1289 return 0;
1290 }
1291
1292 if (crc != file_crc)
1293 {
1294 unsigned long parent_crc;
1295
1296 /* If the files could not be verified as different with
1297 bfd_stat then we need to calculate the parent's CRC
1298 to verify whether the files are different or not. */
1299
1300 if (!verified_as_different)
1301 {
1302 if (!gdb_bfd_crc (parent_objfile->obfd.get (), &parent_crc))
1303 {
1304 separate_debug_file_debug_printf ("error computing CRC");
1305 return 0;
1306 }
1307 }
1308
1309 if (verified_as_different || parent_crc != file_crc)
1310 {
1311 separate_debug_file_debug_printf
1312 ("the debug information found in \"%s\" does not match "
1313 "\"%s\" (CRC mismatch).", name.c_str (),
1314 objfile_name (parent_objfile));
1315
1316 warnings->warn (_("the debug information found in \"%ps\""
1317 " does not match \"%ps\" (CRC mismatch)."),
1318 styled_string (file_name_style.style (),
1319 name.c_str ()),
1320 styled_string (file_name_style.style (),
1321 objfile_name (parent_objfile)));
1322 }
1323
1324 return 0;
1325 }
1326
1327 separate_debug_file_debug_printf ("found a match");
1328
1329 return 1;
1330 }
1331
1332 std::string debug_file_directory;
1333 static void
1334 show_debug_file_directory (struct ui_file *file, int from_tty,
1335 struct cmd_list_element *c, const char *value)
1336 {
1337 gdb_printf (file,
1338 _("The directory where separate debug "
1339 "symbols are searched for is \"%s\".\n"),
1340 value);
1341 }
1342
1343 #if ! defined (DEBUG_SUBDIRECTORY)
1344 #define DEBUG_SUBDIRECTORY ".debug"
1345 #endif
1346
1347 /* Find a separate debuginfo file for OBJFILE, using DIR as the directory
1348 where the original file resides (may not be the same as
1349 dirname(objfile->name) due to symlinks), and DEBUGLINK as the file we are
1350 looking for. CANON_DIR is the "realpath" form of DIR.
1351 DIR must contain a trailing '/'.
1352 Returns the path of the file with separate debug info, or an empty
1353 string.
1354
1355 Any warnings generated as part of the lookup process are added to
1356 WARNINGS. If some other mechanism can be used to lookup the debug
1357 information then the warning will not be shown, however, if GDB fails to
1358 find suitable debug information using any approach, then any warnings
1359 will be printed. */
1360
1361 static std::string
1362 find_separate_debug_file (const char *dir,
1363 const char *canon_dir,
1364 const char *debuglink,
1365 unsigned long crc32, struct objfile *objfile,
1366 deferred_warnings *warnings)
1367 {
1368 SEPARATE_DEBUG_FILE_SCOPED_DEBUG_START_END
1369 ("looking for separate debug info (debug link) for %s",
1370 objfile_name (objfile));
1371
1372 /* First try in the same directory as the original file. */
1373 std::string debugfile = dir;
1374 debugfile += debuglink;
1375
1376 if (separate_debug_file_exists (debugfile, crc32, objfile, warnings))
1377 return debugfile;
1378
1379 /* Then try in the subdirectory named DEBUG_SUBDIRECTORY. */
1380 debugfile = dir;
1381 debugfile += DEBUG_SUBDIRECTORY;
1382 debugfile += "/";
1383 debugfile += debuglink;
1384
1385 if (separate_debug_file_exists (debugfile, crc32, objfile, warnings))
1386 return debugfile;
1387
1388 /* Then try in the global debugfile directories.
1389
1390 Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
1391 cause "/..." lookups. */
1392
1393 bool target_prefix = is_target_filename (dir);
1394 const char *dir_notarget
1395 = target_prefix ? dir + strlen (TARGET_SYSROOT_PREFIX) : dir;
1396 std::vector<gdb::unique_xmalloc_ptr<char>> debugdir_vec
1397 = dirnames_to_char_ptr_vec (debug_file_directory.c_str ());
1398 gdb::unique_xmalloc_ptr<char> canon_sysroot
1399 = gdb_realpath (gdb_sysroot.c_str ());
1400
1401 /* MS-Windows/MS-DOS don't allow colons in file names; we must
1402 convert the drive letter into a one-letter directory, so that the
1403 file name resulting from splicing below will be valid.
1404
1405 FIXME: The below only works when GDB runs on MS-Windows/MS-DOS.
1406 There are various remote-debugging scenarios where such a
1407 transformation of the drive letter might be required when GDB runs
1408 on a Posix host, see
1409
1410 https://sourceware.org/ml/gdb-patches/2019-04/msg00605.html
1411
1412 If some of those scenarios need to be supported, we will need to
1413 use a different condition for HAS_DRIVE_SPEC and a different macro
1414 instead of STRIP_DRIVE_SPEC, which work on Posix systems as well. */
1415 std::string drive;
1416 if (HAS_DRIVE_SPEC (dir_notarget))
1417 {
1418 drive = dir_notarget[0];
1419 dir_notarget = STRIP_DRIVE_SPEC (dir_notarget);
1420 }
1421
1422 for (const gdb::unique_xmalloc_ptr<char> &debugdir : debugdir_vec)
1423 {
1424 debugfile = target_prefix ? TARGET_SYSROOT_PREFIX : "";
1425 debugfile += debugdir;
1426 debugfile += "/";
1427 debugfile += drive;
1428 debugfile += dir_notarget;
1429 debugfile += debuglink;
1430
1431 if (separate_debug_file_exists (debugfile, crc32, objfile, warnings))
1432 return debugfile;
1433
1434 const char *base_path = NULL;
1435 if (canon_dir != NULL)
1436 {
1437 if (canon_sysroot.get () != NULL)
1438 base_path = child_path (canon_sysroot.get (), canon_dir);
1439 else
1440 base_path = child_path (gdb_sysroot.c_str (), canon_dir);
1441 }
1442 if (base_path != NULL)
1443 {
1444 /* If the file is in the sysroot, try using its base path in
1445 the global debugfile directory. */
1446 debugfile = target_prefix ? TARGET_SYSROOT_PREFIX : "";
1447 debugfile += debugdir;
1448 debugfile += "/";
1449 debugfile += base_path;
1450 debugfile += "/";
1451 debugfile += debuglink;
1452
1453 if (separate_debug_file_exists (debugfile, crc32, objfile, warnings))
1454 return debugfile;
1455
1456 /* If the file is in the sysroot, try using its base path in
1457 the sysroot's global debugfile directory. GDB_SYSROOT
1458 might refer to a target: path; we strip the "target:"
1459 prefix -- but if that would yield the empty string, we
1460 don't bother at all, because that would just give the
1461 same result as above. */
1462 if (gdb_sysroot != TARGET_SYSROOT_PREFIX)
1463 {
1464 debugfile = target_prefix ? TARGET_SYSROOT_PREFIX : "";
1465 if (is_target_filename (gdb_sysroot))
1466 {
1467 std::string root
1468 = gdb_sysroot.substr (strlen (TARGET_SYSROOT_PREFIX));
1469 gdb_assert (!root.empty ());
1470 debugfile += root;
1471 }
1472 else
1473 debugfile += gdb_sysroot;
1474 debugfile += debugdir;
1475 debugfile += "/";
1476 debugfile += base_path;
1477 debugfile += "/";
1478 debugfile += debuglink;
1479
1480 if (separate_debug_file_exists (debugfile, crc32, objfile,
1481 warnings))
1482 return debugfile;
1483 }
1484 }
1485 }
1486
1487 return std::string ();
1488 }
1489
1490 /* Modify PATH to contain only "[/]directory/" part of PATH.
1491 If there were no directory separators in PATH, PATH will be empty
1492 string on return. */
1493
1494 static void
1495 terminate_after_last_dir_separator (char *path)
1496 {
1497 int i;
1498
1499 /* Strip off the final filename part, leaving the directory name,
1500 followed by a slash. The directory can be relative or absolute. */
1501 for (i = strlen(path) - 1; i >= 0; i--)
1502 if (IS_DIR_SEPARATOR (path[i]))
1503 break;
1504
1505 /* If I is -1 then no directory is present there and DIR will be "". */
1506 path[i + 1] = '\0';
1507 }
1508
1509 /* See symtab.h. */
1510
1511 std::string
1512 find_separate_debug_file_by_debuglink
1513 (struct objfile *objfile, deferred_warnings *warnings)
1514 {
1515 uint32_t crc32;
1516
1517 gdb::unique_xmalloc_ptr<char> debuglink
1518 (bfd_get_debug_link_info (objfile->obfd.get (), &crc32));
1519
1520 if (debuglink == NULL)
1521 {
1522 /* There's no separate debug info, hence there's no way we could
1523 load it => no warning. */
1524 return std::string ();
1525 }
1526
1527 std::string dir = objfile_name (objfile);
1528 terminate_after_last_dir_separator (&dir[0]);
1529 gdb::unique_xmalloc_ptr<char> canon_dir (lrealpath (dir.c_str ()));
1530
1531 std::string debugfile
1532 = find_separate_debug_file (dir.c_str (), canon_dir.get (),
1533 debuglink.get (), crc32, objfile,
1534 warnings);
1535
1536 if (debugfile.empty ())
1537 {
1538 /* For PR gdb/9538, try again with realpath (if different from the
1539 original). */
1540
1541 struct stat st_buf;
1542
1543 if (lstat (objfile_name (objfile), &st_buf) == 0
1544 && S_ISLNK (st_buf.st_mode))
1545 {
1546 gdb::unique_xmalloc_ptr<char> symlink_dir
1547 (lrealpath (objfile_name (objfile)));
1548 if (symlink_dir != NULL)
1549 {
1550 terminate_after_last_dir_separator (symlink_dir.get ());
1551 if (dir != symlink_dir.get ())
1552 {
1553 /* Different directory, so try using it. */
1554 debugfile = find_separate_debug_file (symlink_dir.get (),
1555 symlink_dir.get (),
1556 debuglink.get (),
1557 crc32,
1558 objfile,
1559 warnings);
1560 }
1561 }
1562 }
1563 }
1564
1565 return debugfile;
1566 }
1567
1568 /* Make sure that OBJF_{READNOW,READNEVER} are not set
1569 simultaneously. */
1570
1571 static void
1572 validate_readnow_readnever (objfile_flags flags)
1573 {
1574 if ((flags & OBJF_READNOW) && (flags & OBJF_READNEVER))
1575 error (_("-readnow and -readnever cannot be used simultaneously"));
1576 }
1577
1578 /* See symfile.h. */
1579
1580 void
1581 symbol_file_command (const char *args, int from_tty)
1582 {
1583 dont_repeat ();
1584
1585 if (args == NULL)
1586 {
1587 symbol_file_clear (from_tty);
1588 }
1589 else
1590 {
1591 objfile_flags flags = OBJF_USERLOADED;
1592 symfile_add_flags add_flags = 0;
1593 char *name = NULL;
1594 bool stop_processing_options = false;
1595 CORE_ADDR offset = 0;
1596 int idx;
1597 char *arg;
1598
1599 if (from_tty)
1600 add_flags |= SYMFILE_VERBOSE;
1601
1602 gdb_argv built_argv (args);
1603 for (arg = built_argv[0], idx = 0; arg != NULL; arg = built_argv[++idx])
1604 {
1605 if (stop_processing_options || *arg != '-')
1606 {
1607 if (name == NULL)
1608 name = arg;
1609 else
1610 error (_("Unrecognized argument \"%s\""), arg);
1611 }
1612 else if (strcmp (arg, "-readnow") == 0)
1613 flags |= OBJF_READNOW;
1614 else if (strcmp (arg, "-readnever") == 0)
1615 flags |= OBJF_READNEVER;
1616 else if (strcmp (arg, "-o") == 0)
1617 {
1618 arg = built_argv[++idx];
1619 if (arg == NULL)
1620 error (_("Missing argument to -o"));
1621
1622 offset = parse_and_eval_address (arg);
1623 }
1624 else if (strcmp (arg, "--") == 0)
1625 stop_processing_options = true;
1626 else
1627 error (_("Unrecognized argument \"%s\""), arg);
1628 }
1629
1630 if (name == NULL)
1631 error (_("no symbol file name was specified"));
1632
1633 validate_readnow_readnever (flags);
1634
1635 /* Set SYMFILE_DEFER_BP_RESET because the proper displacement for a PIE
1636 (Position Independent Executable) main symbol file will only be
1637 computed by the solib_create_inferior_hook below. Without it,
1638 breakpoint_re_set would fail to insert the breakpoints with the zero
1639 displacement. */
1640 add_flags |= SYMFILE_DEFER_BP_RESET;
1641
1642 symbol_file_add_main_1 (name, add_flags, flags, offset);
1643
1644 solib_create_inferior_hook (from_tty);
1645
1646 /* Now it's safe to re-add the breakpoints. */
1647 breakpoint_re_set ();
1648
1649 /* Also, it's safe to re-add varobjs. */
1650 varobj_re_set ();
1651 }
1652 }
1653
1654 /* Lazily set the initial language. */
1655
1656 static void
1657 set_initial_language_callback ()
1658 {
1659 enum language lang = main_language ();
1660 /* Make C the default language. */
1661 enum language default_lang = language_c;
1662
1663 if (lang == language_unknown)
1664 {
1665 const char *name = main_name ();
1666 struct symbol *sym
1667 = lookup_symbol_in_language (name, nullptr, SEARCH_FUNCTION_DOMAIN,
1668 default_lang, nullptr).symbol;
1669
1670 if (sym != NULL)
1671 lang = sym->language ();
1672 }
1673
1674 if (lang == language_unknown)
1675 {
1676 lang = default_lang;
1677 }
1678
1679 set_language (lang);
1680 expected_language = current_language; /* Don't warn the user. */
1681 }
1682
1683 /* Set the initial language. */
1684
1685 void
1686 set_initial_language (void)
1687 {
1688 if (language_mode == language_mode_manual)
1689 return;
1690 lazily_set_language (set_initial_language_callback);
1691 }
1692
1693 /* Open the file specified by NAME and hand it off to BFD for
1694 preliminary analysis. Return a newly initialized bfd *, which
1695 includes a newly malloc'd` copy of NAME (tilde-expanded and made
1696 absolute). In case of trouble, error() is called. */
1697
1698 gdb_bfd_ref_ptr
1699 symfile_bfd_open (const char *name)
1700 {
1701 int desc = -1;
1702
1703 gdb::unique_xmalloc_ptr<char> absolute_name;
1704 if (!is_target_filename (name))
1705 {
1706 gdb::unique_xmalloc_ptr<char> expanded_name (tilde_expand (name));
1707
1708 /* Look down path for it, allocate 2nd new malloc'd copy. */
1709 desc = openp (getenv ("PATH"),
1710 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
1711 expanded_name.get (), O_RDONLY | O_BINARY, &absolute_name);
1712 #if defined(__GO32__) || defined(_WIN32) || defined (__CYGWIN__)
1713 if (desc < 0)
1714 {
1715 char *exename = (char *) alloca (strlen (expanded_name.get ()) + 5);
1716
1717 strcat (strcpy (exename, expanded_name.get ()), ".exe");
1718 desc = openp (getenv ("PATH"),
1719 OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH,
1720 exename, O_RDONLY | O_BINARY, &absolute_name);
1721 }
1722 #endif
1723 if (desc < 0)
1724 perror_with_name (expanded_name.get ());
1725
1726 name = absolute_name.get ();
1727 }
1728
1729 gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (name, gnutarget, desc));
1730 if (sym_bfd == NULL)
1731 error (_("`%s': can't open to read symbols: %s."), name,
1732 bfd_errmsg (bfd_get_error ()));
1733
1734 if (!bfd_check_format (sym_bfd.get (), bfd_object))
1735 error (_("`%s': can't read symbols: %s."), name,
1736 bfd_errmsg (bfd_get_error ()));
1737
1738 return sym_bfd;
1739 }
1740
1741 /* See symfile.h. */
1742
1743 gdb_bfd_ref_ptr
1744 symfile_bfd_open_no_error (const char *name) noexcept
1745 {
1746 try
1747 {
1748 return symfile_bfd_open (name);
1749 }
1750 catch (const gdb_exception_error &err)
1751 {
1752 warning ("%s", err.what ());
1753 }
1754
1755 return nullptr;
1756 }
1757
1758 /* Return the section index for SECTION_NAME on OBJFILE. Return -1 if
1759 the section was not found. */
1760
1761 int
1762 get_section_index (struct objfile *objfile, const char *section_name)
1763 {
1764 asection *sect = bfd_get_section_by_name (objfile->obfd.get (), section_name);
1765
1766 if (sect)
1767 return sect->index;
1768 else
1769 return -1;
1770 }
1771
1772 /* Link SF into the global symtab_fns list.
1773 FLAVOUR is the file format that SF handles.
1774 Called on startup by the _initialize routine in each object file format
1775 reader, to register information about each format the reader is prepared
1776 to handle. */
1777
1778 void
1779 add_symtab_fns (enum bfd_flavour flavour, const struct sym_fns *sf)
1780 {
1781 symtab_fns.emplace_back (flavour, sf);
1782 }
1783
1784 /* Initialize OBJFILE to read symbols from its associated BFD. It
1785 either returns or calls error(). The result is an initialized
1786 struct sym_fns in the objfile structure, that contains cached
1787 information about the symbol file. */
1788
1789 static const struct sym_fns *
1790 find_sym_fns (bfd *abfd)
1791 {
1792 enum bfd_flavour our_flavour = bfd_get_flavour (abfd);
1793
1794 if (our_flavour == bfd_target_srec_flavour
1795 || our_flavour == bfd_target_ihex_flavour
1796 || our_flavour == bfd_target_tekhex_flavour)
1797 return NULL; /* No symbols. */
1798
1799 for (const registered_sym_fns &rsf : symtab_fns)
1800 if (our_flavour == rsf.sym_flavour)
1801 return rsf.sym_fns;
1802
1803 error (_("I'm sorry, Dave, I can't do that. Symbol format `%s' unknown."),
1804 bfd_get_target (abfd));
1805 }
1806 \f
1807
1808 /* This function runs the load command of our current target. */
1809
1810 static void
1811 load_command (const char *arg, int from_tty)
1812 {
1813 dont_repeat ();
1814
1815 /* The user might be reloading because the binary has changed. Take
1816 this opportunity to check. */
1817 reopen_exec_file ();
1818 reread_symbols (from_tty);
1819
1820 std::string temp;
1821 if (arg == NULL)
1822 {
1823 const char *parg, *prev;
1824
1825 arg = current_program_space->exec_filename ();
1826 if (arg == nullptr)
1827 no_executable_specified_error ();
1828
1829 /* We may need to quote this string so buildargv can pull it
1830 apart. */
1831 prev = parg = arg;
1832 while ((parg = strpbrk (parg, "\\\"'\t ")))
1833 {
1834 temp.append (prev, parg - prev);
1835 prev = parg++;
1836 temp.push_back ('\\');
1837 }
1838 /* If we have not copied anything yet, then we didn't see a
1839 character to quote, and we can just leave ARG unchanged. */
1840 if (!temp.empty ())
1841 {
1842 temp.append (prev);
1843 arg = temp.c_str ();
1844 }
1845 }
1846
1847 target_load (arg, from_tty);
1848
1849 /* After re-loading the executable, we don't really know which
1850 overlays are mapped any more. */
1851 overlay_cache_invalid = 1;
1852 }
1853
1854 /* This version of "load" should be usable for any target. Currently
1855 it is just used for remote targets, not inftarg.c or core files,
1856 on the theory that only in that case is it useful.
1857
1858 Avoiding xmodem and the like seems like a win (a) because we don't have
1859 to worry about finding it, and (b) On VMS, fork() is very slow and so
1860 we don't want to run a subprocess. On the other hand, I'm not sure how
1861 performance compares. */
1862
1863 static int validate_download = 0;
1864
1865 /* Opaque data for load_progress. */
1866 struct load_progress_data
1867 {
1868 /* Cumulative data. */
1869 unsigned long write_count = 0;
1870 unsigned long data_count = 0;
1871 bfd_size_type total_size = 0;
1872 };
1873
1874 /* Opaque data for load_progress for a single section. */
1875 struct load_progress_section_data
1876 {
1877 load_progress_section_data (load_progress_data *cumulative_,
1878 const char *section_name_, ULONGEST section_size_,
1879 CORE_ADDR lma_, gdb_byte *buffer_)
1880 : cumulative (cumulative_), section_name (section_name_),
1881 section_size (section_size_), lma (lma_), buffer (buffer_)
1882 {}
1883
1884 struct load_progress_data *cumulative;
1885
1886 /* Per-section data. */
1887 const char *section_name;
1888 ULONGEST section_sent = 0;
1889 ULONGEST section_size;
1890 CORE_ADDR lma;
1891 gdb_byte *buffer;
1892 };
1893
1894 /* Opaque data for load_section_callback. */
1895 struct load_section_data
1896 {
1897 load_section_data (load_progress_data *progress_data_)
1898 : progress_data (progress_data_)
1899 {}
1900
1901 ~load_section_data ()
1902 {
1903 for (auto &&request : requests)
1904 {
1905 xfree (request.data);
1906 delete ((load_progress_section_data *) request.baton);
1907 }
1908 }
1909
1910 CORE_ADDR load_offset = 0;
1911 struct load_progress_data *progress_data;
1912 std::vector<struct memory_write_request> requests;
1913 };
1914
1915 /* Target write callback routine for progress reporting. */
1916
1917 static void
1918 load_progress (ULONGEST bytes, void *untyped_arg)
1919 {
1920 struct load_progress_section_data *args
1921 = (struct load_progress_section_data *) untyped_arg;
1922 struct load_progress_data *totals;
1923
1924 if (args == NULL)
1925 /* Writing padding data. No easy way to get at the cumulative
1926 stats, so just ignore this. */
1927 return;
1928
1929 totals = args->cumulative;
1930
1931 if (bytes == 0 && args->section_sent == 0)
1932 {
1933 /* The write is just starting. Let the user know we've started
1934 this section. */
1935 current_uiout->message ("Loading section %s, size %s lma %s\n",
1936 args->section_name,
1937 hex_string (args->section_size),
1938 paddress (current_inferior ()->arch (),
1939 args->lma));
1940 return;
1941 }
1942
1943 if (validate_download)
1944 {
1945 /* Broken memories and broken monitors manifest themselves here
1946 when bring new computers to life. This doubles already slow
1947 downloads. */
1948 /* NOTE: cagney/1999-10-18: A more efficient implementation
1949 might add a verify_memory() method to the target vector and
1950 then use that. remote.c could implement that method using
1951 the ``qCRC'' packet. */
1952 gdb::byte_vector check (bytes);
1953
1954 if (target_read_memory (args->lma, check.data (), bytes) != 0)
1955 error (_("Download verify read failed at %s"),
1956 paddress (current_inferior ()->arch (), args->lma));
1957 if (memcmp (args->buffer, check.data (), bytes) != 0)
1958 error (_("Download verify compare failed at %s"),
1959 paddress (current_inferior ()->arch (), args->lma));
1960 }
1961 totals->data_count += bytes;
1962 args->lma += bytes;
1963 args->buffer += bytes;
1964 totals->write_count += 1;
1965 args->section_sent += bytes;
1966 if (check_quit_flag ()
1967 || (deprecated_ui_load_progress_hook != NULL
1968 && deprecated_ui_load_progress_hook (args->section_name,
1969 args->section_sent)))
1970 error (_("Canceled the download"));
1971
1972 if (deprecated_show_load_progress != NULL)
1973 deprecated_show_load_progress (args->section_name,
1974 args->section_sent,
1975 args->section_size,
1976 totals->data_count,
1977 totals->total_size);
1978 }
1979
1980 /* Service function for generic_load. */
1981
1982 static void
1983 load_one_section (bfd *abfd, asection *asec,
1984 struct load_section_data *args)
1985 {
1986 bfd_size_type size = bfd_section_size (asec);
1987 const char *sect_name = bfd_section_name (asec);
1988
1989 if ((bfd_section_flags (asec) & SEC_LOAD) == 0)
1990 return;
1991
1992 if (size == 0)
1993 return;
1994
1995 ULONGEST begin = bfd_section_lma (asec) + args->load_offset;
1996 ULONGEST end = begin + size;
1997 gdb_byte *buffer = (gdb_byte *) xmalloc (size);
1998 bfd_get_section_contents (abfd, asec, buffer, 0, size);
1999
2000 load_progress_section_data *section_data
2001 = new load_progress_section_data (args->progress_data, sect_name, size,
2002 begin, buffer);
2003
2004 args->requests.emplace_back (begin, end, buffer, section_data);
2005 }
2006
2007 static void print_transfer_performance (struct ui_file *stream,
2008 unsigned long data_count,
2009 unsigned long write_count,
2010 std::chrono::steady_clock::duration d);
2011
2012 /* See symfile.h. */
2013
2014 void
2015 generic_load (const char *args, int from_tty)
2016 {
2017 struct load_progress_data total_progress;
2018 struct load_section_data cbdata (&total_progress);
2019 struct ui_out *uiout = current_uiout;
2020
2021 if (args == NULL)
2022 error_no_arg (_("file to load"));
2023
2024 gdb_argv argv (args);
2025
2026 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (argv[0]));
2027
2028 if (argv[1] != NULL)
2029 {
2030 const char *endptr;
2031
2032 cbdata.load_offset = strtoulst (argv[1], &endptr, 0);
2033
2034 /* If the last word was not a valid number then
2035 treat it as a file name with spaces in. */
2036 if (argv[1] == endptr)
2037 error (_("Invalid download offset:%s."), argv[1]);
2038
2039 if (argv[2] != NULL)
2040 error (_("Too many parameters."));
2041 }
2042
2043 /* Open the file for loading. */
2044 gdb_bfd_ref_ptr loadfile_bfd (gdb_bfd_open (filename.get (), gnutarget));
2045 if (loadfile_bfd == NULL)
2046 perror_with_name (filename.get ());
2047
2048 if (!bfd_check_format (loadfile_bfd.get (), bfd_object))
2049 {
2050 error (_("\"%s\" is not an object file: %s"), filename.get (),
2051 bfd_errmsg (bfd_get_error ()));
2052 }
2053
2054 for (asection *asec : gdb_bfd_sections (loadfile_bfd))
2055 total_progress.total_size += bfd_section_size (asec);
2056
2057 for (asection *asec : gdb_bfd_sections (loadfile_bfd))
2058 load_one_section (loadfile_bfd.get (), asec, &cbdata);
2059
2060 using namespace std::chrono;
2061
2062 steady_clock::time_point start_time = steady_clock::now ();
2063
2064 if (target_write_memory_blocks (cbdata.requests, flash_discard,
2065 load_progress) != 0)
2066 error (_("Load failed"));
2067
2068 steady_clock::time_point end_time = steady_clock::now ();
2069
2070 CORE_ADDR entry = bfd_get_start_address (loadfile_bfd.get ());
2071 entry = gdbarch_addr_bits_remove (current_inferior ()->arch (), entry);
2072 uiout->text ("Start address ");
2073 uiout->field_core_addr ("address", current_inferior ()->arch (), entry);
2074 uiout->text (", load size ");
2075 uiout->field_unsigned ("load-size", total_progress.data_count);
2076 uiout->text ("\n");
2077 regcache_write_pc (get_thread_regcache (inferior_thread ()), entry);
2078
2079 /* Reset breakpoints, now that we have changed the load image. For
2080 instance, breakpoints may have been set (or reset, by
2081 post_create_inferior) while connected to the target but before we
2082 loaded the program. In that case, the prologue analyzer could
2083 have read instructions from the target to find the right
2084 breakpoint locations. Loading has changed the contents of that
2085 memory. */
2086
2087 breakpoint_re_set ();
2088
2089 print_transfer_performance (gdb_stdout, total_progress.data_count,
2090 total_progress.write_count,
2091 end_time - start_time);
2092 }
2093
2094 /* Report on STREAM the performance of a memory transfer operation,
2095 such as 'load'. DATA_COUNT is the number of bytes transferred.
2096 WRITE_COUNT is the number of separate write operations, or 0, if
2097 that information is not available. TIME is how long the operation
2098 lasted. */
2099
2100 static void
2101 print_transfer_performance (struct ui_file *stream,
2102 unsigned long data_count,
2103 unsigned long write_count,
2104 std::chrono::steady_clock::duration time)
2105 {
2106 using namespace std::chrono;
2107 struct ui_out *uiout = current_uiout;
2108
2109 milliseconds ms = duration_cast<milliseconds> (time);
2110
2111 uiout->text ("Transfer rate: ");
2112 if (ms.count () > 0)
2113 {
2114 unsigned long rate = ((ULONGEST) data_count * 1000) / ms.count ();
2115
2116 if (uiout->is_mi_like_p ())
2117 {
2118 uiout->field_unsigned ("transfer-rate", rate * 8);
2119 uiout->text (" bits/sec");
2120 }
2121 else if (rate < 1024)
2122 {
2123 uiout->field_unsigned ("transfer-rate", rate);
2124 uiout->text (" bytes/sec");
2125 }
2126 else
2127 {
2128 uiout->field_unsigned ("transfer-rate", rate / 1024);
2129 uiout->text (" KB/sec");
2130 }
2131 }
2132 else
2133 {
2134 uiout->field_unsigned ("transferred-bits", (data_count * 8));
2135 uiout->text (" bits in <1 sec");
2136 }
2137 if (write_count > 0)
2138 {
2139 uiout->text (", ");
2140 uiout->field_unsigned ("write-rate", data_count / write_count);
2141 uiout->text (" bytes/write");
2142 }
2143 uiout->text (".\n");
2144 }
2145
2146 /* Add an OFFSET to the start address of each section in OBJF, except
2147 sections that were specified in ADDRS. */
2148
2149 static void
2150 set_objfile_default_section_offset (struct objfile *objf,
2151 const section_addr_info &addrs,
2152 CORE_ADDR offset)
2153 {
2154 /* Add OFFSET to all sections by default. */
2155 section_offsets offsets (objf->section_offsets.size (), offset);
2156
2157 /* Create sorted lists of all sections in ADDRS as well as all
2158 sections in OBJF. */
2159
2160 std::vector<const struct other_sections *> addrs_sorted
2161 = addrs_section_sort (addrs);
2162
2163 section_addr_info objf_addrs
2164 = build_section_addr_info_from_objfile (objf);
2165 std::vector<const struct other_sections *> objf_addrs_sorted
2166 = addrs_section_sort (objf_addrs);
2167
2168 /* Walk the BFD section list, and if a matching section is found in
2169 ADDRS_SORTED_LIST, set its offset to zero to keep its address
2170 unchanged.
2171
2172 Note that both lists may contain multiple sections with the same
2173 name, and then the sections from ADDRS are matched in BFD order
2174 (thanks to sectindex). */
2175
2176 std::vector<const struct other_sections *>::iterator addrs_sorted_iter
2177 = addrs_sorted.begin ();
2178 for (const other_sections *objf_sect : objf_addrs_sorted)
2179 {
2180 const char *objf_name = addr_section_name (objf_sect->name.c_str ());
2181 int cmp = -1;
2182
2183 while (cmp < 0 && addrs_sorted_iter != addrs_sorted.end ())
2184 {
2185 const struct other_sections *sect = *addrs_sorted_iter;
2186 const char *sect_name = addr_section_name (sect->name.c_str ());
2187 cmp = strcmp (sect_name, objf_name);
2188 if (cmp <= 0)
2189 ++addrs_sorted_iter;
2190 }
2191
2192 if (cmp == 0)
2193 offsets[objf_sect->sectindex] = 0;
2194 }
2195
2196 /* Apply the new section offsets. */
2197 objfile_relocate (objf, offsets);
2198 }
2199
2200 /* This function allows the addition of incrementally linked object files.
2201 It does not modify any state in the target, only in the debugger. */
2202
2203 static void
2204 add_symbol_file_command (const char *args, int from_tty)
2205 {
2206 struct gdbarch *gdbarch = get_current_arch ();
2207 gdb::unique_xmalloc_ptr<char> filename;
2208 char *arg;
2209 int argcnt = 0;
2210 struct objfile *objf;
2211 objfile_flags flags = OBJF_USERLOADED | OBJF_SHARED;
2212 symfile_add_flags add_flags = 0;
2213
2214 if (from_tty)
2215 add_flags |= SYMFILE_VERBOSE;
2216
2217 struct sect_opt
2218 {
2219 const char *name;
2220 const char *value;
2221 };
2222
2223 std::vector<sect_opt> sect_opts = { { ".text", NULL } };
2224 bool stop_processing_options = false;
2225 CORE_ADDR offset = 0;
2226
2227 dont_repeat ();
2228
2229 if (args == NULL)
2230 error (_("add-symbol-file takes a file name and an address"));
2231
2232 bool seen_addr = false;
2233 bool seen_offset = false;
2234 gdb_argv argv (args);
2235
2236 for (arg = argv[0], argcnt = 0; arg != NULL; arg = argv[++argcnt])
2237 {
2238 if (stop_processing_options || *arg != '-')
2239 {
2240 if (filename == NULL)
2241 {
2242 /* First non-option argument is always the filename. */
2243 filename.reset (tilde_expand (arg));
2244 }
2245 else if (!seen_addr)
2246 {
2247 /* The second non-option argument is always the text
2248 address at which to load the program. */
2249 sect_opts[0].value = arg;
2250 seen_addr = true;
2251 }
2252 else
2253 error (_("Unrecognized argument \"%s\""), arg);
2254 }
2255 else if (strcmp (arg, "-readnow") == 0)
2256 flags |= OBJF_READNOW;
2257 else if (strcmp (arg, "-readnever") == 0)
2258 flags |= OBJF_READNEVER;
2259 else if (strcmp (arg, "-s") == 0)
2260 {
2261 if (argv[argcnt + 1] == NULL)
2262 error (_("Missing section name after \"-s\""));
2263 else if (argv[argcnt + 2] == NULL)
2264 error (_("Missing section address after \"-s\""));
2265
2266 sect_opt sect = { argv[argcnt + 1], argv[argcnt + 2] };
2267
2268 sect_opts.push_back (sect);
2269 argcnt += 2;
2270 }
2271 else if (strcmp (arg, "-o") == 0)
2272 {
2273 arg = argv[++argcnt];
2274 if (arg == NULL)
2275 error (_("Missing argument to -o"));
2276
2277 offset = parse_and_eval_address (arg);
2278 seen_offset = true;
2279 }
2280 else if (strcmp (arg, "--") == 0)
2281 stop_processing_options = true;
2282 else
2283 error (_("Unrecognized argument \"%s\""), arg);
2284 }
2285
2286 if (filename == NULL)
2287 error (_("You must provide a filename to be loaded."));
2288
2289 validate_readnow_readnever (flags);
2290
2291 /* Print the prompt for the query below. And save the arguments into
2292 a sect_addr_info structure to be passed around to other
2293 functions. We have to split this up into separate print
2294 statements because hex_string returns a local static
2295 string. */
2296
2297 gdb_printf (_("add symbol table from file \"%ps\""),
2298 styled_string (file_name_style.style (), filename.get ()));
2299 section_addr_info section_addrs;
2300 std::vector<sect_opt>::const_iterator it = sect_opts.begin ();
2301 if (!seen_addr)
2302 ++it;
2303 for (; it != sect_opts.end (); ++it)
2304 {
2305 CORE_ADDR addr;
2306 const char *val = it->value;
2307 const char *sec = it->name;
2308
2309 if (section_addrs.empty ())
2310 gdb_printf (_(" at\n"));
2311 addr = parse_and_eval_address (val);
2312
2313 /* Here we store the section offsets in the order they were
2314 entered on the command line. Every array element is
2315 assigned an ascending section index to preserve the above
2316 order over an unstable sorting algorithm. This dummy
2317 index is not used for any other purpose.
2318 */
2319 section_addrs.emplace_back (addr, sec, section_addrs.size ());
2320 gdb_printf ("\t%s_addr = %s\n", sec,
2321 paddress (gdbarch, addr));
2322
2323 /* The object's sections are initialized when a
2324 call is made to build_objfile_section_table (objfile).
2325 This happens in reread_symbols.
2326 At this point, we don't know what file type this is,
2327 so we can't determine what section names are valid. */
2328 }
2329 if (seen_offset)
2330 gdb_printf (_("%s offset by %s\n"),
2331 (section_addrs.empty ()
2332 ? _(" with all sections")
2333 : _("with other sections")),
2334 paddress (gdbarch, offset));
2335 else if (section_addrs.empty ())
2336 gdb_printf ("\n");
2337
2338 if (from_tty && (!query ("%s", "")))
2339 error (_("Not confirmed."));
2340
2341 objf = symbol_file_add (filename.get (), add_flags, &section_addrs,
2342 flags);
2343 if (!objfile_has_symbols (objf) && objf->per_bfd->minimal_symbol_count <= 0)
2344 warning (_("newly-added symbol file \"%ps\" does not provide any symbols"),
2345 styled_string (file_name_style.style (), filename.get ()));
2346
2347 if (seen_offset)
2348 set_objfile_default_section_offset (objf, section_addrs, offset);
2349
2350 current_program_space->add_target_sections (objf);
2351
2352 /* Getting new symbols may change our opinion about what is
2353 frameless. */
2354 reinit_frame_cache ();
2355 }
2356 \f
2357
2358 /* This function removes a symbol file that was added via add-symbol-file. */
2359
2360 static void
2361 remove_symbol_file_command (const char *args, int from_tty)
2362 {
2363 struct objfile *objf = NULL;
2364 struct program_space *pspace = current_program_space;
2365
2366 dont_repeat ();
2367
2368 if (args == NULL)
2369 error (_("remove-symbol-file: no symbol file provided"));
2370
2371 gdb_argv argv (args);
2372
2373 if (strcmp (argv[0], "-a") == 0)
2374 {
2375 /* Interpret the next argument as an address. */
2376 CORE_ADDR addr;
2377
2378 if (argv[1] == NULL)
2379 error (_("Missing address argument"));
2380
2381 if (argv[2] != NULL)
2382 error (_("Junk after %s"), argv[1]);
2383
2384 addr = parse_and_eval_address (argv[1]);
2385
2386 for (objfile *objfile : current_program_space->objfiles ())
2387 {
2388 if ((objfile->flags & OBJF_USERLOADED) != 0
2389 && (objfile->flags & OBJF_SHARED) != 0
2390 && objfile->pspace == pspace
2391 && is_addr_in_objfile (addr, objfile))
2392 {
2393 objf = objfile;
2394 break;
2395 }
2396 }
2397 }
2398 else if (argv[0] != NULL)
2399 {
2400 /* Interpret the current argument as a file name. */
2401
2402 if (argv[1] != NULL)
2403 error (_("Junk after %s"), argv[0]);
2404
2405 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (argv[0]));
2406
2407 for (objfile *objfile : current_program_space->objfiles ())
2408 {
2409 if ((objfile->flags & OBJF_USERLOADED) != 0
2410 && (objfile->flags & OBJF_SHARED) != 0
2411 && objfile->pspace == pspace
2412 && filename_cmp (filename.get (), objfile_name (objfile)) == 0)
2413 {
2414 objf = objfile;
2415 break;
2416 }
2417 }
2418 }
2419
2420 if (objf == NULL)
2421 error (_("No symbol file found"));
2422
2423 if (from_tty
2424 && !query (_("Remove symbol table from file \"%s\"? "),
2425 objfile_name (objf)))
2426 error (_("Not confirmed."));
2427
2428 objf->unlink ();
2429 clear_symtab_users (0);
2430 }
2431
2432 /* Re-read symbols if a symbol-file has changed. */
2433
2434 void
2435 reread_symbols (int from_tty)
2436 {
2437 std::vector<struct objfile *> new_objfiles;
2438
2439 /* Check to see if the executable has changed, and if so reopen it. The
2440 executable might not be in the list of objfiles (if the user set
2441 different values for 'exec-file' and 'symbol-file'), and even if it
2442 is, then we use a separate timestamp (within the program_space) to
2443 indicate when the executable was last reloaded. */
2444 reopen_exec_file ();
2445
2446 for (objfile *objfile : current_program_space->objfiles ())
2447 {
2448 if (objfile->obfd.get () == NULL)
2449 continue;
2450
2451 /* Separate debug objfiles are handled in the main objfile. */
2452 if (objfile->separate_debug_objfile_backlink)
2453 continue;
2454
2455 /* When a in-memory BFD is initially created, it's mtime (as
2456 returned by bfd_get_mtime) is the creation time of the BFD.
2457 However, we call bfd_stat here as we want to see if the
2458 underlying file has changed, and in this case an in-memory BFD
2459 will return an st_mtime of zero, so it appears that the in-memory
2460 file has changed, which isn't what we want here -- this code is
2461 about reloading BFDs that changed on disk.
2462
2463 Just skip any in-memory BFD. */
2464 if (objfile->obfd.get ()->flags & BFD_IN_MEMORY)
2465 continue;
2466
2467 struct stat new_statbuf;
2468 int res = bfd_stat (objfile->obfd.get (), &new_statbuf);
2469 if (res != 0)
2470 {
2471 /* If this object is from an archive (what you usually create
2472 with `ar', often called a `static library' on most systems,
2473 though a `shared library' on AIX is also an archive), then you
2474 should stat on the archive name, not member name. */
2475 const char *filename;
2476 if (objfile->obfd->my_archive)
2477 filename = bfd_get_filename (objfile->obfd->my_archive);
2478 else
2479 filename = objfile_name (objfile);
2480
2481 warning (_("`%ps' has disappeared; keeping its symbols."),
2482 styled_string (file_name_style.style (), filename));
2483 continue;
2484 }
2485 time_t new_modtime = new_statbuf.st_mtime;
2486 if (new_modtime != objfile->mtime)
2487 {
2488 gdb_printf (_("`%ps' has changed; re-reading symbols.\n"),
2489 styled_string (file_name_style.style (),
2490 objfile_name (objfile)));
2491
2492 /* There are various functions like symbol_file_add,
2493 symfile_bfd_open, syms_from_objfile, etc., which might
2494 appear to do what we want. But they have various other
2495 effects which we *don't* want. So we just do stuff
2496 ourselves. We don't worry about mapped files (for one thing,
2497 any mapped file will be out of date). */
2498
2499 /* If we get an error, blow away this objfile (not sure if
2500 that is the correct response for things like shared
2501 libraries). */
2502 objfile_up objfile_holder (objfile);
2503
2504 /* We need to do this whenever any symbols go away. */
2505 clear_symtab_users_cleanup defer_clear_users (0);
2506
2507 /* Keep the calls order approx. the same as in free_objfile. */
2508
2509 /* Free the separate debug objfiles. It will be
2510 automatically recreated by sym_read. */
2511 free_objfile_separate_debug (objfile);
2512
2513 /* Clear the stale source cache. */
2514 forget_cached_source_info ();
2515
2516 /* Remove any references to this objfile in the global
2517 value lists. */
2518 preserve_values (objfile);
2519
2520 /* Nuke all the state that we will re-read. Much of the following
2521 code which sets things to NULL really is necessary to tell
2522 other parts of GDB that there is nothing currently there.
2523
2524 Try to keep the freeing order compatible with free_objfile. */
2525
2526 if (objfile->sf != NULL)
2527 {
2528 (*objfile->sf->sym_finish) (objfile);
2529 }
2530
2531 objfile->registry_fields.clear_registry ();
2532
2533 /* Clean up any state BFD has sitting around. */
2534 {
2535 gdb_bfd_ref_ptr obfd = objfile->obfd;
2536 const char *obfd_filename;
2537
2538 obfd_filename = bfd_get_filename (objfile->obfd.get ());
2539 /* Open the new BFD before freeing the old one, so that
2540 the filename remains live. */
2541 gdb_bfd_ref_ptr temp (gdb_bfd_open (obfd_filename, gnutarget));
2542 objfile->obfd = std::move (temp);
2543 if (objfile->obfd == NULL)
2544 error (_("Can't open %s to read symbols."), obfd_filename);
2545 }
2546
2547 std::string original_name = objfile->original_name;
2548
2549 /* bfd_openr sets cacheable to true, which is what we want. */
2550 if (!bfd_check_format (objfile->obfd.get (), bfd_object))
2551 error (_("Can't read symbols from %s: %s."), objfile_name (objfile),
2552 bfd_errmsg (bfd_get_error ()));
2553
2554 /* NB: after this call to obstack_free, objfiles_changed
2555 will need to be called (see discussion below). */
2556 obstack_free (&objfile->objfile_obstack, 0);
2557 objfile->sections_start = NULL;
2558 objfile->section_offsets.clear ();
2559 objfile->sect_index_bss = -1;
2560 objfile->sect_index_data = -1;
2561 objfile->sect_index_rodata = -1;
2562 objfile->sect_index_text = -1;
2563 objfile->compunit_symtabs = NULL;
2564 objfile->template_symbols = NULL;
2565 objfile->static_links.reset (nullptr);
2566
2567 /* obstack_init also initializes the obstack so it is
2568 empty. We could use obstack_specify_allocation but
2569 gdb_obstack.h specifies the alloc/dealloc functions. */
2570 obstack_init (&objfile->objfile_obstack);
2571
2572 /* set_objfile_per_bfd potentially allocates the per-bfd
2573 data on the objfile's obstack (if sharing data across
2574 multiple users is not possible), so it's important to
2575 do it *after* the obstack has been initialized. */
2576 set_objfile_per_bfd (objfile);
2577
2578 objfile->original_name
2579 = obstack_strdup (&objfile->objfile_obstack, original_name);
2580
2581 /* Reset the sym_fns pointer. The ELF reader can change it
2582 based on whether .gdb_index is present, and we need it to
2583 start over. PR symtab/15885 */
2584 objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd.get ()));
2585 objfile->qf.clear ();
2586
2587 build_objfile_section_table (objfile);
2588
2589 /* What the hell is sym_new_init for, anyway? The concept of
2590 distinguishing between the main file and additional files
2591 in this way seems rather dubious. */
2592 if (objfile == current_program_space->symfile_object_file)
2593 {
2594 (*objfile->sf->sym_new_init) (objfile);
2595 }
2596
2597 (*objfile->sf->sym_init) (objfile);
2598 clear_complaints ();
2599
2600 /* We are about to read new symbols and potentially also
2601 DWARF information. Some targets may want to pass addresses
2602 read from DWARF DIE's through an adjustment function before
2603 saving them, like MIPS, which may call into
2604 "find_pc_section". When called, that function will make
2605 use of per-objfile program space data.
2606
2607 Since we discarded our section information above, we have
2608 dangling pointers in the per-objfile program space data
2609 structure. Force GDB to update the section mapping
2610 information by letting it know the objfile has changed,
2611 making the dangling pointers point to correct data
2612 again. */
2613
2614 objfiles_changed ();
2615
2616 /* Recompute section offsets and section indices. */
2617 objfile->sf->sym_offsets (objfile, {});
2618
2619 read_symbols (objfile, 0);
2620
2621 if ((objfile->flags & OBJF_READNOW))
2622 {
2623 const int mainline = objfile->flags & OBJF_MAINLINE;
2624 const int should_print = (print_symbol_loading_p (from_tty, mainline, 1)
2625 && readnow_symbol_files);
2626 if (should_print)
2627 gdb_printf (_("Expanding full symbols from %ps...\n"),
2628 styled_string (file_name_style.style (),
2629 objfile_name (objfile)));
2630
2631 objfile->expand_all_symtabs ();
2632 }
2633
2634 if (!objfile_has_symbols (objfile))
2635 {
2636 gdb_stdout->wrap_here (0);
2637 gdb_printf (_("(no debugging symbols found)\n"));
2638 gdb_stdout->wrap_here (0);
2639 }
2640
2641 /* We're done reading the symbol file; finish off complaints. */
2642 clear_complaints ();
2643
2644 /* Getting new symbols may change our opinion about what is
2645 frameless. */
2646
2647 reinit_frame_cache ();
2648
2649 /* Discard cleanups as symbol reading was successful. */
2650 objfile_holder.release ();
2651 defer_clear_users.release ();
2652
2653 /* If the mtime has changed between the time we set new_modtime
2654 and now, we *want* this to be out of date, so don't call stat
2655 again now. */
2656 objfile->mtime = new_modtime;
2657 init_entry_point_info (objfile);
2658
2659 new_objfiles.push_back (objfile);
2660 }
2661 }
2662
2663 if (!new_objfiles.empty ())
2664 {
2665 clear_symtab_users (0);
2666
2667 /* The registry for each objfile was cleared and
2668 gdb::observers::new_objfile.notify (NULL) has been called by
2669 clear_symtab_users above. Notify the new files now. */
2670 for (auto iter : new_objfiles)
2671 gdb::observers::new_objfile.notify (iter);
2672 }
2673 }
2674 \f
2675
2676 struct filename_language
2677 {
2678 filename_language (const std::string &ext_, enum language lang_)
2679 : ext (ext_), lang (lang_)
2680 {}
2681
2682 std::string ext;
2683 enum language lang;
2684 };
2685
2686 static std::vector<filename_language> filename_language_table;
2687
2688 /* See symfile.h. */
2689
2690 void
2691 add_filename_language (const char *ext, enum language lang)
2692 {
2693 gdb_assert (ext != nullptr);
2694 filename_language_table.emplace_back (ext, lang);
2695 }
2696
2697 static std::string ext_args;
2698 static void
2699 show_ext_args (struct ui_file *file, int from_tty,
2700 struct cmd_list_element *c, const char *value)
2701 {
2702 gdb_printf (file,
2703 _("Mapping between filename extension "
2704 "and source language is \"%s\".\n"),
2705 value);
2706 }
2707
2708 static void
2709 set_ext_lang_command (const char *args,
2710 int from_tty, struct cmd_list_element *e)
2711 {
2712 const char *begin = ext_args.c_str ();
2713 const char *end = ext_args.c_str ();
2714
2715 /* First arg is filename extension, starting with '.' */
2716 if (*end != '.')
2717 error (_("'%s': Filename extension must begin with '.'"), ext_args.c_str ());
2718
2719 /* Find end of first arg. */
2720 while (*end != '\0' && !isspace (*end))
2721 end++;
2722
2723 if (*end == '\0')
2724 error (_("'%s': two arguments required -- "
2725 "filename extension and language"),
2726 ext_args.c_str ());
2727
2728 /* Extract first arg, the extension. */
2729 std::string extension = ext_args.substr (0, end - begin);
2730
2731 /* Find beginning of second arg, which should be a source language. */
2732 begin = skip_spaces (end);
2733
2734 if (*begin == '\0')
2735 error (_("'%s': two arguments required -- "
2736 "filename extension and language"),
2737 ext_args.c_str ());
2738
2739 /* Lookup the language from among those we know. */
2740 language lang = language_enum (begin);
2741
2742 auto it = filename_language_table.begin ();
2743 /* Now lookup the filename extension: do we already know it? */
2744 for (; it != filename_language_table.end (); it++)
2745 {
2746 if (it->ext == extension)
2747 break;
2748 }
2749
2750 if (it == filename_language_table.end ())
2751 {
2752 /* New file extension. */
2753 add_filename_language (extension.data (), lang);
2754 }
2755 else
2756 {
2757 /* Redefining a previously known filename extension. */
2758
2759 /* if (from_tty) */
2760 /* query ("Really make files of type %s '%s'?", */
2761 /* ext_args, language_str (lang)); */
2762
2763 it->lang = lang;
2764 }
2765 }
2766
2767 static void
2768 info_ext_lang_command (const char *args, int from_tty)
2769 {
2770 gdb_printf (_("Filename extensions and the languages they represent:"));
2771 gdb_printf ("\n\n");
2772 for (const filename_language &entry : filename_language_table)
2773 gdb_printf ("\t%s\t- %s\n", entry.ext.c_str (),
2774 language_str (entry.lang));
2775 }
2776
2777 enum language
2778 deduce_language_from_filename (const char *filename)
2779 {
2780 const char *cp;
2781
2782 if (filename != NULL)
2783 if ((cp = strrchr (filename, '.')) != NULL)
2784 {
2785 for (const filename_language &entry : filename_language_table)
2786 if (entry.ext == cp)
2787 return entry.lang;
2788 }
2789
2790 return language_unknown;
2791 }
2792 \f
2793 /* Allocate and initialize a new symbol table.
2794 CUST is from the result of allocate_compunit_symtab. */
2795
2796 struct symtab *
2797 allocate_symtab (struct compunit_symtab *cust, const char *filename,
2798 const char *filename_for_id)
2799 {
2800 struct objfile *objfile = cust->objfile ();
2801 struct symtab *symtab
2802 = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct symtab);
2803
2804 symtab->filename = objfile->intern (filename);
2805 symtab->filename_for_id = objfile->intern (filename_for_id);
2806 symtab->fullname = NULL;
2807 symtab->set_language (deduce_language_from_filename (filename));
2808
2809 /* This can be very verbose with lots of headers.
2810 Only print at higher debug levels. */
2811 if (symtab_create_debug >= 2)
2812 {
2813 /* Be a bit clever with debugging messages, and don't print objfile
2814 every time, only when it changes. */
2815 static std::string last_objfile_name;
2816 const char *this_objfile_name = objfile_name (objfile);
2817
2818 if (last_objfile_name.empty () || last_objfile_name != this_objfile_name)
2819 {
2820 last_objfile_name = this_objfile_name;
2821
2822 symtab_create_debug_printf_v
2823 ("creating one or more symtabs for objfile %s", this_objfile_name);
2824 }
2825
2826 symtab_create_debug_printf_v ("created symtab %s for module %s",
2827 host_address_to_string (symtab), filename);
2828 }
2829
2830 /* Add it to CUST's list of symtabs. */
2831 cust->add_filetab (symtab);
2832
2833 /* Backlink to the containing compunit symtab. */
2834 symtab->set_compunit (cust);
2835
2836 return symtab;
2837 }
2838
2839 /* Allocate and initialize a new compunit.
2840 NAME is the name of the main source file, if there is one, or some
2841 descriptive text if there are no source files. */
2842
2843 struct compunit_symtab *
2844 allocate_compunit_symtab (struct objfile *objfile, const char *name)
2845 {
2846 struct compunit_symtab *cu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2847 struct compunit_symtab);
2848 const char *saved_name;
2849
2850 cu->set_objfile (objfile);
2851
2852 /* The name we record here is only for display/debugging purposes.
2853 Just save the basename to avoid path issues (too long for display,
2854 relative vs absolute, etc.). */
2855 saved_name = lbasename (name);
2856 cu->name = obstack_strdup (&objfile->objfile_obstack, saved_name);
2857
2858 cu->set_debugformat ("unknown");
2859
2860 symtab_create_debug_printf_v ("created compunit symtab %s for %s",
2861 host_address_to_string (cu),
2862 cu->name);
2863
2864 return cu;
2865 }
2866
2867 /* Hook CU to the objfile it comes from. */
2868
2869 void
2870 add_compunit_symtab_to_objfile (struct compunit_symtab *cu)
2871 {
2872 cu->next = cu->objfile ()->compunit_symtabs;
2873 cu->objfile ()->compunit_symtabs = cu;
2874 }
2875 \f
2876
2877 /* Reset all data structures in gdb which may contain references to
2878 symbol table data. */
2879
2880 void
2881 clear_symtab_users (symfile_add_flags add_flags)
2882 {
2883 /* Someday, we should do better than this, by only blowing away
2884 the things that really need to be blown. */
2885
2886 /* Clear the "current" symtab first, because it is no longer valid.
2887 breakpoint_re_set may try to access the current symtab. */
2888 clear_current_source_symtab_and_line ();
2889
2890 clear_displays ();
2891 clear_last_displayed_sal ();
2892 clear_pc_function_cache ();
2893 gdb::observers::all_objfiles_removed.notify (current_program_space);
2894
2895 /* Now that the various caches have been cleared, we can re_set
2896 our breakpoints without risking it using stale data. */
2897 if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
2898 breakpoint_re_set ();
2899 }
2900 \f
2901 /* OVERLAYS:
2902 The following code implements an abstraction for debugging overlay sections.
2903
2904 The target model is as follows:
2905 1) The gnu linker will permit multiple sections to be mapped into the
2906 same VMA, each with its own unique LMA (or load address).
2907 2) It is assumed that some runtime mechanism exists for mapping the
2908 sections, one by one, from the load address into the VMA address.
2909 3) This code provides a mechanism for gdb to keep track of which
2910 sections should be considered to be mapped from the VMA to the LMA.
2911 This information is used for symbol lookup, and memory read/write.
2912 For instance, if a section has been mapped then its contents
2913 should be read from the VMA, otherwise from the LMA.
2914
2915 Two levels of debugger support for overlays are available. One is
2916 "manual", in which the debugger relies on the user to tell it which
2917 overlays are currently mapped. This level of support is
2918 implemented entirely in the core debugger, and the information about
2919 whether a section is mapped is kept in the objfile->obj_section table.
2920
2921 The second level of support is "automatic", and is only available if
2922 the target-specific code provides functionality to read the target's
2923 overlay mapping table, and translate its contents for the debugger
2924 (by updating the mapped state information in the obj_section tables).
2925
2926 The interface is as follows:
2927 User commands:
2928 overlay map <name> -- tell gdb to consider this section mapped
2929 overlay unmap <name> -- tell gdb to consider this section unmapped
2930 overlay list -- list the sections that GDB thinks are mapped
2931 overlay read-target -- get the target's state of what's mapped
2932 overlay off/manual/auto -- set overlay debugging state
2933 Functional interface:
2934 find_pc_mapped_section(pc): if the pc is in the range of a mapped
2935 section, return that section.
2936 find_pc_overlay(pc): find any overlay section that contains
2937 the pc, either in its VMA or its LMA
2938 section_is_mapped(sect): true if overlay is marked as mapped
2939 section_is_overlay(sect): true if section's VMA != LMA
2940 pc_in_mapped_range(pc,sec): true if pc belongs to section's VMA
2941 pc_in_unmapped_range(...): true if pc belongs to section's LMA
2942 sections_overlap(sec1, sec2): true if mapped sec1 and sec2 ranges overlap
2943 overlay_mapped_address(...): map an address from section's LMA to VMA
2944 overlay_unmapped_address(...): map an address from section's VMA to LMA
2945 symbol_overlayed_address(...): Return a "current" address for symbol:
2946 either in VMA or LMA depending on whether
2947 the symbol's section is currently mapped. */
2948
2949 /* Overlay debugging state: */
2950
2951 enum overlay_debugging_state overlay_debugging = ovly_off;
2952 int overlay_cache_invalid = 0; /* True if need to refresh mapped state. */
2953
2954 /* Function: section_is_overlay (SECTION)
2955 Returns true if SECTION has VMA not equal to LMA, ie.
2956 SECTION is loaded at an address different from where it will "run". */
2957
2958 int
2959 section_is_overlay (struct obj_section *section)
2960 {
2961 if (overlay_debugging && section)
2962 {
2963 asection *bfd_section = section->the_bfd_section;
2964
2965 if (bfd_section_lma (bfd_section) != 0
2966 && bfd_section_lma (bfd_section) != bfd_section_vma (bfd_section))
2967 return 1;
2968 }
2969
2970 return 0;
2971 }
2972
2973 /* Function: overlay_invalidate_all (void)
2974 Invalidate the mapped state of all overlay sections (mark it as stale). */
2975
2976 static void
2977 overlay_invalidate_all (void)
2978 {
2979 for (objfile *objfile : current_program_space->objfiles ())
2980 for (obj_section *sect : objfile->sections ())
2981 if (section_is_overlay (sect))
2982 sect->ovly_mapped = -1;
2983 }
2984
2985 /* Function: section_is_mapped (SECTION)
2986 Returns true if section is an overlay, and is currently mapped.
2987
2988 Access to the ovly_mapped flag is restricted to this function, so
2989 that we can do automatic update. If the global flag
2990 OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
2991 overlay_invalidate_all. If the mapped state of the particular
2992 section is stale, then call TARGET_OVERLAY_UPDATE to refresh it. */
2993
2994 int
2995 section_is_mapped (struct obj_section *osect)
2996 {
2997 struct gdbarch *gdbarch;
2998
2999 if (osect == 0 || !section_is_overlay (osect))
3000 return 0;
3001
3002 switch (overlay_debugging)
3003 {
3004 default:
3005 case ovly_off:
3006 return 0; /* overlay debugging off */
3007 case ovly_auto: /* overlay debugging automatic */
3008 /* Unles there is a gdbarch_overlay_update function,
3009 there's really nothing useful to do here (can't really go auto). */
3010 gdbarch = osect->objfile->arch ();
3011 if (gdbarch_overlay_update_p (gdbarch))
3012 {
3013 if (overlay_cache_invalid)
3014 {
3015 overlay_invalidate_all ();
3016 overlay_cache_invalid = 0;
3017 }
3018 if (osect->ovly_mapped == -1)
3019 gdbarch_overlay_update (gdbarch, osect);
3020 }
3021 [[fallthrough]];
3022 case ovly_on: /* overlay debugging manual */
3023 return osect->ovly_mapped == 1;
3024 }
3025 }
3026
3027 /* Function: pc_in_unmapped_range
3028 If PC falls into the lma range of SECTION, return true, else false. */
3029
3030 bool
3031 pc_in_unmapped_range (CORE_ADDR pc, struct obj_section *section)
3032 {
3033 if (section_is_overlay (section))
3034 {
3035 asection *bfd_section = section->the_bfd_section;
3036
3037 /* We assume the LMA is relocated by the same offset as the VMA. */
3038 bfd_vma size = bfd_section_size (bfd_section);
3039 CORE_ADDR offset = section->offset ();
3040
3041 if (bfd_section_lma (bfd_section) + offset <= pc
3042 && pc < bfd_section_lma (bfd_section) + offset + size)
3043 return true;
3044 }
3045
3046 return false;
3047 }
3048
3049 /* Function: pc_in_mapped_range
3050 If PC falls into the vma range of SECTION, return true, else false. */
3051
3052 bool
3053 pc_in_mapped_range (CORE_ADDR pc, struct obj_section *section)
3054 {
3055 if (section_is_overlay (section))
3056 {
3057 if (section->contains (pc))
3058 return true;
3059 }
3060
3061 return false;
3062 }
3063
3064 /* Return true if the mapped ranges of sections A and B overlap, false
3065 otherwise. */
3066
3067 static int
3068 sections_overlap (struct obj_section *a, struct obj_section *b)
3069 {
3070 CORE_ADDR a_start = a->addr ();
3071 CORE_ADDR a_end = a->endaddr ();
3072 CORE_ADDR b_start = b->addr ();
3073 CORE_ADDR b_end = b->endaddr ();
3074
3075 return (a_start < b_end && b_start < a_end);
3076 }
3077
3078 /* Function: overlay_unmapped_address (PC, SECTION)
3079 Returns the address corresponding to PC in the unmapped (load) range.
3080 May be the same as PC. */
3081
3082 CORE_ADDR
3083 overlay_unmapped_address (CORE_ADDR pc, struct obj_section *section)
3084 {
3085 if (section_is_overlay (section) && pc_in_mapped_range (pc, section))
3086 {
3087 asection *bfd_section = section->the_bfd_section;
3088
3089 return (pc + bfd_section_lma (bfd_section)
3090 - bfd_section_vma (bfd_section));
3091 }
3092
3093 return pc;
3094 }
3095
3096 /* Function: overlay_mapped_address (PC, SECTION)
3097 Returns the address corresponding to PC in the mapped (runtime) range.
3098 May be the same as PC. */
3099
3100 CORE_ADDR
3101 overlay_mapped_address (CORE_ADDR pc, struct obj_section *section)
3102 {
3103 if (section_is_overlay (section) && pc_in_unmapped_range (pc, section))
3104 {
3105 asection *bfd_section = section->the_bfd_section;
3106
3107 return (pc + bfd_section_vma (bfd_section)
3108 - bfd_section_lma (bfd_section));
3109 }
3110
3111 return pc;
3112 }
3113
3114 /* Function: symbol_overlayed_address
3115 Return one of two addresses (relative to the VMA or to the LMA),
3116 depending on whether the section is mapped or not. */
3117
3118 CORE_ADDR
3119 symbol_overlayed_address (CORE_ADDR address, struct obj_section *section)
3120 {
3121 if (overlay_debugging)
3122 {
3123 /* If the symbol has no section, just return its regular address. */
3124 if (section == 0)
3125 return address;
3126 /* If the symbol's section is not an overlay, just return its
3127 address. */
3128 if (!section_is_overlay (section))
3129 return address;
3130 /* If the symbol's section is mapped, just return its address. */
3131 if (section_is_mapped (section))
3132 return address;
3133 /*
3134 * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
3135 * then return its LOADED address rather than its vma address!!
3136 */
3137 return overlay_unmapped_address (address, section);
3138 }
3139 return address;
3140 }
3141
3142 /* Function: find_pc_overlay (PC)
3143 Return the best-match overlay section for PC:
3144 If PC matches a mapped overlay section's VMA, return that section.
3145 Else if PC matches an unmapped section's VMA, return that section.
3146 Else if PC matches an unmapped section's LMA, return that section. */
3147
3148 struct obj_section *
3149 find_pc_overlay (CORE_ADDR pc)
3150 {
3151 struct obj_section *best_match = NULL;
3152
3153 if (overlay_debugging)
3154 {
3155 for (objfile *objfile : current_program_space->objfiles ())
3156 for (obj_section *osect : objfile->sections ())
3157 if (section_is_overlay (osect))
3158 {
3159 if (pc_in_mapped_range (pc, osect))
3160 {
3161 if (section_is_mapped (osect))
3162 return osect;
3163 else
3164 best_match = osect;
3165 }
3166 else if (pc_in_unmapped_range (pc, osect))
3167 best_match = osect;
3168 }
3169 }
3170 return best_match;
3171 }
3172
3173 /* Function: find_pc_mapped_section (PC)
3174 If PC falls into the VMA address range of an overlay section that is
3175 currently marked as MAPPED, return that section. Else return NULL. */
3176
3177 struct obj_section *
3178 find_pc_mapped_section (CORE_ADDR pc)
3179 {
3180 if (overlay_debugging)
3181 {
3182 for (objfile *objfile : current_program_space->objfiles ())
3183 for (obj_section *osect : objfile->sections ())
3184 if (pc_in_mapped_range (pc, osect) && section_is_mapped (osect))
3185 return osect;
3186 }
3187
3188 return NULL;
3189 }
3190
3191 /* Function: list_overlays_command
3192 Print a list of mapped sections and their PC ranges. */
3193
3194 static void
3195 list_overlays_command (const char *args, int from_tty)
3196 {
3197 int nmapped = 0;
3198
3199 if (overlay_debugging)
3200 {
3201 for (objfile *objfile : current_program_space->objfiles ())
3202 for (obj_section *osect : objfile->sections ())
3203 if (section_is_mapped (osect))
3204 {
3205 struct gdbarch *gdbarch = objfile->arch ();
3206 const char *name;
3207 bfd_vma lma, vma;
3208 int size;
3209
3210 vma = bfd_section_vma (osect->the_bfd_section);
3211 lma = bfd_section_lma (osect->the_bfd_section);
3212 size = bfd_section_size (osect->the_bfd_section);
3213 name = bfd_section_name (osect->the_bfd_section);
3214
3215 gdb_printf ("Section %s, loaded at ", name);
3216 gdb_puts (paddress (gdbarch, lma));
3217 gdb_puts (" - ");
3218 gdb_puts (paddress (gdbarch, lma + size));
3219 gdb_printf (", mapped at ");
3220 gdb_puts (paddress (gdbarch, vma));
3221 gdb_puts (" - ");
3222 gdb_puts (paddress (gdbarch, vma + size));
3223 gdb_puts ("\n");
3224
3225 nmapped++;
3226 }
3227 }
3228 if (nmapped == 0)
3229 gdb_printf (_("No sections are mapped.\n"));
3230 }
3231
3232 /* Function: map_overlay_command
3233 Mark the named section as mapped (ie. residing at its VMA address). */
3234
3235 static void
3236 map_overlay_command (const char *args, int from_tty)
3237 {
3238 if (!overlay_debugging)
3239 error (_("Overlay debugging not enabled. Use "
3240 "either the 'overlay auto' or\n"
3241 "the 'overlay manual' command."));
3242
3243 if (args == 0 || *args == 0)
3244 error (_("Argument required: name of an overlay section"));
3245
3246 /* First, find a section matching the user supplied argument. */
3247 for (objfile *obj_file : current_program_space->objfiles ())
3248 for (obj_section *sec : obj_file->sections ())
3249 if (!strcmp (bfd_section_name (sec->the_bfd_section), args))
3250 {
3251 /* Now, check to see if the section is an overlay. */
3252 if (!section_is_overlay (sec))
3253 continue; /* not an overlay section */
3254
3255 /* Mark the overlay as "mapped". */
3256 sec->ovly_mapped = 1;
3257
3258 /* Next, make a pass and unmap any sections that are
3259 overlapped by this new section: */
3260 for (objfile *objfile2 : current_program_space->objfiles ())
3261 for (obj_section *sec2 : objfile2->sections ())
3262 if (sec2->ovly_mapped && sec != sec2 && sections_overlap (sec,
3263 sec2))
3264 {
3265 if (info_verbose)
3266 gdb_printf (_("Note: section %s unmapped by overlap\n"),
3267 bfd_section_name (sec2->the_bfd_section));
3268 sec2->ovly_mapped = 0; /* sec2 overlaps sec: unmap sec2. */
3269 }
3270 return;
3271 }
3272 error (_("No overlay section called %s"), args);
3273 }
3274
3275 /* Function: unmap_overlay_command
3276 Mark the overlay section as unmapped
3277 (ie. resident in its LMA address range, rather than the VMA range). */
3278
3279 static void
3280 unmap_overlay_command (const char *args, int from_tty)
3281 {
3282 if (!overlay_debugging)
3283 error (_("Overlay debugging not enabled. "
3284 "Use either the 'overlay auto' or\n"
3285 "the 'overlay manual' command."));
3286
3287 if (args == 0 || *args == 0)
3288 error (_("Argument required: name of an overlay section"));
3289
3290 /* First, find a section matching the user supplied argument. */
3291 for (objfile *objfile : current_program_space->objfiles ())
3292 for (obj_section *sec : objfile->sections ())
3293 if (!strcmp (bfd_section_name (sec->the_bfd_section), args))
3294 {
3295 if (!sec->ovly_mapped)
3296 error (_("Section %s is not mapped"), args);
3297 sec->ovly_mapped = 0;
3298 return;
3299 }
3300 error (_("No overlay section called %s"), args);
3301 }
3302
3303 /* Function: overlay_auto_command
3304 A utility command to turn on overlay debugging.
3305 Possibly this should be done via a set/show command. */
3306
3307 static void
3308 overlay_auto_command (const char *args, int from_tty)
3309 {
3310 overlay_debugging = ovly_auto;
3311 enable_overlay_breakpoints ();
3312 if (info_verbose)
3313 gdb_printf (_("Automatic overlay debugging enabled."));
3314 }
3315
3316 /* Function: overlay_manual_command
3317 A utility command to turn on overlay debugging.
3318 Possibly this should be done via a set/show command. */
3319
3320 static void
3321 overlay_manual_command (const char *args, int from_tty)
3322 {
3323 overlay_debugging = ovly_on;
3324 disable_overlay_breakpoints ();
3325 if (info_verbose)
3326 gdb_printf (_("Overlay debugging enabled."));
3327 }
3328
3329 /* Function: overlay_off_command
3330 A utility command to turn on overlay debugging.
3331 Possibly this should be done via a set/show command. */
3332
3333 static void
3334 overlay_off_command (const char *args, int from_tty)
3335 {
3336 overlay_debugging = ovly_off;
3337 disable_overlay_breakpoints ();
3338 if (info_verbose)
3339 gdb_printf (_("Overlay debugging disabled."));
3340 }
3341
3342 static void
3343 overlay_load_command (const char *args, int from_tty)
3344 {
3345 struct gdbarch *gdbarch = get_current_arch ();
3346
3347 if (gdbarch_overlay_update_p (gdbarch))
3348 gdbarch_overlay_update (gdbarch, NULL);
3349 else
3350 error (_("This target does not know how to read its overlay state."));
3351 }
3352
3353 /* Command list chain containing all defined "overlay" subcommands. */
3354 static struct cmd_list_element *overlaylist;
3355
3356 /* Target Overlays for the "Simplest" overlay manager:
3357
3358 This is GDB's default target overlay layer. It works with the
3359 minimal overlay manager supplied as an example by Cygnus. The
3360 entry point is via a function pointer "gdbarch_overlay_update",
3361 so targets that use a different runtime overlay manager can
3362 substitute their own overlay_update function and take over the
3363 function pointer.
3364
3365 The overlay_update function pokes around in the target's data structures
3366 to see what overlays are mapped, and updates GDB's overlay mapping with
3367 this information.
3368
3369 In this simple implementation, the target data structures are as follows:
3370 unsigned _novlys; /# number of overlay sections #/
3371 unsigned _ovly_table[_novlys][4] = {
3372 {VMA, OSIZE, LMA, MAPPED}, /# one entry per overlay section #/
3373 {..., ..., ..., ...},
3374 }
3375 unsigned _novly_regions; /# number of overlay regions #/
3376 unsigned _ovly_region_table[_novly_regions][3] = {
3377 {VMA, OSIZE, MAPPED_TO_LMA}, /# one entry per overlay region #/
3378 {..., ..., ...},
3379 }
3380 These functions will attempt to update GDB's mappedness state in the
3381 symbol section table, based on the target's mappedness state.
3382
3383 To do this, we keep a cached copy of the target's _ovly_table, and
3384 attempt to detect when the cached copy is invalidated. The main
3385 entry point is "simple_overlay_update(SECT), which looks up SECT in
3386 the cached table and re-reads only the entry for that section from
3387 the target (whenever possible). */
3388
3389 /* Cached, dynamically allocated copies of the target data structures: */
3390 static unsigned (*cache_ovly_table)[4] = 0;
3391 static unsigned cache_novlys = 0;
3392 static CORE_ADDR cache_ovly_table_base = 0;
3393 enum ovly_index
3394 {
3395 VMA, OSIZE, LMA, MAPPED
3396 };
3397
3398 /* Throw away the cached copy of _ovly_table. */
3399
3400 static void
3401 simple_free_overlay_table (void)
3402 {
3403 xfree (cache_ovly_table);
3404 cache_novlys = 0;
3405 cache_ovly_table = NULL;
3406 cache_ovly_table_base = 0;
3407 }
3408
3409 /* Read an array of ints of size SIZE from the target into a local buffer.
3410 Convert to host order. int LEN is number of ints. */
3411
3412 static void
3413 read_target_long_array (CORE_ADDR memaddr, unsigned int *myaddr,
3414 int len, int size, enum bfd_endian byte_order)
3415 {
3416 /* FIXME (alloca): Not safe if array is very large. */
3417 gdb_byte *buf = (gdb_byte *) alloca (len * size);
3418 int i;
3419
3420 read_memory (memaddr, buf, len * size);
3421 for (i = 0; i < len; i++)
3422 myaddr[i] = extract_unsigned_integer (size * i + buf, size, byte_order);
3423 }
3424
3425 /* Find and grab a copy of the target _ovly_table
3426 (and _novlys, which is needed for the table's size). */
3427
3428 static int
3429 simple_read_overlay_table (void)
3430 {
3431 struct bound_minimal_symbol novlys_msym;
3432 struct bound_minimal_symbol ovly_table_msym;
3433 struct gdbarch *gdbarch;
3434 int word_size;
3435 enum bfd_endian byte_order;
3436
3437 simple_free_overlay_table ();
3438 novlys_msym = lookup_minimal_symbol ("_novlys", NULL, NULL);
3439 if (! novlys_msym.minsym)
3440 {
3441 error (_("Error reading inferior's overlay table: "
3442 "couldn't find `_novlys' variable\n"
3443 "in inferior. Use `overlay manual' mode."));
3444 return 0;
3445 }
3446
3447 ovly_table_msym = lookup_bound_minimal_symbol ("_ovly_table");
3448 if (! ovly_table_msym.minsym)
3449 {
3450 error (_("Error reading inferior's overlay table: couldn't find "
3451 "`_ovly_table' array\n"
3452 "in inferior. Use `overlay manual' mode."));
3453 return 0;
3454 }
3455
3456 gdbarch = ovly_table_msym.objfile->arch ();
3457 word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
3458 byte_order = gdbarch_byte_order (gdbarch);
3459
3460 cache_novlys = read_memory_integer (novlys_msym.value_address (),
3461 4, byte_order);
3462 cache_ovly_table
3463 = (unsigned int (*)[4]) xmalloc (cache_novlys * sizeof (*cache_ovly_table));
3464 cache_ovly_table_base = ovly_table_msym.value_address ();
3465 read_target_long_array (cache_ovly_table_base,
3466 (unsigned int *) cache_ovly_table,
3467 cache_novlys * 4, word_size, byte_order);
3468
3469 return 1; /* SUCCESS */
3470 }
3471
3472 /* Function: simple_overlay_update_1
3473 A helper function for simple_overlay_update. Assuming a cached copy
3474 of _ovly_table exists, look through it to find an entry whose vma,
3475 lma and size match those of OSECT. Re-read the entry and make sure
3476 it still matches OSECT (else the table may no longer be valid).
3477 Set OSECT's mapped state to match the entry. Return: 1 for
3478 success, 0 for failure. */
3479
3480 static int
3481 simple_overlay_update_1 (struct obj_section *osect)
3482 {
3483 int i;
3484 asection *bsect = osect->the_bfd_section;
3485 struct gdbarch *gdbarch = osect->objfile->arch ();
3486 int word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
3487 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3488
3489 for (i = 0; i < cache_novlys; i++)
3490 if (cache_ovly_table[i][VMA] == bfd_section_vma (bsect)
3491 && cache_ovly_table[i][LMA] == bfd_section_lma (bsect))
3492 {
3493 read_target_long_array (cache_ovly_table_base + i * word_size,
3494 (unsigned int *) cache_ovly_table[i],
3495 4, word_size, byte_order);
3496 if (cache_ovly_table[i][VMA] == bfd_section_vma (bsect)
3497 && cache_ovly_table[i][LMA] == bfd_section_lma (bsect))
3498 {
3499 osect->ovly_mapped = cache_ovly_table[i][MAPPED];
3500 return 1;
3501 }
3502 else /* Warning! Warning! Target's ovly table has changed! */
3503 return 0;
3504 }
3505 return 0;
3506 }
3507
3508 /* Function: simple_overlay_update
3509 If OSECT is NULL, then update all sections' mapped state
3510 (after re-reading the entire target _ovly_table).
3511 If OSECT is non-NULL, then try to find a matching entry in the
3512 cached ovly_table and update only OSECT's mapped state.
3513 If a cached entry can't be found or the cache isn't valid, then
3514 re-read the entire cache, and go ahead and update all sections. */
3515
3516 void
3517 simple_overlay_update (struct obj_section *osect)
3518 {
3519 /* Were we given an osect to look up? NULL means do all of them. */
3520 if (osect)
3521 /* Have we got a cached copy of the target's overlay table? */
3522 if (cache_ovly_table != NULL)
3523 {
3524 /* Does its cached location match what's currently in the
3525 symtab? */
3526 struct bound_minimal_symbol minsym
3527 = lookup_minimal_symbol ("_ovly_table", NULL, NULL);
3528
3529 if (minsym.minsym == NULL)
3530 error (_("Error reading inferior's overlay table: couldn't "
3531 "find `_ovly_table' array\n"
3532 "in inferior. Use `overlay manual' mode."));
3533
3534 if (cache_ovly_table_base == minsym.value_address ())
3535 /* Then go ahead and try to look up this single section in
3536 the cache. */
3537 if (simple_overlay_update_1 (osect))
3538 /* Found it! We're done. */
3539 return;
3540 }
3541
3542 /* Cached table no good: need to read the entire table anew.
3543 Or else we want all the sections, in which case it's actually
3544 more efficient to read the whole table in one block anyway. */
3545
3546 if (! simple_read_overlay_table ())
3547 return;
3548
3549 /* Now may as well update all sections, even if only one was requested. */
3550 for (objfile *objfile : current_program_space->objfiles ())
3551 for (obj_section *sect : objfile->sections ())
3552 if (section_is_overlay (sect))
3553 {
3554 int i;
3555 asection *bsect = sect->the_bfd_section;
3556
3557 for (i = 0; i < cache_novlys; i++)
3558 if (cache_ovly_table[i][VMA] == bfd_section_vma (bsect)
3559 && cache_ovly_table[i][LMA] == bfd_section_lma (bsect))
3560 { /* obj_section matches i'th entry in ovly_table. */
3561 sect->ovly_mapped = cache_ovly_table[i][MAPPED];
3562 break; /* finished with inner for loop: break out. */
3563 }
3564 }
3565 }
3566
3567 /* Default implementation for sym_relocate. */
3568
3569 bfd_byte *
3570 default_symfile_relocate (struct objfile *objfile, asection *sectp,
3571 bfd_byte *buf)
3572 {
3573 /* Use sectp->owner instead of objfile->obfd. sectp may point to a
3574 DWO file. */
3575 bfd *abfd = sectp->owner;
3576
3577 /* We're only interested in sections with relocation
3578 information. */
3579 if ((sectp->flags & SEC_RELOC) == 0)
3580 return NULL;
3581
3582 /* We will handle section offsets properly elsewhere, so relocate as if
3583 all sections begin at 0. */
3584 for (asection *sect : gdb_bfd_sections (abfd))
3585 {
3586 sect->output_section = sect;
3587 sect->output_offset = 0;
3588 }
3589
3590 return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL);
3591 }
3592
3593 /* Relocate the contents of a debug section SECTP in ABFD. The
3594 contents are stored in BUF if it is non-NULL, or returned in a
3595 malloc'd buffer otherwise.
3596
3597 For some platforms and debug info formats, shared libraries contain
3598 relocations against the debug sections (particularly for DWARF-2;
3599 one affected platform is PowerPC GNU/Linux, although it depends on
3600 the version of the linker in use). Also, ELF object files naturally
3601 have unresolved relocations for their debug sections. We need to apply
3602 the relocations in order to get the locations of symbols correct.
3603 Another example that may require relocation processing, is the
3604 DWARF-2 .eh_frame section in .o files, although it isn't strictly a
3605 debug section. */
3606
3607 bfd_byte *
3608 symfile_relocate_debug_section (struct objfile *objfile,
3609 asection *sectp, bfd_byte *buf)
3610 {
3611 gdb_assert (objfile->sf->sym_relocate);
3612
3613 return (*objfile->sf->sym_relocate) (objfile, sectp, buf);
3614 }
3615
3616 symfile_segment_data_up
3617 get_symfile_segment_data (bfd *abfd)
3618 {
3619 const struct sym_fns *sf = find_sym_fns (abfd);
3620
3621 if (sf == NULL)
3622 return NULL;
3623
3624 return sf->sym_segments (abfd);
3625 }
3626
3627 /* Given:
3628 - DATA, containing segment addresses from the object file ABFD, and
3629 the mapping from ABFD's sections onto the segments that own them,
3630 and
3631 - SEGMENT_BASES[0 .. NUM_SEGMENT_BASES - 1], holding the actual
3632 segment addresses reported by the target,
3633 store the appropriate offsets for each section in OFFSETS.
3634
3635 If there are fewer entries in SEGMENT_BASES than there are segments
3636 in DATA, then apply SEGMENT_BASES' last entry to all the segments.
3637
3638 If there are more entries, then ignore the extra. The target may
3639 not be able to distinguish between an empty data segment and a
3640 missing data segment; a missing text segment is less plausible. */
3641
3642 int
3643 symfile_map_offsets_to_segments (bfd *abfd,
3644 const struct symfile_segment_data *data,
3645 section_offsets &offsets,
3646 int num_segment_bases,
3647 const CORE_ADDR *segment_bases)
3648 {
3649 int i;
3650 asection *sect;
3651
3652 /* It doesn't make sense to call this function unless you have some
3653 segment base addresses. */
3654 gdb_assert (num_segment_bases > 0);
3655
3656 /* If we do not have segment mappings for the object file, we
3657 can not relocate it by segments. */
3658 gdb_assert (data != NULL);
3659 gdb_assert (data->segments.size () > 0);
3660
3661 for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
3662 {
3663 int which = data->segment_info[i];
3664
3665 gdb_assert (0 <= which && which <= data->segments.size ());
3666
3667 /* Don't bother computing offsets for sections that aren't
3668 loaded as part of any segment. */
3669 if (! which)
3670 continue;
3671
3672 /* Use the last SEGMENT_BASES entry as the address of any extra
3673 segments mentioned in DATA->segment_info. */
3674 if (which > num_segment_bases)
3675 which = num_segment_bases;
3676
3677 offsets[i] = segment_bases[which - 1] - data->segments[which - 1].base;
3678 }
3679
3680 return 1;
3681 }
3682
3683 static void
3684 symfile_find_segment_sections (struct objfile *objfile)
3685 {
3686 bfd *abfd = objfile->obfd.get ();
3687 int i;
3688 asection *sect;
3689
3690 symfile_segment_data_up data = get_symfile_segment_data (abfd);
3691 if (data == NULL)
3692 return;
3693
3694 if (data->segments.size () != 1 && data->segments.size () != 2)
3695 return;
3696
3697 for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
3698 {
3699 int which = data->segment_info[i];
3700
3701 if (which == 1)
3702 {
3703 if (objfile->sect_index_text == -1)
3704 objfile->sect_index_text = sect->index;
3705
3706 if (objfile->sect_index_rodata == -1)
3707 objfile->sect_index_rodata = sect->index;
3708 }
3709 else if (which == 2)
3710 {
3711 if (objfile->sect_index_data == -1)
3712 objfile->sect_index_data = sect->index;
3713
3714 if (objfile->sect_index_bss == -1)
3715 objfile->sect_index_bss = sect->index;
3716 }
3717 }
3718 }
3719
3720 /* Listen for free_objfile events. */
3721
3722 static void
3723 symfile_free_objfile (struct objfile *objfile)
3724 {
3725 /* Remove the target sections owned by this objfile. */
3726 objfile->pspace->remove_target_sections (objfile);
3727 }
3728
3729 /* Wrapper around the quick_symbol_functions expand_symtabs_matching "method".
3730 Expand all symtabs that match the specified criteria.
3731 See quick_symbol_functions.expand_symtabs_matching for details. */
3732
3733 bool
3734 expand_symtabs_matching
3735 (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
3736 const lookup_name_info &lookup_name,
3737 gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
3738 gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
3739 block_search_flags search_flags,
3740 domain_search_flags domain)
3741 {
3742 for (objfile *objfile : current_program_space->objfiles ())
3743 if (!objfile->expand_symtabs_matching (file_matcher,
3744 &lookup_name,
3745 symbol_matcher,
3746 expansion_notify,
3747 search_flags,
3748 domain))
3749 return false;
3750 return true;
3751 }
3752
3753 /* Wrapper around the quick_symbol_functions map_symbol_filenames "method".
3754 Map function FUN over every file.
3755 See quick_symbol_functions.map_symbol_filenames for details. */
3756
3757 void
3758 map_symbol_filenames (gdb::function_view<symbol_filename_ftype> fun,
3759 bool need_fullname)
3760 {
3761 for (objfile *objfile : current_program_space->objfiles ())
3762 objfile->map_symbol_filenames (fun, need_fullname);
3763 }
3764
3765 #if GDB_SELF_TEST
3766
3767 namespace selftests {
3768 namespace filename_language {
3769
3770 static void test_filename_language ()
3771 {
3772 /* This test messes up the filename_language_table global. */
3773 scoped_restore restore_flt = make_scoped_restore (&filename_language_table);
3774
3775 /* Test deducing an unknown extension. */
3776 language lang = deduce_language_from_filename ("myfile.blah");
3777 SELF_CHECK (lang == language_unknown);
3778
3779 /* Test deducing a known extension. */
3780 lang = deduce_language_from_filename ("myfile.c");
3781 SELF_CHECK (lang == language_c);
3782
3783 /* Test adding a new extension using the internal API. */
3784 add_filename_language (".blah", language_pascal);
3785 lang = deduce_language_from_filename ("myfile.blah");
3786 SELF_CHECK (lang == language_pascal);
3787 }
3788
3789 static void
3790 test_set_ext_lang_command ()
3791 {
3792 /* This test messes up the filename_language_table global. */
3793 scoped_restore restore_flt = make_scoped_restore (&filename_language_table);
3794
3795 /* Confirm that the .hello extension is not known. */
3796 language lang = deduce_language_from_filename ("cake.hello");
3797 SELF_CHECK (lang == language_unknown);
3798
3799 /* Test adding a new extension using the CLI command. */
3800 ext_args = ".hello rust";
3801 set_ext_lang_command (NULL, 1, NULL);
3802
3803 lang = deduce_language_from_filename ("cake.hello");
3804 SELF_CHECK (lang == language_rust);
3805
3806 /* Test overriding an existing extension using the CLI command. */
3807 int size_before = filename_language_table.size ();
3808 ext_args = ".hello pascal";
3809 set_ext_lang_command (NULL, 1, NULL);
3810 int size_after = filename_language_table.size ();
3811
3812 lang = deduce_language_from_filename ("cake.hello");
3813 SELF_CHECK (lang == language_pascal);
3814 SELF_CHECK (size_before == size_after);
3815 }
3816
3817 } /* namespace filename_language */
3818 } /* namespace selftests */
3819
3820 #endif /* GDB_SELF_TEST */
3821
3822 void _initialize_symfile ();
3823 void
3824 _initialize_symfile ()
3825 {
3826 struct cmd_list_element *c;
3827
3828 gdb::observers::free_objfile.attach (symfile_free_objfile, "symfile");
3829
3830 #define READNOW_READNEVER_HELP \
3831 "The '-readnow' option will cause GDB to read the entire symbol file\n\
3832 immediately. This makes the command slower, but may make future operations\n\
3833 faster.\n\
3834 The '-readnever' option will prevent GDB from reading the symbol file's\n\
3835 symbolic debug information."
3836
3837 c = add_cmd ("symbol-file", class_files, symbol_file_command, _("\
3838 Load symbol table from executable file FILE.\n\
3839 Usage: symbol-file [-readnow | -readnever] [-o OFF] FILE\n\
3840 OFF is an optional offset which is added to each section address.\n\
3841 The `file' command can also load symbol tables, as well as setting the file\n\
3842 to execute.\n" READNOW_READNEVER_HELP), &cmdlist);
3843 set_cmd_completer (c, filename_completer);
3844
3845 c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command, _("\
3846 Load symbols from FILE, assuming FILE has been dynamically loaded.\n\
3847 Usage: add-symbol-file FILE [-readnow | -readnever] [-o OFF] [ADDR] \
3848 [-s SECT-NAME SECT-ADDR]...\n\
3849 ADDR is the starting address of the file's text.\n\
3850 Each '-s' argument provides a section name and address, and\n\
3851 should be specified if the data and bss segments are not contiguous\n\
3852 with the text. SECT-NAME is a section name to be loaded at SECT-ADDR.\n\
3853 OFF is an optional offset which is added to the default load addresses\n\
3854 of all sections for which no other address was specified.\n"
3855 READNOW_READNEVER_HELP),
3856 &cmdlist);
3857 set_cmd_completer (c, filename_completer);
3858
3859 c = add_cmd ("remove-symbol-file", class_files,
3860 remove_symbol_file_command, _("\
3861 Remove a symbol file added via the add-symbol-file command.\n\
3862 Usage: remove-symbol-file FILENAME\n\
3863 remove-symbol-file -a ADDRESS\n\
3864 The file to remove can be identified by its filename or by an address\n\
3865 that lies within the boundaries of this symbol file in memory."),
3866 &cmdlist);
3867
3868 c = add_cmd ("load", class_files, load_command, _("\
3869 Dynamically load FILE into the running program.\n\
3870 FILE symbols are recorded for access from GDB.\n\
3871 Usage: load [FILE] [OFFSET]\n\
3872 An optional load OFFSET may also be given as a literal address.\n\
3873 When OFFSET is provided, FILE must also be provided. FILE can be provided\n\
3874 on its own."), &cmdlist);
3875 set_cmd_completer (c, filename_completer);
3876
3877 cmd_list_element *overlay_cmd
3878 = add_basic_prefix_cmd ("overlay", class_support,
3879 _("Commands for debugging overlays."), &overlaylist,
3880 0, &cmdlist);
3881
3882 add_com_alias ("ovly", overlay_cmd, class_support, 1);
3883 add_com_alias ("ov", overlay_cmd, class_support, 1);
3884
3885 add_cmd ("map-overlay", class_support, map_overlay_command,
3886 _("Assert that an overlay section is mapped."), &overlaylist);
3887
3888 add_cmd ("unmap-overlay", class_support, unmap_overlay_command,
3889 _("Assert that an overlay section is unmapped."), &overlaylist);
3890
3891 add_cmd ("list-overlays", class_support, list_overlays_command,
3892 _("List mappings of overlay sections."), &overlaylist);
3893
3894 add_cmd ("manual", class_support, overlay_manual_command,
3895 _("Enable overlay debugging."), &overlaylist);
3896 add_cmd ("off", class_support, overlay_off_command,
3897 _("Disable overlay debugging."), &overlaylist);
3898 add_cmd ("auto", class_support, overlay_auto_command,
3899 _("Enable automatic overlay debugging."), &overlaylist);
3900 add_cmd ("load-target", class_support, overlay_load_command,
3901 _("Read the overlay mapping state from the target."), &overlaylist);
3902
3903 /* Filename extension to source language lookup table: */
3904 add_setshow_string_noescape_cmd ("extension-language", class_files,
3905 &ext_args, _("\
3906 Set mapping between filename extension and source language."), _("\
3907 Show mapping between filename extension and source language."), _("\
3908 Usage: set extension-language .foo bar"),
3909 set_ext_lang_command,
3910 show_ext_args,
3911 &setlist, &showlist);
3912
3913 add_info ("extensions", info_ext_lang_command,
3914 _("All filename extensions associated with a source language."));
3915
3916 add_setshow_optional_filename_cmd ("debug-file-directory", class_support,
3917 &debug_file_directory, _("\
3918 Set the directories where separate debug symbols are searched for."), _("\
3919 Show the directories where separate debug symbols are searched for."), _("\
3920 Separate debug symbols are first searched for in the same\n\
3921 directory as the binary, then in the `" DEBUG_SUBDIRECTORY "' subdirectory,\n\
3922 and lastly at the path of the directory of the binary with\n\
3923 each global debug-file-directory component prepended."),
3924 NULL,
3925 show_debug_file_directory,
3926 &setlist, &showlist);
3927
3928 add_setshow_enum_cmd ("symbol-loading", no_class,
3929 print_symbol_loading_enums, &print_symbol_loading,
3930 _("\
3931 Set printing of symbol loading messages."), _("\
3932 Show printing of symbol loading messages."), _("\
3933 off == turn all messages off\n\
3934 brief == print messages for the executable,\n\
3935 and brief messages for shared libraries\n\
3936 full == print messages for the executable,\n\
3937 and messages for each shared library."),
3938 NULL,
3939 NULL,
3940 &setprintlist, &showprintlist);
3941
3942 add_setshow_boolean_cmd ("separate-debug-file", no_class,
3943 &separate_debug_file_debug, _("\
3944 Set printing of separate debug info file search debug."), _("\
3945 Show printing of separate debug info file search debug."), _("\
3946 When on, GDB prints the searched locations while looking for separate debug \
3947 info files."), NULL, NULL, &setdebuglist, &showdebuglist);
3948
3949 #if GDB_SELF_TEST
3950 selftests::register_test
3951 ("filename_language", selftests::filename_language::test_filename_language);
3952 selftests::register_test
3953 ("set_ext_lang_command",
3954 selftests::filename_language::test_set_ext_lang_command);
3955 #endif
3956 }