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