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