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