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