arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / ld / ldlang.c
blob6335e1f67ad101355fbb52fc67537a0ea0a7226e
1 /* Linker command language support.
2 Copyright (C) 1991-2024 Free Software Foundation, Inc.
4 This file is part of the GNU Binutils.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19 MA 02110-1301, USA. */
21 #include "sysdep.h"
22 #include <limits.h>
23 #include "bfd.h"
24 #include "libiberty.h"
25 #include "filenames.h"
26 #include "safe-ctype.h"
27 #include "obstack.h"
28 #include "bfdlink.h"
29 #include "ctf-api.h"
30 #include "ld.h"
31 #include "ldmain.h"
32 #include "ldexp.h"
33 #include "ldlang.h"
34 #include <ldgram.h>
35 #include "ldlex.h"
36 #include "ldmisc.h"
37 #include "ldctor.h"
38 #include "ldfile.h"
39 #include "ldemul.h"
40 #include "fnmatch.h"
41 #include "demangle.h"
42 #include "hashtab.h"
43 #include "elf-bfd.h"
44 #include "bfdver.h"
46 #if BFD_SUPPORTS_PLUGINS
47 #include "plugin.h"
48 #endif
50 #ifndef offsetof
51 #define offsetof(TYPE, MEMBER) ((size_t) & (((TYPE*) 0)->MEMBER))
52 #endif
54 /* Convert between addresses in bytes and sizes in octets.
55 For currently supported targets, octets_per_byte is always a power
56 of two, so we can use shifts. */
57 #define TO_ADDR(X) ((X) >> opb_shift)
58 #define TO_SIZE(X) ((X) << opb_shift)
60 /* Local variables. */
61 static struct obstack stat_obstack;
62 static struct obstack map_obstack;
63 static struct obstack pt_obstack;
65 #define obstack_chunk_alloc xmalloc
66 #define obstack_chunk_free free
67 static const char *entry_symbol_default = "start";
68 static bool map_head_is_link_order = false;
69 static lang_output_section_statement_type *default_common_section;
70 static bool map_option_f;
71 static bfd_vma print_dot;
72 static lang_input_statement_type *first_file;
73 static const char *current_target;
74 static lang_statement_list_type *stat_save[10];
75 static lang_statement_list_type **stat_save_ptr = &stat_save[0];
76 static struct unique_sections *unique_section_list;
77 static struct asneeded_minfo *asneeded_list_head;
78 static unsigned int opb_shift = 0;
80 /* Forward declarations. */
81 static void exp_init_os (etree_type *);
82 static lang_input_statement_type *lookup_name (const char *);
83 static bool wont_add_section_p (asection *,
84 lang_output_section_statement_type *);
85 static void insert_undefined (const char *);
86 static bool sort_def_symbol (struct bfd_link_hash_entry *, void *);
87 static lang_statement_union_type *new_statement (enum statement_enum type,
88 size_t size,
89 lang_statement_list_type *list);
90 static void print_statement (lang_statement_union_type *,
91 lang_output_section_statement_type *);
92 static void print_statement_list (lang_statement_union_type *,
93 lang_output_section_statement_type *);
94 static void print_statements (void);
95 static void print_input_section (asection *, bool);
96 static bool lang_one_common (struct bfd_link_hash_entry *, void *);
97 static void lang_record_phdrs (void);
98 static void lang_do_version_exports_section (void);
99 static void lang_finalize_version_expr_head
100 (struct bfd_elf_version_expr_head *);
101 static void lang_do_memory_regions (bool);
103 /* Exported variables. */
104 const char *output_target;
105 lang_output_section_statement_type *abs_output_section;
106 /* Header for list of statements corresponding to any files involved in the
107 link, either specified from the command-line or added implicitely (eg.
108 archive member used to resolved undefined symbol, wildcard statement from
109 linker script, etc.). Next pointer is in next field of a
110 lang_statement_header_type (reached via header field in a
111 lang_statement_union). */
112 lang_statement_list_type statement_list;
113 lang_statement_list_type lang_os_list;
114 lang_statement_list_type *stat_ptr = &statement_list;
115 /* Header for list of statements corresponding to files used in the final
116 executable. This can be either object file specified on the command-line
117 or library member resolving an undefined reference. Next pointer is in next
118 field of a lang_input_statement_type (reached via input_statement field in a
119 lang_statement_union). */
120 lang_statement_list_type file_chain = { NULL, NULL };
121 /* Header for list of statements corresponding to files specified on the
122 command-line for linking. It thus contains real object files and archive
123 but not archive members. Next pointer is in next_real_file field of a
124 lang_input_statement_type statement (reached via input_statement field in a
125 lang_statement_union). */
126 lang_statement_list_type input_file_chain;
127 static const char *current_input_file;
128 struct bfd_elf_dynamic_list **current_dynamic_list_p;
129 struct bfd_sym_chain entry_symbol = { NULL, NULL };
130 const char *entry_section = ".text";
131 struct lang_input_statement_flags input_flags;
132 bool entry_from_cmdline;
133 bool lang_has_input_file = false;
134 bool had_output_filename = false;
135 bool lang_float_flag = false;
136 bool delete_output_file_on_failure = false;
137 bool enable_linker_version = false;
138 struct lang_phdr *lang_phdr_list;
139 struct lang_nocrossrefs *nocrossref_list;
140 struct asneeded_minfo **asneeded_list_tail;
141 #ifdef ENABLE_LIBCTF
142 static ctf_dict_t *ctf_output;
143 #endif
145 /* Functions that traverse the linker script and might evaluate
146 DEFINED() need to increment this at the start of the traversal. */
147 int lang_statement_iteration = 0;
149 /* Count times through one_lang_size_sections_pass after mark phase. */
150 static int lang_sizing_iteration = 0;
152 /* Return TRUE if the PATTERN argument is a wildcard pattern.
153 Although backslashes are treated specially if a pattern contains
154 wildcards, we do not consider the mere presence of a backslash to
155 be enough to cause the pattern to be treated as a wildcard.
156 That lets us handle DOS filenames more naturally. */
157 #define wildcardp(pattern) (strpbrk ((pattern), "?*[") != NULL)
159 #define new_stat(x, y) \
160 (x##_type *) new_statement (x##_enum, sizeof (x##_type), y)
162 #define outside_section_address(q) \
163 ((q)->output_offset + (q)->output_section->vma)
165 #define outside_symbol_address(q) \
166 ((q)->value + outside_section_address (q->section))
168 /* CTF sections smaller than this are not compressed: compression of
169 dictionaries this small doesn't gain much, and this lets consumers mmap the
170 sections directly out of the ELF file and use them with no decompression
171 overhead if they want to. */
172 #define CTF_COMPRESSION_THRESHOLD 4096
174 void *
175 stat_alloc (size_t size)
177 return obstack_alloc (&stat_obstack, size);
180 /* Code for handling simple wildcards without going through fnmatch,
181 which can be expensive because of charset translations etc. */
183 /* A simple wild is a literal string followed by a single '*',
184 where the literal part is at least 4 characters long. */
186 static bool
187 is_simple_wild (const char *name)
189 size_t len = strcspn (name, "*?[");
190 return len >= 4 && name[len] == '*' && name[len + 1] == '\0';
193 static bool
194 match_simple_wild (const char *pattern, const char *name)
196 /* The first four characters of the pattern are guaranteed valid
197 non-wildcard characters. So we can go faster. */
198 if (pattern[0] != name[0] || pattern[1] != name[1]
199 || pattern[2] != name[2] || pattern[3] != name[3])
200 return false;
202 pattern += 4;
203 name += 4;
204 while (*pattern != '*')
205 if (*name++ != *pattern++)
206 return false;
208 return true;
211 static int
212 name_match (const char *pattern, const char *name)
214 if (is_simple_wild (pattern))
215 return !match_simple_wild (pattern, name);
216 if (wildcardp (pattern))
217 return fnmatch (pattern, name, 0);
218 return strcmp (pattern, name);
221 /* Given an analyzed wildcard_spec SPEC, match it against NAME,
222 returns zero on a match, non-zero if there's no match. */
224 static int
225 spec_match (const struct wildcard_spec *spec, const char *name)
227 size_t nl = spec->namelen;
228 size_t pl = spec->prefixlen;
229 size_t sl = spec->suffixlen;
230 size_t inputlen = strlen (name);
231 int r;
233 if (pl)
235 if (inputlen < pl)
236 return 1;
238 r = memcmp (spec->name, name, pl);
239 if (r)
240 return r;
243 if (sl)
245 if (inputlen < sl)
246 return 1;
248 r = memcmp (spec->name + nl - sl, name + inputlen - sl, sl);
249 if (r)
250 return r;
253 if (nl == pl + sl + 1 && spec->name[pl] == '*')
254 return 0;
256 if (nl > pl)
257 return fnmatch (spec->name + pl, name + pl, 0);
259 if (inputlen >= nl)
260 return name[nl];
262 return 0;
265 static char *
266 ldirname (const char *name)
268 const char *base = lbasename (name);
269 char *dirname;
271 while (base > name && IS_DIR_SEPARATOR (base[-1]))
272 --base;
273 if (base == name)
274 return strdup (".");
275 dirname = strdup (name);
276 dirname[base - name] = '\0';
277 return dirname;
280 /* If PATTERN is of the form archive:file, return a pointer to the
281 separator. If not, return NULL. */
283 static char *
284 archive_path (const char *pattern)
286 char *p = NULL;
288 if (link_info.path_separator == 0)
289 return p;
291 p = strchr (pattern, link_info.path_separator);
292 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
293 if (p == NULL || link_info.path_separator != ':')
294 return p;
296 /* Assume a match on the second char is part of drive specifier,
297 as in "c:\silly.dos". */
298 if (p == pattern + 1 && ISALPHA (*pattern))
299 p = strchr (p + 1, link_info.path_separator);
300 #endif
301 return p;
304 /* Given that FILE_SPEC results in a non-NULL SEP result from archive_path,
305 return whether F matches FILE_SPEC. */
307 static bool
308 input_statement_is_archive_path (const char *file_spec, char *sep,
309 lang_input_statement_type *f)
311 bool match = false;
313 if ((*(sep + 1) == 0
314 || name_match (sep + 1, f->filename) == 0)
315 && ((sep != file_spec)
316 == (f->the_bfd != NULL && f->the_bfd->my_archive != NULL)))
318 match = true;
320 if (sep != file_spec)
322 const char *aname = bfd_get_filename (f->the_bfd->my_archive);
323 *sep = 0;
324 match = name_match (file_spec, aname) == 0;
325 *sep = link_info.path_separator;
328 return match;
331 static bool
332 unique_section_p (const asection *sec,
333 const lang_output_section_statement_type *os)
335 struct unique_sections *unam;
336 const char *secnam;
338 if (!link_info.resolve_section_groups
339 && sec->owner != NULL
340 && bfd_is_group_section (sec->owner, sec))
341 return !(os != NULL
342 && strcmp (os->name, DISCARD_SECTION_NAME) == 0);
344 secnam = sec->name;
345 for (unam = unique_section_list; unam; unam = unam->next)
346 if (name_match (unam->name, secnam) == 0)
347 return true;
349 return false;
352 /* Generic traversal routines for finding matching sections. */
354 /* Return true if FILE matches a pattern in EXCLUDE_LIST, otherwise return
355 false. */
357 static bool
358 walk_wild_file_in_exclude_list (struct name_list *exclude_list,
359 lang_input_statement_type *file)
361 struct name_list *list_tmp;
363 for (list_tmp = exclude_list;
364 list_tmp;
365 list_tmp = list_tmp->next)
367 char *p = archive_path (list_tmp->name);
369 if (p != NULL)
371 if (input_statement_is_archive_path (list_tmp->name, p, file))
372 return true;
375 else if (name_match (list_tmp->name, file->filename) == 0)
376 return true;
378 /* FIXME: Perhaps remove the following at some stage? Matching
379 unadorned archives like this was never documented and has
380 been superceded by the archive:path syntax. */
381 else if (file->the_bfd != NULL
382 && file->the_bfd->my_archive != NULL
383 && name_match (list_tmp->name,
384 bfd_get_filename (file->the_bfd->my_archive)) == 0)
385 return true;
388 return false;
391 /* Add SECTION (from input FILE) to the list of matching sections
392 within PTR (the matching wildcard is SEC). */
394 static void
395 add_matching_section (lang_wild_statement_type *ptr,
396 struct wildcard_list *sec,
397 asection *section,
398 lang_input_statement_type *file)
400 lang_input_matcher_type *new_section;
401 /* Add a section reference to the list. */
402 new_section = new_stat (lang_input_matcher, &ptr->matching_sections);
403 new_section->section = section;
404 new_section->pattern = sec;
405 new_section->input_stmt = file;
408 /* Process section S (from input file FILE) in relation to wildcard
409 statement PTR. We already know that a prefix of the name of S matches
410 some wildcard in PTR's wildcard list. Here we check if the filename
411 matches as well (if it's specified) and if any of the wildcards in fact
412 does match. */
414 static void
415 walk_wild_section_match (lang_wild_statement_type *ptr,
416 lang_input_statement_type *file,
417 asection *s)
419 struct wildcard_list *sec;
420 const char *file_spec = ptr->filename;
421 char *p;
423 /* Check if filenames match. */
424 if (file_spec == NULL)
426 else if ((p = archive_path (file_spec)) != NULL)
428 if (!input_statement_is_archive_path (file_spec, p, file))
429 return;
431 else if (wildcardp (file_spec))
433 if (fnmatch (file_spec, file->filename, 0) != 0)
434 return;
436 else
438 /* XXX Matching against non-wildcard filename in wild statements
439 was done by going through lookup_name, which uses
440 ->local_sym_name to compare against, not ->filename. We retain
441 this behaviour even though the above code paths use filename.
442 It would be more logical to use it here as well, in which
443 case the above wildcard() arm could be folded into this by using
444 name_match. This would also solve the worry of what to do
445 about unset local_sym_name (in which case lookup_name simply adds
446 the input file again). */
447 const char *filename = file->local_sym_name;
448 lang_input_statement_type *arch_is;
449 if (filename && filename_cmp (filename, file_spec) == 0)
451 /* FIXME: see also walk_wild_file_in_exclude_list for why we
452 also check parents BFD (local_sym_)name to match input statements
453 with unadorned archive names. */
454 else if (file->the_bfd
455 && file->the_bfd->my_archive
456 && (arch_is = bfd_usrdata (file->the_bfd->my_archive))
457 && arch_is->local_sym_name
458 && filename_cmp (arch_is->local_sym_name, file_spec) == 0)
460 else
461 return;
464 /* If filename is excluded we're done. */
465 if (walk_wild_file_in_exclude_list (ptr->exclude_name_list, file))
466 return;
468 /* Check section name against each wildcard spec. If there's no
469 wildcard all sections match. */
470 sec = ptr->section_list;
471 if (sec == NULL)
472 add_matching_section (ptr, sec, s, file);
473 else
475 const char *sname = bfd_section_name (s);
476 for (; sec != NULL; sec = sec->next)
478 if (sec->spec.name != NULL
479 && spec_match (&sec->spec, sname) != 0)
480 continue;
482 /* Don't process sections from files which were excluded. */
483 if (!walk_wild_file_in_exclude_list (sec->spec.exclude_name_list,
484 file))
485 add_matching_section (ptr, sec, s, file);
490 /* Return the numerical value of the init_priority attribute from
491 section name NAME. */
493 static int
494 get_init_priority (const asection *sec)
496 const char *name = bfd_section_name (sec);
497 const char *dot;
499 /* GCC uses the following section names for the init_priority
500 attribute with numerical values 101 to 65535 inclusive. A
501 lower value means a higher priority.
503 1: .init_array.NNNNN/.fini_array.NNNNN: Where NNNNN is the
504 decimal numerical value of the init_priority attribute.
505 The order of execution in .init_array is forward and
506 .fini_array is backward.
507 2: .ctors.NNNNN/.dtors.NNNNN: Where NNNNN is 65535 minus the
508 decimal numerical value of the init_priority attribute.
509 The order of execution in .ctors is backward and .dtors
510 is forward.
512 .init_array.NNNNN sections would normally be placed in an output
513 .init_array section, .fini_array.NNNNN in .fini_array,
514 .ctors.NNNNN in .ctors, and .dtors.NNNNN in .dtors. This means
515 we should sort by increasing number (and could just use
516 SORT_BY_NAME in scripts). However if .ctors.NNNNN sections are
517 being placed in .init_array (which may also contain
518 .init_array.NNNNN sections) or .dtors.NNNNN sections are being
519 placed in .fini_array then we need to extract the init_priority
520 attribute and sort on that. */
521 dot = strrchr (name, '.');
522 if (dot != NULL && ISDIGIT (dot[1]))
524 char *end;
525 unsigned long init_priority = strtoul (dot + 1, &end, 10);
526 if (*end == 0)
528 if (dot == name + 6
529 && (strncmp (name, ".ctors", 6) == 0
530 || strncmp (name, ".dtors", 6) == 0))
531 init_priority = 65535 - init_priority;
532 if (init_priority <= INT_MAX)
533 return init_priority;
536 return -1;
539 /* Compare sections ASEC and BSEC according to SORT. */
541 static int
542 compare_section (sort_type sort, asection *asec, asection *bsec, bool reversed)
544 int ret;
545 int a_priority, b_priority;
547 switch (sort)
549 default:
550 abort ();
552 case by_init_priority:
553 a_priority = get_init_priority (asec);
554 b_priority = get_init_priority (bsec);
555 if (a_priority < 0 || b_priority < 0)
556 goto sort_by_name;
557 if (reversed)
558 ret = b_priority - a_priority;
559 else
560 ret = a_priority - b_priority;
561 if (ret)
562 break;
563 else
564 goto sort_by_name;
566 case by_alignment_name:
567 ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
568 if (ret)
569 break;
570 /* Fall through. */
572 case by_name:
573 sort_by_name:
574 if (reversed)
575 ret = strcmp (bfd_section_name (bsec), bfd_section_name (asec));
576 else
577 ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
578 break;
580 case by_name_alignment:
581 if (reversed)
582 ret = strcmp (bfd_section_name (bsec), bfd_section_name (asec));
583 else
584 ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
585 if (ret)
586 break;
587 /* Fall through. */
589 case by_alignment:
590 ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
591 break;
594 return ret;
597 /* PE puts the sort key in the input statement. */
599 static const char *
600 sort_filename (bfd *abfd)
602 lang_input_statement_type *is = bfd_usrdata (abfd);
603 if (is->sort_key)
604 return is->sort_key;
605 return bfd_get_filename (abfd);
608 /* Handle wildcard sorting. This returns the place in a binary search tree
609 where this FILE:SECTION should be inserted for wild statement WILD where
610 the spec SEC was the matching one. The tree is later linearized. */
612 static lang_section_bst_type **
613 wild_sort (lang_wild_statement_type *wild,
614 struct wildcard_list *sec,
615 lang_input_statement_type *file,
616 asection *section)
618 lang_section_bst_type **tree;
620 if (!wild->filenames_sorted
621 && (sec == NULL || sec->spec.sorted == none
622 || sec->spec.sorted == by_none))
624 /* We might be called even if _this_ spec doesn't need sorting,
625 in which case we simply append at the right end of tree. */
626 return wild->rightmost;
629 tree = &wild->tree;
630 while (*tree)
632 /* Sorting by filename takes precedence over sorting by section
633 name. */
635 if (wild->filenames_sorted)
637 const char *fn, *ln;
638 bool fa, la;
639 int i;
640 asection *lsec = (*tree)->section;
642 /* The PE support for the .idata section as generated by
643 dlltool assumes that files will be sorted by the name of
644 the archive and then the name of the file within the
645 archive. */
647 fa = file->the_bfd->my_archive != NULL;
648 if (fa)
649 fn = sort_filename (file->the_bfd->my_archive);
650 else
651 fn = sort_filename (file->the_bfd);
653 la = lsec->owner->my_archive != NULL;
654 if (la)
655 ln = sort_filename (lsec->owner->my_archive);
656 else
657 ln = sort_filename (lsec->owner);
659 if (wild->filenames_reversed)
660 i = filename_cmp (ln, fn);
661 else
662 i = filename_cmp (fn, ln);
664 if (i > 0)
665 { tree = &((*tree)->right); continue; }
666 else if (i < 0)
667 { tree = &((*tree)->left); continue; }
669 if (fa || la)
671 if (fa)
672 fn = sort_filename (file->the_bfd);
673 if (la)
674 ln = sort_filename (lsec->owner);
676 if (wild->filenames_reversed)
677 i = filename_cmp (ln, fn);
678 else
679 i = filename_cmp (fn, ln);
681 if (i > 0)
682 { tree = &((*tree)->right); continue; }
683 else if (i < 0)
684 { tree = &((*tree)->left); continue; }
688 /* Here either the files are not sorted by name, or we are
689 looking at the sections for this file. */
691 /* Find the correct node to append this section. */
692 if (sec && sec->spec.sorted != none && sec->spec.sorted != by_none
693 && compare_section (sec->spec.sorted, section, (*tree)->section, sec->spec.reversed) < 0)
694 tree = &((*tree)->left);
695 else
696 tree = &((*tree)->right);
699 return tree;
702 /* Use wild_sort to build a BST to sort sections. */
704 static void
705 output_section_callback_sort (lang_wild_statement_type *ptr,
706 struct wildcard_list *sec,
707 asection *section,
708 lang_input_statement_type *file,
709 void *output)
711 lang_section_bst_type *node;
712 lang_section_bst_type **tree;
713 lang_output_section_statement_type *os;
715 os = (lang_output_section_statement_type *) output;
717 if (unique_section_p (section, os))
718 return;
720 /* Don't add sections to the tree when we already know that
721 lang_add_section won't do anything with it. */
722 if (wont_add_section_p (section, os))
723 return;
725 node = (lang_section_bst_type *) xmalloc (sizeof (lang_section_bst_type));
726 node->left = 0;
727 node->right = 0;
728 node->section = section;
729 node->pattern = ptr->section_list;
731 tree = wild_sort (ptr, sec, file, section);
732 if (tree != NULL)
734 *tree = node;
735 if (tree == ptr->rightmost)
736 ptr->rightmost = &node->right;
740 /* Convert a sorted sections' BST back to list form. */
742 static void
743 output_section_callback_tree_to_list (lang_wild_statement_type *ptr,
744 lang_section_bst_type *tree,
745 void *output)
747 if (tree->left)
748 output_section_callback_tree_to_list (ptr, tree->left, output);
750 lang_add_section (&ptr->children, tree->section, tree->pattern,
751 ptr->section_flag_list,
752 (lang_output_section_statement_type *) output);
754 if (tree->right)
755 output_section_callback_tree_to_list (ptr, tree->right, output);
757 free (tree);
761 /* Sections are matched against wildcard statements via a prefix tree.
762 The prefix tree holds prefixes of all matching patterns (up to the first
763 wildcard character), and the wild statement from which those patterns
764 came. When matching a section name against the tree we're walking through
765 the tree character by character. Each statement we hit is one that
766 potentially matches. This is checked by actually going through the
767 (glob) matching routines.
769 When the section name turns out to actually match we record that section
770 in the wild statements list of matching sections. */
772 /* A prefix can be matched by multiple statement, so we need a list of them. */
773 struct wild_stmt_list
775 lang_wild_statement_type *stmt;
776 struct wild_stmt_list *next;
779 /* The prefix tree itself. */
780 struct prefixtree
782 /* The list of all children (linked via .next). */
783 struct prefixtree *child;
784 struct prefixtree *next;
785 /* This tree node is responsible for the prefix of parent plus 'c'. */
786 char c;
787 /* The statements that potentially can match this prefix. */
788 struct wild_stmt_list *stmt;
791 /* We always have a root node in the prefix tree. It corresponds to the
792 empty prefix. E.g. a glob like "*" would sit in this root. */
793 static struct prefixtree the_root, *ptroot = &the_root;
795 /* Given a prefix tree in *TREE, corresponding to prefix P, find or
796 INSERT the tree node corresponding to prefix P+C. */
798 static struct prefixtree *
799 get_prefix_tree (struct prefixtree **tree, char c, bool insert)
801 struct prefixtree *t;
802 for (t = *tree; t; t = t->next)
803 if (t->c == c)
804 return t;
805 if (!insert)
806 return NULL;
807 t = (struct prefixtree *) obstack_alloc (&pt_obstack, sizeof *t);
808 t->child = NULL;
809 t->next = *tree;
810 t->c = c;
811 t->stmt = NULL;
812 *tree = t;
813 return t;
816 /* Add STMT to the set of statements that can be matched by the prefix
817 corresponding to prefix tree T. */
819 static void
820 pt_add_stmt (struct prefixtree *t, lang_wild_statement_type *stmt)
822 struct wild_stmt_list *sl, **psl;
823 sl = (struct wild_stmt_list *) obstack_alloc (&pt_obstack, sizeof *sl);
824 sl->stmt = stmt;
825 sl->next = NULL;
826 psl = &t->stmt;
827 while (*psl)
828 psl = &(*psl)->next;
829 *psl = sl;
832 /* Insert STMT into the global prefix tree. */
834 static void
835 insert_prefix_tree (lang_wild_statement_type *stmt)
837 struct wildcard_list *sec;
838 struct prefixtree *t;
840 if (!stmt->section_list)
842 /* If we have no section_list (no wildcards in the wild STMT),
843 then every section name will match, so add this to the root. */
844 pt_add_stmt (ptroot, stmt);
845 return;
848 for (sec = stmt->section_list; sec; sec = sec->next)
850 const char *name = sec->spec.name ? sec->spec.name : "*";
851 char c;
852 t = ptroot;
853 for (; (c = *name); name++)
855 if (c == '*' || c == '[' || c == '?')
856 break;
857 t = get_prefix_tree (&t->child, c, true);
859 /* If we hit a glob character, the matching prefix is what we saw
860 until now. If we hit the end of pattern (hence it's no glob) then
861 we can do better: we only need to record a match when a section name
862 completely matches, not merely a prefix, so record the trailing 0
863 as well. */
864 if (!c)
865 t = get_prefix_tree (&t->child, 0, true);
866 pt_add_stmt (t, stmt);
870 /* Dump T indented by INDENT spaces. */
872 static void
873 debug_prefix_tree_rec (struct prefixtree *t, int indent)
875 for (; t; t = t->next)
877 struct wild_stmt_list *sl;
878 printf ("%*s %c", indent, "", t->c);
879 for (sl = t->stmt; sl; sl = sl->next)
881 struct wildcard_list *curr;
882 printf (" %p ", sl->stmt);
883 for (curr = sl->stmt->section_list; curr; curr = curr->next)
884 printf ("%s ", curr->spec.name ? curr->spec.name : "*");
886 printf ("\n");
887 debug_prefix_tree_rec (t->child, indent + 2);
891 /* Dump the global prefix tree. */
893 static void
894 debug_prefix_tree (void)
896 debug_prefix_tree_rec (ptroot, 2);
899 /* Like strcspn() but start to look from the end to beginning of
900 S. Returns the length of the suffix of S consisting entirely
901 of characters not in REJECT. */
903 static size_t
904 rstrcspn (const char *s, const char *reject)
906 size_t len = strlen (s), sufflen = 0;
907 while (len--)
909 char c = s[len];
910 if (strchr (reject, c) != 0)
911 break;
912 sufflen++;
914 return sufflen;
917 /* Analyze the wildcards in wild statement PTR to setup various
918 things for quick matching. */
920 static void
921 analyze_walk_wild_section_handler (lang_wild_statement_type *ptr)
923 struct wildcard_list *sec;
925 ptr->tree = NULL;
926 ptr->rightmost = &ptr->tree;
928 for (sec = ptr->section_list; sec != NULL; sec = sec->next)
930 if (sec->spec.name)
932 sec->spec.namelen = strlen (sec->spec.name);
933 sec->spec.prefixlen = strcspn (sec->spec.name, "?*[");
934 sec->spec.suffixlen = rstrcspn (sec->spec.name + sec->spec.prefixlen,
935 "?*]");
937 else
938 sec->spec.namelen = sec->spec.prefixlen = sec->spec.suffixlen = 0;
941 insert_prefix_tree (ptr);
944 /* Match all sections from FILE against the global prefix tree,
945 and record them into each wild statement that has a match. */
947 static void
948 resolve_wild_sections (lang_input_statement_type *file)
950 asection *s;
952 if (file->flags.just_syms)
953 return;
955 for (s = file->the_bfd->sections; s != NULL; s = s->next)
957 const char *sname = bfd_section_name (s);
958 char c = 1;
959 struct prefixtree *t = ptroot;
960 //printf (" YYY consider %s of %s\n", sname, file->the_bfd->filename);
963 if (t->stmt)
965 struct wild_stmt_list *sl;
966 for (sl = t->stmt; sl; sl = sl->next)
968 walk_wild_section_match (sl->stmt, file, s);
969 //printf (" ZZZ maybe place into %p\n", sl->stmt);
972 if (!c)
973 break;
974 c = *sname++;
975 t = get_prefix_tree (&t->child, c, false);
977 while (t);
981 /* Match all sections from all input files against the global prefix tree. */
983 static void
984 resolve_wilds (void)
986 LANG_FOR_EACH_INPUT_STATEMENT (f)
988 //printf("XXX %s\n", f->filename);
989 if (f->the_bfd == NULL
990 || !bfd_check_format (f->the_bfd, bfd_archive))
991 resolve_wild_sections (f);
992 else
994 bfd *member;
996 /* This is an archive file. We must map each member of the
997 archive separately. */
998 member = bfd_openr_next_archived_file (f->the_bfd, NULL);
999 while (member != NULL)
1001 /* When lookup_name is called, it will call the add_symbols
1002 entry point for the archive. For each element of the
1003 archive which is included, BFD will call ldlang_add_file,
1004 which will set the usrdata field of the member to the
1005 lang_input_statement. */
1006 if (bfd_usrdata (member) != NULL)
1007 resolve_wild_sections (bfd_usrdata (member));
1009 member = bfd_openr_next_archived_file (f->the_bfd, member);
1015 /* For each input section that matches wild statement S calls
1016 CALLBACK with DATA. */
1018 static void
1019 walk_wild (lang_wild_statement_type *s, callback_t callback, void *data)
1021 lang_statement_union_type *l;
1023 for (l = s->matching_sections.head; l; l = l->header.next)
1025 (*callback) (s, l->input_matcher.pattern, l->input_matcher.section,
1026 l->input_matcher.input_stmt, data);
1030 /* lang_for_each_statement walks the parse tree and calls the provided
1031 function for each node, except those inside output section statements
1032 with constraint set to -1. */
1034 void
1035 lang_for_each_statement_worker (void (*func) (lang_statement_union_type *),
1036 lang_statement_union_type *s)
1038 for (; s != NULL; s = s->header.next)
1040 func (s);
1042 switch (s->header.type)
1044 case lang_constructors_statement_enum:
1045 lang_for_each_statement_worker (func, constructor_list.head);
1046 break;
1047 case lang_output_section_statement_enum:
1048 if (s->output_section_statement.constraint != -1)
1049 lang_for_each_statement_worker
1050 (func, s->output_section_statement.children.head);
1051 break;
1052 case lang_wild_statement_enum:
1053 lang_for_each_statement_worker (func,
1054 s->wild_statement.children.head);
1055 break;
1056 case lang_group_statement_enum:
1057 lang_for_each_statement_worker (func,
1058 s->group_statement.children.head);
1059 break;
1060 case lang_data_statement_enum:
1061 case lang_reloc_statement_enum:
1062 case lang_object_symbols_statement_enum:
1063 case lang_output_statement_enum:
1064 case lang_target_statement_enum:
1065 case lang_input_section_enum:
1066 case lang_input_statement_enum:
1067 case lang_assignment_statement_enum:
1068 case lang_padding_statement_enum:
1069 case lang_address_statement_enum:
1070 case lang_fill_statement_enum:
1071 case lang_insert_statement_enum:
1072 break;
1073 default:
1074 FAIL ();
1075 break;
1080 void
1081 lang_for_each_statement (void (*func) (lang_statement_union_type *))
1083 lang_for_each_statement_worker (func, statement_list.head);
1086 /*----------------------------------------------------------------------*/
1088 void
1089 lang_list_init (lang_statement_list_type *list)
1091 list->head = NULL;
1092 list->tail = &list->head;
1095 static void
1096 lang_statement_append (lang_statement_list_type *list,
1097 void *element,
1098 void *field)
1100 *(list->tail) = element;
1101 list->tail = field;
1104 void
1105 push_stat_ptr (lang_statement_list_type *new_ptr)
1107 if (stat_save_ptr >= stat_save + sizeof (stat_save) / sizeof (stat_save[0]))
1108 abort ();
1109 *stat_save_ptr++ = stat_ptr;
1110 stat_ptr = new_ptr;
1113 void
1114 pop_stat_ptr (void)
1116 if (stat_save_ptr <= stat_save)
1117 abort ();
1118 stat_ptr = *--stat_save_ptr;
1121 /* Build a new statement node for the parse tree. */
1123 static lang_statement_union_type *
1124 new_statement (enum statement_enum type,
1125 size_t size,
1126 lang_statement_list_type *list)
1128 lang_statement_union_type *new_stmt;
1130 new_stmt = stat_alloc (size);
1131 new_stmt->header.type = type;
1132 new_stmt->header.next = NULL;
1133 lang_statement_append (list, new_stmt, &new_stmt->header.next);
1134 return new_stmt;
1137 /* Build a new input file node for the language. There are several
1138 ways in which we treat an input file, eg, we only look at symbols,
1139 or prefix it with a -l etc.
1141 We can be supplied with requests for input files more than once;
1142 they may, for example be split over several lines like foo.o(.text)
1143 foo.o(.data) etc, so when asked for a file we check that we haven't
1144 got it already so we don't duplicate the bfd. */
1146 static lang_input_statement_type *
1147 new_afile (const char *name,
1148 lang_input_file_enum_type file_type,
1149 const char *target,
1150 const char *from_filename)
1152 lang_input_statement_type *p;
1154 lang_has_input_file = true;
1156 /* PR 30632: It is OK for name to be NULL. For example
1157 see the initialization of first_file in lang_init(). */
1158 if (name != NULL)
1160 name = ldfile_possibly_remap_input (name);
1161 /* But if a name is remapped to NULL, it should be ignored. */
1162 if (name == NULL)
1163 return NULL;
1166 p = new_stat (lang_input_statement, stat_ptr);
1167 memset (&p->the_bfd, 0,
1168 sizeof (*p) - offsetof (lang_input_statement_type, the_bfd));
1169 p->extra_search_path = NULL;
1170 p->target = target;
1171 p->flags.dynamic = input_flags.dynamic;
1172 p->flags.add_DT_NEEDED_for_dynamic = input_flags.add_DT_NEEDED_for_dynamic;
1173 p->flags.add_DT_NEEDED_for_regular = input_flags.add_DT_NEEDED_for_regular;
1174 p->flags.whole_archive = input_flags.whole_archive;
1175 p->flags.sysrooted = input_flags.sysrooted;
1176 p->sort_key = NULL;
1178 switch (file_type)
1180 case lang_input_file_is_symbols_only_enum:
1181 p->filename = name;
1182 p->local_sym_name = name;
1183 p->flags.real = true;
1184 p->flags.just_syms = true;
1185 break;
1186 case lang_input_file_is_fake_enum:
1187 p->filename = name;
1188 p->local_sym_name = name;
1189 break;
1190 case lang_input_file_is_l_enum:
1191 if (name[0] == ':' && name[1] != '\0')
1193 p->filename = name + 1;
1194 p->flags.full_name_provided = true;
1196 else
1197 p->filename = name;
1198 p->local_sym_name = concat ("-l", name, (const char *) NULL);
1199 p->flags.maybe_archive = true;
1200 p->flags.real = true;
1201 p->flags.search_dirs = true;
1202 break;
1203 case lang_input_file_is_marker_enum:
1204 p->filename = name;
1205 p->local_sym_name = name;
1206 p->flags.search_dirs = true;
1207 break;
1208 case lang_input_file_is_search_file_enum:
1209 p->filename = name;
1210 p->local_sym_name = name;
1211 /* If name is a relative path, search the directory of the current linker
1212 script first. */
1213 if (from_filename && !IS_ABSOLUTE_PATH (name))
1214 p->extra_search_path = ldirname (from_filename);
1215 p->flags.real = true;
1216 p->flags.search_dirs = true;
1217 break;
1218 case lang_input_file_is_file_enum:
1219 p->filename = name;
1220 p->local_sym_name = name;
1221 p->flags.real = true;
1222 break;
1223 default:
1224 FAIL ();
1227 lang_statement_append (&input_file_chain, p, &p->next_real_file);
1228 return p;
1231 lang_input_statement_type *
1232 lang_add_input_file (const char *name,
1233 lang_input_file_enum_type file_type,
1234 const char *target)
1236 if (name != NULL
1237 && (*name == '=' || startswith (name, "$SYSROOT")))
1239 lang_input_statement_type *ret;
1240 char *sysrooted_name
1241 = concat (ld_sysroot,
1242 name + (*name == '=' ? 1 : strlen ("$SYSROOT")),
1243 (const char *) NULL);
1245 /* We've now forcibly prepended the sysroot, making the input
1246 file independent of the context. Therefore, temporarily
1247 force a non-sysrooted context for this statement, so it won't
1248 get the sysroot prepended again when opened. (N.B. if it's a
1249 script, any child nodes with input files starting with "/"
1250 will be handled as "sysrooted" as they'll be found to be
1251 within the sysroot subdirectory.) */
1252 unsigned int outer_sysrooted = input_flags.sysrooted;
1253 input_flags.sysrooted = 0;
1254 ret = new_afile (sysrooted_name, file_type, target, NULL);
1255 input_flags.sysrooted = outer_sysrooted;
1256 return ret;
1259 return new_afile (name, file_type, target, current_input_file);
1262 struct out_section_hash_entry
1264 struct bfd_hash_entry root;
1265 lang_statement_union_type s;
1268 /* The hash table. */
1270 static struct bfd_hash_table output_section_statement_table;
1272 /* Support routines for the hash table used by lang_output_section_find,
1273 initialize the table, fill in an entry and remove the table. */
1275 static struct bfd_hash_entry *
1276 output_section_statement_newfunc (struct bfd_hash_entry *entry,
1277 struct bfd_hash_table *table,
1278 const char *string)
1280 lang_output_section_statement_type **nextp;
1281 struct out_section_hash_entry *ret;
1283 if (entry == NULL)
1285 entry = (struct bfd_hash_entry *) bfd_hash_allocate (table,
1286 sizeof (*ret));
1287 if (entry == NULL)
1288 return entry;
1291 entry = bfd_hash_newfunc (entry, table, string);
1292 if (entry == NULL)
1293 return entry;
1295 ret = (struct out_section_hash_entry *) entry;
1296 memset (&ret->s, 0, sizeof (ret->s));
1297 ret->s.header.type = lang_output_section_statement_enum;
1298 ret->s.output_section_statement.subsection_alignment = NULL;
1299 ret->s.output_section_statement.section_alignment = NULL;
1300 ret->s.output_section_statement.block_value = 1;
1301 lang_list_init (&ret->s.output_section_statement.children);
1302 lang_list_init (&ret->s.output_section_statement.sort_children);
1303 lang_statement_append (stat_ptr, &ret->s, &ret->s.header.next);
1305 /* For every output section statement added to the list, except the
1306 first one, lang_os_list.tail points to the "next"
1307 field of the last element of the list. */
1308 if (lang_os_list.head != NULL)
1309 ret->s.output_section_statement.prev
1310 = ((lang_output_section_statement_type *)
1311 ((char *) lang_os_list.tail
1312 - offsetof (lang_output_section_statement_type, next)));
1314 /* GCC's strict aliasing rules prevent us from just casting the
1315 address, so we store the pointer in a variable and cast that
1316 instead. */
1317 nextp = &ret->s.output_section_statement.next;
1318 lang_statement_append (&lang_os_list, &ret->s, nextp);
1319 return &ret->root;
1322 static void
1323 output_section_statement_table_init (void)
1325 if (!bfd_hash_table_init_n (&output_section_statement_table,
1326 output_section_statement_newfunc,
1327 sizeof (struct out_section_hash_entry),
1328 61))
1329 einfo (_("%F%P: can not create hash table: %E\n"));
1332 static void
1333 output_section_statement_table_free (void)
1335 bfd_hash_table_free (&output_section_statement_table);
1338 /* Build enough state so that the parser can build its tree. */
1340 void
1341 lang_init (void)
1343 obstack_begin (&stat_obstack, 1000);
1344 obstack_init (&pt_obstack);
1346 stat_ptr = &statement_list;
1348 output_section_statement_table_init ();
1350 lang_list_init (stat_ptr);
1352 lang_list_init (&input_file_chain);
1353 lang_list_init (&lang_os_list);
1354 lang_list_init (&file_chain);
1355 first_file = lang_add_input_file (NULL, lang_input_file_is_marker_enum,
1356 NULL);
1357 abs_output_section =
1358 lang_output_section_statement_lookup (BFD_ABS_SECTION_NAME, 0, 1);
1360 abs_output_section->bfd_section = bfd_abs_section_ptr;
1362 asneeded_list_head = NULL;
1363 asneeded_list_tail = &asneeded_list_head;
1366 void
1367 lang_finish (void)
1369 output_section_statement_table_free ();
1370 ldfile_remap_input_free ();
1373 /*----------------------------------------------------------------------
1374 A region is an area of memory declared with the
1375 MEMORY { name:org=exp, len=exp ... }
1376 syntax.
1378 We maintain a list of all the regions here.
1380 If no regions are specified in the script, then the default is used
1381 which is created when looked up to be the entire data space.
1383 If create is true we are creating a region inside a MEMORY block.
1384 In this case it is probably an error to create a region that has
1385 already been created. If we are not inside a MEMORY block it is
1386 dubious to use an undeclared region name (except DEFAULT_MEMORY_REGION)
1387 and so we issue a warning.
1389 Each region has at least one name. The first name is either
1390 DEFAULT_MEMORY_REGION or the name given in the MEMORY block. You can add
1391 alias names to an existing region within a script with
1392 REGION_ALIAS (alias, region_name). Each name corresponds to at most one
1393 region. */
1395 static lang_memory_region_type *lang_memory_region_list;
1396 static lang_memory_region_type **lang_memory_region_list_tail
1397 = &lang_memory_region_list;
1399 lang_memory_region_type *
1400 lang_memory_region_lookup (const char *const name, bool create)
1402 lang_memory_region_name *n;
1403 lang_memory_region_type *r;
1404 lang_memory_region_type *new_region;
1406 /* NAME is NULL for LMA memspecs if no region was specified. */
1407 if (name == NULL)
1408 return NULL;
1410 for (r = lang_memory_region_list; r != NULL; r = r->next)
1411 for (n = &r->name_list; n != NULL; n = n->next)
1412 if (strcmp (n->name, name) == 0)
1414 if (create)
1415 einfo (_("%P:%pS: warning: redeclaration of memory region `%s'\n"),
1416 NULL, name);
1417 return r;
1420 if (!create && strcmp (name, DEFAULT_MEMORY_REGION))
1421 einfo (_("%P:%pS: warning: memory region `%s' not declared\n"),
1422 NULL, name);
1424 new_region = stat_alloc (sizeof (lang_memory_region_type));
1426 new_region->name_list.name = xstrdup (name);
1427 new_region->name_list.next = NULL;
1428 new_region->next = NULL;
1429 new_region->origin_exp = NULL;
1430 new_region->origin = 0;
1431 new_region->length_exp = NULL;
1432 new_region->length = ~(bfd_size_type) 0;
1433 new_region->current = 0;
1434 new_region->last_os = NULL;
1435 new_region->flags = 0;
1436 new_region->not_flags = 0;
1437 new_region->had_full_message = false;
1439 *lang_memory_region_list_tail = new_region;
1440 lang_memory_region_list_tail = &new_region->next;
1442 return new_region;
1445 void
1446 lang_memory_region_alias (const char *alias, const char *region_name)
1448 lang_memory_region_name *n;
1449 lang_memory_region_type *r;
1450 lang_memory_region_type *region;
1452 /* The default region must be unique. This ensures that it is not necessary
1453 to iterate through the name list if someone wants the check if a region is
1454 the default memory region. */
1455 if (strcmp (region_name, DEFAULT_MEMORY_REGION) == 0
1456 || strcmp (alias, DEFAULT_MEMORY_REGION) == 0)
1457 einfo (_("%F%P:%pS: error: alias for default memory region\n"), NULL);
1459 /* Look for the target region and check if the alias is not already
1460 in use. */
1461 region = NULL;
1462 for (r = lang_memory_region_list; r != NULL; r = r->next)
1463 for (n = &r->name_list; n != NULL; n = n->next)
1465 if (region == NULL && strcmp (n->name, region_name) == 0)
1466 region = r;
1467 if (strcmp (n->name, alias) == 0)
1468 einfo (_("%F%P:%pS: error: redefinition of memory region "
1469 "alias `%s'\n"),
1470 NULL, alias);
1473 /* Check if the target region exists. */
1474 if (region == NULL)
1475 einfo (_("%F%P:%pS: error: memory region `%s' "
1476 "for alias `%s' does not exist\n"),
1477 NULL, region_name, alias);
1479 /* Add alias to region name list. */
1480 n = stat_alloc (sizeof (lang_memory_region_name));
1481 n->name = xstrdup (alias);
1482 n->next = region->name_list.next;
1483 region->name_list.next = n;
1486 static lang_memory_region_type *
1487 lang_memory_default (asection *section)
1489 lang_memory_region_type *p;
1491 flagword sec_flags = section->flags;
1493 /* Override SEC_DATA to mean a writable section. */
1494 if ((sec_flags & (SEC_ALLOC | SEC_READONLY | SEC_CODE)) == SEC_ALLOC)
1495 sec_flags |= SEC_DATA;
1497 for (p = lang_memory_region_list; p != NULL; p = p->next)
1499 if ((p->flags & sec_flags) != 0
1500 && (p->not_flags & sec_flags) == 0)
1502 return p;
1505 return lang_memory_region_lookup (DEFAULT_MEMORY_REGION, false);
1508 /* Get the output section statement directly from the userdata. */
1510 lang_output_section_statement_type *
1511 lang_output_section_get (const asection *output_section)
1513 return bfd_section_userdata (output_section);
1516 /* Find or create an output_section_statement with the given NAME.
1517 If CONSTRAINT is non-zero match one with that constraint, otherwise
1518 match any non-negative constraint. If CREATE is 0 return NULL when
1519 no match exists. If CREATE is 1, create an output_section_statement
1520 when no match exists or if CONSTRAINT is SPECIAL. If CREATE is 2,
1521 always make a new output_section_statement. */
1523 lang_output_section_statement_type *
1524 lang_output_section_statement_lookup (const char *name,
1525 int constraint,
1526 int create)
1528 struct out_section_hash_entry *entry;
1530 entry = ((struct out_section_hash_entry *)
1531 bfd_hash_lookup (&output_section_statement_table, name,
1532 create != 0, false));
1533 if (entry == NULL)
1535 if (create)
1536 einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1537 return NULL;
1540 if (entry->s.output_section_statement.name != NULL)
1542 /* We have a section of this name, but it might not have the correct
1543 constraint. */
1544 struct out_section_hash_entry *last_ent;
1546 name = entry->s.output_section_statement.name;
1549 if (create != 2
1550 && !(create && constraint == SPECIAL)
1551 && (constraint == entry->s.output_section_statement.constraint
1552 || (constraint == 0
1553 && entry->s.output_section_statement.constraint >= 0)))
1554 return &entry->s.output_section_statement;
1555 last_ent = entry;
1556 entry = (struct out_section_hash_entry *) entry->root.next;
1558 while (entry != NULL
1559 && name == entry->s.output_section_statement.name);
1561 if (!create)
1562 return NULL;
1564 entry
1565 = ((struct out_section_hash_entry *)
1566 output_section_statement_newfunc (NULL,
1567 &output_section_statement_table,
1568 name));
1569 if (entry == NULL)
1571 einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1572 return NULL;
1574 entry->root = last_ent->root;
1575 last_ent->root.next = &entry->root;
1578 entry->s.output_section_statement.name = name;
1579 entry->s.output_section_statement.constraint = constraint;
1580 entry->s.output_section_statement.dup_output = (create == 2
1581 || constraint == SPECIAL);
1582 return &entry->s.output_section_statement;
1585 /* Find the next output_section_statement with the same name as OS.
1586 If CONSTRAINT is non-zero, find one with that constraint otherwise
1587 match any non-negative constraint. */
1589 lang_output_section_statement_type *
1590 next_matching_output_section_statement (lang_output_section_statement_type *os,
1591 int constraint)
1593 /* All output_section_statements are actually part of a
1594 struct out_section_hash_entry. */
1595 struct out_section_hash_entry *entry = (struct out_section_hash_entry *)
1596 ((char *) os
1597 - offsetof (struct out_section_hash_entry, s.output_section_statement));
1598 const char *name = os->name;
1600 ASSERT (name == entry->root.string);
1603 entry = (struct out_section_hash_entry *) entry->root.next;
1604 if (entry == NULL
1605 || name != entry->s.output_section_statement.name)
1606 return NULL;
1608 while (constraint != entry->s.output_section_statement.constraint
1609 && (constraint != 0
1610 || entry->s.output_section_statement.constraint < 0));
1612 return &entry->s.output_section_statement;
1615 /* A variant of lang_output_section_find used by place_orphan.
1616 Returns the output statement that should precede a new output
1617 statement for SEC. If an exact match is found on certain flags,
1618 sets *EXACT too. */
1620 lang_output_section_statement_type *
1621 lang_output_section_find_by_flags (const asection *sec,
1622 flagword sec_flags,
1623 lang_output_section_statement_type **exact,
1624 lang_match_sec_type_func match_type)
1626 lang_output_section_statement_type *first, *look, *found;
1627 flagword look_flags, differ;
1629 /* We know the first statement on this list is *ABS*. May as well
1630 skip it. */
1631 first = (void *) lang_os_list.head;
1632 first = first->next;
1634 /* First try for an exact match. */
1635 found = NULL;
1636 for (look = first; look; look = look->next)
1638 look_flags = look->flags;
1639 if (look->bfd_section != NULL)
1641 look_flags = look->bfd_section->flags;
1642 if (match_type && !match_type (link_info.output_bfd,
1643 look->bfd_section,
1644 sec->owner, sec))
1645 continue;
1647 differ = look_flags ^ sec_flags;
1648 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY
1649 | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1650 found = look;
1652 if (found != NULL)
1654 if (exact != NULL)
1655 *exact = found;
1656 return found;
1659 if ((sec_flags & SEC_CODE) != 0
1660 && (sec_flags & SEC_ALLOC) != 0)
1662 /* Try for a rw code section. */
1663 for (look = first; look; look = look->next)
1665 look_flags = look->flags;
1666 if (look->bfd_section != NULL)
1668 look_flags = look->bfd_section->flags;
1669 if (match_type && !match_type (link_info.output_bfd,
1670 look->bfd_section,
1671 sec->owner, sec))
1672 continue;
1674 differ = look_flags ^ sec_flags;
1675 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1676 | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1677 found = look;
1680 else if ((sec_flags & SEC_READONLY) != 0
1681 && (sec_flags & SEC_ALLOC) != 0)
1683 /* .rodata can go after .text, .sdata2 after .rodata. */
1684 for (look = first; look; look = look->next)
1686 look_flags = look->flags;
1687 if (look->bfd_section != NULL)
1689 look_flags = look->bfd_section->flags;
1690 if (match_type && !match_type (link_info.output_bfd,
1691 look->bfd_section,
1692 sec->owner, sec))
1693 continue;
1695 differ = look_flags ^ sec_flags;
1696 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1697 | SEC_READONLY | SEC_SMALL_DATA))
1698 || (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1699 | SEC_READONLY))
1700 && !(look_flags & SEC_SMALL_DATA)))
1701 found = look;
1704 else if ((sec_flags & SEC_THREAD_LOCAL) != 0
1705 && (sec_flags & SEC_ALLOC) != 0)
1707 /* .tdata can go after .data, .tbss after .tdata. Treat .tbss
1708 as if it were a loaded section, and don't use match_type. */
1709 bool seen_thread_local = false;
1711 match_type = NULL;
1712 for (look = first; look; look = look->next)
1714 look_flags = look->flags;
1715 if (look->bfd_section != NULL)
1716 look_flags = look->bfd_section->flags;
1718 differ = look_flags ^ (sec_flags | SEC_LOAD | SEC_HAS_CONTENTS);
1719 if (!(differ & (SEC_THREAD_LOCAL | SEC_ALLOC)))
1721 /* .tdata and .tbss must be adjacent and in that order. */
1722 if (!(look_flags & SEC_LOAD)
1723 && (sec_flags & SEC_LOAD))
1724 /* ..so if we're at a .tbss section and we're placing
1725 a .tdata section stop looking and return the
1726 previous section. */
1727 break;
1728 found = look;
1729 seen_thread_local = true;
1731 else if (seen_thread_local)
1732 break;
1733 else if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD)))
1734 found = look;
1737 else if ((sec_flags & SEC_SMALL_DATA) != 0
1738 && (sec_flags & SEC_ALLOC) != 0)
1740 /* .sdata goes after .data, .sbss after .sdata. */
1741 for (look = first; look; look = look->next)
1743 look_flags = look->flags;
1744 if (look->bfd_section != NULL)
1746 look_flags = look->bfd_section->flags;
1747 if (match_type && !match_type (link_info.output_bfd,
1748 look->bfd_section,
1749 sec->owner, sec))
1750 continue;
1752 differ = look_flags ^ sec_flags;
1753 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1754 | SEC_THREAD_LOCAL))
1755 || ((look_flags & SEC_SMALL_DATA)
1756 && !(sec_flags & SEC_HAS_CONTENTS)))
1757 found = look;
1760 else if ((sec_flags & SEC_HAS_CONTENTS) != 0
1761 && (sec_flags & SEC_ALLOC) != 0)
1763 /* .data goes after .rodata. */
1764 for (look = first; look; look = look->next)
1766 look_flags = look->flags;
1767 if (look->bfd_section != NULL)
1769 look_flags = look->bfd_section->flags;
1770 if (match_type && !match_type (link_info.output_bfd,
1771 look->bfd_section,
1772 sec->owner, sec))
1773 continue;
1775 differ = look_flags ^ sec_flags;
1776 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1777 | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1778 found = look;
1781 else if ((sec_flags & SEC_ALLOC) != 0)
1783 /* .bss goes after any other alloc section. */
1784 for (look = first; look; look = look->next)
1786 look_flags = look->flags;
1787 if (look->bfd_section != NULL)
1789 look_flags = look->bfd_section->flags;
1790 if (match_type && !match_type (link_info.output_bfd,
1791 look->bfd_section,
1792 sec->owner, sec))
1793 continue;
1795 differ = look_flags ^ sec_flags;
1796 if (!(differ & SEC_ALLOC))
1797 found = look;
1800 else
1802 /* non-alloc go last. */
1803 for (look = first; look; look = look->next)
1805 look_flags = look->flags;
1806 if (look->bfd_section != NULL)
1807 look_flags = look->bfd_section->flags;
1808 differ = look_flags ^ sec_flags;
1809 if (!(differ & SEC_DEBUGGING))
1810 found = look;
1812 return found;
1815 if (found || !match_type)
1816 return found;
1818 return lang_output_section_find_by_flags (sec, sec_flags, NULL, NULL);
1821 /* Find the last output section before given output statement.
1822 Used by place_orphan. */
1824 static asection *
1825 output_prev_sec_find (lang_output_section_statement_type *os)
1827 lang_output_section_statement_type *lookup;
1829 for (lookup = os->prev; lookup != NULL; lookup = lookup->prev)
1831 if (lookup->constraint < 0)
1832 continue;
1834 if (lookup->bfd_section != NULL)
1835 return lookup->bfd_section;
1838 return NULL;
1841 /* Look for a suitable place for a new output section statement. The
1842 idea is to skip over anything that might be inside a SECTIONS {}
1843 statement in a script, before we find another output section
1844 statement. Assignments to "dot" before an output section statement
1845 are assumed to belong to it, except in two cases; The first
1846 assignment to dot, and assignments before non-alloc sections.
1847 Otherwise we might put an orphan before . = . + SIZEOF_HEADERS or
1848 similar assignments that set the initial address, or we might
1849 insert non-alloc note sections among assignments setting end of
1850 image symbols. */
1852 static lang_statement_union_type **
1853 insert_os_after (lang_statement_union_type *after)
1855 lang_statement_union_type **where;
1856 lang_statement_union_type **assign = NULL;
1857 bool ignore_first;
1859 ignore_first = after == lang_os_list.head;
1861 for (where = &after->header.next;
1862 *where != NULL;
1863 where = &(*where)->header.next)
1865 switch ((*where)->header.type)
1867 case lang_assignment_statement_enum:
1868 if (assign == NULL)
1870 lang_assignment_statement_type *ass;
1872 ass = &(*where)->assignment_statement;
1873 if (ass->exp->type.node_class != etree_assert
1874 && ass->exp->assign.dst[0] == '.'
1875 && ass->exp->assign.dst[1] == 0)
1877 if (!ignore_first)
1878 assign = where;
1879 ignore_first = false;
1882 continue;
1883 case lang_wild_statement_enum:
1884 case lang_input_section_enum:
1885 case lang_object_symbols_statement_enum:
1886 case lang_fill_statement_enum:
1887 case lang_data_statement_enum:
1888 case lang_reloc_statement_enum:
1889 case lang_padding_statement_enum:
1890 case lang_constructors_statement_enum:
1891 assign = NULL;
1892 ignore_first = false;
1893 continue;
1894 case lang_output_section_statement_enum:
1895 if (assign != NULL)
1897 asection *s = (*where)->output_section_statement.bfd_section;
1899 if (s == NULL
1900 || s->map_head.s == NULL
1901 || (s->flags & SEC_ALLOC) != 0)
1902 where = assign;
1904 break;
1905 case lang_input_statement_enum:
1906 case lang_address_statement_enum:
1907 case lang_target_statement_enum:
1908 case lang_output_statement_enum:
1909 case lang_group_statement_enum:
1910 case lang_insert_statement_enum:
1911 continue;
1912 case lang_input_matcher_enum:
1913 FAIL ();
1915 break;
1918 return where;
1921 lang_output_section_statement_type *
1922 lang_insert_orphan (asection *s,
1923 const char *secname,
1924 int constraint,
1925 lang_output_section_statement_type *after,
1926 struct orphan_save *place,
1927 etree_type *address,
1928 lang_statement_list_type *add_child)
1930 lang_statement_list_type add;
1931 lang_output_section_statement_type *os;
1932 lang_output_section_statement_type **os_tail;
1934 /* If we have found an appropriate place for the output section
1935 statements for this orphan, add them to our own private list,
1936 inserting them later into the global statement list. */
1937 if (after != NULL)
1939 lang_list_init (&add);
1940 push_stat_ptr (&add);
1943 if (bfd_link_relocatable (&link_info)
1944 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0)
1945 address = exp_intop (0);
1947 os_tail = (lang_output_section_statement_type **) lang_os_list.tail;
1948 os = lang_enter_output_section_statement (
1949 secname, address, normal_section, 0, NULL, NULL, NULL, constraint, 0);
1951 if (add_child == NULL)
1952 add_child = &os->children;
1953 lang_add_section (add_child, s, NULL, NULL, os);
1955 if (after && (s->flags & (SEC_LOAD | SEC_ALLOC)) != 0)
1957 const char *region = (after->region
1958 ? after->region->name_list.name
1959 : DEFAULT_MEMORY_REGION);
1960 const char *lma_region = (after->lma_region
1961 ? after->lma_region->name_list.name
1962 : NULL);
1963 lang_leave_output_section_statement (NULL, region, after->phdrs,
1964 lma_region);
1966 else
1967 lang_leave_output_section_statement (NULL, DEFAULT_MEMORY_REGION, NULL,
1968 NULL);
1970 /* Restore the global list pointer. */
1971 if (after != NULL)
1972 pop_stat_ptr ();
1974 if (after != NULL && os->bfd_section != NULL)
1976 asection *snew, *as;
1977 bool place_after = place->stmt == NULL;
1978 bool insert_after = true;
1980 snew = os->bfd_section;
1982 /* Shuffle the bfd section list to make the output file look
1983 neater. This is really only cosmetic. */
1984 if (place->section == NULL
1985 && after != (void *) lang_os_list.head)
1987 asection *bfd_section = after->bfd_section;
1989 /* If the output statement hasn't been used to place any input
1990 sections (and thus doesn't have an output bfd_section),
1991 look for the closest prior output statement having an
1992 output section. */
1993 if (bfd_section == NULL)
1994 bfd_section = output_prev_sec_find (after);
1996 if (bfd_section != NULL
1997 && bfd_section->owner != NULL
1998 && bfd_section != snew)
1999 place->section = &bfd_section->next;
2002 if (place->section == NULL)
2003 place->section = &link_info.output_bfd->sections;
2005 as = *place->section;
2007 if (!as)
2009 /* Put the section at the end of the list. */
2011 /* Unlink the section. */
2012 bfd_section_list_remove (link_info.output_bfd, snew);
2014 /* Now tack it back on in the right place. */
2015 bfd_section_list_append (link_info.output_bfd, snew);
2017 else if ((bfd_get_flavour (link_info.output_bfd)
2018 == bfd_target_elf_flavour)
2019 && (bfd_get_flavour (s->owner)
2020 == bfd_target_elf_flavour)
2021 && ((elf_section_type (s) == SHT_NOTE
2022 && (s->flags & SEC_LOAD) != 0)
2023 || (elf_section_type (as) == SHT_NOTE
2024 && (as->flags & SEC_LOAD) != 0)))
2026 /* Make sure that output note sections are grouped and sorted
2027 by alignments when inserting a note section or insert a
2028 section after a note section, */
2029 asection *sec;
2030 /* A specific section after which the output note section
2031 should be placed. */
2032 asection *after_sec;
2033 /* True if we need to insert the orphan section after a
2034 specific section to maintain output note section order. */
2035 bool after_sec_note = false;
2037 static asection *first_orphan_note = NULL;
2039 /* Group and sort output note section by alignments in
2040 ascending order. */
2041 after_sec = NULL;
2042 if (elf_section_type (s) == SHT_NOTE
2043 && (s->flags & SEC_LOAD) != 0)
2045 /* Search from the beginning for the last output note
2046 section with equal or larger alignments. NB: Don't
2047 place orphan note section after non-note sections. */
2049 first_orphan_note = NULL;
2051 /* NB: When --rosegment is used, the .note.gnu.build-id
2052 section is placed before text sections. Ignore the
2053 .note.gnu.build-id section if -z separate-code and
2054 --rosegment are used together to avoid putting any
2055 note sections between the .note.gnu.build-id section
2056 and text sections in the same PT_LOAD segment. */
2057 bool ignore_build_id = (link_info.separate_code
2058 && link_info.one_rosegment);
2060 for (sec = link_info.output_bfd->sections;
2061 (sec != NULL
2062 && !bfd_is_abs_section (sec));
2063 sec = sec->next)
2064 if (sec != snew
2065 && elf_section_type (sec) == SHT_NOTE
2066 && (sec->flags & SEC_LOAD) != 0
2067 && (!ignore_build_id
2068 || strcmp (sec->name, ".note.gnu.build-id") != 0))
2070 if (!first_orphan_note)
2071 first_orphan_note = sec;
2072 if (sec->alignment_power >= s->alignment_power)
2073 after_sec = sec;
2075 else if (first_orphan_note)
2077 /* Stop if there is non-note section after the first
2078 orphan note section. */
2079 break;
2082 /* If this will be the first orphan note section, it can
2083 be placed at the default location. */
2084 after_sec_note = first_orphan_note != NULL;
2085 if (after_sec == NULL && after_sec_note)
2087 /* If all output note sections have smaller
2088 alignments, place the section before all
2089 output orphan note sections. */
2090 after_sec = first_orphan_note;
2091 insert_after = false;
2094 else if (first_orphan_note)
2096 /* Don't place non-note sections in the middle of orphan
2097 note sections. */
2098 after_sec_note = true;
2099 after_sec = as;
2100 for (sec = as->next;
2101 (sec != NULL
2102 && !bfd_is_abs_section (sec));
2103 sec = sec->next)
2104 if (elf_section_type (sec) == SHT_NOTE
2105 && (sec->flags & SEC_LOAD) != 0)
2106 after_sec = sec;
2109 if (after_sec_note)
2111 if (after_sec)
2113 /* Search forward to insert OS after AFTER_SEC output
2114 statement. */
2115 lang_output_section_statement_type *stmt, *next;
2116 bool found = false;
2117 for (stmt = after; stmt != NULL; stmt = next)
2119 next = stmt->next;
2120 if (insert_after)
2122 if (stmt->bfd_section == after_sec)
2124 place_after = true;
2125 found = true;
2126 after = stmt;
2127 break;
2130 else
2132 /* If INSERT_AFTER is FALSE, place OS before
2133 AFTER_SEC output statement. */
2134 if (next && next->bfd_section == after_sec)
2136 place_after = true;
2137 found = true;
2138 after = stmt;
2139 break;
2144 /* Search backward to insert OS after AFTER_SEC output
2145 statement. */
2146 if (!found)
2147 for (stmt = after; stmt != NULL; stmt = stmt->prev)
2149 if (insert_after)
2151 if (stmt->bfd_section == after_sec)
2153 place_after = true;
2154 after = stmt;
2155 break;
2158 else
2160 /* If INSERT_AFTER is FALSE, place OS before
2161 AFTER_SEC output statement. */
2162 if (stmt->next->bfd_section == after_sec)
2164 place_after = true;
2165 after = stmt;
2166 break;
2172 if (after_sec == NULL
2173 || (insert_after && after_sec->next != snew)
2174 || (!insert_after && after_sec->prev != snew))
2176 /* Unlink the section. */
2177 bfd_section_list_remove (link_info.output_bfd, snew);
2179 /* Place SNEW after AFTER_SEC. If AFTER_SEC is NULL,
2180 prepend SNEW. */
2181 if (after_sec)
2183 if (insert_after)
2184 bfd_section_list_insert_after (link_info.output_bfd,
2185 after_sec, snew);
2186 else
2187 bfd_section_list_insert_before (link_info.output_bfd,
2188 after_sec, snew);
2190 else
2191 bfd_section_list_prepend (link_info.output_bfd, snew);
2194 else if (as != snew && as->prev != snew)
2196 /* Unlink the section. */
2197 bfd_section_list_remove (link_info.output_bfd, snew);
2199 /* Now tack it back on in the right place. */
2200 bfd_section_list_insert_before (link_info.output_bfd,
2201 as, snew);
2204 else if (as != snew && as->prev != snew)
2206 /* Unlink the section. */
2207 bfd_section_list_remove (link_info.output_bfd, snew);
2209 /* Now tack it back on in the right place. */
2210 bfd_section_list_insert_before (link_info.output_bfd, as, snew);
2213 /* Save the end of this list. Further ophans of this type will
2214 follow the one we've just added. */
2215 place->section = &snew->next;
2217 /* The following is non-cosmetic. We try to put the output
2218 statements in some sort of reasonable order here, because they
2219 determine the final load addresses of the orphan sections.
2220 In addition, placing output statements in the wrong order may
2221 require extra segments. For instance, given a typical
2222 situation of all read-only sections placed in one segment and
2223 following that a segment containing all the read-write
2224 sections, we wouldn't want to place an orphan read/write
2225 section before or amongst the read-only ones. */
2226 if (add.head != NULL)
2228 lang_output_section_statement_type *newly_added_os;
2230 /* Place OS after AFTER if AFTER_NOTE is TRUE. */
2231 if (place_after)
2233 lang_statement_union_type **where;
2235 where = insert_os_after ((lang_statement_union_type *) after);
2236 *add.tail = *where;
2237 *where = add.head;
2239 place->os_tail = &after->next;
2241 else
2243 /* Put it after the last orphan statement we added. */
2244 *add.tail = *place->stmt;
2245 *place->stmt = add.head;
2248 /* Fix the global list pointer if we happened to tack our
2249 new list at the tail. */
2250 if (*stat_ptr->tail == add.head)
2251 stat_ptr->tail = add.tail;
2253 /* Save the end of this list. */
2254 place->stmt = add.tail;
2256 /* Do the same for the list of output section statements. */
2257 newly_added_os = *os_tail;
2258 *os_tail = NULL;
2259 newly_added_os->prev = (lang_output_section_statement_type *)
2260 ((char *) place->os_tail
2261 - offsetof (lang_output_section_statement_type, next));
2262 newly_added_os->next = *place->os_tail;
2263 if (newly_added_os->next != NULL)
2264 newly_added_os->next->prev = newly_added_os;
2265 *place->os_tail = newly_added_os;
2266 place->os_tail = &newly_added_os->next;
2268 /* Fixing the global list pointer here is a little different.
2269 We added to the list in lang_enter_output_section_statement,
2270 trimmed off the new output_section_statment above when
2271 assigning *os_tail = NULL, but possibly added it back in
2272 the same place when assigning *place->os_tail. */
2273 if (*os_tail == NULL)
2274 lang_os_list.tail = (lang_statement_union_type **) os_tail;
2277 return os;
2280 static void
2281 lang_print_asneeded (void)
2283 struct asneeded_minfo *m;
2285 if (asneeded_list_head == NULL)
2286 return;
2288 minfo (_("\nAs-needed library included to satisfy reference by file (symbol)\n\n"));
2290 for (m = asneeded_list_head; m != NULL; m = m->next)
2292 int len;
2294 minfo ("%s", m->soname);
2295 len = strlen (m->soname);
2297 if (len >= 29)
2299 print_nl ();
2300 len = 0;
2302 print_spaces (30 - len);
2304 if (m->ref != NULL)
2305 minfo ("%pB ", m->ref);
2306 minfo ("(%pT)\n", m->name);
2310 static void
2311 lang_map_flags (flagword flag)
2313 if (flag & SEC_ALLOC)
2314 minfo ("a");
2316 if (flag & SEC_CODE)
2317 minfo ("x");
2319 if (flag & SEC_READONLY)
2320 minfo ("r");
2322 if (flag & SEC_DATA)
2323 minfo ("w");
2325 if (flag & SEC_LOAD)
2326 minfo ("l");
2329 void
2330 lang_map (void)
2332 lang_memory_region_type *m;
2333 bool dis_header_printed = false;
2335 ldfile_print_input_remaps ();
2337 LANG_FOR_EACH_INPUT_STATEMENT (file)
2339 asection *s;
2341 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
2342 || file->flags.just_syms)
2343 continue;
2345 if (config.print_map_discarded)
2346 for (s = file->the_bfd->sections; s != NULL; s = s->next)
2347 if ((s->output_section == NULL
2348 || s->output_section->owner != link_info.output_bfd)
2349 && (s->flags & (SEC_LINKER_CREATED | SEC_KEEP)) == 0)
2351 if (! dis_header_printed)
2353 minfo (_("\nDiscarded input sections\n\n"));
2354 dis_header_printed = true;
2357 print_input_section (s, true);
2360 if (config.print_map_discarded && ! dis_header_printed)
2361 minfo (_("\nThere are no discarded input sections\n"));
2363 minfo (_("\nMemory Configuration\n\n"));
2364 fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
2365 _("Name"), _("Origin"), _("Length"), _("Attributes"));
2367 for (m = lang_memory_region_list; m != NULL; m = m->next)
2369 fprintf (config.map_file, "%-16s", m->name_list.name);
2371 char buf[32];
2372 bfd_sprintf_vma (link_info.output_bfd, buf, m->origin);
2373 fprintf (config.map_file, " 0x%-16s", buf);
2374 bfd_sprintf_vma (link_info.output_bfd, buf, m->length);
2375 fprintf (config.map_file,
2376 " 0x%*s", m->flags || m->not_flags ? -17 : 0, buf);
2377 if (m->flags)
2378 lang_map_flags (m->flags);
2380 if (m->not_flags)
2382 minfo ("!");
2383 lang_map_flags (m->not_flags);
2386 print_nl ();
2389 minfo (_("\nLinker script and memory map\n\n"));
2391 if (!link_info.reduce_memory_overheads)
2393 obstack_begin (&map_obstack, 1000);
2394 bfd_link_hash_traverse (link_info.hash, sort_def_symbol, 0);
2396 expld.phase = lang_fixed_phase_enum;
2397 lang_statement_iteration++;
2398 print_statements ();
2400 ldemul_extra_map_file_text (link_info.output_bfd, &link_info,
2401 config.map_file);
2404 static bool
2405 sort_def_symbol (struct bfd_link_hash_entry *hash_entry,
2406 void *info ATTRIBUTE_UNUSED)
2408 if ((hash_entry->type == bfd_link_hash_defined
2409 || hash_entry->type == bfd_link_hash_defweak)
2410 && hash_entry->u.def.section->owner != link_info.output_bfd
2411 && hash_entry->u.def.section->owner != NULL)
2413 input_section_userdata_type *ud;
2414 struct map_symbol_def *def;
2416 ud = bfd_section_userdata (hash_entry->u.def.section);
2417 if (!ud)
2419 ud = stat_alloc (sizeof (*ud));
2420 bfd_set_section_userdata (hash_entry->u.def.section, ud);
2421 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2422 ud->map_symbol_def_count = 0;
2424 else if (!ud->map_symbol_def_tail)
2425 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2427 def = (struct map_symbol_def *) obstack_alloc (&map_obstack, sizeof *def);
2428 def->entry = hash_entry;
2429 *(ud->map_symbol_def_tail) = def;
2430 ud->map_symbol_def_tail = &def->next;
2431 ud->map_symbol_def_count++;
2433 return true;
2436 /* Initialize an output section. */
2438 static void
2439 init_os (lang_output_section_statement_type *s, flagword flags)
2441 if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
2442 einfo (_("%F%P: illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
2444 if (!s->dup_output)
2445 s->bfd_section = bfd_get_section_by_name (link_info.output_bfd, s->name);
2446 if (s->bfd_section == NULL)
2447 s->bfd_section = bfd_make_section_anyway_with_flags (link_info.output_bfd,
2448 s->name, flags);
2449 if (s->bfd_section == NULL)
2451 einfo (_("%F%P: output format %s cannot represent section"
2452 " called %s: %E\n"),
2453 link_info.output_bfd->xvec->name, s->name);
2455 s->bfd_section->output_section = s->bfd_section;
2456 s->bfd_section->output_offset = 0;
2458 /* Set the userdata of the output section to the output section
2459 statement to avoid lookup. */
2460 bfd_set_section_userdata (s->bfd_section, s);
2462 /* If there is a base address, make sure that any sections it might
2463 mention are initialized. */
2464 if (s->addr_tree != NULL)
2465 exp_init_os (s->addr_tree);
2467 if (s->load_base != NULL)
2468 exp_init_os (s->load_base);
2470 /* If supplied an alignment, set it. */
2471 if (s->section_alignment != NULL)
2472 s->bfd_section->alignment_power = exp_get_power (s->section_alignment, s,
2473 "section alignment");
2476 static flagword
2477 get_os_init_flag (lang_output_section_statement_type * os)
2479 if (os != NULL)
2480 switch (os->sectype)
2482 case readonly_section: return SEC_READONLY;
2483 case noload_section: return SEC_NEVER_LOAD;
2484 default: break;
2487 return 0;
2490 /* Make sure that all output sections mentioned in an expression are
2491 initialized. */
2493 static void
2494 exp_init_os (etree_type *exp)
2496 switch (exp->type.node_class)
2498 case etree_assign:
2499 case etree_provide:
2500 case etree_provided:
2501 exp_init_os (exp->assign.src);
2502 break;
2504 case etree_binary:
2505 exp_init_os (exp->binary.lhs);
2506 exp_init_os (exp->binary.rhs);
2507 break;
2509 case etree_trinary:
2510 exp_init_os (exp->trinary.cond);
2511 exp_init_os (exp->trinary.lhs);
2512 exp_init_os (exp->trinary.rhs);
2513 break;
2515 case etree_assert:
2516 exp_init_os (exp->assert_s.child);
2517 break;
2519 case etree_unary:
2520 exp_init_os (exp->unary.child);
2521 break;
2523 case etree_name:
2524 switch (exp->type.node_code)
2526 case ADDR:
2527 case LOADADDR:
2529 lang_output_section_statement_type *os;
2531 os = lang_output_section_find (exp->name.name);
2532 if (os != NULL && os->bfd_section == NULL)
2533 init_os (os, get_os_init_flag (os));
2536 break;
2538 default:
2539 break;
2543 static void
2544 section_already_linked (bfd *abfd, asection *sec, void *data)
2546 lang_input_statement_type *entry = (lang_input_statement_type *) data;
2548 /* If we are only reading symbols from this object, then we want to
2549 discard all sections. */
2550 if (entry->flags.just_syms)
2552 bfd_link_just_syms (abfd, sec, &link_info);
2553 return;
2556 /* Deal with SHF_EXCLUDE ELF sections. */
2557 if (!bfd_link_relocatable (&link_info)
2558 && (abfd->flags & BFD_PLUGIN) == 0
2559 && (sec->flags & (SEC_GROUP | SEC_KEEP | SEC_EXCLUDE)) == SEC_EXCLUDE)
2560 sec->output_section = bfd_abs_section_ptr;
2562 if (!(abfd->flags & DYNAMIC))
2563 bfd_section_already_linked (abfd, sec, &link_info);
2567 /* Returns true if SECTION is one we know will be discarded based on its
2568 section flags, otherwise returns false. */
2570 static bool
2571 lang_discard_section_p (asection *section)
2573 bool discard;
2574 flagword flags = section->flags;
2576 /* Discard sections marked with SEC_EXCLUDE. */
2577 discard = (flags & SEC_EXCLUDE) != 0;
2579 /* Discard the group descriptor sections when we're finally placing the
2580 sections from within the group. */
2581 if ((flags & SEC_GROUP) != 0
2582 && link_info.resolve_section_groups)
2583 discard = true;
2585 /* Discard debugging sections if we are stripping debugging
2586 information. */
2587 if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
2588 && (flags & SEC_DEBUGGING) != 0)
2589 discard = true;
2591 /* Discard non-alloc sections if we are stripping section headers. */
2592 else if (config.no_section_header && (flags & SEC_ALLOC) == 0)
2593 discard = true;
2595 return discard;
2598 /* Return TRUE if SECTION is never going to be added to output statement
2599 OUTPUT. lang_add_section() definitely won't do anything with SECTION
2600 if this returns TRUE. It may do something (or not) if this returns FALSE.
2602 Can be used as early-out to filter matches. This may set
2603 output_section of SECTION, if it was unset, to the abs section in case
2604 we discover SECTION to be always discarded. This may also give
2605 warning messages. */
2607 static bool
2608 wont_add_section_p (asection *section,
2609 lang_output_section_statement_type *output)
2611 bool discard;
2613 /* Is this section one we know should be discarded? */
2614 discard = lang_discard_section_p (section);
2616 /* Discard input sections which are assigned to a section named
2617 DISCARD_SECTION_NAME. */
2618 if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
2619 discard = true;
2621 if (discard)
2623 if (section->output_section == NULL)
2625 /* This prevents future calls from assigning this section or
2626 warning about it again. */
2627 section->output_section = bfd_abs_section_ptr;
2629 else if (bfd_is_abs_section (section->output_section))
2631 else if (link_info.non_contiguous_regions_warnings)
2632 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions makes "
2633 "section `%pA' from `%pB' match /DISCARD/ clause.\n"),
2634 NULL, section, section->owner);
2636 return true;
2639 if (section->output_section != NULL)
2641 if (!link_info.non_contiguous_regions)
2642 return true;
2644 /* SECTION has already been handled in a special way
2645 (eg. LINK_ONCE): skip it. */
2646 if (bfd_is_abs_section (section->output_section))
2647 return true;
2649 /* Already assigned to the same output section, do not process
2650 it again, to avoid creating loops between duplicate sections
2651 later. */
2652 if (section->output_section == output->bfd_section)
2653 return true;
2655 if (link_info.non_contiguous_regions_warnings && output->bfd_section)
2656 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions may "
2657 "change behaviour for section `%pA' from `%pB' (assigned to "
2658 "%pA, but additional match: %pA)\n"),
2659 NULL, section, section->owner, section->output_section,
2660 output->bfd_section);
2662 /* SECTION has already been assigned to an output section, but
2663 the user allows it to be mapped to another one in case it
2664 overflows. We'll later update the actual output section in
2665 size_input_section as appropriate. */
2668 return false;
2671 /* The wild routines.
2673 These expand statements like *(.text) and foo.o to a list of
2674 explicit actions, like foo.o(.text), bar.o(.text) and
2675 foo.o(.text, .data). */
2677 /* Add SECTION to the output section OUTPUT. Do this by creating a
2678 lang_input_section statement which is placed at PTR. */
2680 void
2681 lang_add_section (lang_statement_list_type *ptr,
2682 asection *section,
2683 struct wildcard_list *pattern,
2684 struct flag_info *sflag_info,
2685 lang_output_section_statement_type *output)
2687 flagword flags = section->flags;
2689 lang_input_section_type *new_section;
2690 bfd *abfd = link_info.output_bfd;
2692 if (wont_add_section_p (section, output))
2693 return;
2695 if (sflag_info)
2697 bool keep;
2699 keep = bfd_lookup_section_flags (&link_info, sflag_info, section);
2700 if (!keep)
2701 return;
2704 /* We don't copy the SEC_NEVER_LOAD flag from an input section
2705 to an output section, because we want to be able to include a
2706 SEC_NEVER_LOAD section in the middle of an otherwise loaded
2707 section (I don't know why we want to do this, but we do).
2708 build_link_order in ldwrite.c handles this case by turning
2709 the embedded SEC_NEVER_LOAD section into a fill. */
2710 flags &= ~ SEC_NEVER_LOAD;
2712 /* If final link, don't copy the SEC_LINK_ONCE flags, they've
2713 already been processed. One reason to do this is that on pe
2714 format targets, .text$foo sections go into .text and it's odd
2715 to see .text with SEC_LINK_ONCE set. */
2716 if ((flags & (SEC_LINK_ONCE | SEC_GROUP)) == (SEC_LINK_ONCE | SEC_GROUP))
2718 if (link_info.resolve_section_groups)
2719 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2720 else
2721 flags &= ~(SEC_LINK_DUPLICATES | SEC_RELOC);
2723 else if (!bfd_link_relocatable (&link_info))
2724 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2726 switch (output->sectype)
2728 case normal_section:
2729 case overlay_section:
2730 case first_overlay_section:
2731 case type_section:
2732 break;
2733 case noalloc_section:
2734 flags &= ~SEC_ALLOC;
2735 break;
2736 case typed_readonly_section:
2737 case readonly_section:
2738 flags |= SEC_READONLY;
2739 break;
2740 case noload_section:
2741 flags &= ~SEC_LOAD;
2742 flags |= SEC_NEVER_LOAD;
2743 /* Unfortunately GNU ld has managed to evolve two different
2744 meanings to NOLOAD in scripts. ELF gets a .bss style noload,
2745 alloc, no contents section. All others get a noload, noalloc
2746 section. */
2747 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
2748 flags &= ~SEC_HAS_CONTENTS;
2749 else
2750 flags &= ~SEC_ALLOC;
2751 break;
2754 if (output->bfd_section == NULL)
2755 init_os (output, flags);
2757 /* If SEC_READONLY is not set in the input section, then clear
2758 it from the output section. */
2759 output->bfd_section->flags &= flags | ~SEC_READONLY;
2761 if (output->bfd_section->linker_has_input)
2763 /* Only set SEC_READONLY flag on the first input section. */
2764 flags &= ~ SEC_READONLY;
2766 /* Keep SEC_MERGE and SEC_STRINGS only if they are the same. */
2767 if ((output->bfd_section->flags & (SEC_MERGE | SEC_STRINGS))
2768 != (flags & (SEC_MERGE | SEC_STRINGS))
2769 || ((flags & SEC_MERGE) != 0
2770 && output->bfd_section->entsize != section->entsize))
2772 output->bfd_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
2773 flags &= ~ (SEC_MERGE | SEC_STRINGS);
2776 output->bfd_section->flags |= flags;
2778 if (!output->bfd_section->linker_has_input)
2780 output->bfd_section->linker_has_input = 1;
2781 /* This must happen after flags have been updated. The output
2782 section may have been created before we saw its first input
2783 section, eg. for a data statement. */
2784 bfd_init_private_section_data (section->owner, section,
2785 link_info.output_bfd,
2786 output->bfd_section,
2787 &link_info);
2788 if ((flags & SEC_MERGE) != 0)
2789 output->bfd_section->entsize = section->entsize;
2792 if ((flags & SEC_TIC54X_BLOCK) != 0
2793 && bfd_get_arch (section->owner) == bfd_arch_tic54x)
2795 /* FIXME: This value should really be obtained from the bfd... */
2796 output->block_value = 128;
2799 /* When a .ctors section is placed in .init_array it must be copied
2800 in reverse order. Similarly for .dtors. Set that up. */
2801 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
2802 && ((startswith (section->name, ".ctors")
2803 && strcmp (output->bfd_section->name, ".init_array") == 0)
2804 || (startswith (section->name, ".dtors")
2805 && strcmp (output->bfd_section->name, ".fini_array") == 0))
2806 && (section->name[6] == 0 || section->name[6] == '.'))
2807 section->flags |= SEC_ELF_REVERSE_COPY;
2809 if (section->alignment_power > output->bfd_section->alignment_power)
2810 output->bfd_section->alignment_power = section->alignment_power;
2812 section->output_section = output->bfd_section;
2814 if (!map_head_is_link_order)
2816 asection *s = output->bfd_section->map_tail.s;
2817 output->bfd_section->map_tail.s = section;
2818 section->map_head.s = NULL;
2819 section->map_tail.s = s;
2820 if (s != NULL)
2821 s->map_head.s = section;
2822 else
2823 output->bfd_section->map_head.s = section;
2826 /* Add a section reference to the list. */
2827 new_section = new_stat (lang_input_section, ptr);
2828 new_section->section = section;
2829 new_section->pattern = pattern;
2832 /* Expand a wild statement for a particular FILE. SECTION may be
2833 NULL, in which case it is a wild card. This assumes that the
2834 wild statement doesn't need any sorting (of filenames or sections). */
2836 static void
2837 output_section_callback_nosort (lang_wild_statement_type *ptr,
2838 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2839 asection *section,
2840 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2841 void *output)
2843 lang_output_section_statement_type *os;
2845 os = (lang_output_section_statement_type *) output;
2847 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2848 if (unique_section_p (section, os))
2849 return;
2851 lang_add_section (&ptr->children, section, ptr->section_list,
2852 ptr->section_flag_list, os);
2855 /* Check if all sections in a wild statement for a particular FILE
2856 are readonly. */
2858 static void
2859 check_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
2860 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2861 asection *section,
2862 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2863 void *output)
2865 lang_output_section_statement_type *os;
2867 os = (lang_output_section_statement_type *) output;
2869 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2870 if (unique_section_p (section, os))
2871 return;
2873 if (section->output_section == NULL && (section->flags & SEC_READONLY) == 0)
2874 os->all_input_readonly = false;
2877 /* This is passed a file name which must have been seen already and
2878 added to the statement tree. We will see if it has been opened
2879 already and had its symbols read. If not then we'll read it. */
2881 static lang_input_statement_type *
2882 lookup_name (const char *name)
2884 lang_input_statement_type *search;
2886 for (search = (void *) input_file_chain.head;
2887 search != NULL;
2888 search = search->next_real_file)
2890 /* Use the local_sym_name as the name of the file that has
2891 already been loaded as filename might have been transformed
2892 via the search directory lookup mechanism. */
2893 const char *filename = search->local_sym_name;
2895 if (filename != NULL
2896 && filename_cmp (filename, name) == 0)
2897 break;
2900 if (search == NULL)
2902 /* Arrange to splice the input statement added by new_afile into
2903 statement_list after the current input_file_chain tail.
2904 We know input_file_chain is not an empty list, and that
2905 lookup_name was called via open_input_bfds. Later calls to
2906 lookup_name should always match an existing input_statement. */
2907 lang_statement_union_type **tail = stat_ptr->tail;
2908 lang_statement_union_type **after
2909 = (void *) ((char *) input_file_chain.tail
2910 - offsetof (lang_input_statement_type, next_real_file)
2911 + offsetof (lang_input_statement_type, header.next));
2912 lang_statement_union_type *rest = *after;
2913 stat_ptr->tail = after;
2914 search = new_afile (name, lang_input_file_is_search_file_enum,
2915 default_target, NULL);
2916 *stat_ptr->tail = rest;
2917 if (*tail == NULL)
2918 stat_ptr->tail = tail;
2921 /* If we have already added this file, or this file is not real
2922 don't add this file. */
2923 if (search->flags.loaded || !search->flags.real)
2924 return search;
2926 if (!load_symbols (search, NULL))
2927 return NULL;
2929 return search;
2932 /* Save LIST as a list of libraries whose symbols should not be exported. */
2934 struct excluded_lib
2936 char *name;
2937 struct excluded_lib *next;
2939 static struct excluded_lib *excluded_libs;
2941 void
2942 add_excluded_libs (const char *list)
2944 const char *p = list, *end;
2946 while (*p != '\0')
2948 struct excluded_lib *entry;
2949 end = strpbrk (p, ",:");
2950 if (end == NULL)
2951 end = p + strlen (p);
2952 entry = (struct excluded_lib *) xmalloc (sizeof (*entry));
2953 entry->next = excluded_libs;
2954 entry->name = (char *) xmalloc (end - p + 1);
2955 memcpy (entry->name, p, end - p);
2956 entry->name[end - p] = '\0';
2957 excluded_libs = entry;
2958 if (*end == '\0')
2959 break;
2960 p = end + 1;
2964 static void
2965 check_excluded_libs (bfd *abfd)
2967 struct excluded_lib *lib = excluded_libs;
2969 while (lib)
2971 int len = strlen (lib->name);
2972 const char *filename = lbasename (bfd_get_filename (abfd));
2974 if (strcmp (lib->name, "ALL") == 0)
2976 abfd->no_export = true;
2977 return;
2980 if (filename_ncmp (lib->name, filename, len) == 0
2981 && (filename[len] == '\0'
2982 || (filename[len] == '.' && filename[len + 1] == 'a'
2983 && filename[len + 2] == '\0')))
2985 abfd->no_export = true;
2986 return;
2989 lib = lib->next;
2993 /* Get the symbols for an input file. */
2995 bool
2996 load_symbols (lang_input_statement_type *entry,
2997 lang_statement_list_type *place)
2999 char **matching;
3001 if (entry->flags.loaded)
3002 return true;
3004 ldfile_open_file (entry);
3006 /* Do not process further if the file was missing. */
3007 if (entry->flags.missing_file)
3008 return true;
3010 if (trace_files || verbose)
3011 info_msg ("%pI\n", entry);
3013 if (!bfd_check_format (entry->the_bfd, bfd_archive)
3014 && !bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
3016 bfd_error_type err;
3017 struct lang_input_statement_flags save_flags;
3018 extern FILE *yyin;
3020 err = bfd_get_error ();
3022 /* See if the emulation has some special knowledge. */
3023 if (ldemul_unrecognized_file (entry))
3025 if (err == bfd_error_file_ambiguously_recognized)
3026 free (matching);
3027 return true;
3030 if (err == bfd_error_file_ambiguously_recognized)
3032 char **p;
3034 einfo (_("%P: %pB: file not recognized: %E;"
3035 " matching formats:"), entry->the_bfd);
3036 for (p = matching; *p != NULL; p++)
3037 einfo (" %s", *p);
3038 free (matching);
3039 einfo ("%F\n");
3041 else if (err != bfd_error_file_not_recognized
3042 || place == NULL)
3043 einfo (_("%F%P: %pB: file not recognized: %E\n"), entry->the_bfd);
3045 bfd_close (entry->the_bfd);
3046 entry->the_bfd = NULL;
3048 /* Try to interpret the file as a linker script. */
3049 save_flags = input_flags;
3050 ldfile_open_command_file (entry->filename);
3052 push_stat_ptr (place);
3053 input_flags.add_DT_NEEDED_for_regular
3054 = entry->flags.add_DT_NEEDED_for_regular;
3055 input_flags.add_DT_NEEDED_for_dynamic
3056 = entry->flags.add_DT_NEEDED_for_dynamic;
3057 input_flags.whole_archive = entry->flags.whole_archive;
3058 input_flags.dynamic = entry->flags.dynamic;
3060 ldfile_assumed_script = true;
3061 parser_input = input_script;
3062 current_input_file = entry->filename;
3063 yyparse ();
3064 current_input_file = NULL;
3065 ldfile_assumed_script = false;
3067 /* missing_file is sticky. sysrooted will already have been
3068 restored when seeing EOF in yyparse, but no harm to restore
3069 again. */
3070 save_flags.missing_file |= input_flags.missing_file;
3071 input_flags = save_flags;
3072 pop_stat_ptr ();
3073 fclose (yyin);
3074 yyin = NULL;
3075 entry->flags.loaded = true;
3077 return true;
3080 if (ldemul_recognized_file (entry))
3081 return true;
3083 /* We don't call ldlang_add_file for an archive. Instead, the
3084 add_symbols entry point will call ldlang_add_file, via the
3085 add_archive_element callback, for each element of the archive
3086 which is used. */
3087 switch (bfd_get_format (entry->the_bfd))
3089 default:
3090 break;
3092 case bfd_object:
3093 if (!entry->flags.reload)
3094 ldlang_add_file (entry);
3095 break;
3097 case bfd_archive:
3098 check_excluded_libs (entry->the_bfd);
3100 bfd_set_usrdata (entry->the_bfd, entry);
3101 if (entry->flags.whole_archive)
3103 bfd *member = NULL;
3104 bool loaded = true;
3106 for (;;)
3108 bfd *subsbfd;
3109 member = bfd_openr_next_archived_file (entry->the_bfd, member);
3111 if (member == NULL)
3112 break;
3114 if (!bfd_check_format (member, bfd_object))
3116 einfo (_("%F%P: %pB: member %pB in archive is not an object\n"),
3117 entry->the_bfd, member);
3118 loaded = false;
3121 subsbfd = member;
3122 if (!(*link_info.callbacks
3123 ->add_archive_element) (&link_info, member,
3124 "--whole-archive", &subsbfd))
3125 abort ();
3127 /* Potentially, the add_archive_element hook may have set a
3128 substitute BFD for us. */
3129 if (!bfd_link_add_symbols (subsbfd, &link_info))
3131 einfo (_("%F%P: %pB: error adding symbols: %E\n"), member);
3132 loaded = false;
3136 entry->flags.loaded = loaded;
3137 return loaded;
3139 break;
3142 if (bfd_link_add_symbols (entry->the_bfd, &link_info))
3143 entry->flags.loaded = true;
3144 else
3145 einfo (_("%F%P: %pB: error adding symbols: %E\n"), entry->the_bfd);
3147 return entry->flags.loaded;
3150 /* Handle a wild statement. S->FILENAME or S->SECTION_LIST or both
3151 may be NULL, indicating that it is a wildcard. Separate
3152 lang_input_section statements are created for each part of the
3153 expansion; they are added after the wild statement S. OUTPUT is
3154 the output section. */
3156 static void
3157 wild (lang_wild_statement_type *s,
3158 const char *target ATTRIBUTE_UNUSED,
3159 lang_output_section_statement_type *output)
3161 struct wildcard_list *sec;
3163 if (s->filenames_sorted || s->any_specs_sorted)
3165 lang_section_bst_type *tree;
3167 walk_wild (s, output_section_callback_sort, output);
3169 tree = s->tree;
3170 if (tree)
3172 output_section_callback_tree_to_list (s, tree, output);
3173 s->tree = NULL;
3174 s->rightmost = &s->tree;
3177 else
3178 walk_wild (s, output_section_callback_nosort, output);
3180 if (default_common_section == NULL)
3181 for (sec = s->section_list; sec != NULL; sec = sec->next)
3182 if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
3184 /* Remember the section that common is going to in case we
3185 later get something which doesn't know where to put it. */
3186 default_common_section = output;
3187 break;
3191 /* Return TRUE iff target is the sought target. */
3193 static int
3194 get_target (const bfd_target *target, void *data)
3196 const char *sought = (const char *) data;
3198 return strcmp (target->name, sought) == 0;
3201 /* Like strcpy() but convert to lower case as well. */
3203 static void
3204 stricpy (char *dest, const char *src)
3206 char c;
3208 while ((c = *src++) != 0)
3209 *dest++ = TOLOWER (c);
3211 *dest = 0;
3214 /* Remove the first occurrence of needle (if any) in haystack
3215 from haystack. */
3217 static void
3218 strcut (char *haystack, const char *needle)
3220 haystack = strstr (haystack, needle);
3222 if (haystack)
3224 char *src;
3226 for (src = haystack + strlen (needle); *src;)
3227 *haystack++ = *src++;
3229 *haystack = 0;
3233 /* Compare two target format name strings.
3234 Return a value indicating how "similar" they are. */
3236 static int
3237 name_compare (const char *first, const char *second)
3239 char *copy1;
3240 char *copy2;
3241 int result;
3243 copy1 = (char *) xmalloc (strlen (first) + 1);
3244 copy2 = (char *) xmalloc (strlen (second) + 1);
3246 /* Convert the names to lower case. */
3247 stricpy (copy1, first);
3248 stricpy (copy2, second);
3250 /* Remove size and endian strings from the name. */
3251 strcut (copy1, "big");
3252 strcut (copy1, "little");
3253 strcut (copy2, "big");
3254 strcut (copy2, "little");
3256 /* Return a value based on how many characters match,
3257 starting from the beginning. If both strings are
3258 the same then return 10 * their length. */
3259 for (result = 0; copy1[result] == copy2[result]; result++)
3260 if (copy1[result] == 0)
3262 result *= 10;
3263 break;
3266 free (copy1);
3267 free (copy2);
3269 return result;
3272 /* Set by closest_target_match() below. */
3273 static const bfd_target *winner;
3275 /* Scan all the valid bfd targets looking for one that has the endianness
3276 requirement that was specified on the command line, and is the nearest
3277 match to the original output target. */
3279 static int
3280 closest_target_match (const bfd_target *target, void *data)
3282 const bfd_target *original = (const bfd_target *) data;
3284 if (command_line.endian == ENDIAN_BIG
3285 && target->byteorder != BFD_ENDIAN_BIG)
3286 return 0;
3288 if (command_line.endian == ENDIAN_LITTLE
3289 && target->byteorder != BFD_ENDIAN_LITTLE)
3290 return 0;
3292 /* Must be the same flavour. */
3293 if (target->flavour != original->flavour)
3294 return 0;
3296 /* Ignore generic big and little endian elf vectors. */
3297 if (strcmp (target->name, "elf32-big") == 0
3298 || strcmp (target->name, "elf64-big") == 0
3299 || strcmp (target->name, "elf32-little") == 0
3300 || strcmp (target->name, "elf64-little") == 0)
3301 return 0;
3303 /* If we have not found a potential winner yet, then record this one. */
3304 if (winner == NULL)
3306 winner = target;
3307 return 0;
3310 /* Oh dear, we now have two potential candidates for a successful match.
3311 Compare their names and choose the better one. */
3312 if (name_compare (target->name, original->name)
3313 > name_compare (winner->name, original->name))
3314 winner = target;
3316 /* Keep on searching until wqe have checked them all. */
3317 return 0;
3320 /* Return the BFD target format of the first input file. */
3322 static const char *
3323 get_first_input_target (void)
3325 const char *target = NULL;
3327 LANG_FOR_EACH_INPUT_STATEMENT (s)
3329 if (s->header.type == lang_input_statement_enum
3330 && s->flags.real)
3332 ldfile_open_file (s);
3334 if (s->the_bfd != NULL
3335 && bfd_check_format (s->the_bfd, bfd_object))
3337 target = bfd_get_target (s->the_bfd);
3339 if (target != NULL)
3340 break;
3345 return target;
3348 const char *
3349 lang_get_output_target (void)
3351 const char *target;
3353 /* Has the user told us which output format to use? */
3354 if (output_target != NULL)
3355 return output_target;
3357 /* No - has the current target been set to something other than
3358 the default? */
3359 if (current_target != default_target && current_target != NULL)
3360 return current_target;
3362 /* No - can we determine the format of the first input file? */
3363 target = get_first_input_target ();
3364 if (target != NULL)
3365 return target;
3367 /* Failed - use the default output target. */
3368 return default_target;
3371 /* Open the output file. */
3373 static void
3374 open_output (const char *name)
3376 lang_input_statement_type *f;
3377 char *out = lrealpath (name);
3379 for (f = (void *) input_file_chain.head;
3380 f != NULL;
3381 f = f->next_real_file)
3382 if (f->flags.real)
3384 char *in = lrealpath (f->local_sym_name);
3385 if (filename_cmp (in, out) == 0)
3386 einfo (_("%F%P: input file '%s' is the same as output file\n"),
3387 f->filename);
3388 free (in);
3390 free (out);
3392 output_target = lang_get_output_target ();
3394 /* Has the user requested a particular endianness on the command
3395 line? */
3396 if (command_line.endian != ENDIAN_UNSET)
3398 /* Get the chosen target. */
3399 const bfd_target *target
3400 = bfd_iterate_over_targets (get_target, (void *) output_target);
3402 /* If the target is not supported, we cannot do anything. */
3403 if (target != NULL)
3405 enum bfd_endian desired_endian;
3407 if (command_line.endian == ENDIAN_BIG)
3408 desired_endian = BFD_ENDIAN_BIG;
3409 else
3410 desired_endian = BFD_ENDIAN_LITTLE;
3412 /* See if the target has the wrong endianness. This should
3413 not happen if the linker script has provided big and
3414 little endian alternatives, but some scrips don't do
3415 this. */
3416 if (target->byteorder != desired_endian)
3418 /* If it does, then see if the target provides
3419 an alternative with the correct endianness. */
3420 if (target->alternative_target != NULL
3421 && (target->alternative_target->byteorder == desired_endian))
3422 output_target = target->alternative_target->name;
3423 else
3425 /* Try to find a target as similar as possible to
3426 the default target, but which has the desired
3427 endian characteristic. */
3428 bfd_iterate_over_targets (closest_target_match,
3429 (void *) target);
3431 /* Oh dear - we could not find any targets that
3432 satisfy our requirements. */
3433 if (winner == NULL)
3434 einfo (_("%P: warning: could not find any targets"
3435 " that match endianness requirement\n"));
3436 else
3437 output_target = winner->name;
3443 link_info.output_bfd = bfd_openw (name, output_target);
3445 if (link_info.output_bfd == NULL)
3447 if (bfd_get_error () == bfd_error_invalid_target)
3448 einfo (_("%F%P: target %s not found\n"), output_target);
3450 einfo (_("%F%P: cannot open output file %s: %E\n"), name);
3453 delete_output_file_on_failure = true;
3455 if (!bfd_set_format (link_info.output_bfd, bfd_object))
3456 einfo (_("%F%P: %s: can not make object file: %E\n"), name);
3457 if (!bfd_set_arch_mach (link_info.output_bfd,
3458 ldfile_output_architecture,
3459 ldfile_output_machine))
3460 einfo (_("%F%P: %s: can not set architecture: %E\n"), name);
3462 link_info.hash = bfd_link_hash_table_create (link_info.output_bfd);
3463 if (link_info.hash == NULL)
3464 einfo (_("%F%P: can not create hash table: %E\n"));
3466 bfd_set_gp_size (link_info.output_bfd, g_switch_value);
3469 static void
3470 ldlang_open_output (lang_statement_union_type *statement)
3472 switch (statement->header.type)
3474 case lang_output_statement_enum:
3475 ASSERT (link_info.output_bfd == NULL);
3476 open_output (statement->output_statement.name);
3477 ldemul_set_output_arch ();
3478 if (config.magic_demand_paged
3479 && !bfd_link_relocatable (&link_info))
3480 link_info.output_bfd->flags |= D_PAGED;
3481 else
3482 link_info.output_bfd->flags &= ~D_PAGED;
3483 if (config.text_read_only)
3484 link_info.output_bfd->flags |= WP_TEXT;
3485 else
3486 link_info.output_bfd->flags &= ~WP_TEXT;
3487 if (link_info.traditional_format)
3488 link_info.output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
3489 else
3490 link_info.output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
3491 if (config.no_section_header)
3492 link_info.output_bfd->flags |= BFD_NO_SECTION_HEADER;
3493 else
3494 link_info.output_bfd->flags &= ~BFD_NO_SECTION_HEADER;
3495 break;
3497 case lang_target_statement_enum:
3498 current_target = statement->target_statement.target;
3499 break;
3500 default:
3501 break;
3505 static void
3506 init_opb (asection *s)
3508 unsigned int x;
3510 opb_shift = 0;
3511 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
3512 && s != NULL
3513 && (s->flags & SEC_ELF_OCTETS) != 0)
3514 return;
3516 x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3517 ldfile_output_machine);
3518 if (x > 1)
3519 while ((x & 1) == 0)
3521 x >>= 1;
3522 ++opb_shift;
3524 ASSERT (x == 1);
3527 /* Open all the input files. */
3529 enum open_bfd_mode
3531 OPEN_BFD_NORMAL = 0,
3532 OPEN_BFD_FORCE = 1,
3533 OPEN_BFD_RESCAN = 2
3535 #if BFD_SUPPORTS_PLUGINS
3536 static lang_input_statement_type *plugin_insert = NULL;
3537 static struct bfd_link_hash_entry *plugin_undefs = NULL;
3538 #endif
3540 static void
3541 open_input_bfds (lang_statement_union_type *s,
3542 lang_output_section_statement_type *os,
3543 enum open_bfd_mode mode)
3545 for (; s != NULL; s = s->header.next)
3547 switch (s->header.type)
3549 case lang_constructors_statement_enum:
3550 open_input_bfds (constructor_list.head, os, mode);
3551 break;
3552 case lang_output_section_statement_enum:
3553 os = &s->output_section_statement;
3554 open_input_bfds (os->children.head, os, mode);
3555 break;
3556 case lang_wild_statement_enum:
3557 /* Maybe we should load the file's symbols. */
3558 if ((mode & OPEN_BFD_RESCAN) == 0
3559 && s->wild_statement.filename
3560 && !wildcardp (s->wild_statement.filename)
3561 && !archive_path (s->wild_statement.filename))
3562 lookup_name (s->wild_statement.filename);
3563 open_input_bfds (s->wild_statement.children.head, os, mode);
3564 break;
3565 case lang_group_statement_enum:
3567 struct bfd_link_hash_entry *undefs;
3568 #if BFD_SUPPORTS_PLUGINS
3569 lang_input_statement_type *plugin_insert_save;
3570 #endif
3572 /* We must continually search the entries in the group
3573 until no new symbols are added to the list of undefined
3574 symbols. */
3578 #if BFD_SUPPORTS_PLUGINS
3579 plugin_insert_save = plugin_insert;
3580 #endif
3581 undefs = link_info.hash->undefs_tail;
3582 open_input_bfds (s->group_statement.children.head, os,
3583 mode | OPEN_BFD_FORCE);
3585 while (undefs != link_info.hash->undefs_tail
3586 #if BFD_SUPPORTS_PLUGINS
3587 /* Objects inserted by a plugin, which are loaded
3588 before we hit this loop, may have added new
3589 undefs. */
3590 || (plugin_insert != plugin_insert_save && plugin_undefs)
3591 #endif
3594 break;
3595 case lang_target_statement_enum:
3596 current_target = s->target_statement.target;
3597 break;
3598 case lang_input_statement_enum:
3599 if (s->input_statement.flags.real)
3601 lang_statement_union_type **os_tail;
3602 lang_statement_list_type add;
3603 bfd *abfd;
3605 s->input_statement.target = current_target;
3607 /* If we are being called from within a group, and this
3608 is an archive which has already been searched, then
3609 force it to be researched unless the whole archive
3610 has been loaded already. Do the same for a rescan.
3611 Likewise reload --as-needed shared libs. */
3612 if (mode != OPEN_BFD_NORMAL
3613 #if BFD_SUPPORTS_PLUGINS
3614 && ((mode & OPEN_BFD_RESCAN) == 0
3615 || plugin_insert == NULL)
3616 #endif
3617 && s->input_statement.flags.loaded
3618 && (abfd = s->input_statement.the_bfd) != NULL
3619 && ((bfd_get_format (abfd) == bfd_archive
3620 && !s->input_statement.flags.whole_archive)
3621 || (bfd_get_format (abfd) == bfd_object
3622 && ((abfd->flags) & DYNAMIC) != 0
3623 && s->input_statement.flags.add_DT_NEEDED_for_regular
3624 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
3625 && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)))
3627 s->input_statement.flags.loaded = false;
3628 s->input_statement.flags.reload = true;
3631 os_tail = lang_os_list.tail;
3632 lang_list_init (&add);
3634 if (!load_symbols (&s->input_statement, &add))
3635 config.make_executable = false;
3637 if (add.head != NULL)
3639 /* If this was a script with output sections then
3640 tack any added statements on to the end of the
3641 list. This avoids having to reorder the output
3642 section statement list. Very likely the user
3643 forgot -T, and whatever we do here will not meet
3644 naive user expectations. */
3645 if (os_tail != lang_os_list.tail)
3647 einfo (_("%P: warning: %s contains output sections;"
3648 " did you forget -T?\n"),
3649 s->input_statement.filename);
3650 *stat_ptr->tail = add.head;
3651 stat_ptr->tail = add.tail;
3653 else
3655 *add.tail = s->header.next;
3656 s->header.next = add.head;
3660 #if BFD_SUPPORTS_PLUGINS
3661 /* If we have found the point at which a plugin added new
3662 files, clear plugin_insert to enable archive rescan. */
3663 if (&s->input_statement == plugin_insert)
3664 plugin_insert = NULL;
3665 #endif
3666 break;
3667 case lang_assignment_statement_enum:
3668 if (s->assignment_statement.exp->type.node_class != etree_assert)
3669 exp_fold_tree_no_dot (s->assignment_statement.exp, os);
3670 break;
3671 default:
3672 break;
3676 /* Exit if any of the files were missing. */
3677 if (input_flags.missing_file)
3678 einfo ("%F");
3681 #ifdef ENABLE_LIBCTF
3682 /* Emit CTF errors and warnings. fp can be NULL to report errors/warnings
3683 that happened specifically at CTF open time. */
3684 static void
3685 lang_ctf_errs_warnings (ctf_dict_t *fp)
3687 ctf_next_t *i = NULL;
3688 char *text;
3689 int is_warning;
3690 int err;
3692 while ((text = ctf_errwarning_next (fp, &i, &is_warning, &err)) != NULL)
3694 einfo (_("%s: %s\n"), is_warning ? _("CTF warning"): _("CTF error"),
3695 text);
3696 free (text);
3698 if (err != ECTF_NEXT_END)
3700 einfo (_("CTF error: cannot get CTF errors: `%s'\n"),
3701 ctf_errmsg (err));
3704 /* `err' returns errors from the error/warning iterator in particular.
3705 These never assert. But if we have an fp, that could have recorded
3706 an assertion failure: assert if it has done so. */
3707 ASSERT (!fp || ctf_errno (fp) != ECTF_INTERNAL);
3710 /* Open the CTF sections in the input files with libctf: if any were opened,
3711 create a fake input file that we'll write the merged CTF data to later
3712 on. */
3714 static void
3715 ldlang_open_ctf (void)
3717 int any_ctf = 0;
3718 int err;
3720 LANG_FOR_EACH_INPUT_STATEMENT (file)
3722 asection *sect;
3724 /* Incoming files from the compiler have a single ctf_dict_t in them
3725 (which is presented to us by the libctf API in a ctf_archive_t
3726 wrapper): files derived from a previous relocatable link have a CTF
3727 archive containing possibly many CTF files. */
3729 if ((file->the_ctf = ctf_bfdopen (file->the_bfd, &err)) == NULL)
3731 if (err != ECTF_NOCTFDATA)
3733 lang_ctf_errs_warnings (NULL);
3734 einfo (_("%P: warning: CTF section in %pB not loaded; "
3735 "its types will be discarded: %s\n"), file->the_bfd,
3736 ctf_errmsg (err));
3738 continue;
3741 /* Prevent the contents of this section from being written, while
3742 requiring the section itself to be duplicated in the output, but only
3743 once. */
3744 /* This section must exist if ctf_bfdopen() succeeded. */
3745 sect = bfd_get_section_by_name (file->the_bfd, ".ctf");
3746 sect->size = 0;
3747 sect->flags |= SEC_NEVER_LOAD | SEC_HAS_CONTENTS | SEC_LINKER_CREATED;
3749 if (any_ctf)
3750 sect->flags |= SEC_EXCLUDE;
3751 any_ctf = 1;
3754 if (!any_ctf)
3756 ctf_output = NULL;
3757 return;
3760 if ((ctf_output = ctf_create (&err)) != NULL)
3761 return;
3763 einfo (_("%P: warning: CTF output not created: `%s'\n"),
3764 ctf_errmsg (err));
3766 LANG_FOR_EACH_INPUT_STATEMENT (errfile)
3767 ctf_close (errfile->the_ctf);
3770 /* Merge together CTF sections. After this, only the symtab-dependent
3771 function and data object sections need adjustment. */
3773 static void
3774 lang_merge_ctf (void)
3776 asection *output_sect;
3777 int flags = 0;
3779 if (!ctf_output)
3780 return;
3782 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3784 /* If the section was discarded, don't waste time merging. */
3785 if (output_sect == NULL)
3787 ctf_dict_close (ctf_output);
3788 ctf_output = NULL;
3790 LANG_FOR_EACH_INPUT_STATEMENT (file)
3792 ctf_close (file->the_ctf);
3793 file->the_ctf = NULL;
3795 return;
3798 LANG_FOR_EACH_INPUT_STATEMENT (file)
3800 if (!file->the_ctf)
3801 continue;
3803 /* Takes ownership of file->the_ctf. */
3804 if (ctf_link_add_ctf (ctf_output, file->the_ctf, file->filename) < 0)
3806 einfo (_("%P: warning: CTF section in %pB cannot be linked: `%s'\n"),
3807 file->the_bfd, ctf_errmsg (ctf_errno (ctf_output)));
3808 ctf_close (file->the_ctf);
3809 file->the_ctf = NULL;
3810 continue;
3814 if (!config.ctf_share_duplicated)
3815 flags = CTF_LINK_SHARE_UNCONFLICTED;
3816 else
3817 flags = CTF_LINK_SHARE_DUPLICATED;
3818 if (!config.ctf_variables)
3819 flags |= CTF_LINK_OMIT_VARIABLES_SECTION;
3820 if (bfd_link_relocatable (&link_info))
3821 flags |= CTF_LINK_NO_FILTER_REPORTED_SYMS;
3823 if (ctf_link (ctf_output, flags) < 0)
3825 lang_ctf_errs_warnings (ctf_output);
3826 einfo (_("%P: warning: CTF linking failed; "
3827 "output will have no CTF section: %s\n"),
3828 ctf_errmsg (ctf_errno (ctf_output)));
3829 if (output_sect)
3831 output_sect->size = 0;
3832 output_sect->flags |= SEC_EXCLUDE;
3835 /* Output any lingering errors that didn't come from ctf_link. */
3836 lang_ctf_errs_warnings (ctf_output);
3839 /* Let the emulation acquire strings from the dynamic strtab to help it optimize
3840 the CTF, if supported. */
3842 void
3843 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab)
3845 ldemul_acquire_strings_for_ctf (ctf_output, dynstrtab);
3848 /* Inform the emulation about the addition of a new dynamic symbol, in BFD
3849 internal format. */
3850 void ldlang_ctf_new_dynsym (int symidx, struct elf_internal_sym *sym)
3852 ldemul_new_dynsym_for_ctf (ctf_output, symidx, sym);
3855 /* Write out the CTF section. Called early, if the emulation isn't going to
3856 need to dedup against the strtab and symtab, then possibly called from the
3857 target linker code if the dedup has happened. */
3858 static void
3859 lang_write_ctf (int late)
3861 size_t output_size;
3862 asection *output_sect;
3864 if (!ctf_output)
3865 return;
3867 if (late)
3869 /* Emit CTF late if this emulation says it can do so. */
3870 if (ldemul_emit_ctf_early ())
3871 return;
3873 else
3875 if (!ldemul_emit_ctf_early ())
3876 return;
3879 /* Inform the emulation that all the symbols that will be received have
3880 been. */
3882 ldemul_new_dynsym_for_ctf (ctf_output, 0, NULL);
3884 /* Emit CTF. */
3886 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3887 if (output_sect)
3889 output_sect->contents = ctf_link_write (ctf_output, &output_size,
3890 CTF_COMPRESSION_THRESHOLD);
3891 output_sect->size = output_size;
3892 output_sect->flags |= SEC_IN_MEMORY | SEC_KEEP;
3894 lang_ctf_errs_warnings (ctf_output);
3895 if (!output_sect->contents)
3897 einfo (_("%P: warning: CTF section emission failed; "
3898 "output will have no CTF section: %s\n"),
3899 ctf_errmsg (ctf_errno (ctf_output)));
3900 output_sect->size = 0;
3901 output_sect->flags |= SEC_EXCLUDE;
3905 /* This also closes every CTF input file used in the link. */
3906 ctf_dict_close (ctf_output);
3907 ctf_output = NULL;
3909 LANG_FOR_EACH_INPUT_STATEMENT (file)
3910 file->the_ctf = NULL;
3913 /* Write out the CTF section late, if the emulation needs that. */
3915 void
3916 ldlang_write_ctf_late (void)
3918 /* Trigger a "late call", if the emulation needs one. */
3920 lang_write_ctf (1);
3922 #else
3923 static void
3924 ldlang_open_ctf (void)
3926 LANG_FOR_EACH_INPUT_STATEMENT (file)
3928 asection *sect;
3930 /* If built without CTF, warn and delete all CTF sections from the output.
3931 (The alternative would be to simply concatenate them, which does not
3932 yield a valid CTF section.) */
3934 if ((sect = bfd_get_section_by_name (file->the_bfd, ".ctf")) != NULL)
3936 einfo (_("%P: warning: CTF section in %pB not linkable: "
3937 "%P was built without support for CTF\n"), file->the_bfd);
3938 sect->size = 0;
3939 sect->flags |= SEC_EXCLUDE;
3944 static void lang_merge_ctf (void) {}
3945 void
3946 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab
3947 ATTRIBUTE_UNUSED) {}
3948 void
3949 ldlang_ctf_new_dynsym (int symidx ATTRIBUTE_UNUSED,
3950 struct elf_internal_sym *sym ATTRIBUTE_UNUSED) {}
3951 static void lang_write_ctf (int late ATTRIBUTE_UNUSED) {}
3952 void ldlang_write_ctf_late (void) {}
3953 #endif
3955 /* Add the supplied name to the symbol table as an undefined reference.
3956 This is a two step process as the symbol table doesn't even exist at
3957 the time the ld command line is processed. First we put the name
3958 on a list, then, once the output file has been opened, transfer the
3959 name to the symbol table. */
3961 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
3963 #define ldlang_undef_chain_list_head entry_symbol.next
3965 void
3966 ldlang_add_undef (const char *const name, bool cmdline ATTRIBUTE_UNUSED)
3968 ldlang_undef_chain_list_type *new_undef;
3970 new_undef = stat_alloc (sizeof (*new_undef));
3971 new_undef->next = ldlang_undef_chain_list_head;
3972 ldlang_undef_chain_list_head = new_undef;
3974 new_undef->name = xstrdup (name);
3976 if (link_info.output_bfd != NULL)
3977 insert_undefined (new_undef->name);
3980 /* Insert NAME as undefined in the symbol table. */
3982 static void
3983 insert_undefined (const char *name)
3985 struct bfd_link_hash_entry *h;
3987 h = bfd_link_hash_lookup (link_info.hash, name, true, false, true);
3988 if (h == NULL)
3989 einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
3990 if (h->type == bfd_link_hash_new)
3992 h->type = bfd_link_hash_undefined;
3993 h->u.undef.abfd = NULL;
3994 h->non_ir_ref_regular = true;
3995 bfd_link_add_undef (link_info.hash, h);
3999 /* Run through the list of undefineds created above and place them
4000 into the linker hash table as undefined symbols belonging to the
4001 script file. */
4003 static void
4004 lang_place_undefineds (void)
4006 ldlang_undef_chain_list_type *ptr;
4008 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
4009 insert_undefined (ptr->name);
4012 /* Mark -u symbols against garbage collection. */
4014 static void
4015 lang_mark_undefineds (void)
4017 ldlang_undef_chain_list_type *ptr;
4019 if (is_elf_hash_table (link_info.hash))
4020 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
4022 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
4023 bfd_link_hash_lookup (link_info.hash, ptr->name, false, false, true);
4024 if (h != NULL)
4025 h->mark = 1;
4029 /* Structure used to build the list of symbols that the user has required
4030 be defined. */
4032 struct require_defined_symbol
4034 const char *name;
4035 struct require_defined_symbol *next;
4038 /* The list of symbols that the user has required be defined. */
4040 static struct require_defined_symbol *require_defined_symbol_list;
4042 /* Add a new symbol NAME to the list of symbols that are required to be
4043 defined. */
4045 void
4046 ldlang_add_require_defined (const char *const name)
4048 struct require_defined_symbol *ptr;
4050 ldlang_add_undef (name, true);
4051 ptr = stat_alloc (sizeof (*ptr));
4052 ptr->next = require_defined_symbol_list;
4053 ptr->name = strdup (name);
4054 require_defined_symbol_list = ptr;
4057 /* Check that all symbols the user required to be defined, are defined,
4058 raise an error if we find a symbol that is not defined. */
4060 static void
4061 ldlang_check_require_defined_symbols (void)
4063 struct require_defined_symbol *ptr;
4065 for (ptr = require_defined_symbol_list; ptr != NULL; ptr = ptr->next)
4067 struct bfd_link_hash_entry *h;
4069 h = bfd_link_hash_lookup (link_info.hash, ptr->name,
4070 false, false, true);
4071 if (h == NULL
4072 || (h->type != bfd_link_hash_defined
4073 && h->type != bfd_link_hash_defweak))
4074 einfo(_("%X%P: required symbol `%s' not defined\n"), ptr->name);
4078 /* Check for all readonly or some readwrite sections. */
4080 static void
4081 check_input_sections
4082 (lang_statement_union_type *s,
4083 lang_output_section_statement_type *output_section_statement)
4085 for (; s != NULL; s = s->header.next)
4087 switch (s->header.type)
4089 case lang_wild_statement_enum:
4090 walk_wild (&s->wild_statement, check_section_callback,
4091 output_section_statement);
4092 if (!output_section_statement->all_input_readonly)
4093 return;
4094 break;
4095 case lang_constructors_statement_enum:
4096 check_input_sections (constructor_list.head,
4097 output_section_statement);
4098 if (!output_section_statement->all_input_readonly)
4099 return;
4100 break;
4101 case lang_group_statement_enum:
4102 check_input_sections (s->group_statement.children.head,
4103 output_section_statement);
4104 if (!output_section_statement->all_input_readonly)
4105 return;
4106 break;
4107 default:
4108 break;
4113 /* Update wildcard statements if needed. */
4115 static void
4116 update_wild_statements (lang_statement_union_type *s)
4118 struct wildcard_list *sec;
4120 switch (sort_section)
4122 default:
4123 FAIL ();
4125 case none:
4126 break;
4128 case by_name:
4129 case by_alignment:
4130 for (; s != NULL; s = s->header.next)
4132 switch (s->header.type)
4134 default:
4135 break;
4137 case lang_wild_statement_enum:
4138 for (sec = s->wild_statement.section_list; sec != NULL;
4139 sec = sec->next)
4140 /* Don't sort .init/.fini sections. */
4141 if (strcmp (sec->spec.name, ".init") != 0
4142 && strcmp (sec->spec.name, ".fini") != 0)
4144 switch (sec->spec.sorted)
4146 case none:
4147 sec->spec.sorted = sort_section;
4148 break;
4149 case by_name:
4150 if (sort_section == by_alignment)
4151 sec->spec.sorted = by_name_alignment;
4152 break;
4153 case by_alignment:
4154 if (sort_section == by_name)
4155 sec->spec.sorted = by_alignment_name;
4156 break;
4157 default:
4158 break;
4160 s->wild_statement.any_specs_sorted = true;
4162 break;
4164 case lang_constructors_statement_enum:
4165 update_wild_statements (constructor_list.head);
4166 break;
4168 case lang_output_section_statement_enum:
4169 update_wild_statements
4170 (s->output_section_statement.children.head);
4171 break;
4173 case lang_group_statement_enum:
4174 update_wild_statements (s->group_statement.children.head);
4175 break;
4178 break;
4182 /* Open input files and attach to output sections. */
4184 static void
4185 map_input_to_output_sections
4186 (lang_statement_union_type *s, const char *target,
4187 lang_output_section_statement_type *os)
4189 for (; s != NULL; s = s->header.next)
4191 lang_output_section_statement_type *tos;
4192 flagword flags;
4193 unsigned int type = 0;
4195 switch (s->header.type)
4197 case lang_wild_statement_enum:
4198 wild (&s->wild_statement, target, os);
4199 break;
4200 case lang_constructors_statement_enum:
4201 map_input_to_output_sections (constructor_list.head,
4202 target,
4203 os);
4204 break;
4205 case lang_output_section_statement_enum:
4206 tos = &s->output_section_statement;
4207 if (tos->constraint == ONLY_IF_RW
4208 || tos->constraint == ONLY_IF_RO)
4210 tos->all_input_readonly = true;
4211 check_input_sections (tos->children.head, tos);
4212 if (tos->all_input_readonly != (tos->constraint == ONLY_IF_RO))
4213 tos->constraint = -1;
4215 if (tos->constraint >= 0)
4216 map_input_to_output_sections (tos->children.head,
4217 target,
4218 tos);
4219 break;
4220 case lang_output_statement_enum:
4221 break;
4222 case lang_target_statement_enum:
4223 target = s->target_statement.target;
4224 break;
4225 case lang_group_statement_enum:
4226 map_input_to_output_sections (s->group_statement.children.head,
4227 target,
4228 os);
4229 break;
4230 case lang_data_statement_enum:
4231 if (os == NULL)
4232 /* This should never happen. */
4233 FAIL ();
4234 /* Make sure that any sections mentioned in the expression
4235 are initialized. */
4236 exp_init_os (s->data_statement.exp);
4237 /* The output section gets CONTENTS, ALLOC and LOAD, but
4238 these may be overridden by the script. */
4239 flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD;
4240 switch (os->sectype)
4242 case normal_section:
4243 case overlay_section:
4244 case first_overlay_section:
4245 break;
4246 case noalloc_section:
4247 flags = SEC_HAS_CONTENTS;
4248 break;
4249 case readonly_section:
4250 flags |= SEC_READONLY;
4251 break;
4252 case typed_readonly_section:
4253 flags |= SEC_READONLY;
4254 /* Fall through. */
4255 case type_section:
4256 if (os->sectype_value->type.node_class == etree_name
4257 && os->sectype_value->type.node_code == NAME)
4259 const char *name = os->sectype_value->name.name;
4260 if (strcmp (name, "SHT_PROGBITS") == 0)
4261 type = SHT_PROGBITS;
4262 else if (strcmp (name, "SHT_STRTAB") == 0)
4263 type = SHT_STRTAB;
4264 else if (strcmp (name, "SHT_NOTE") == 0)
4265 type = SHT_NOTE;
4266 else if (strcmp (name, "SHT_NOBITS") == 0)
4267 type = SHT_NOBITS;
4268 else if (strcmp (name, "SHT_INIT_ARRAY") == 0)
4269 type = SHT_INIT_ARRAY;
4270 else if (strcmp (name, "SHT_FINI_ARRAY") == 0)
4271 type = SHT_FINI_ARRAY;
4272 else if (strcmp (name, "SHT_PREINIT_ARRAY") == 0)
4273 type = SHT_PREINIT_ARRAY;
4274 else
4275 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4276 os->name);
4278 else
4280 exp_fold_tree_no_dot (os->sectype_value, os);
4281 if (expld.result.valid_p)
4282 type = expld.result.value;
4283 else
4284 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4285 os->name);
4287 break;
4288 case noload_section:
4289 if (bfd_get_flavour (link_info.output_bfd)
4290 == bfd_target_elf_flavour)
4291 flags = SEC_NEVER_LOAD | SEC_ALLOC;
4292 else
4293 flags = SEC_NEVER_LOAD | SEC_HAS_CONTENTS;
4294 break;
4296 if (os->bfd_section == NULL)
4297 init_os (os, flags | SEC_READONLY);
4298 else
4299 os->bfd_section->flags |= flags;
4300 os->bfd_section->type = type;
4301 break;
4302 case lang_input_section_enum:
4303 break;
4304 case lang_fill_statement_enum:
4305 case lang_object_symbols_statement_enum:
4306 case lang_reloc_statement_enum:
4307 case lang_padding_statement_enum:
4308 case lang_input_statement_enum:
4309 if (os != NULL && os->bfd_section == NULL)
4310 init_os (os, 0);
4311 break;
4313 case lang_assignment_statement_enum:
4314 if (os != NULL && os->bfd_section == NULL)
4315 init_os (os, get_os_init_flag (os));
4317 /* Make sure that any sections mentioned in the assignment
4318 are initialized. */
4319 exp_init_os (s->assignment_statement.exp);
4320 break;
4322 case lang_address_statement_enum:
4323 /* Mark the specified section with the supplied address.
4324 If this section was actually a segment marker, then the
4325 directive is ignored if the linker script explicitly
4326 processed the segment marker. Originally, the linker
4327 treated segment directives (like -Ttext on the
4328 command-line) as section directives. We honor the
4329 section directive semantics for backwards compatibility;
4330 linker scripts that do not specifically check for
4331 SEGMENT_START automatically get the old semantics. */
4332 if (!s->address_statement.segment
4333 || !s->address_statement.segment->used)
4335 const char *name = s->address_statement.section_name;
4337 /* Create the output section statement here so that
4338 orphans with a set address will be placed after other
4339 script sections. If we let the orphan placement code
4340 place them in amongst other sections then the address
4341 will affect following script sections, which is
4342 likely to surprise naive users. */
4343 tos = lang_output_section_statement_lookup (name, 0, 1);
4344 tos->addr_tree = s->address_statement.address;
4345 if (tos->bfd_section == NULL)
4346 init_os (tos, 0);
4348 break;
4349 case lang_insert_statement_enum:
4350 break;
4351 case lang_input_matcher_enum:
4352 FAIL ();
4357 /* An insert statement snips out all the linker statements from the
4358 start of the list and places them after the output section
4359 statement specified by the insert. This operation is complicated
4360 by the fact that we keep a doubly linked list of output section
4361 statements as well as the singly linked list of all statements.
4362 FIXME someday: Twiddling with the list not only moves statements
4363 from the user's script but also input and group statements that are
4364 built from command line object files and --start-group. We only
4365 get away with this because the list pointers used by file_chain
4366 and input_file_chain are not reordered, and processing via
4367 statement_list after this point mostly ignores input statements.
4368 One exception is the map file, where LOAD and START GROUP/END GROUP
4369 can end up looking odd. */
4371 static void
4372 process_insert_statements (lang_statement_union_type **start)
4374 lang_statement_union_type **s;
4375 lang_output_section_statement_type *first_os = NULL;
4376 lang_output_section_statement_type *last_os = NULL;
4377 lang_output_section_statement_type *os;
4379 s = start;
4380 while (*s != NULL)
4382 if ((*s)->header.type == lang_output_section_statement_enum)
4384 /* Keep pointers to the first and last output section
4385 statement in the sequence we may be about to move. */
4386 os = &(*s)->output_section_statement;
4388 ASSERT (last_os == NULL || last_os->next == os);
4389 last_os = os;
4391 /* Set constraint negative so that lang_output_section_find
4392 won't match this output section statement. At this
4393 stage in linking constraint has values in the range
4394 [-1, ONLY_IN_RW]. */
4395 last_os->constraint = -2 - last_os->constraint;
4396 if (first_os == NULL)
4397 first_os = last_os;
4399 else if ((*s)->header.type == lang_group_statement_enum)
4401 /* A user might put -T between --start-group and
4402 --end-group. One way this odd construct might arise is
4403 from a wrapper around ld to change library search
4404 behaviour. For example:
4405 #! /bin/sh
4406 exec real_ld --start-group "$@" --end-group
4407 This isn't completely unreasonable so go looking inside a
4408 group statement for insert statements. */
4409 process_insert_statements (&(*s)->group_statement.children.head);
4411 else if ((*s)->header.type == lang_insert_statement_enum)
4413 lang_insert_statement_type *i = &(*s)->insert_statement;
4414 lang_output_section_statement_type *where;
4415 lang_statement_union_type **ptr;
4416 lang_statement_union_type *first;
4418 if (link_info.non_contiguous_regions)
4420 einfo (_("warning: INSERT statement in linker script is "
4421 "incompatible with --enable-non-contiguous-regions.\n"));
4424 where = lang_output_section_find (i->where);
4425 if (where != NULL && i->is_before)
4428 where = where->prev;
4429 while (where != NULL && where->constraint < 0);
4431 if (where == NULL)
4433 einfo (_("%F%P: %s not found for insert\n"), i->where);
4434 return;
4437 /* Deal with reordering the output section statement list. */
4438 if (last_os != NULL)
4440 asection *first_sec, *last_sec;
4441 struct lang_output_section_statement_struct **next;
4443 /* Snip out the output sections we are moving. */
4444 first_os->prev->next = last_os->next;
4445 if (last_os->next == NULL)
4447 next = &first_os->prev->next;
4448 lang_os_list.tail = (lang_statement_union_type **) next;
4450 else
4451 last_os->next->prev = first_os->prev;
4452 /* Add them in at the new position. */
4453 last_os->next = where->next;
4454 if (where->next == NULL)
4456 next = &last_os->next;
4457 lang_os_list.tail = (lang_statement_union_type **) next;
4459 else
4460 where->next->prev = last_os;
4461 first_os->prev = where;
4462 where->next = first_os;
4464 /* Move the bfd sections in the same way. */
4465 first_sec = NULL;
4466 last_sec = NULL;
4467 for (os = first_os; os != NULL; os = os->next)
4469 os->constraint = -2 - os->constraint;
4470 if (os->bfd_section != NULL
4471 && os->bfd_section->owner != NULL)
4473 last_sec = os->bfd_section;
4474 if (first_sec == NULL)
4475 first_sec = last_sec;
4477 if (os == last_os)
4478 break;
4480 if (last_sec != NULL)
4482 asection *sec = where->bfd_section;
4483 if (sec == NULL)
4484 sec = output_prev_sec_find (where);
4486 /* The place we want to insert must come after the
4487 sections we are moving. So if we find no
4488 section or if the section is the same as our
4489 last section, then no move is needed. */
4490 if (sec != NULL && sec != last_sec)
4492 /* Trim them off. */
4493 if (first_sec->prev != NULL)
4494 first_sec->prev->next = last_sec->next;
4495 else
4496 link_info.output_bfd->sections = last_sec->next;
4497 if (last_sec->next != NULL)
4498 last_sec->next->prev = first_sec->prev;
4499 else
4500 link_info.output_bfd->section_last = first_sec->prev;
4501 /* Add back. */
4502 if (sec->owner == NULL)
4503 /* SEC is the absolute section, from the
4504 first dummy output section statement. Add
4505 back the sections we trimmed off to the
4506 start of the bfd sections. */
4507 sec = NULL;
4508 if (sec != NULL)
4509 last_sec->next = sec->next;
4510 else
4511 last_sec->next = link_info.output_bfd->sections;
4512 if (last_sec->next != NULL)
4513 last_sec->next->prev = last_sec;
4514 else
4515 link_info.output_bfd->section_last = last_sec;
4516 first_sec->prev = sec;
4517 if (first_sec->prev != NULL)
4518 first_sec->prev->next = first_sec;
4519 else
4520 link_info.output_bfd->sections = first_sec;
4525 lang_statement_union_type *after = (void *) where;
4526 if (where == &lang_os_list.head->output_section_statement
4527 && where->next == first_os)
4529 /* PR30155. Handle a corner case where the statement
4530 list is something like the following:
4531 . LOAD t.o
4532 . .data 0x0000000000000000 0x0
4533 . [0x0000000000000000] b = .
4534 . *(.data)
4535 . .data 0x0000000000000000 0x0 t.o
4536 . 0x0000000000000000 0x4 LONG 0x0
4537 . INSERT BEFORE .text.start
4538 . [0x0000000000000004] a = .
4539 . .text.start 0x0000000000000000 0x0
4540 . [0x0000000000000000] c = .
4541 . OUTPUT(a.out elf64-x86-64)
4542 Here we do not want to allow insert_os_after to
4543 choose a point inside the list we are moving.
4544 That would lose the list. Instead, let
4545 insert_os_after work from the INSERT, which in this
4546 particular example will result in inserting after
4547 the assignment "a = .". */
4548 after = *s;
4550 ptr = insert_os_after (after);
4551 /* Snip everything from the start of the list, up to and
4552 including the insert statement we are currently processing. */
4553 first = *start;
4554 *start = (*s)->header.next;
4555 /* Add them back where they belong, minus the insert. */
4556 *s = *ptr;
4557 if (*s == NULL)
4558 statement_list.tail = s;
4559 *ptr = first;
4560 s = start;
4561 first_os = NULL;
4562 last_os = NULL;
4563 continue;
4565 s = &(*s)->header.next;
4568 /* Undo constraint twiddling. */
4569 for (os = first_os; os != NULL; os = os->next)
4571 os->constraint = -2 - os->constraint;
4572 if (os == last_os)
4573 break;
4577 /* An output section might have been removed after its statement was
4578 added. For example, ldemul_before_allocation can remove dynamic
4579 sections if they turn out to be not needed. Clean them up here. */
4581 void
4582 strip_excluded_output_sections (void)
4584 lang_output_section_statement_type *os;
4586 /* Run lang_size_sections (if not already done). */
4587 if (expld.phase != lang_mark_phase_enum)
4589 expld.phase = lang_mark_phase_enum;
4590 expld.dataseg.phase = exp_seg_none;
4591 one_lang_size_sections_pass (NULL, false);
4592 lang_reset_memory_regions ();
4595 for (os = (void *) lang_os_list.head;
4596 os != NULL;
4597 os = os->next)
4599 asection *output_section;
4600 bool exclude;
4602 if (os->constraint < 0)
4603 continue;
4605 output_section = os->bfd_section;
4606 if (output_section == NULL)
4607 continue;
4609 exclude = (output_section->rawsize == 0
4610 && (output_section->flags & SEC_KEEP) == 0
4611 && !bfd_section_removed_from_list (link_info.output_bfd,
4612 output_section));
4614 /* Some sections have not yet been sized, notably .gnu.version,
4615 .dynsym, .dynstr and .hash. These all have SEC_LINKER_CREATED
4616 input sections, so don't drop output sections that have such
4617 input sections unless they are also marked SEC_EXCLUDE. */
4618 if (exclude && output_section->map_head.s != NULL)
4620 asection *s;
4622 for (s = output_section->map_head.s; s != NULL; s = s->map_head.s)
4623 if ((s->flags & SEC_EXCLUDE) == 0
4624 && ((s->flags & SEC_LINKER_CREATED) != 0
4625 || link_info.emitrelocations))
4627 exclude = false;
4628 break;
4632 if (exclude)
4634 /* We don't set bfd_section to NULL since bfd_section of the
4635 removed output section statement may still be used. */
4636 if (!os->update_dot)
4637 os->ignored = true;
4638 output_section->flags |= SEC_EXCLUDE;
4639 bfd_section_list_remove (link_info.output_bfd, output_section);
4640 link_info.output_bfd->section_count--;
4645 /* Called from ldwrite to clear out asection.map_head and
4646 asection.map_tail for use as link_orders in ldwrite. */
4648 void
4649 lang_clear_os_map (void)
4651 lang_output_section_statement_type *os;
4653 if (map_head_is_link_order)
4654 return;
4656 for (os = (void *) lang_os_list.head;
4657 os != NULL;
4658 os = os->next)
4660 asection *output_section;
4662 if (os->constraint < 0)
4663 continue;
4665 output_section = os->bfd_section;
4666 if (output_section == NULL)
4667 continue;
4669 /* TODO: Don't just junk map_head.s, turn them into link_orders. */
4670 output_section->map_head.link_order = NULL;
4671 output_section->map_tail.link_order = NULL;
4674 /* Stop future calls to lang_add_section from messing with map_head
4675 and map_tail link_order fields. */
4676 map_head_is_link_order = true;
4679 static void
4680 print_output_section_statement
4681 (lang_output_section_statement_type *output_section_statement)
4683 asection *section = output_section_statement->bfd_section;
4684 int len;
4686 if (output_section_statement != abs_output_section)
4688 minfo ("\n%s", output_section_statement->name);
4690 if (section != NULL)
4692 print_dot = section->vma;
4694 len = strlen (output_section_statement->name);
4695 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4697 print_nl ();
4698 len = 0;
4700 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4702 minfo ("0x%V %W", section->vma, TO_ADDR (section->size));
4704 if (section->vma != section->lma)
4705 minfo (_(" load address 0x%V"), section->lma);
4707 if (output_section_statement->update_dot_tree != NULL)
4708 exp_fold_tree (output_section_statement->update_dot_tree,
4709 output_section_statement,
4710 bfd_abs_section_ptr, &print_dot);
4713 print_nl ();
4716 print_statement_list (output_section_statement->children.head,
4717 output_section_statement);
4720 static void
4721 print_assignment (lang_assignment_statement_type *assignment,
4722 lang_output_section_statement_type *output_section)
4724 bool is_dot;
4725 etree_type *tree;
4726 asection *osec;
4728 print_spaces (SECTION_NAME_MAP_LENGTH);
4730 if (assignment->exp->type.node_class == etree_assert)
4732 is_dot = false;
4733 tree = assignment->exp->assert_s.child;
4735 else
4737 const char *dst = assignment->exp->assign.dst;
4739 is_dot = (dst[0] == '.' && dst[1] == 0);
4740 tree = assignment->exp;
4743 osec = output_section->bfd_section;
4744 if (osec == NULL)
4745 osec = bfd_abs_section_ptr;
4747 if (assignment->exp->type.node_class != etree_provide)
4748 exp_fold_tree (tree, output_section, osec, &print_dot);
4749 else
4750 expld.result.valid_p = false;
4752 char buf[32];
4753 const char *str = buf;
4754 if (expld.result.valid_p)
4756 bfd_vma value;
4758 if (assignment->exp->type.node_class == etree_assert
4759 || is_dot
4760 || expld.assign_name != NULL)
4762 value = expld.result.value;
4764 if (expld.result.section != NULL)
4765 value += expld.result.section->vma;
4767 buf[0] = '0';
4768 buf[1] = 'x';
4769 bfd_sprintf_vma (link_info.output_bfd, buf + 2, value);
4770 if (is_dot)
4771 print_dot = value;
4773 else
4775 struct bfd_link_hash_entry *h;
4777 h = bfd_link_hash_lookup (link_info.hash, assignment->exp->assign.dst,
4778 false, false, true);
4779 if (h != NULL
4780 && (h->type == bfd_link_hash_defined
4781 || h->type == bfd_link_hash_defweak))
4783 value = h->u.def.value;
4784 value += h->u.def.section->output_section->vma;
4785 value += h->u.def.section->output_offset;
4787 buf[0] = '[';
4788 buf[1] = '0';
4789 buf[2] = 'x';
4790 bfd_sprintf_vma (link_info.output_bfd, buf + 3, value);
4791 strcat (buf, "]");
4793 else
4794 str = "[unresolved]";
4797 else
4799 if (assignment->exp->type.node_class == etree_provide)
4800 str = "[!provide]";
4801 else
4802 str = "*undef*";
4804 expld.assign_name = NULL;
4806 fprintf (config.map_file, "%-34s", str);
4807 exp_print_tree (assignment->exp);
4808 print_nl ();
4811 static void
4812 print_input_statement (lang_input_statement_type *statm)
4814 if (statm->filename != NULL)
4815 fprintf (config.map_file, "LOAD %s\n", statm->filename);
4818 /* Print all symbols defined in a particular section. This is called
4819 via bfd_link_hash_traverse, or by print_all_symbols. */
4821 bool
4822 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
4824 asection *sec = (asection *) ptr;
4826 if ((hash_entry->type == bfd_link_hash_defined
4827 || hash_entry->type == bfd_link_hash_defweak)
4828 && sec == hash_entry->u.def.section)
4830 print_spaces (SECTION_NAME_MAP_LENGTH);
4831 minfo ("0x%V ",
4832 (hash_entry->u.def.value
4833 + hash_entry->u.def.section->output_offset
4834 + hash_entry->u.def.section->output_section->vma));
4836 minfo (" %pT\n", hash_entry->root.string);
4839 return true;
4842 static int
4843 hash_entry_addr_cmp (const void *a, const void *b)
4845 const struct bfd_link_hash_entry *l = *(const struct bfd_link_hash_entry **)a;
4846 const struct bfd_link_hash_entry *r = *(const struct bfd_link_hash_entry **)b;
4848 if (l->u.def.value < r->u.def.value)
4849 return -1;
4850 else if (l->u.def.value > r->u.def.value)
4851 return 1;
4852 else
4853 return 0;
4856 static void
4857 print_all_symbols (asection *sec)
4859 input_section_userdata_type *ud = bfd_section_userdata (sec);
4860 struct map_symbol_def *def;
4861 struct bfd_link_hash_entry **entries;
4862 unsigned int i;
4864 if (!ud)
4865 return;
4867 *ud->map_symbol_def_tail = 0;
4869 /* Sort the symbols by address. */
4870 entries = (struct bfd_link_hash_entry **)
4871 obstack_alloc (&map_obstack,
4872 ud->map_symbol_def_count * sizeof (*entries));
4874 for (i = 0, def = ud->map_symbol_def_head; def; def = def->next, i++)
4875 entries[i] = def->entry;
4877 qsort (entries, ud->map_symbol_def_count, sizeof (*entries),
4878 hash_entry_addr_cmp);
4880 /* Print the symbols. */
4881 for (i = 0; i < ud->map_symbol_def_count; i++)
4882 ldemul_print_symbol (entries[i], sec);
4884 obstack_free (&map_obstack, entries);
4887 /* Returns TRUE if SYM is a symbol suitable for printing
4888 in a linker map as a local symbol. */
4890 static bool
4891 ld_is_local_symbol (asymbol * sym)
4893 const char * name = bfd_asymbol_name (sym);
4895 if (name == NULL || *name == 0)
4896 return false;
4898 /* Skip .Lxxx and such like. */
4899 if (bfd_is_local_label (link_info.output_bfd, sym))
4900 return false;
4902 /* FIXME: This is intended to skip ARM mapping symbols,
4903 which for some reason are not excluded by bfd_is_local_label,
4904 but maybe it is wrong for other architectures.
4905 It would be better to fix bfd_is_local_label. */
4906 if (*name == '$')
4907 return false;
4909 /* Some local symbols, eg _GLOBAL_OFFSET_TABLE_, are present
4910 in the hash table, so do not print duplicates here. */
4911 struct bfd_link_hash_entry * h;
4912 h = bfd_link_hash_lookup (link_info.hash, name, false /* create */,
4913 false /* copy */, true /* follow */);
4914 if (h == NULL)
4915 return true;
4917 /* Symbols from the plugin owned BFD will not get their own
4918 iteration of this function, but can be on the link_info
4919 list. So include them here. */
4920 if (h->u.def.section->owner != NULL
4921 && ((bfd_get_file_flags (h->u.def.section->owner) & (BFD_LINKER_CREATED | BFD_PLUGIN))
4922 == (BFD_LINKER_CREATED | BFD_PLUGIN)))
4923 return true;
4925 return false;
4928 /* Print information about an input section to the map file. */
4930 static void
4931 print_input_section (asection *i, bool is_discarded)
4933 bfd_size_type size = i->size;
4934 int len;
4935 bfd_vma addr;
4937 init_opb (i);
4939 minfo (" %s", i->name);
4941 len = 1 + strlen (i->name);
4942 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4944 print_nl ();
4945 len = 0;
4947 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4949 if (i->output_section != NULL
4950 && i->output_section->owner == link_info.output_bfd)
4951 addr = i->output_section->vma + i->output_offset;
4952 else
4954 addr = print_dot;
4955 if (!is_discarded)
4956 size = 0;
4959 char buf[32];
4960 bfd_sprintf_vma (link_info.output_bfd, buf, addr);
4961 minfo ("0x%s %W %pB\n", buf, TO_ADDR (size), i->owner);
4963 if (size != i->rawsize && i->rawsize != 0)
4965 len = SECTION_NAME_MAP_LENGTH + 3 + strlen (buf);
4966 print_spaces (len);
4967 minfo (_("%W (size before relaxing)\n"), TO_ADDR (i->rawsize));
4970 if (i->output_section != NULL
4971 && i->output_section->owner == link_info.output_bfd)
4973 if (link_info.reduce_memory_overheads)
4974 bfd_link_hash_traverse (link_info.hash, ldemul_print_symbol, i);
4975 else
4976 print_all_symbols (i);
4978 /* Update print_dot, but make sure that we do not move it
4979 backwards - this could happen if we have overlays and a
4980 later overlay is shorter than an earier one. */
4981 if (addr + TO_ADDR (size) > print_dot)
4982 print_dot = addr + TO_ADDR (size);
4984 if (config.print_map_locals)
4986 long storage_needed;
4988 /* FIXME: It would be better to cache this table, rather
4989 than recreating it for each output section. */
4990 /* FIXME: This call is not working for non-ELF based targets.
4991 Find out why. */
4992 storage_needed = bfd_get_symtab_upper_bound (link_info.output_bfd);
4993 if (storage_needed > 0)
4995 asymbol ** symbol_table;
4996 long number_of_symbols;
4997 long j;
4999 symbol_table = xmalloc (storage_needed);
5000 number_of_symbols = bfd_canonicalize_symtab (link_info.output_bfd, symbol_table);
5002 for (j = 0; j < number_of_symbols; j++)
5004 asymbol * sym = symbol_table[j];
5005 bfd_vma sym_addr = sym->value + i->output_section->vma;
5007 if (sym->section == i->output_section
5008 && (sym->flags & BSF_LOCAL) != 0
5009 && sym_addr >= addr
5010 && sym_addr < print_dot
5011 && ld_is_local_symbol (sym))
5013 print_spaces (SECTION_NAME_MAP_LENGTH);
5014 minfo ("0x%V (local) %s\n", sym_addr, bfd_asymbol_name (sym));
5018 free (symbol_table);
5024 static void
5025 print_fill_statement (lang_fill_statement_type *fill)
5027 size_t size;
5028 unsigned char *p;
5029 fputs (" FILL mask 0x", config.map_file);
5030 for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
5031 fprintf (config.map_file, "%02x", *p);
5032 fputs ("\n", config.map_file);
5035 static void
5036 print_data_statement (lang_data_statement_type *data)
5038 bfd_vma addr;
5039 bfd_size_type size;
5040 const char *name;
5042 init_opb (data->output_section);
5043 print_spaces (SECTION_NAME_MAP_LENGTH);
5045 addr = data->output_offset;
5046 if (data->output_section != NULL)
5047 addr += data->output_section->vma;
5049 switch (data->type)
5051 default:
5052 abort ();
5053 case BYTE:
5054 size = BYTE_SIZE;
5055 name = "BYTE";
5056 break;
5057 case SHORT:
5058 size = SHORT_SIZE;
5059 name = "SHORT";
5060 break;
5061 case LONG:
5062 size = LONG_SIZE;
5063 name = "LONG";
5064 break;
5065 case QUAD:
5066 size = QUAD_SIZE;
5067 name = "QUAD";
5068 break;
5069 case SQUAD:
5070 size = QUAD_SIZE;
5071 name = "SQUAD";
5072 break;
5075 if (size < TO_SIZE ((unsigned) 1))
5076 size = TO_SIZE ((unsigned) 1);
5077 minfo ("0x%V %W %s 0x%v", addr, TO_ADDR (size), name, data->value);
5079 if (data->exp->type.node_class != etree_value)
5081 print_space ();
5082 exp_print_tree (data->exp);
5085 print_nl ();
5087 print_dot = addr + TO_ADDR (size);
5090 /* Print an address statement. These are generated by options like
5091 -Ttext. */
5093 static void
5094 print_address_statement (lang_address_statement_type *address)
5096 minfo (_("Address of section %s set to "), address->section_name);
5097 exp_print_tree (address->address);
5098 print_nl ();
5101 /* Print a reloc statement. */
5103 static void
5104 print_reloc_statement (lang_reloc_statement_type *reloc)
5106 bfd_vma addr;
5107 bfd_size_type size;
5109 init_opb (reloc->output_section);
5110 print_spaces (SECTION_NAME_MAP_LENGTH);
5112 addr = reloc->output_offset;
5113 if (reloc->output_section != NULL)
5114 addr += reloc->output_section->vma;
5116 size = bfd_get_reloc_size (reloc->howto);
5118 minfo ("0x%V %W RELOC %s ", addr, TO_ADDR (size), reloc->howto->name);
5120 if (reloc->name != NULL)
5121 minfo ("%s+", reloc->name);
5122 else
5123 minfo ("%s+", reloc->section->name);
5125 exp_print_tree (reloc->addend_exp);
5127 print_nl ();
5129 print_dot = addr + TO_ADDR (size);
5132 static void
5133 print_padding_statement (lang_padding_statement_type *s)
5135 int len;
5136 bfd_vma addr;
5138 init_opb (s->output_section);
5139 minfo (" *fill*");
5141 len = sizeof " *fill*" - 1;
5142 print_spaces (SECTION_NAME_MAP_LENGTH - len);
5144 addr = s->output_offset;
5145 if (s->output_section != NULL)
5146 addr += s->output_section->vma;
5147 minfo ("0x%V %W ", addr, TO_ADDR (s->size));
5149 if (s->fill->size != 0)
5151 size_t size;
5152 unsigned char *p;
5153 for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
5154 fprintf (config.map_file, "%02x", *p);
5157 print_nl ();
5159 print_dot = addr + TO_ADDR (s->size);
5162 static void
5163 print_wild_statement (lang_wild_statement_type *w,
5164 lang_output_section_statement_type *os)
5166 struct wildcard_list *sec;
5168 print_space ();
5170 if (w->exclude_name_list)
5172 name_list *tmp;
5173 minfo ("EXCLUDE_FILE(%s", w->exclude_name_list->name);
5174 for (tmp = w->exclude_name_list->next; tmp; tmp = tmp->next)
5175 minfo (" %s", tmp->name);
5176 minfo (") ");
5179 if (w->filenames_sorted)
5180 minfo ("SORT_BY_NAME(");
5181 if (w->filenames_reversed)
5182 minfo ("REVERSE(");
5183 if (w->filename != NULL)
5184 minfo ("%s", w->filename);
5185 else
5186 minfo ("*");
5187 if (w->filenames_reversed)
5188 minfo (")");
5189 if (w->filenames_sorted)
5190 minfo (")");
5192 minfo ("(");
5193 for (sec = w->section_list; sec; sec = sec->next)
5195 int closing_paren = 0;
5197 switch (sec->spec.sorted)
5199 case none:
5200 break;
5202 case by_name:
5203 minfo ("SORT_BY_NAME(");
5204 closing_paren = 1;
5205 break;
5207 case by_alignment:
5208 minfo ("SORT_BY_ALIGNMENT(");
5209 closing_paren = 1;
5210 break;
5212 case by_name_alignment:
5213 minfo ("SORT_BY_NAME(SORT_BY_ALIGNMENT(");
5214 closing_paren = 2;
5215 break;
5217 case by_alignment_name:
5218 minfo ("SORT_BY_ALIGNMENT(SORT_BY_NAME(");
5219 closing_paren = 2;
5220 break;
5222 case by_none:
5223 minfo ("SORT_NONE(");
5224 closing_paren = 1;
5225 break;
5227 case by_init_priority:
5228 minfo ("SORT_BY_INIT_PRIORITY(");
5229 closing_paren = 1;
5230 break;
5233 if (sec->spec.reversed)
5235 minfo ("REVERSE(");
5236 closing_paren++;
5239 if (sec->spec.exclude_name_list != NULL)
5241 name_list *tmp;
5242 minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
5243 for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
5244 minfo (" %s", tmp->name);
5245 minfo (") ");
5247 if (sec->spec.name != NULL)
5248 minfo ("%s", sec->spec.name);
5249 else
5250 minfo ("*");
5251 for (;closing_paren > 0; closing_paren--)
5252 minfo (")");
5253 if (sec->next)
5254 minfo (" ");
5256 minfo (")");
5258 print_nl ();
5260 print_statement_list (w->children.head, os);
5263 /* Print a group statement. */
5265 static void
5266 print_group (lang_group_statement_type *s,
5267 lang_output_section_statement_type *os)
5269 fprintf (config.map_file, "START GROUP\n");
5270 print_statement_list (s->children.head, os);
5271 fprintf (config.map_file, "END GROUP\n");
5274 /* Print the list of statements in S.
5275 This can be called for any statement type. */
5277 static void
5278 print_statement_list (lang_statement_union_type *s,
5279 lang_output_section_statement_type *os)
5281 while (s != NULL)
5283 print_statement (s, os);
5284 s = s->header.next;
5288 /* Print the first statement in statement list S.
5289 This can be called for any statement type. */
5291 static void
5292 print_statement (lang_statement_union_type *s,
5293 lang_output_section_statement_type *os)
5295 switch (s->header.type)
5297 default:
5298 fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
5299 FAIL ();
5300 break;
5301 case lang_constructors_statement_enum:
5302 if (constructor_list.head != NULL)
5304 if (constructors_sorted)
5305 minfo (" SORT (CONSTRUCTORS)\n");
5306 else
5307 minfo (" CONSTRUCTORS\n");
5308 print_statement_list (constructor_list.head, os);
5310 break;
5311 case lang_wild_statement_enum:
5312 print_wild_statement (&s->wild_statement, os);
5313 break;
5314 case lang_address_statement_enum:
5315 print_address_statement (&s->address_statement);
5316 break;
5317 case lang_object_symbols_statement_enum:
5318 minfo (" CREATE_OBJECT_SYMBOLS\n");
5319 break;
5320 case lang_fill_statement_enum:
5321 print_fill_statement (&s->fill_statement);
5322 break;
5323 case lang_data_statement_enum:
5324 print_data_statement (&s->data_statement);
5325 break;
5326 case lang_reloc_statement_enum:
5327 print_reloc_statement (&s->reloc_statement);
5328 break;
5329 case lang_input_section_enum:
5330 print_input_section (s->input_section.section, false);
5331 break;
5332 case lang_padding_statement_enum:
5333 print_padding_statement (&s->padding_statement);
5334 break;
5335 case lang_output_section_statement_enum:
5336 print_output_section_statement (&s->output_section_statement);
5337 break;
5338 case lang_assignment_statement_enum:
5339 print_assignment (&s->assignment_statement, os);
5340 break;
5341 case lang_target_statement_enum:
5342 fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
5343 break;
5344 case lang_output_statement_enum:
5345 minfo ("OUTPUT(%s", s->output_statement.name);
5346 if (output_target != NULL)
5347 minfo (" %s", output_target);
5348 minfo (")\n");
5349 break;
5350 case lang_input_statement_enum:
5351 print_input_statement (&s->input_statement);
5352 break;
5353 case lang_group_statement_enum:
5354 print_group (&s->group_statement, os);
5355 break;
5356 case lang_insert_statement_enum:
5357 minfo ("INSERT %s %s\n",
5358 s->insert_statement.is_before ? "BEFORE" : "AFTER",
5359 s->insert_statement.where);
5360 break;
5364 static void
5365 print_statements (void)
5367 print_statement_list (statement_list.head, abs_output_section);
5370 /* Print the first N statements in statement list S to STDERR.
5371 If N == 0, nothing is printed.
5372 If N < 0, the entire list is printed.
5373 Intended to be called from GDB. */
5375 void
5376 dprint_statement (lang_statement_union_type *s, int n)
5378 FILE *map_save = config.map_file;
5380 config.map_file = stderr;
5382 if (n < 0)
5383 print_statement_list (s, abs_output_section);
5384 else
5386 while (s && --n >= 0)
5388 print_statement (s, abs_output_section);
5389 s = s->header.next;
5393 config.map_file = map_save;
5396 static void
5397 insert_pad (lang_statement_union_type **ptr,
5398 fill_type *fill,
5399 bfd_size_type alignment_needed,
5400 asection *output_section,
5401 bfd_vma dot)
5403 static fill_type zero_fill;
5404 lang_statement_union_type *pad = NULL;
5406 if (ptr != &statement_list.head)
5407 pad = ((lang_statement_union_type *)
5408 ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
5409 if (pad != NULL
5410 && pad->header.type == lang_padding_statement_enum
5411 && pad->padding_statement.output_section == output_section)
5413 /* Use the existing pad statement. */
5415 else if ((pad = *ptr) != NULL
5416 && pad->header.type == lang_padding_statement_enum
5417 && pad->padding_statement.output_section == output_section)
5419 /* Use the existing pad statement. */
5421 else
5423 /* Make a new padding statement, linked into existing chain. */
5424 pad = stat_alloc (sizeof (lang_padding_statement_type));
5425 pad->header.next = *ptr;
5426 *ptr = pad;
5427 pad->header.type = lang_padding_statement_enum;
5428 pad->padding_statement.output_section = output_section;
5429 if (fill == NULL)
5430 fill = &zero_fill;
5431 pad->padding_statement.fill = fill;
5433 pad->padding_statement.output_offset = dot - output_section->vma;
5434 pad->padding_statement.size = alignment_needed;
5435 if (!(output_section->flags & SEC_FIXED_SIZE))
5436 output_section->size = TO_SIZE (dot + TO_ADDR (alignment_needed)
5437 - output_section->vma);
5440 /* Work out how much this section will move the dot point. */
5442 static bfd_vma
5443 size_input_section
5444 (lang_statement_union_type **this_ptr,
5445 lang_output_section_statement_type *output_section_statement,
5446 fill_type *fill,
5447 bool *removed,
5448 bfd_vma dot)
5450 lang_input_section_type *is = &((*this_ptr)->input_section);
5451 asection *i = is->section;
5452 asection *o = output_section_statement->bfd_section;
5453 *removed = 0;
5455 if (link_info.non_contiguous_regions)
5457 /* If the input section I has already been successfully assigned
5458 to an output section other than O, don't bother with it and
5459 let the caller remove it from the list. Keep processing in
5460 case we have already handled O, because the repeated passes
5461 have reinitialized its size. */
5462 if (i->already_assigned && i->already_assigned != o)
5464 *removed = 1;
5465 return dot;
5469 if (i->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
5470 i->output_offset = i->vma - o->vma;
5471 else if (((i->flags & SEC_EXCLUDE) != 0)
5472 || output_section_statement->ignored)
5473 i->output_offset = dot - o->vma;
5474 else
5476 bfd_size_type alignment_needed;
5478 /* Align this section first to the input sections requirement,
5479 then to the output section's requirement. If this alignment
5480 is greater than any seen before, then record it too. Perform
5481 the alignment by inserting a magic 'padding' statement.
5482 We can force input section alignment within an output section
5483 by using SUBALIGN. The value specified overrides any alignment
5484 given by input sections, whether larger or smaller. */
5486 if (output_section_statement->subsection_alignment != NULL)
5487 o->alignment_power = i->alignment_power =
5488 exp_get_power (output_section_statement->subsection_alignment,
5489 output_section_statement,
5490 "subsection alignment");
5492 if (o->alignment_power < i->alignment_power)
5493 o->alignment_power = i->alignment_power;
5495 alignment_needed = align_power (dot, i->alignment_power) - dot;
5497 if (alignment_needed != 0)
5499 insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
5500 dot += alignment_needed;
5503 if (link_info.non_contiguous_regions)
5505 /* If I would overflow O, let the caller remove I from the
5506 list. */
5507 if (output_section_statement->region)
5509 bfd_vma end = output_section_statement->region->origin
5510 + output_section_statement->region->length;
5512 if (dot + TO_ADDR (i->size) > end)
5514 if (i->flags & SEC_LINKER_CREATED)
5515 einfo (_("%F%P: Output section `%pA' not large enough for "
5516 "the linker-created stubs section `%pA'.\n"),
5517 i->output_section, i);
5519 if (i->rawsize && i->rawsize != i->size)
5520 einfo (_("%F%P: Relaxation not supported with "
5521 "--enable-non-contiguous-regions (section `%pA' "
5522 "would overflow `%pA' after it changed size).\n"),
5523 i, i->output_section);
5525 *removed = 1;
5526 dot = end;
5527 i->output_section = NULL;
5528 return dot;
5533 /* Remember where in the output section this input section goes. */
5534 i->output_offset = dot - o->vma;
5536 /* Mark how big the output section must be to contain this now. */
5537 dot += TO_ADDR (i->size);
5538 if (!(o->flags & SEC_FIXED_SIZE))
5539 o->size = TO_SIZE (dot - o->vma);
5541 if (link_info.non_contiguous_regions)
5543 /* Record that I was successfully assigned to O, and update
5544 its actual output section too. */
5545 i->already_assigned = o;
5546 i->output_section = o;
5550 return dot;
5553 struct check_sec
5555 asection *sec;
5556 bool warned;
5559 static int
5560 sort_sections_by_lma (const void *arg1, const void *arg2)
5562 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5563 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5565 if (sec1->lma < sec2->lma)
5566 return -1;
5567 else if (sec1->lma > sec2->lma)
5568 return 1;
5569 else if (sec1->id < sec2->id)
5570 return -1;
5571 else if (sec1->id > sec2->id)
5572 return 1;
5574 return 0;
5577 static int
5578 sort_sections_by_vma (const void *arg1, const void *arg2)
5580 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5581 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5583 if (sec1->vma < sec2->vma)
5584 return -1;
5585 else if (sec1->vma > sec2->vma)
5586 return 1;
5587 else if (sec1->id < sec2->id)
5588 return -1;
5589 else if (sec1->id > sec2->id)
5590 return 1;
5592 return 0;
5595 #define IS_TBSS(s) \
5596 ((s->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == SEC_THREAD_LOCAL)
5598 #define IGNORE_SECTION(s) \
5599 ((s->flags & SEC_ALLOC) == 0 || IS_TBSS (s))
5601 /* Check to see if any allocated sections overlap with other allocated
5602 sections. This can happen if a linker script specifies the output
5603 section addresses of the two sections. Also check whether any memory
5604 region has overflowed. */
5606 static void
5607 lang_check_section_addresses (void)
5609 asection *s, *p;
5610 struct check_sec *sections;
5611 size_t i, count;
5612 bfd_vma addr_mask;
5613 bfd_vma s_start;
5614 bfd_vma s_end;
5615 bfd_vma p_start = 0;
5616 bfd_vma p_end = 0;
5617 lang_memory_region_type *m;
5618 bool overlays;
5620 /* Detect address space overflow on allocated sections. */
5621 addr_mask = ((bfd_vma) 1 <<
5622 (bfd_arch_bits_per_address (link_info.output_bfd) - 1)) - 1;
5623 addr_mask = (addr_mask << 1) + 1;
5624 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5625 if ((s->flags & SEC_ALLOC) != 0)
5627 s_end = (s->vma + s->size) & addr_mask;
5628 if (s_end != 0 && s_end < (s->vma & addr_mask))
5629 einfo (_("%X%P: section %s VMA wraps around address space\n"),
5630 s->name);
5631 else
5633 s_end = (s->lma + s->size) & addr_mask;
5634 if (s_end != 0 && s_end < (s->lma & addr_mask))
5635 einfo (_("%X%P: section %s LMA wraps around address space\n"),
5636 s->name);
5640 if (bfd_count_sections (link_info.output_bfd) <= 1)
5641 return;
5643 count = bfd_count_sections (link_info.output_bfd);
5644 sections = XNEWVEC (struct check_sec, count);
5646 /* Scan all sections in the output list. */
5647 count = 0;
5648 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5650 if (IGNORE_SECTION (s)
5651 || s->size == 0)
5652 continue;
5654 sections[count].sec = s;
5655 sections[count].warned = false;
5656 count++;
5659 if (count <= 1)
5661 free (sections);
5662 return;
5665 qsort (sections, count, sizeof (*sections), sort_sections_by_lma);
5667 /* First check section LMAs. There should be no overlap of LMAs on
5668 loadable sections, even with overlays. */
5669 for (p = NULL, i = 0; i < count; i++)
5671 s = sections[i].sec;
5672 init_opb (s);
5673 if ((s->flags & SEC_LOAD) != 0)
5675 s_start = s->lma;
5676 s_end = s_start + TO_ADDR (s->size) - 1;
5678 /* Look for an overlap. We have sorted sections by lma, so
5679 we know that s_start >= p_start. Besides the obvious
5680 case of overlap when the current section starts before
5681 the previous one ends, we also must have overlap if the
5682 previous section wraps around the address space. */
5683 if (p != NULL
5684 && (s_start <= p_end
5685 || p_end < p_start))
5687 einfo (_("%X%P: section %s LMA [%V,%V]"
5688 " overlaps section %s LMA [%V,%V]\n"),
5689 s->name, s_start, s_end, p->name, p_start, p_end);
5690 sections[i].warned = true;
5692 p = s;
5693 p_start = s_start;
5694 p_end = s_end;
5698 /* If any non-zero size allocated section (excluding tbss) starts at
5699 exactly the same VMA as another such section, then we have
5700 overlays. Overlays generated by the OVERLAY keyword will have
5701 this property. It is possible to intentionally generate overlays
5702 that fail this test, but it would be unusual. */
5703 qsort (sections, count, sizeof (*sections), sort_sections_by_vma);
5704 overlays = false;
5705 p_start = sections[0].sec->vma;
5706 for (i = 1; i < count; i++)
5708 s_start = sections[i].sec->vma;
5709 if (p_start == s_start)
5711 overlays = true;
5712 break;
5714 p_start = s_start;
5717 /* Now check section VMAs if no overlays were detected. */
5718 if (!overlays)
5720 for (p = NULL, i = 0; i < count; i++)
5722 s = sections[i].sec;
5723 init_opb (s);
5724 s_start = s->vma;
5725 s_end = s_start + TO_ADDR (s->size) - 1;
5727 if (p != NULL
5728 && !sections[i].warned
5729 && (s_start <= p_end
5730 || p_end < p_start))
5731 einfo (_("%X%P: section %s VMA [%V,%V]"
5732 " overlaps section %s VMA [%V,%V]\n"),
5733 s->name, s_start, s_end, p->name, p_start, p_end);
5734 p = s;
5735 p_start = s_start;
5736 p_end = s_end;
5740 free (sections);
5742 /* If any memory region has overflowed, report by how much.
5743 We do not issue this diagnostic for regions that had sections
5744 explicitly placed outside their bounds; os_region_check's
5745 diagnostics are adequate for that case.
5747 FIXME: It is conceivable that m->current - (m->origin + m->length)
5748 might overflow a 32-bit integer. There is, alas, no way to print
5749 a bfd_vma quantity in decimal. */
5750 for (m = lang_memory_region_list; m; m = m->next)
5751 if (m->had_full_message)
5753 unsigned long over = m->current - (m->origin + m->length);
5754 einfo (ngettext ("%X%P: region `%s' overflowed by %lu byte\n",
5755 "%X%P: region `%s' overflowed by %lu bytes\n",
5756 over),
5757 m->name_list.name, over);
5761 /* Make sure the new address is within the region. We explicitly permit the
5762 current address to be at the exact end of the region when the address is
5763 non-zero, in case the region is at the end of addressable memory and the
5764 calculation wraps around. */
5766 static void
5767 os_region_check (lang_output_section_statement_type *os,
5768 lang_memory_region_type *region,
5769 etree_type *tree,
5770 bfd_vma rbase)
5772 if ((region->current < region->origin
5773 || (region->current - region->origin > region->length))
5774 && ((region->current != region->origin + region->length)
5775 || rbase == 0))
5777 if (tree != NULL)
5779 einfo (_("%X%P: address 0x%v of %pB section `%s'"
5780 " is not within region `%s'\n"),
5781 region->current,
5782 os->bfd_section->owner,
5783 os->bfd_section->name,
5784 region->name_list.name);
5786 else if (!region->had_full_message)
5788 region->had_full_message = true;
5790 einfo (_("%X%P: %pB section `%s' will not fit in region `%s'\n"),
5791 os->bfd_section->owner,
5792 os->bfd_section->name,
5793 region->name_list.name);
5798 static void
5799 ldlang_check_relro_region (lang_statement_union_type *s)
5801 seg_align_type *seg = &expld.dataseg;
5803 if (seg->relro == exp_seg_relro_start)
5805 if (!seg->relro_start_stat)
5806 seg->relro_start_stat = s;
5807 else
5809 ASSERT (seg->relro_start_stat == s);
5812 else if (seg->relro == exp_seg_relro_end)
5814 if (!seg->relro_end_stat)
5815 seg->relro_end_stat = s;
5816 else
5818 ASSERT (seg->relro_end_stat == s);
5823 /* Set the sizes for all the output sections. */
5825 static bfd_vma
5826 lang_size_sections_1
5827 (lang_statement_union_type **prev,
5828 lang_output_section_statement_type *current_os,
5829 fill_type *fill,
5830 bfd_vma dot,
5831 bool *relax,
5832 bool check_regions)
5834 lang_statement_union_type *s;
5835 lang_statement_union_type *prev_s = NULL;
5836 bool removed_prev_s = false;
5837 lang_output_section_statement_type *os = current_os;
5839 /* Size up the sections from their constituent parts. */
5840 for (s = *prev; s != NULL; prev_s = s, s = s->header.next)
5842 bool removed = false;
5844 switch (s->header.type)
5846 case lang_output_section_statement_enum:
5848 bfd_vma newdot, after, dotdelta;
5849 lang_memory_region_type *r;
5850 int section_alignment = 0;
5852 os = &s->output_section_statement;
5853 init_opb (os->bfd_section);
5854 if (os->constraint == -1)
5855 break;
5857 /* FIXME: We shouldn't need to zero section vmas for ld -r
5858 here, in lang_insert_orphan, or in the default linker scripts.
5859 This is covering for coff backend linker bugs. See PR6945. */
5860 if (os->addr_tree == NULL
5861 && bfd_link_relocatable (&link_info)
5862 && (bfd_get_flavour (link_info.output_bfd)
5863 == bfd_target_coff_flavour))
5864 os->addr_tree = exp_intop (0);
5865 if (os->addr_tree != NULL)
5867 exp_fold_tree (os->addr_tree, os, bfd_abs_section_ptr, &dot);
5869 if (expld.result.valid_p)
5871 dot = expld.result.value;
5872 if (expld.result.section != NULL)
5873 dot += expld.result.section->vma;
5875 else if (expld.phase != lang_mark_phase_enum)
5876 einfo (_("%F%P:%pS: non constant or forward reference"
5877 " address expression for section %s\n"),
5878 os->addr_tree, os->name);
5881 if (os->bfd_section == NULL)
5882 /* This section was removed or never actually created. */
5883 break;
5885 /* If this is a COFF shared library section, use the size and
5886 address from the input section. FIXME: This is COFF
5887 specific; it would be cleaner if there were some other way
5888 to do this, but nothing simple comes to mind. */
5889 if (((bfd_get_flavour (link_info.output_bfd)
5890 == bfd_target_ecoff_flavour)
5891 || (bfd_get_flavour (link_info.output_bfd)
5892 == bfd_target_coff_flavour))
5893 && (os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
5895 asection *input;
5897 if (os->children.head == NULL
5898 || os->children.head->header.next != NULL
5899 || (os->children.head->header.type
5900 != lang_input_section_enum))
5901 einfo (_("%X%P: internal error on COFF shared library"
5902 " section %s\n"), os->name);
5904 input = os->children.head->input_section.section;
5905 bfd_set_section_vma (os->bfd_section,
5906 bfd_section_vma (input));
5907 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5908 os->bfd_section->size = input->size;
5909 break;
5912 newdot = dot;
5913 dotdelta = 0;
5914 if (bfd_is_abs_section (os->bfd_section))
5916 /* No matter what happens, an abs section starts at zero. */
5917 ASSERT (os->bfd_section->vma == 0);
5919 else
5921 if (os->addr_tree == NULL)
5923 /* No address specified for this section, get one
5924 from the region specification. */
5925 if (os->region == NULL
5926 || ((os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))
5927 && os->region->name_list.name[0] == '*'
5928 && strcmp (os->region->name_list.name,
5929 DEFAULT_MEMORY_REGION) == 0))
5931 os->region = lang_memory_default (os->bfd_section);
5934 /* If a loadable section is using the default memory
5935 region, and some non default memory regions were
5936 defined, issue an error message. */
5937 if (!os->ignored
5938 && !IGNORE_SECTION (os->bfd_section)
5939 && !bfd_link_relocatable (&link_info)
5940 && check_regions
5941 && strcmp (os->region->name_list.name,
5942 DEFAULT_MEMORY_REGION) == 0
5943 && lang_memory_region_list != NULL
5944 && (strcmp (lang_memory_region_list->name_list.name,
5945 DEFAULT_MEMORY_REGION) != 0
5946 || lang_memory_region_list->next != NULL)
5947 && lang_sizing_iteration == 1)
5949 /* By default this is an error rather than just a
5950 warning because if we allocate the section to the
5951 default memory region we can end up creating an
5952 excessively large binary, or even seg faulting when
5953 attempting to perform a negative seek. See
5954 sources.redhat.com/ml/binutils/2003-04/msg00423.html
5955 for an example of this. This behaviour can be
5956 overridden by the using the --no-check-sections
5957 switch. */
5958 if (command_line.check_section_addresses)
5959 einfo (_("%F%P: error: no memory region specified"
5960 " for loadable section `%s'\n"),
5961 bfd_section_name (os->bfd_section));
5962 else
5963 einfo (_("%P: warning: no memory region specified"
5964 " for loadable section `%s'\n"),
5965 bfd_section_name (os->bfd_section));
5968 newdot = os->region->current;
5969 section_alignment = os->bfd_section->alignment_power;
5971 else
5972 section_alignment = exp_get_power (os->section_alignment, os,
5973 "section alignment");
5975 /* Align to what the section needs. */
5976 if (section_alignment > 0)
5978 bfd_vma savedot = newdot;
5979 bfd_vma diff = 0;
5981 newdot = align_power (newdot, section_alignment);
5982 dotdelta = newdot - savedot;
5984 if (lang_sizing_iteration == 1)
5985 diff = dotdelta;
5986 else if (lang_sizing_iteration > 1)
5988 /* Only report adjustments that would change
5989 alignment from what we have already reported. */
5990 diff = newdot - os->bfd_section->vma;
5991 if (!(diff & (((bfd_vma) 1 << section_alignment) - 1)))
5992 diff = 0;
5994 if (diff != 0
5995 && (config.warn_section_align
5996 || os->addr_tree != NULL))
5997 einfo (_("%P: warning: "
5998 "start of section %s changed by %ld\n"),
5999 os->name, (long) diff);
6002 bfd_set_section_vma (os->bfd_section, newdot);
6004 os->bfd_section->output_offset = 0;
6007 lang_size_sections_1 (&os->children.head, os,
6008 os->fill, newdot, relax, check_regions);
6010 os->processed_vma = true;
6012 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
6013 /* Except for some special linker created sections,
6014 no output section should change from zero size
6015 after strip_excluded_output_sections. A non-zero
6016 size on an ignored section indicates that some
6017 input section was not sized early enough. */
6018 ASSERT (os->bfd_section->size == 0);
6019 else
6021 dot = os->bfd_section->vma;
6023 /* Put the section within the requested block size, or
6024 align at the block boundary. */
6025 after = ((dot
6026 + TO_ADDR (os->bfd_section->size)
6027 + os->block_value - 1)
6028 & - (bfd_vma) os->block_value);
6030 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
6031 os->bfd_section->size = TO_SIZE (after
6032 - os->bfd_section->vma);
6035 /* Set section lma. */
6036 r = os->region;
6037 if (r == NULL)
6038 r = lang_memory_region_lookup (DEFAULT_MEMORY_REGION, false);
6040 if (os->load_base)
6042 bfd_vma lma = exp_get_abs_int (os->load_base, 0, "load base");
6043 os->bfd_section->lma = lma;
6045 else if (os->lma_region != NULL)
6047 bfd_vma lma = os->lma_region->current;
6049 if (os->align_lma_with_input)
6050 lma += dotdelta;
6051 else
6053 /* When LMA_REGION is the same as REGION, align the LMA
6054 as we did for the VMA, possibly including alignment
6055 from the bfd section. If a different region, then
6056 only align according to the value in the output
6057 statement. */
6058 if (os->lma_region != os->region)
6059 section_alignment = exp_get_power (os->section_alignment,
6061 "section alignment");
6062 if (section_alignment > 0)
6063 lma = align_power (lma, section_alignment);
6065 os->bfd_section->lma = lma;
6067 else if (r->last_os != NULL
6068 && (os->bfd_section->flags & SEC_ALLOC) != 0)
6070 bfd_vma lma;
6071 asection *last;
6073 last = r->last_os->output_section_statement.bfd_section;
6075 /* A backwards move of dot should be accompanied by
6076 an explicit assignment to the section LMA (ie.
6077 os->load_base set) because backwards moves can
6078 create overlapping LMAs. */
6079 if (dot < last->vma
6080 && os->bfd_section->size != 0
6081 && dot + TO_ADDR (os->bfd_section->size) <= last->vma)
6083 /* If dot moved backwards then leave lma equal to
6084 vma. This is the old default lma, which might
6085 just happen to work when the backwards move is
6086 sufficiently large. Nag if this changes anything,
6087 so people can fix their linker scripts. */
6089 if (last->vma != last->lma)
6090 einfo (_("%P: warning: dot moved backwards "
6091 "before `%s'\n"), os->name);
6093 else
6095 /* If this is an overlay, set the current lma to that
6096 at the end of the previous section. */
6097 if (os->sectype == overlay_section)
6098 lma = last->lma + TO_ADDR (last->size);
6100 /* Otherwise, keep the same lma to vma relationship
6101 as the previous section. */
6102 else
6103 lma = os->bfd_section->vma + last->lma - last->vma;
6105 if (section_alignment > 0)
6106 lma = align_power (lma, section_alignment);
6107 os->bfd_section->lma = lma;
6110 os->processed_lma = true;
6112 /* Keep track of normal sections using the default
6113 lma region. We use this to set the lma for
6114 following sections. Overlays or other linker
6115 script assignment to lma might mean that the
6116 default lma == vma is incorrect.
6117 To avoid warnings about dot moving backwards when using
6118 -Ttext, don't start tracking sections until we find one
6119 of non-zero size or with lma set differently to vma.
6120 Do this tracking before we short-cut the loop so that we
6121 track changes for the case where the section size is zero,
6122 but the lma is set differently to the vma. This is
6123 important, if an orphan section is placed after an
6124 otherwise empty output section that has an explicit lma
6125 set, we want that lma reflected in the orphans lma. */
6126 if (((!IGNORE_SECTION (os->bfd_section)
6127 && (os->bfd_section->size != 0
6128 || (r->last_os == NULL
6129 && os->bfd_section->vma != os->bfd_section->lma)
6130 || (r->last_os != NULL
6131 && dot >= (r->last_os->output_section_statement
6132 .bfd_section->vma))))
6133 || os->sectype == first_overlay_section)
6134 && os->lma_region == NULL
6135 && !bfd_link_relocatable (&link_info))
6136 r->last_os = s;
6138 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
6139 break;
6141 /* .tbss sections effectively have zero size. */
6142 if (!IS_TBSS (os->bfd_section)
6143 || bfd_link_relocatable (&link_info))
6144 dotdelta = TO_ADDR (os->bfd_section->size);
6145 else
6146 dotdelta = 0;
6147 dot += dotdelta;
6149 if (os->update_dot_tree != 0)
6150 exp_fold_tree (os->update_dot_tree, os, bfd_abs_section_ptr, &dot);
6152 /* Update dot in the region ?
6153 We only do this if the section is going to be allocated,
6154 since unallocated sections do not contribute to the region's
6155 overall size in memory. */
6156 if (os->region != NULL
6157 && (os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD)))
6159 os->region->current = dot;
6161 if (check_regions)
6162 /* Make sure the new address is within the region. */
6163 os_region_check (os, os->region, os->addr_tree,
6164 os->bfd_section->vma);
6166 if (os->lma_region != NULL && os->lma_region != os->region
6167 && ((os->bfd_section->flags & SEC_LOAD)
6168 || os->align_lma_with_input))
6170 os->lma_region->current = os->bfd_section->lma + dotdelta;
6172 if (check_regions)
6173 os_region_check (os, os->lma_region, NULL,
6174 os->bfd_section->lma);
6178 break;
6180 case lang_constructors_statement_enum:
6181 dot = lang_size_sections_1 (&constructor_list.head, current_os,
6182 fill, dot, relax, check_regions);
6183 break;
6185 case lang_data_statement_enum:
6187 unsigned int size = 0;
6189 s->data_statement.output_offset = dot - current_os->bfd_section->vma;
6190 s->data_statement.output_section = current_os->bfd_section;
6192 /* We might refer to provided symbols in the expression, and
6193 need to mark them as needed. */
6194 exp_fold_tree (s->data_statement.exp, os,
6195 bfd_abs_section_ptr, &dot);
6197 switch (s->data_statement.type)
6199 default:
6200 abort ();
6201 case QUAD:
6202 case SQUAD:
6203 size = QUAD_SIZE;
6204 break;
6205 case LONG:
6206 size = LONG_SIZE;
6207 break;
6208 case SHORT:
6209 size = SHORT_SIZE;
6210 break;
6211 case BYTE:
6212 size = BYTE_SIZE;
6213 break;
6215 if (size < TO_SIZE ((unsigned) 1))
6216 size = TO_SIZE ((unsigned) 1);
6217 dot += TO_ADDR (size);
6218 if (!(current_os->bfd_section->flags & SEC_FIXED_SIZE))
6219 current_os->bfd_section->size
6220 = TO_SIZE (dot - current_os->bfd_section->vma);
6223 break;
6225 case lang_reloc_statement_enum:
6227 int size;
6229 s->reloc_statement.output_offset
6230 = dot - current_os->bfd_section->vma;
6231 s->reloc_statement.output_section
6232 = current_os->bfd_section;
6233 size = bfd_get_reloc_size (s->reloc_statement.howto);
6234 dot += TO_ADDR (size);
6235 if (!(current_os->bfd_section->flags & SEC_FIXED_SIZE))
6236 current_os->bfd_section->size
6237 = TO_SIZE (dot - current_os->bfd_section->vma);
6239 break;
6241 case lang_wild_statement_enum:
6242 dot = lang_size_sections_1 (&s->wild_statement.children.head,
6243 current_os, fill, dot, relax,
6244 check_regions);
6245 break;
6247 case lang_object_symbols_statement_enum:
6248 link_info.create_object_symbols_section = current_os->bfd_section;
6249 current_os->bfd_section->flags |= SEC_KEEP;
6250 break;
6252 case lang_output_statement_enum:
6253 case lang_target_statement_enum:
6254 break;
6256 case lang_input_section_enum:
6258 asection *i;
6260 i = s->input_section.section;
6261 if (relax)
6263 bool again;
6265 if (!bfd_relax_section (i->owner, i, &link_info, &again))
6266 einfo (_("%F%P: can't relax section: %E\n"));
6267 if (again)
6268 *relax = true;
6270 dot = size_input_section (prev, current_os, fill, &removed, dot);
6272 break;
6274 case lang_input_statement_enum:
6275 break;
6277 case lang_fill_statement_enum:
6278 s->fill_statement.output_section = current_os->bfd_section;
6280 fill = s->fill_statement.fill;
6281 break;
6283 case lang_assignment_statement_enum:
6285 bfd_vma newdot = dot;
6286 etree_type *tree = s->assignment_statement.exp;
6288 expld.dataseg.relro = exp_seg_relro_none;
6290 exp_fold_tree (tree, os, current_os->bfd_section, &newdot);
6292 ldlang_check_relro_region (s);
6294 expld.dataseg.relro = exp_seg_relro_none;
6296 /* This symbol may be relative to this section. */
6297 if ((tree->type.node_class == etree_provided
6298 || tree->type.node_class == etree_assign)
6299 && (tree->assign.dst [0] != '.'
6300 || tree->assign.dst [1] != '\0'))
6301 current_os->update_dot = 1;
6303 if (!current_os->ignored)
6305 if (current_os == abs_output_section)
6307 /* If we don't have an output section, then just adjust
6308 the default memory address. */
6309 lang_memory_region_lookup (DEFAULT_MEMORY_REGION,
6310 false)->current = newdot;
6312 else if (newdot != dot)
6314 /* Insert a pad after this statement. We can't
6315 put the pad before when relaxing, in case the
6316 assignment references dot. */
6317 insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
6318 current_os->bfd_section, dot);
6320 /* Don't neuter the pad below when relaxing. */
6321 s = s->header.next;
6323 /* If dot is advanced, this implies that the section
6324 should have space allocated to it, unless the
6325 user has explicitly stated that the section
6326 should not be allocated. */
6327 if (current_os->sectype != noalloc_section
6328 && (current_os->sectype != noload_section
6329 || (bfd_get_flavour (link_info.output_bfd)
6330 == bfd_target_elf_flavour)))
6331 current_os->bfd_section->flags |= SEC_ALLOC;
6333 dot = newdot;
6336 break;
6338 case lang_padding_statement_enum:
6339 /* If this is the first time lang_size_sections is called,
6340 we won't have any padding statements. If this is the
6341 second or later passes when relaxing, we should allow
6342 padding to shrink. If padding is needed on this pass, it
6343 will be added back in. */
6344 s->padding_statement.size = 0;
6346 /* Make sure output_offset is valid. If relaxation shrinks
6347 the section and this pad isn't needed, it's possible to
6348 have output_offset larger than the final size of the
6349 section. bfd_set_section_contents will complain even for
6350 a pad size of zero. */
6351 s->padding_statement.output_offset
6352 = dot - current_os->bfd_section->vma;
6353 break;
6355 case lang_group_statement_enum:
6356 dot = lang_size_sections_1 (&s->group_statement.children.head,
6357 current_os, fill, dot, relax,
6358 check_regions);
6359 break;
6361 case lang_insert_statement_enum:
6362 break;
6364 /* We can only get here when relaxing is turned on. */
6365 case lang_address_statement_enum:
6366 break;
6368 default:
6369 FAIL ();
6370 break;
6373 /* If an input section doesn't fit in the current output
6374 section, remove it from the list. Handle the case where we
6375 have to remove an input_section statement here: there is a
6376 special case to remove the first element of the list. */
6377 if (link_info.non_contiguous_regions && removed)
6379 /* If we removed the first element during the previous
6380 iteration, override the loop assignment of prev_s. */
6381 if (removed_prev_s)
6382 prev_s = NULL;
6384 if (prev_s)
6386 /* If there was a real previous input section, just skip
6387 the current one. */
6388 prev_s->header.next=s->header.next;
6389 s = prev_s;
6390 removed_prev_s = false;
6392 else
6394 /* Remove the first input section of the list. */
6395 *prev = s->header.next;
6396 removed_prev_s = true;
6399 /* Move to next element, unless we removed the head of the
6400 list. */
6401 if (!removed_prev_s)
6402 prev = &s->header.next;
6404 else
6406 prev = &s->header.next;
6407 removed_prev_s = false;
6410 return dot;
6413 /* Callback routine that is used in _bfd_elf_map_sections_to_segments.
6414 The BFD library has set NEW_SEGMENT to TRUE iff it thinks that
6415 CURRENT_SECTION and PREVIOUS_SECTION ought to be placed into different
6416 segments. We are allowed an opportunity to override this decision. */
6418 bool
6419 ldlang_override_segment_assignment (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6420 bfd *abfd ATTRIBUTE_UNUSED,
6421 asection *current_section,
6422 asection *previous_section,
6423 bool new_segment)
6425 lang_output_section_statement_type *cur;
6426 lang_output_section_statement_type *prev;
6428 /* The checks below are only necessary when the BFD library has decided
6429 that the two sections ought to be placed into the same segment. */
6430 if (new_segment)
6431 return true;
6433 /* Paranoia checks. */
6434 if (current_section == NULL || previous_section == NULL)
6435 return new_segment;
6437 /* If this flag is set, the target never wants code and non-code
6438 sections comingled in the same segment. */
6439 if (config.separate_code
6440 && ((current_section->flags ^ previous_section->flags) & SEC_CODE))
6441 return true;
6443 /* Find the memory regions associated with the two sections.
6444 We call lang_output_section_find() here rather than scanning the list
6445 of output sections looking for a matching section pointer because if
6446 we have a large number of sections then a hash lookup is faster. */
6447 cur = lang_output_section_find (current_section->name);
6448 prev = lang_output_section_find (previous_section->name);
6450 /* More paranoia. */
6451 if (cur == NULL || prev == NULL)
6452 return new_segment;
6454 /* If the regions are different then force the sections to live in
6455 different segments. See the email thread starting at the following
6456 URL for the reasons why this is necessary:
6457 http://sourceware.org/ml/binutils/2007-02/msg00216.html */
6458 return cur->region != prev->region;
6461 void
6462 one_lang_size_sections_pass (bool *relax, bool check_regions)
6464 lang_statement_iteration++;
6465 if (expld.phase != lang_mark_phase_enum)
6466 lang_sizing_iteration++;
6467 lang_size_sections_1 (&statement_list.head, abs_output_section,
6468 0, 0, relax, check_regions);
6471 static bool
6472 lang_size_segment (void)
6474 /* If XXX_SEGMENT_ALIGN XXX_SEGMENT_END pair was seen, check whether
6475 a page could be saved in the data segment. */
6476 seg_align_type *seg = &expld.dataseg;
6477 bfd_vma first, last;
6479 first = -seg->base & (seg->commonpagesize - 1);
6480 last = seg->end & (seg->commonpagesize - 1);
6481 if (first && last
6482 && ((seg->base & ~(seg->commonpagesize - 1))
6483 != (seg->end & ~(seg->commonpagesize - 1)))
6484 && first + last <= seg->commonpagesize)
6486 seg->phase = exp_seg_adjust;
6487 return true;
6490 seg->phase = exp_seg_done;
6491 return false;
6494 static bfd_vma
6495 lang_size_relro_segment_1 (void)
6497 seg_align_type *seg = &expld.dataseg;
6498 bfd_vma relro_end, desired_end;
6499 asection *sec;
6501 /* Compute the expected PT_GNU_RELRO/PT_LOAD segment end. */
6502 relro_end = (seg->relro_end + seg->relropagesize - 1) & -seg->relropagesize;
6504 /* Adjust by the offset arg of XXX_SEGMENT_RELRO_END. */
6505 desired_end = relro_end - seg->relro_offset;
6507 /* For sections in the relro segment.. */
6508 for (sec = link_info.output_bfd->section_last; sec; sec = sec->prev)
6509 if ((sec->flags & SEC_ALLOC) != 0
6510 && sec->vma >= seg->base
6511 && sec->vma < seg->relro_end - seg->relro_offset)
6513 /* Where do we want to put this section so that it ends as
6514 desired? */
6515 bfd_vma start, end, bump;
6517 end = start = sec->vma;
6518 if (!IS_TBSS (sec))
6519 end += TO_ADDR (sec->size);
6520 bump = desired_end - end;
6521 /* We'd like to increase START by BUMP, but we must heed
6522 alignment so the increase might be less than optimum. */
6523 start += bump;
6524 start &= ~(((bfd_vma) 1 << sec->alignment_power) - 1);
6525 /* This is now the desired end for the previous section. */
6526 desired_end = start;
6529 seg->phase = exp_seg_relro_adjust;
6530 ASSERT (desired_end >= seg->base);
6531 seg->base = desired_end;
6532 return relro_end;
6535 static bool
6536 lang_size_relro_segment (bool *relax, bool check_regions)
6538 bool do_reset = false;
6540 if (link_info.relro && expld.dataseg.relro_end)
6542 bfd_vma data_initial_base = expld.dataseg.base;
6543 bfd_vma data_relro_end = lang_size_relro_segment_1 ();
6545 lang_reset_memory_regions ();
6546 one_lang_size_sections_pass (relax, check_regions);
6548 /* Assignments to dot, or to output section address in a user
6549 script have increased padding over the original. Revert. */
6550 if (expld.dataseg.relro_end > data_relro_end)
6552 expld.dataseg.base = data_initial_base;
6553 do_reset = true;
6556 else if (lang_size_segment ())
6557 do_reset = true;
6559 return do_reset;
6562 void
6563 lang_size_sections (bool *relax, bool check_regions)
6565 expld.phase = lang_allocating_phase_enum;
6566 expld.dataseg.phase = exp_seg_none;
6568 one_lang_size_sections_pass (relax, check_regions);
6570 if (expld.dataseg.phase != exp_seg_end_seen)
6571 expld.dataseg.phase = exp_seg_done;
6573 if (expld.dataseg.phase == exp_seg_end_seen)
6575 bool do_reset
6576 = lang_size_relro_segment (relax, check_regions);
6578 if (do_reset)
6580 lang_reset_memory_regions ();
6581 one_lang_size_sections_pass (relax, check_regions);
6584 if (link_info.relro && expld.dataseg.relro_end)
6586 link_info.relro_start = expld.dataseg.base;
6587 link_info.relro_end = expld.dataseg.relro_end;
6592 static lang_output_section_statement_type *current_section;
6593 static lang_assignment_statement_type *current_assign;
6594 static bool prefer_next_section;
6596 /* Worker function for lang_do_assignments. Recursiveness goes here. */
6598 static bfd_vma
6599 lang_do_assignments_1 (lang_statement_union_type *s,
6600 lang_output_section_statement_type *current_os,
6601 fill_type *fill,
6602 bfd_vma dot,
6603 bool *found_end)
6605 lang_output_section_statement_type *os = current_os;
6607 for (; s != NULL; s = s->header.next)
6609 switch (s->header.type)
6611 case lang_constructors_statement_enum:
6612 dot = lang_do_assignments_1 (constructor_list.head,
6613 current_os, fill, dot, found_end);
6614 break;
6616 case lang_output_section_statement_enum:
6618 bfd_vma newdot;
6620 os = &s->output_section_statement;
6621 os->after_end = *found_end;
6622 init_opb (os->bfd_section);
6623 newdot = dot;
6624 if (os->bfd_section != NULL)
6626 if (!os->ignored && (os->bfd_section->flags & SEC_ALLOC) != 0)
6628 current_section = os;
6629 prefer_next_section = false;
6631 newdot = os->bfd_section->vma;
6633 newdot = lang_do_assignments_1 (os->children.head,
6634 os, os->fill, newdot, found_end);
6635 if (!os->ignored)
6637 if (os->bfd_section != NULL)
6639 newdot = os->bfd_section->vma;
6641 /* .tbss sections effectively have zero size. */
6642 if (!IS_TBSS (os->bfd_section)
6643 || bfd_link_relocatable (&link_info))
6644 newdot += TO_ADDR (os->bfd_section->size);
6646 if (os->update_dot_tree != NULL)
6647 exp_fold_tree (os->update_dot_tree, os,
6648 bfd_abs_section_ptr, &newdot);
6650 dot = newdot;
6653 break;
6655 case lang_wild_statement_enum:
6657 dot = lang_do_assignments_1 (s->wild_statement.children.head,
6658 current_os, fill, dot, found_end);
6659 break;
6661 case lang_object_symbols_statement_enum:
6662 case lang_output_statement_enum:
6663 case lang_target_statement_enum:
6664 break;
6666 case lang_data_statement_enum:
6667 exp_fold_tree (s->data_statement.exp, os, bfd_abs_section_ptr, &dot);
6668 if (expld.result.valid_p)
6670 s->data_statement.value = expld.result.value;
6671 if (expld.result.section != NULL)
6672 s->data_statement.value += expld.result.section->vma;
6674 else if (expld.phase == lang_final_phase_enum)
6675 einfo (_("%F%P: invalid data statement\n"));
6677 unsigned int size;
6678 switch (s->data_statement.type)
6680 default:
6681 abort ();
6682 case QUAD:
6683 case SQUAD:
6684 size = QUAD_SIZE;
6685 break;
6686 case LONG:
6687 size = LONG_SIZE;
6688 break;
6689 case SHORT:
6690 size = SHORT_SIZE;
6691 break;
6692 case BYTE:
6693 size = BYTE_SIZE;
6694 break;
6696 if (size < TO_SIZE ((unsigned) 1))
6697 size = TO_SIZE ((unsigned) 1);
6698 dot += TO_ADDR (size);
6700 break;
6702 case lang_reloc_statement_enum:
6703 exp_fold_tree (s->reloc_statement.addend_exp, os,
6704 bfd_abs_section_ptr, &dot);
6705 if (expld.result.valid_p)
6706 s->reloc_statement.addend_value = expld.result.value;
6707 else if (expld.phase == lang_final_phase_enum)
6708 einfo (_("%F%P: invalid reloc statement\n"));
6709 dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
6710 break;
6712 case lang_input_section_enum:
6714 asection *in = s->input_section.section;
6716 if ((in->flags & SEC_EXCLUDE) == 0)
6717 dot += TO_ADDR (in->size);
6719 break;
6721 case lang_input_statement_enum:
6722 break;
6724 case lang_fill_statement_enum:
6725 fill = s->fill_statement.fill;
6726 break;
6728 case lang_assignment_statement_enum:
6729 current_assign = &s->assignment_statement;
6730 if (current_assign->exp->type.node_class != etree_assert)
6732 const char *p = current_assign->exp->assign.dst;
6734 if (current_os == abs_output_section && p[0] == '.' && p[1] == 0)
6735 prefer_next_section = true;
6737 while (*p == '_')
6738 ++p;
6739 if (strcmp (p, "end") == 0)
6740 *found_end = true;
6742 exp_fold_tree (s->assignment_statement.exp, os,
6743 (current_os->bfd_section != NULL
6744 ? current_os->bfd_section : bfd_und_section_ptr),
6745 &dot);
6746 break;
6748 case lang_padding_statement_enum:
6749 dot += TO_ADDR (s->padding_statement.size);
6750 break;
6752 case lang_group_statement_enum:
6753 dot = lang_do_assignments_1 (s->group_statement.children.head,
6754 current_os, fill, dot, found_end);
6755 break;
6757 case lang_insert_statement_enum:
6758 break;
6760 case lang_address_statement_enum:
6761 break;
6763 default:
6764 FAIL ();
6765 break;
6768 return dot;
6771 void
6772 lang_do_assignments (lang_phase_type phase)
6774 bool found_end = false;
6776 current_section = NULL;
6777 prefer_next_section = false;
6778 expld.phase = phase;
6779 lang_statement_iteration++;
6780 lang_do_assignments_1 (statement_list.head,
6781 abs_output_section, NULL, 0, &found_end);
6784 /* For an assignment statement outside of an output section statement,
6785 choose the best of neighbouring output sections to use for values
6786 of "dot". */
6788 asection *
6789 section_for_dot (void)
6791 asection *s;
6793 /* Assignments belong to the previous output section, unless there
6794 has been an assignment to "dot", in which case following
6795 assignments belong to the next output section. (The assumption
6796 is that an assignment to "dot" is setting up the address for the
6797 next output section.) Except that past the assignment to "_end"
6798 we always associate with the previous section. This exception is
6799 for targets like SH that define an alloc .stack or other
6800 weirdness after non-alloc sections. */
6801 if (current_section == NULL || prefer_next_section)
6803 lang_statement_union_type *stmt;
6804 lang_output_section_statement_type *os;
6806 for (stmt = (lang_statement_union_type *) current_assign;
6807 stmt != NULL;
6808 stmt = stmt->header.next)
6809 if (stmt->header.type == lang_output_section_statement_enum)
6810 break;
6812 os = stmt ? &stmt->output_section_statement : NULL;
6813 while (os != NULL
6814 && !os->after_end
6815 && (os->bfd_section == NULL
6816 || (os->bfd_section->flags & SEC_EXCLUDE) != 0
6817 || bfd_section_removed_from_list (link_info.output_bfd,
6818 os->bfd_section)))
6819 os = os->next;
6821 if (current_section == NULL || os == NULL || !os->after_end)
6823 if (os != NULL)
6824 s = os->bfd_section;
6825 else
6826 s = link_info.output_bfd->section_last;
6827 while (s != NULL
6828 && ((s->flags & SEC_ALLOC) == 0
6829 || (s->flags & SEC_THREAD_LOCAL) != 0))
6830 s = s->prev;
6831 if (s != NULL)
6832 return s;
6834 return bfd_abs_section_ptr;
6838 s = current_section->bfd_section;
6840 /* The section may have been stripped. */
6841 while (s != NULL
6842 && ((s->flags & SEC_EXCLUDE) != 0
6843 || (s->flags & SEC_ALLOC) == 0
6844 || (s->flags & SEC_THREAD_LOCAL) != 0
6845 || bfd_section_removed_from_list (link_info.output_bfd, s)))
6846 s = s->prev;
6847 if (s == NULL)
6848 s = link_info.output_bfd->sections;
6849 while (s != NULL
6850 && ((s->flags & SEC_ALLOC) == 0
6851 || (s->flags & SEC_THREAD_LOCAL) != 0))
6852 s = s->next;
6853 if (s != NULL)
6854 return s;
6856 return bfd_abs_section_ptr;
6859 /* Array of __start/__stop/.startof./.sizeof/ symbols. */
6861 static struct bfd_link_hash_entry **start_stop_syms;
6862 static size_t start_stop_count = 0;
6863 static size_t start_stop_alloc = 0;
6865 /* Give start/stop SYMBOL for SEC a preliminary definition, and add it
6866 to start_stop_syms. */
6868 static void
6869 lang_define_start_stop (const char *symbol, asection *sec)
6871 struct bfd_link_hash_entry *h;
6873 h = bfd_define_start_stop (link_info.output_bfd, &link_info, symbol, sec);
6874 if (h != NULL)
6876 if (start_stop_count == start_stop_alloc)
6878 start_stop_alloc = 2 * start_stop_alloc + 10;
6879 start_stop_syms
6880 = xrealloc (start_stop_syms,
6881 start_stop_alloc * sizeof (*start_stop_syms));
6883 start_stop_syms[start_stop_count++] = h;
6887 /* Check for input sections whose names match references to
6888 __start_SECNAME or __stop_SECNAME symbols. Give the symbols
6889 preliminary definitions. */
6891 static void
6892 lang_init_start_stop (void)
6894 bfd *abfd;
6895 asection *s;
6896 char leading_char = bfd_get_symbol_leading_char (link_info.output_bfd);
6898 for (abfd = link_info.input_bfds; abfd != NULL; abfd = abfd->link.next)
6899 for (s = abfd->sections; s != NULL; s = s->next)
6901 const char *ps;
6902 const char *secname = s->name;
6904 for (ps = secname; *ps != '\0'; ps++)
6905 if (!ISALNUM ((unsigned char) *ps) && *ps != '_')
6906 break;
6907 if (*ps == '\0')
6909 char *symbol = (char *) xmalloc (10 + strlen (secname));
6911 symbol[0] = leading_char;
6912 sprintf (symbol + (leading_char != 0), "__start_%s", secname);
6913 lang_define_start_stop (symbol, s);
6915 symbol[1] = leading_char;
6916 memcpy (symbol + 1 + (leading_char != 0), "__stop", 6);
6917 lang_define_start_stop (symbol + 1, s);
6919 free (symbol);
6924 /* Iterate over start_stop_syms. */
6926 static void
6927 foreach_start_stop (void (*func) (struct bfd_link_hash_entry *))
6929 size_t i;
6931 for (i = 0; i < start_stop_count; ++i)
6932 func (start_stop_syms[i]);
6935 /* __start and __stop symbols are only supposed to be defined by the
6936 linker for orphan sections, but we now extend that to sections that
6937 map to an output section of the same name. The symbols were
6938 defined early for --gc-sections, before we mapped input to output
6939 sections, so undo those that don't satisfy this rule. */
6941 static void
6942 undef_start_stop (struct bfd_link_hash_entry *h)
6944 if (h->ldscript_def)
6945 return;
6947 if (h->u.def.section->output_section == NULL
6948 || h->u.def.section->output_section->owner != link_info.output_bfd
6949 || strcmp (h->u.def.section->name,
6950 h->u.def.section->output_section->name) != 0)
6952 asection *sec = bfd_get_section_by_name (link_info.output_bfd,
6953 h->u.def.section->name);
6954 if (sec != NULL)
6956 /* When there are more than one input sections with the same
6957 section name, SECNAME, linker picks the first one to define
6958 __start_SECNAME and __stop_SECNAME symbols. When the first
6959 input section is removed by comdat group, we need to check
6960 if there is still an output section with section name
6961 SECNAME. */
6962 asection *i;
6963 for (i = sec->map_head.s; i != NULL; i = i->map_head.s)
6964 if (strcmp (h->u.def.section->name, i->name) == 0)
6966 h->u.def.section = i;
6967 return;
6970 h->type = bfd_link_hash_undefined;
6971 h->u.undef.abfd = NULL;
6972 if (is_elf_hash_table (link_info.hash))
6974 const struct elf_backend_data *bed;
6975 struct elf_link_hash_entry *eh = (struct elf_link_hash_entry *) h;
6976 unsigned int was_forced = eh->forced_local;
6978 bed = get_elf_backend_data (link_info.output_bfd);
6979 (*bed->elf_backend_hide_symbol) (&link_info, eh, true);
6980 if (!eh->ref_regular_nonweak)
6981 h->type = bfd_link_hash_undefweak;
6982 eh->def_regular = 0;
6983 eh->forced_local = was_forced;
6988 static void
6989 lang_undef_start_stop (void)
6991 foreach_start_stop (undef_start_stop);
6994 /* Check for output sections whose names match references to
6995 .startof.SECNAME or .sizeof.SECNAME symbols. Give the symbols
6996 preliminary definitions. */
6998 static void
6999 lang_init_startof_sizeof (void)
7001 asection *s;
7003 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
7005 const char *secname = s->name;
7006 char *symbol = (char *) xmalloc (10 + strlen (secname));
7008 sprintf (symbol, ".startof.%s", secname);
7009 lang_define_start_stop (symbol, s);
7011 memcpy (symbol + 1, ".size", 5);
7012 lang_define_start_stop (symbol + 1, s);
7013 free (symbol);
7017 /* Set .startof., .sizeof., __start and __stop symbols final values. */
7019 static void
7020 set_start_stop (struct bfd_link_hash_entry *h)
7022 if (h->ldscript_def
7023 || h->type != bfd_link_hash_defined)
7024 return;
7026 if (h->root.string[0] == '.')
7028 /* .startof. or .sizeof. symbol.
7029 .startof. already has final value. */
7030 if (h->root.string[2] == 'i')
7032 /* .sizeof. */
7033 h->u.def.value = TO_ADDR (h->u.def.section->size);
7034 h->u.def.section = bfd_abs_section_ptr;
7037 else
7039 /* __start or __stop symbol. */
7040 int has_lead = bfd_get_symbol_leading_char (link_info.output_bfd) != 0;
7042 h->u.def.section = h->u.def.section->output_section;
7043 if (h->root.string[4 + has_lead] == 'o')
7045 /* __stop_ */
7046 h->u.def.value = TO_ADDR (h->u.def.section->size);
7051 static void
7052 lang_finalize_start_stop (void)
7054 foreach_start_stop (set_start_stop);
7057 static void
7058 lang_symbol_tweaks (void)
7060 /* Give initial values for __start and __stop symbols, so that ELF
7061 gc_sections will keep sections referenced by these symbols. Must
7062 be done before lang_do_assignments. */
7063 if (config.build_constructors)
7064 lang_init_start_stop ();
7066 /* Make __ehdr_start hidden, and set def_regular even though it is
7067 likely undefined at this stage. For lang_check_relocs. */
7068 if (is_elf_hash_table (link_info.hash)
7069 && !bfd_link_relocatable (&link_info))
7071 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
7072 bfd_link_hash_lookup (link_info.hash, "__ehdr_start",
7073 false, false, true);
7075 /* Only adjust the export class if the symbol was referenced
7076 and not defined, otherwise leave it alone. */
7077 if (h != NULL
7078 && (h->root.type == bfd_link_hash_new
7079 || h->root.type == bfd_link_hash_undefined
7080 || h->root.type == bfd_link_hash_undefweak
7081 || h->root.type == bfd_link_hash_common))
7083 const struct elf_backend_data *bed;
7084 bed = get_elf_backend_data (link_info.output_bfd);
7085 (*bed->elf_backend_hide_symbol) (&link_info, h, true);
7086 if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
7087 h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
7088 h->def_regular = 1;
7089 h->root.linker_def = 1;
7090 h->root.rel_from_abs = 1;
7095 static void
7096 lang_end (void)
7098 struct bfd_link_hash_entry *h;
7099 bool warn;
7101 if ((bfd_link_relocatable (&link_info) && !link_info.gc_sections)
7102 || bfd_link_dll (&link_info))
7103 warn = entry_from_cmdline;
7104 else
7105 warn = true;
7107 /* Force the user to specify a root when generating a relocatable with
7108 --gc-sections, unless --gc-keep-exported was also given. */
7109 if (bfd_link_relocatable (&link_info)
7110 && link_info.gc_sections
7111 && !link_info.gc_keep_exported)
7113 struct bfd_sym_chain *sym;
7115 for (sym = link_info.gc_sym_list; sym != NULL; sym = sym->next)
7117 h = bfd_link_hash_lookup (link_info.hash, sym->name,
7118 false, false, false);
7119 if (h != NULL
7120 && (h->type == bfd_link_hash_defined
7121 || h->type == bfd_link_hash_defweak)
7122 && !bfd_is_const_section (h->u.def.section))
7123 break;
7125 if (!sym)
7126 einfo (_("%F%P: --gc-sections requires a defined symbol root "
7127 "specified by -e or -u\n"));
7130 if (entry_symbol.name == NULL)
7132 /* No entry has been specified. Look for the default entry, but
7133 don't warn if we don't find it. */
7134 entry_symbol.name = entry_symbol_default;
7135 warn = false;
7138 h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
7139 false, false, true);
7140 if (h != NULL
7141 && (h->type == bfd_link_hash_defined
7142 || h->type == bfd_link_hash_defweak)
7143 && h->u.def.section->output_section != NULL)
7145 bfd_vma val;
7147 val = (h->u.def.value
7148 + bfd_section_vma (h->u.def.section->output_section)
7149 + h->u.def.section->output_offset);
7150 if (!bfd_set_start_address (link_info.output_bfd, val))
7151 einfo (_("%F%P: %s: can't set start address\n"), entry_symbol.name);
7153 else
7155 bfd_vma val;
7156 const char *send;
7158 /* We couldn't find the entry symbol. Try parsing it as a
7159 number. */
7160 val = bfd_scan_vma (entry_symbol.name, &send, 0);
7161 if (*send == '\0')
7163 if (!bfd_set_start_address (link_info.output_bfd, val))
7164 einfo (_("%F%P: can't set start address\n"));
7166 /* BZ 2004952: Only use the start of the entry section for executables. */
7167 else if bfd_link_executable (&link_info)
7169 asection *ts;
7171 /* Can't find the entry symbol, and it's not a number. Use
7172 the first address in the text section. */
7173 ts = bfd_get_section_by_name (link_info.output_bfd, entry_section);
7174 if (ts != NULL)
7176 if (warn)
7177 einfo (_("%P: warning: cannot find entry symbol %s;"
7178 " defaulting to %V\n"),
7179 entry_symbol.name,
7180 bfd_section_vma (ts));
7181 if (!bfd_set_start_address (link_info.output_bfd,
7182 bfd_section_vma (ts)))
7183 einfo (_("%F%P: can't set start address\n"));
7185 else
7187 if (warn)
7188 einfo (_("%P: warning: cannot find entry symbol %s;"
7189 " not setting start address\n"),
7190 entry_symbol.name);
7193 else
7195 if (warn)
7196 einfo (_("%P: warning: cannot find entry symbol %s;"
7197 " not setting start address\n"),
7198 entry_symbol.name);
7203 /* This is a small function used when we want to ignore errors from
7204 BFD. */
7206 static void
7207 ignore_bfd_errors (const char *fmt ATTRIBUTE_UNUSED,
7208 va_list ap ATTRIBUTE_UNUSED)
7210 /* Don't do anything. */
7213 /* Check that the architecture of all the input files is compatible
7214 with the output file. Also call the backend to let it do any
7215 other checking that is needed. */
7217 static void
7218 lang_check (void)
7220 lang_input_statement_type *file;
7221 bfd *input_bfd;
7222 const bfd_arch_info_type *compatible;
7224 for (file = (void *) file_chain.head;
7225 file != NULL;
7226 file = file->next)
7228 #if BFD_SUPPORTS_PLUGINS
7229 /* Don't check format of files claimed by plugin. */
7230 if (file->flags.claimed)
7231 continue;
7232 #endif /* BFD_SUPPORTS_PLUGINS */
7233 input_bfd = file->the_bfd;
7234 compatible
7235 = bfd_arch_get_compatible (input_bfd, link_info.output_bfd,
7236 command_line.accept_unknown_input_arch);
7238 /* In general it is not possible to perform a relocatable
7239 link between differing object formats when the input
7240 file has relocations, because the relocations in the
7241 input format may not have equivalent representations in
7242 the output format (and besides BFD does not translate
7243 relocs for other link purposes than a final link). */
7244 if (!file->flags.just_syms
7245 && (bfd_link_relocatable (&link_info)
7246 || link_info.emitrelocations)
7247 && (compatible == NULL
7248 || (bfd_get_flavour (input_bfd)
7249 != bfd_get_flavour (link_info.output_bfd)))
7250 && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
7252 einfo (_("%F%P: relocatable linking with relocations from"
7253 " format %s (%pB) to format %s (%pB) is not supported\n"),
7254 bfd_get_target (input_bfd), input_bfd,
7255 bfd_get_target (link_info.output_bfd), link_info.output_bfd);
7256 /* einfo with %F exits. */
7259 if (compatible == NULL)
7261 if (command_line.warn_mismatch)
7262 einfo (_("%X%P: %s architecture of input file `%pB'"
7263 " is incompatible with %s output\n"),
7264 bfd_printable_name (input_bfd), input_bfd,
7265 bfd_printable_name (link_info.output_bfd));
7268 /* If the input bfd has no contents, it shouldn't set the
7269 private data of the output bfd. */
7270 else if (!file->flags.just_syms
7271 && ((input_bfd->flags & DYNAMIC) != 0
7272 || bfd_count_sections (input_bfd) != 0))
7274 bfd_error_handler_type pfn = NULL;
7276 /* If we aren't supposed to warn about mismatched input
7277 files, temporarily set the BFD error handler to a
7278 function which will do nothing. We still want to call
7279 bfd_merge_private_bfd_data, since it may set up
7280 information which is needed in the output file. */
7281 if (!command_line.warn_mismatch)
7282 pfn = bfd_set_error_handler (ignore_bfd_errors);
7283 if (!bfd_merge_private_bfd_data (input_bfd, &link_info))
7285 if (command_line.warn_mismatch)
7286 einfo (_("%X%P: failed to merge target specific data"
7287 " of file %pB\n"), input_bfd);
7289 if (!command_line.warn_mismatch)
7290 bfd_set_error_handler (pfn);
7295 /* Look through all the global common symbols and attach them to the
7296 correct section. The -sort-common command line switch may be used
7297 to roughly sort the entries by alignment. */
7299 static void
7300 lang_common (void)
7302 if (link_info.inhibit_common_definition)
7303 return;
7304 if (bfd_link_relocatable (&link_info)
7305 && !command_line.force_common_definition)
7306 return;
7308 if (!config.sort_common)
7309 bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
7310 else
7312 unsigned int power;
7314 if (config.sort_common == sort_descending)
7316 for (power = 4; power > 0; power--)
7317 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7319 power = 0;
7320 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7322 else
7324 for (power = 0; power <= 4; power++)
7325 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7327 power = (unsigned int) -1;
7328 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7333 /* Place one common symbol in the correct section. */
7335 static bool
7336 lang_one_common (struct bfd_link_hash_entry *h, void *info)
7338 unsigned int power_of_two;
7339 bfd_vma size;
7340 asection *section;
7342 if (h->type != bfd_link_hash_common)
7343 return true;
7345 size = h->u.c.size;
7346 power_of_two = h->u.c.p->alignment_power;
7348 if (config.sort_common == sort_descending
7349 && power_of_two < *(unsigned int *) info)
7350 return true;
7351 else if (config.sort_common == sort_ascending
7352 && power_of_two > *(unsigned int *) info)
7353 return true;
7355 section = h->u.c.p->section;
7356 if (!bfd_define_common_symbol (link_info.output_bfd, &link_info, h))
7357 einfo (_("%F%P: could not define common symbol `%pT': %E\n"),
7358 h->root.string);
7360 if (config.map_file != NULL)
7362 static bool header_printed;
7363 int len;
7364 char *name;
7365 char buf[32];
7367 if (!header_printed)
7369 minfo (_("\nAllocating common symbols\n"));
7370 minfo (_("Common symbol size file\n\n"));
7371 header_printed = true;
7374 name = bfd_demangle (link_info.output_bfd, h->root.string,
7375 DMGL_ANSI | DMGL_PARAMS);
7376 if (name == NULL)
7378 minfo ("%s", h->root.string);
7379 len = strlen (h->root.string);
7381 else
7383 minfo ("%s", name);
7384 len = strlen (name);
7385 free (name);
7388 if (len >= 19)
7390 print_nl ();
7391 len = 0;
7394 sprintf (buf, "%" PRIx64, (uint64_t) size);
7395 fprintf (config.map_file, "%*s0x%-16s", 20 - len, "", buf);
7397 minfo ("%pB\n", section->owner);
7400 return true;
7403 /* Handle a single orphan section S, placing the orphan into an appropriate
7404 output section. The effects of the --orphan-handling command line
7405 option are handled here. */
7407 static void
7408 ldlang_place_orphan (asection *s)
7410 if (config.orphan_handling == orphan_handling_discard)
7412 lang_output_section_statement_type *os;
7413 os = lang_output_section_statement_lookup (DISCARD_SECTION_NAME, 0, 1);
7414 if (os->addr_tree == NULL
7415 && (bfd_link_relocatable (&link_info)
7416 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7417 os->addr_tree = exp_intop (0);
7418 lang_add_section (&os->children, s, NULL, NULL, os);
7420 else
7422 lang_output_section_statement_type *os;
7423 const char *name = s->name;
7424 int constraint = 0;
7426 if (config.orphan_handling == orphan_handling_error)
7427 einfo (_("%X%P: error: unplaced orphan section `%pA' from `%pB'\n"),
7428 s, s->owner);
7430 if (config.unique_orphan_sections || unique_section_p (s, NULL))
7431 constraint = SPECIAL;
7433 os = ldemul_place_orphan (s, name, constraint);
7434 if (os == NULL)
7436 os = lang_output_section_statement_lookup (name, constraint, 1);
7437 if (os->addr_tree == NULL
7438 && (bfd_link_relocatable (&link_info)
7439 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7440 os->addr_tree = exp_intop (0);
7441 lang_add_section (&os->children, s, NULL, NULL, os);
7444 if (config.orphan_handling == orphan_handling_warn)
7445 einfo (_("%P: warning: orphan section `%pA' from `%pB' being "
7446 "placed in section `%s'\n"),
7447 s, s->owner, os->name);
7451 /* Run through the input files and ensure that every input section has
7452 somewhere to go. If one is found without a destination then create
7453 an input request and place it into the statement tree. */
7455 static void
7456 lang_place_orphans (void)
7458 LANG_FOR_EACH_INPUT_STATEMENT (file)
7460 asection *s;
7462 for (s = file->the_bfd->sections; s != NULL; s = s->next)
7464 if (s->output_section == NULL)
7466 /* This section of the file is not attached, root
7467 around for a sensible place for it to go. */
7469 if (file->flags.just_syms)
7470 bfd_link_just_syms (file->the_bfd, s, &link_info);
7471 else if (lang_discard_section_p (s))
7472 s->output_section = bfd_abs_section_ptr;
7473 else if (strcmp (s->name, "COMMON") == 0)
7475 /* This is a lonely common section which must have
7476 come from an archive. We attach to the section
7477 with the wildcard. */
7478 if (!bfd_link_relocatable (&link_info)
7479 || command_line.force_common_definition)
7481 if (default_common_section == NULL)
7482 default_common_section
7483 = lang_output_section_statement_lookup (".bss", 0, 1);
7484 lang_add_section (&default_common_section->children, s,
7485 NULL, NULL, default_common_section);
7488 else
7489 ldlang_place_orphan (s);
7495 void
7496 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
7498 flagword *ptr_flags;
7500 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7502 while (*flags)
7504 switch (*flags)
7506 /* PR 17900: An exclamation mark in the attributes reverses
7507 the sense of any of the attributes that follow. */
7508 case '!':
7509 invert = !invert;
7510 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7511 break;
7513 case 'A': case 'a':
7514 *ptr_flags |= SEC_ALLOC;
7515 break;
7517 case 'R': case 'r':
7518 *ptr_flags |= SEC_READONLY;
7519 break;
7521 case 'W': case 'w':
7522 *ptr_flags |= SEC_DATA;
7523 break;
7525 case 'X': case 'x':
7526 *ptr_flags |= SEC_CODE;
7527 break;
7529 case 'L': case 'l':
7530 case 'I': case 'i':
7531 *ptr_flags |= SEC_LOAD;
7532 break;
7534 default:
7535 einfo (_("%F%P: invalid character %c (%d) in flags\n"),
7536 *flags, *flags);
7537 break;
7539 flags++;
7543 /* Call a function on each real input file. This function will be
7544 called on an archive, but not on the elements. */
7546 void
7547 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
7549 lang_input_statement_type *f;
7551 for (f = (void *) input_file_chain.head;
7552 f != NULL;
7553 f = f->next_real_file)
7554 if (f->flags.real)
7555 func (f);
7558 /* Call a function on each real file. The function will be called on
7559 all the elements of an archive which are included in the link, but
7560 will not be called on the archive file itself. */
7562 void
7563 lang_for_each_file (void (*func) (lang_input_statement_type *))
7565 LANG_FOR_EACH_INPUT_STATEMENT (f)
7567 if (f->flags.real)
7568 func (f);
7572 void
7573 ldlang_add_file (lang_input_statement_type *entry)
7575 lang_statement_append (&file_chain, entry, &entry->next);
7577 /* The BFD linker needs to have a list of all input BFDs involved in
7578 a link. */
7579 ASSERT (link_info.input_bfds_tail != &entry->the_bfd->link.next
7580 && entry->the_bfd->link.next == NULL);
7581 ASSERT (entry->the_bfd != link_info.output_bfd);
7583 *link_info.input_bfds_tail = entry->the_bfd;
7584 link_info.input_bfds_tail = &entry->the_bfd->link.next;
7585 bfd_set_usrdata (entry->the_bfd, entry);
7586 bfd_set_gp_size (entry->the_bfd, g_switch_value);
7588 /* Look through the sections and check for any which should not be
7589 included in the link. We need to do this now, so that we can
7590 notice when the backend linker tries to report multiple
7591 definition errors for symbols which are in sections we aren't
7592 going to link. FIXME: It might be better to entirely ignore
7593 symbols which are defined in sections which are going to be
7594 discarded. This would require modifying the backend linker for
7595 each backend which might set the SEC_LINK_ONCE flag. If we do
7596 this, we should probably handle SEC_EXCLUDE in the same way. */
7598 bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
7601 void
7602 lang_add_output (const char *name, int from_script)
7604 /* Make -o on command line override OUTPUT in script. */
7605 if (!had_output_filename || !from_script)
7607 output_filename = name;
7608 had_output_filename = true;
7612 lang_output_section_statement_type *
7613 lang_enter_output_section_statement (const char *output_section_statement_name,
7614 etree_type *address_exp,
7615 enum section_type sectype,
7616 etree_type *sectype_value,
7617 etree_type *align,
7618 etree_type *subalign,
7619 etree_type *ebase,
7620 int constraint,
7621 int align_with_input)
7623 lang_output_section_statement_type *os;
7625 os = lang_output_section_statement_lookup (output_section_statement_name,
7626 constraint,
7627 in_section_ordering ? 0 : 2);
7628 if (os == NULL) /* && in_section_ordering */
7629 einfo (_("%F%P:%pS: error: output section '%s' must already exist\n"),
7630 NULL, output_section_statement_name);
7631 current_section = os;
7633 /* Make next things chain into subchain of this. */
7634 push_stat_ptr (in_section_ordering ? &os->sort_children : &os->children);
7636 if (in_section_ordering)
7637 return os;
7639 if (os->addr_tree == NULL)
7640 os->addr_tree = address_exp;
7642 os->sectype = sectype;
7643 if (sectype == type_section || sectype == typed_readonly_section)
7644 os->sectype_value = sectype_value;
7645 else if (sectype == noload_section)
7646 os->flags = SEC_NEVER_LOAD;
7647 else
7648 os->flags = SEC_NO_FLAGS;
7649 os->block_value = 1;
7651 os->align_lma_with_input = align_with_input == ALIGN_WITH_INPUT;
7652 if (os->align_lma_with_input && align != NULL)
7653 einfo (_("%F%P:%pS: error: align with input and explicit align specified\n"),
7654 NULL);
7656 os->subsection_alignment = subalign;
7657 os->section_alignment = align;
7659 os->load_base = ebase;
7660 return os;
7663 void
7664 lang_final (void)
7666 lang_output_statement_type *new_stmt;
7668 new_stmt = new_stat (lang_output_statement, stat_ptr);
7669 new_stmt->name = output_filename;
7672 /* Reset the current counters in the regions. */
7674 void
7675 lang_reset_memory_regions (void)
7677 lang_memory_region_type *p = lang_memory_region_list;
7678 asection *o;
7679 lang_output_section_statement_type *os;
7681 for (p = lang_memory_region_list; p != NULL; p = p->next)
7683 p->current = p->origin;
7684 p->last_os = NULL;
7687 for (os = (void *) lang_os_list.head;
7688 os != NULL;
7689 os = os->next)
7691 os->processed_vma = false;
7692 os->processed_lma = false;
7695 for (o = link_info.output_bfd->sections; o != NULL; o = o->next)
7697 /* Save the last size for possible use by bfd_relax_section. */
7698 o->rawsize = o->size;
7699 if (!(o->flags & SEC_FIXED_SIZE))
7700 o->size = 0;
7704 /* Worker for lang_gc_sections_1. */
7706 static void
7707 gc_section_callback (lang_wild_statement_type *ptr,
7708 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7709 asection *section,
7710 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7711 void *data ATTRIBUTE_UNUSED)
7713 /* If the wild pattern was marked KEEP, the member sections
7714 should be as well. */
7715 if (ptr->keep_sections)
7716 section->flags |= SEC_KEEP;
7719 /* Iterate over sections marking them against GC. */
7721 static void
7722 lang_gc_sections_1 (lang_statement_union_type *s)
7724 for (; s != NULL; s = s->header.next)
7726 switch (s->header.type)
7728 case lang_wild_statement_enum:
7729 walk_wild (&s->wild_statement, gc_section_callback, NULL);
7730 break;
7731 case lang_constructors_statement_enum:
7732 lang_gc_sections_1 (constructor_list.head);
7733 break;
7734 case lang_output_section_statement_enum:
7735 lang_gc_sections_1 (s->output_section_statement.children.head);
7736 break;
7737 case lang_group_statement_enum:
7738 lang_gc_sections_1 (s->group_statement.children.head);
7739 break;
7740 default:
7741 break;
7746 static void
7747 lang_gc_sections (void)
7749 /* Keep all sections so marked in the link script. */
7750 lang_gc_sections_1 (statement_list.head);
7752 /* SEC_EXCLUDE is ignored when doing a relocatable link, except in
7753 the special case of .stabstr debug info. (See bfd/stabs.c)
7754 Twiddle the flag here, to simplify later linker code. */
7755 if (bfd_link_relocatable (&link_info))
7757 LANG_FOR_EACH_INPUT_STATEMENT (f)
7759 asection *sec;
7760 #if BFD_SUPPORTS_PLUGINS
7761 if (f->flags.claimed)
7762 continue;
7763 #endif
7764 for (sec = f->the_bfd->sections; sec != NULL; sec = sec->next)
7765 if ((sec->flags & SEC_DEBUGGING) == 0
7766 || strcmp (sec->name, ".stabstr") != 0)
7767 sec->flags &= ~SEC_EXCLUDE;
7771 if (link_info.gc_sections)
7772 bfd_gc_sections (link_info.output_bfd, &link_info);
7775 /* Worker for lang_find_relro_sections_1. */
7777 static void
7778 find_relro_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
7779 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7780 asection *section,
7781 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7782 void *data)
7784 /* Discarded, excluded and ignored sections effectively have zero
7785 size. */
7786 if (section->output_section != NULL
7787 && section->output_section->owner == link_info.output_bfd
7788 && (section->output_section->flags & SEC_EXCLUDE) == 0
7789 && !IGNORE_SECTION (section)
7790 && section->size != 0)
7792 bool *has_relro_section = (bool *) data;
7793 *has_relro_section = true;
7797 /* Iterate over sections for relro sections. */
7799 static void
7800 lang_find_relro_sections_1 (lang_statement_union_type *s,
7801 bool *has_relro_section)
7803 if (*has_relro_section)
7804 return;
7806 for (; s != NULL; s = s->header.next)
7808 if (s == expld.dataseg.relro_end_stat)
7809 break;
7811 switch (s->header.type)
7813 case lang_wild_statement_enum:
7814 walk_wild (&s->wild_statement,
7815 find_relro_section_callback,
7816 has_relro_section);
7817 break;
7818 case lang_constructors_statement_enum:
7819 lang_find_relro_sections_1 (constructor_list.head,
7820 has_relro_section);
7821 break;
7822 case lang_output_section_statement_enum:
7823 lang_find_relro_sections_1 (s->output_section_statement.children.head,
7824 has_relro_section);
7825 break;
7826 case lang_group_statement_enum:
7827 lang_find_relro_sections_1 (s->group_statement.children.head,
7828 has_relro_section);
7829 break;
7830 default:
7831 break;
7836 static void
7837 lang_find_relro_sections (void)
7839 bool has_relro_section = false;
7841 /* Check all sections in the link script. */
7843 lang_find_relro_sections_1 (expld.dataseg.relro_start_stat,
7844 &has_relro_section);
7846 if (!has_relro_section)
7847 link_info.relro = false;
7850 /* Relax all sections until bfd_relax_section gives up. */
7852 void
7853 lang_relax_sections (bool need_layout)
7855 /* NB: Also enable relaxation to layout sections for DT_RELR. */
7856 if (RELAXATION_ENABLED || link_info.enable_dt_relr)
7858 /* We may need more than one relaxation pass. */
7859 int i = link_info.relax_pass;
7861 /* The backend can use it to determine the current pass. */
7862 link_info.relax_pass = 0;
7864 while (i--)
7866 /* Keep relaxing until bfd_relax_section gives up. */
7867 bool relax_again;
7869 link_info.relax_trip = -1;
7872 link_info.relax_trip++;
7874 /* Note: pe-dll.c does something like this also. If you find
7875 you need to change this code, you probably need to change
7876 pe-dll.c also. DJ */
7878 /* Do all the assignments with our current guesses as to
7879 section sizes. */
7880 lang_do_assignments (lang_assigning_phase_enum);
7882 /* We must do this after lang_do_assignments, because it uses
7883 size. */
7884 lang_reset_memory_regions ();
7886 /* Perform another relax pass - this time we know where the
7887 globals are, so can make a better guess. */
7888 relax_again = false;
7889 lang_size_sections (&relax_again, false);
7891 while (relax_again);
7893 link_info.relax_pass++;
7895 need_layout = true;
7898 if (need_layout)
7900 /* Final extra sizing to report errors. */
7901 lang_do_assignments (lang_assigning_phase_enum);
7902 lang_reset_memory_regions ();
7903 lang_size_sections (NULL, true);
7907 #if BFD_SUPPORTS_PLUGINS
7908 /* Find the insert point for the plugin's replacement files. We
7909 place them after the first claimed real object file, or if the
7910 first claimed object is an archive member, after the last real
7911 object file immediately preceding the archive. In the event
7912 no objects have been claimed at all, we return the first dummy
7913 object file on the list as the insert point; that works, but
7914 the callee must be careful when relinking the file_chain as it
7915 is not actually on that chain, only the statement_list and the
7916 input_file list; in that case, the replacement files must be
7917 inserted at the head of the file_chain. */
7919 static lang_input_statement_type *
7920 find_replacements_insert_point (bool *before)
7922 lang_input_statement_type *claim1, *lastobject;
7923 lastobject = (void *) input_file_chain.head;
7924 for (claim1 = (void *) file_chain.head;
7925 claim1 != NULL;
7926 claim1 = claim1->next)
7928 if (claim1->flags.claimed)
7930 *before = claim1->flags.claim_archive;
7931 return claim1->flags.claim_archive ? lastobject : claim1;
7933 /* Update lastobject if this is a real object file. */
7934 if (claim1->the_bfd != NULL && claim1->the_bfd->my_archive == NULL)
7935 lastobject = claim1;
7937 /* No files were claimed by the plugin. Choose the last object
7938 file found on the list (maybe the first, dummy entry) as the
7939 insert point. */
7940 *before = false;
7941 return lastobject;
7944 /* Find where to insert ADD, an archive element or shared library
7945 added during a rescan. */
7947 static lang_input_statement_type **
7948 find_rescan_insertion (lang_input_statement_type *add)
7950 bfd *add_bfd = add->the_bfd;
7951 lang_input_statement_type *f;
7952 lang_input_statement_type *last_loaded = NULL;
7953 lang_input_statement_type *before = NULL;
7954 lang_input_statement_type **iter = NULL;
7956 if (add_bfd->my_archive != NULL)
7957 add_bfd = add_bfd->my_archive;
7959 /* First look through the input file chain, to find an object file
7960 before the one we've rescanned. Normal object files always
7961 appear on both the input file chain and the file chain, so this
7962 lets us get quickly to somewhere near the correct place on the
7963 file chain if it is full of archive elements. Archives don't
7964 appear on the file chain, but if an element has been extracted
7965 then their input_statement->next points at it. */
7966 for (f = (void *) input_file_chain.head;
7967 f != NULL;
7968 f = f->next_real_file)
7970 if (f->the_bfd == add_bfd)
7972 before = last_loaded;
7973 if (f->next != NULL)
7974 return &f->next->next;
7976 if (f->the_bfd != NULL && f->next != NULL)
7977 last_loaded = f;
7980 for (iter = before ? &before->next : &file_chain.head->input_statement.next;
7981 *iter != NULL;
7982 iter = &(*iter)->next)
7983 if (!(*iter)->flags.claim_archive
7984 && (*iter)->the_bfd->my_archive == NULL)
7985 break;
7987 return iter;
7990 /* Detach new nodes added to DESTLIST since the time ORIGLIST
7991 was taken as a copy of it and leave them in ORIGLIST. */
7993 static void
7994 lang_list_remove_tail (lang_statement_list_type *destlist,
7995 lang_statement_list_type *origlist)
7997 union lang_statement_union **savetail;
7998 /* Check that ORIGLIST really is an earlier state of DESTLIST. */
7999 ASSERT (origlist->head == destlist->head);
8000 savetail = origlist->tail;
8001 origlist->head = *(savetail);
8002 origlist->tail = destlist->tail;
8003 destlist->tail = savetail;
8004 *savetail = NULL;
8007 static lang_statement_union_type **
8008 find_next_input_statement (lang_statement_union_type **s)
8010 for ( ; *s; s = &(*s)->header.next)
8012 lang_statement_union_type **t;
8013 switch ((*s)->header.type)
8015 case lang_input_statement_enum:
8016 return s;
8017 case lang_wild_statement_enum:
8018 t = &(*s)->wild_statement.children.head;
8019 break;
8020 case lang_group_statement_enum:
8021 t = &(*s)->group_statement.children.head;
8022 break;
8023 case lang_output_section_statement_enum:
8024 t = &(*s)->output_section_statement.children.head;
8025 break;
8026 default:
8027 continue;
8029 t = find_next_input_statement (t);
8030 if (*t)
8031 return t;
8033 return s;
8035 #endif /* BFD_SUPPORTS_PLUGINS */
8037 /* Insert SRCLIST into DESTLIST after given element by chaining
8038 on FIELD as the next-pointer. (Counterintuitively does not need
8039 a pointer to the actual after-node itself, just its chain field.) */
8041 static void
8042 lang_list_insert_after (lang_statement_list_type *destlist,
8043 lang_statement_list_type *srclist,
8044 lang_statement_union_type **field)
8046 *(srclist->tail) = *field;
8047 *field = srclist->head;
8048 if (destlist->tail == field)
8049 destlist->tail = srclist->tail;
8052 /* Add NAME to the list of garbage collection entry points. */
8054 void
8055 lang_add_gc_name (const char *name)
8057 struct bfd_sym_chain *sym;
8059 if (name == NULL)
8060 return;
8062 sym = stat_alloc (sizeof (*sym));
8064 sym->next = link_info.gc_sym_list;
8065 sym->name = name;
8066 link_info.gc_sym_list = sym;
8069 /* Check relocations. */
8071 static void
8072 lang_check_relocs (void)
8074 if (link_info.check_relocs_after_open_input)
8076 bfd *abfd;
8078 for (abfd = link_info.input_bfds;
8079 abfd != (bfd *) NULL; abfd = abfd->link.next)
8080 if (!bfd_link_check_relocs (abfd, &link_info))
8082 /* No object output, fail return. */
8083 config.make_executable = false;
8084 /* Note: we do not abort the loop, but rather
8085 continue the scan in case there are other
8086 bad relocations to report. */
8091 /* Look through all output sections looking for places where we can
8092 propagate forward the lma region. */
8094 static void
8095 lang_propagate_lma_regions (void)
8097 lang_output_section_statement_type *os;
8099 for (os = (void *) lang_os_list.head;
8100 os != NULL;
8101 os = os->next)
8103 if (os->prev != NULL
8104 && os->lma_region == NULL
8105 && os->load_base == NULL
8106 && os->addr_tree == NULL
8107 && os->region == os->prev->region)
8108 os->lma_region = os->prev->lma_region;
8112 static void
8113 warn_non_contiguous_discards (void)
8115 LANG_FOR_EACH_INPUT_STATEMENT (file)
8117 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
8118 || file->flags.just_syms)
8119 continue;
8121 for (asection *s = file->the_bfd->sections; s != NULL; s = s->next)
8122 if (s->output_section == NULL
8123 && (s->flags & SEC_LINKER_CREATED) == 0)
8124 einfo (_("%P: warning: --enable-non-contiguous-regions "
8125 "discards section `%pA' from `%pB'\n"),
8126 s, file->the_bfd);
8130 static void
8131 reset_one_wild (lang_statement_union_type *statement)
8133 if (statement->header.type == lang_wild_statement_enum)
8135 lang_wild_statement_type *stmt = &statement->wild_statement;
8136 lang_list_init (&stmt->matching_sections);
8140 static void
8141 reset_resolved_wilds (void)
8143 lang_for_each_statement (reset_one_wild);
8146 /* For each output section statement, splice any entries on the
8147 sort_children list before the first wild statement on the children
8148 list. */
8150 static void
8151 lang_os_merge_sort_children (void)
8153 lang_output_section_statement_type *os;
8154 for (os = (void *) lang_os_list.head; os != NULL; os = os->next)
8156 if (os->sort_children.head != NULL)
8158 lang_statement_union_type **where;
8159 for (where = &os->children.head;
8160 *where != NULL;
8161 where = &(*where)->header.next)
8162 if ((*where)->header.type == lang_wild_statement_enum)
8163 break;
8164 lang_list_insert_after (&os->children, &os->sort_children, where);
8169 void
8170 lang_process (void)
8172 lang_os_merge_sort_children ();
8174 /* Finalize dynamic list. */
8175 if (link_info.dynamic_list)
8176 lang_finalize_version_expr_head (&link_info.dynamic_list->head);
8178 current_target = default_target;
8180 /* Open the output file. */
8181 lang_for_each_statement (ldlang_open_output);
8182 init_opb (NULL);
8184 ldemul_create_output_section_statements ();
8186 /* Add to the hash table all undefineds on the command line. */
8187 lang_place_undefineds ();
8189 if (!bfd_section_already_linked_table_init ())
8190 einfo (_("%F%P: can not create hash table: %E\n"));
8192 /* A first pass through the memory regions ensures that if any region
8193 references a symbol for its origin or length then this symbol will be
8194 added to the symbol table. Having these symbols in the symbol table
8195 means that when we call open_input_bfds PROVIDE statements will
8196 trigger to provide any needed symbols. The regions origins and
8197 lengths are not assigned as a result of this call. */
8198 lang_do_memory_regions (false);
8200 /* Create a bfd for each input file. */
8201 current_target = default_target;
8202 lang_statement_iteration++;
8203 open_input_bfds (statement_list.head, NULL, OPEN_BFD_NORMAL);
8205 /* Now that open_input_bfds has processed assignments and provide
8206 statements we can give values to symbolic origin/length now. */
8207 lang_do_memory_regions (true);
8209 ldemul_before_plugin_all_symbols_read ();
8211 #if BFD_SUPPORTS_PLUGINS
8212 if (link_info.lto_plugin_active)
8214 lang_statement_list_type added;
8215 lang_statement_list_type files, inputfiles;
8217 /* Now all files are read, let the plugin(s) decide if there
8218 are any more to be added to the link before we call the
8219 emulation's after_open hook. We create a private list of
8220 input statements for this purpose, which we will eventually
8221 insert into the global statement list after the first claimed
8222 file. */
8223 added = *stat_ptr;
8224 /* We need to manipulate all three chains in synchrony. */
8225 files = file_chain;
8226 inputfiles = input_file_chain;
8227 if (plugin_call_all_symbols_read ())
8228 einfo (_("%F%P: %s: plugin reported error after all symbols read\n"),
8229 plugin_error_plugin ());
8230 link_info.lto_all_symbols_read = true;
8231 /* Open any newly added files, updating the file chains. */
8232 plugin_undefs = link_info.hash->undefs_tail;
8233 lang_output_section_statement_type *last_os = NULL;
8234 if (lang_os_list.head != NULL)
8235 last_os = ((lang_output_section_statement_type *)
8236 ((char *) lang_os_list.tail
8237 - offsetof (lang_output_section_statement_type, next)));
8238 open_input_bfds (*added.tail, last_os, OPEN_BFD_NORMAL);
8239 if (plugin_undefs == link_info.hash->undefs_tail)
8240 plugin_undefs = NULL;
8241 /* Restore the global list pointer now they have all been added. */
8242 lang_list_remove_tail (stat_ptr, &added);
8243 /* And detach the fresh ends of the file lists. */
8244 lang_list_remove_tail (&file_chain, &files);
8245 lang_list_remove_tail (&input_file_chain, &inputfiles);
8246 /* Were any new files added? */
8247 if (added.head != NULL)
8249 /* If so, we will insert them into the statement list immediately
8250 after the first input file that was claimed by the plugin,
8251 unless that file was an archive in which case it is inserted
8252 immediately before. */
8253 bool before;
8254 lang_statement_union_type **prev;
8255 plugin_insert = find_replacements_insert_point (&before);
8256 /* If a plugin adds input files without having claimed any, we
8257 don't really have a good idea where to place them. Just putting
8258 them at the start or end of the list is liable to leave them
8259 outside the crtbegin...crtend range. */
8260 ASSERT (plugin_insert != NULL);
8261 /* Splice the new statement list into the old one. */
8262 prev = &plugin_insert->header.next;
8263 if (before)
8265 prev = find_next_input_statement (prev);
8266 if (*prev != (void *) plugin_insert->next_real_file)
8268 /* We didn't find the expected input statement.
8269 Fall back to adding after plugin_insert. */
8270 prev = &plugin_insert->header.next;
8273 lang_list_insert_after (stat_ptr, &added, prev);
8274 /* Likewise for the file chains. */
8275 lang_list_insert_after (&input_file_chain, &inputfiles,
8276 (void *) &plugin_insert->next_real_file);
8277 /* We must be careful when relinking file_chain; we may need to
8278 insert the new files at the head of the list if the insert
8279 point chosen is the dummy first input file. */
8280 if (plugin_insert->filename)
8281 lang_list_insert_after (&file_chain, &files,
8282 (void *) &plugin_insert->next);
8283 else
8284 lang_list_insert_after (&file_chain, &files, &file_chain.head);
8286 /* Rescan archives in case new undefined symbols have appeared. */
8287 files = file_chain;
8288 lang_statement_iteration++;
8289 open_input_bfds (statement_list.head, NULL, OPEN_BFD_RESCAN);
8290 lang_list_remove_tail (&file_chain, &files);
8291 while (files.head != NULL)
8293 lang_input_statement_type **insert;
8294 lang_input_statement_type **iter, *temp;
8295 bfd *my_arch;
8297 insert = find_rescan_insertion (&files.head->input_statement);
8298 /* All elements from an archive can be added at once. */
8299 iter = &files.head->input_statement.next;
8300 my_arch = files.head->input_statement.the_bfd->my_archive;
8301 if (my_arch != NULL)
8302 for (; *iter != NULL; iter = &(*iter)->next)
8303 if ((*iter)->the_bfd->my_archive != my_arch)
8304 break;
8305 temp = *insert;
8306 *insert = &files.head->input_statement;
8307 files.head = (lang_statement_union_type *) *iter;
8308 *iter = temp;
8309 if (file_chain.tail == (lang_statement_union_type **) insert)
8310 file_chain.tail = (lang_statement_union_type **) iter;
8311 if (my_arch != NULL)
8313 lang_input_statement_type *parent = bfd_usrdata (my_arch);
8314 if (parent != NULL)
8315 parent->next = (lang_input_statement_type *)
8316 ((char *) iter
8317 - offsetof (lang_input_statement_type, next));
8322 #endif /* BFD_SUPPORTS_PLUGINS */
8324 struct bfd_sym_chain **sym = &link_info.gc_sym_list;
8325 while (*sym)
8326 sym = &(*sym)->next;
8328 *sym = &entry_symbol;
8330 if (entry_symbol.name == NULL)
8332 *sym = ldlang_undef_chain_list_head;
8334 /* entry_symbol is normally initialised by an ENTRY definition in the
8335 linker script or the -e command line option. But if neither of
8336 these have been used, the target specific backend may still have
8337 provided an entry symbol via a call to lang_default_entry().
8338 Unfortunately this value will not be processed until lang_end()
8339 is called, long after this function has finished. So detect this
8340 case here and add the target's entry symbol to the list of starting
8341 points for garbage collection resolution. */
8342 lang_add_gc_name (entry_symbol_default);
8345 lang_add_gc_name (link_info.init_function);
8346 lang_add_gc_name (link_info.fini_function);
8348 ldemul_after_open ();
8349 if (config.map_file != NULL)
8350 lang_print_asneeded ();
8352 ldlang_open_ctf ();
8354 bfd_section_already_linked_table_free ();
8356 /* Make sure that we're not mixing architectures. We call this
8357 after all the input files have been opened, but before we do any
8358 other processing, so that any operations merge_private_bfd_data
8359 does on the output file will be known during the rest of the
8360 link. */
8361 lang_check ();
8363 /* Handle .exports instead of a version script if we're told to do so. */
8364 if (command_line.version_exports_section)
8365 lang_do_version_exports_section ();
8367 /* Build all sets based on the information gathered from the input
8368 files. */
8369 ldctor_build_sets ();
8371 lang_symbol_tweaks ();
8373 /* PR 13683: We must rerun the assignments prior to running garbage
8374 collection in order to make sure that all symbol aliases are resolved. */
8375 lang_do_assignments (lang_mark_phase_enum);
8376 expld.phase = lang_first_phase_enum;
8378 /* Size up the common data. */
8379 lang_common ();
8381 if (0)
8382 debug_prefix_tree ();
8384 resolve_wilds ();
8386 /* Remove unreferenced sections if asked to. */
8387 lang_gc_sections ();
8389 lang_mark_undefineds ();
8391 /* Check relocations. */
8392 lang_check_relocs ();
8394 ldemul_after_check_relocs ();
8396 /* There might have been new sections created (e.g. as result of
8397 checking relocs to need a .got, or suchlike), so to properly order
8398 them into our lists of matching sections reset them here. */
8399 reset_resolved_wilds ();
8400 resolve_wilds ();
8402 /* Update wild statements in case the user gave --sort-section.
8403 Note how the option might have come after the linker script and
8404 so couldn't have been set when the wild statements were created. */
8405 update_wild_statements (statement_list.head);
8407 /* Run through the contours of the script and attach input sections
8408 to the correct output sections. */
8409 lang_statement_iteration++;
8410 map_input_to_output_sections (statement_list.head, NULL, NULL);
8412 /* Start at the statement immediately after the special abs_section
8413 output statement, so that it isn't reordered. */
8414 process_insert_statements (&lang_os_list.head->header.next);
8416 ldemul_before_place_orphans ();
8418 /* Find any sections not attached explicitly and handle them. */
8419 lang_place_orphans ();
8421 if (!bfd_link_relocatable (&link_info))
8423 asection *found;
8425 /* Merge SEC_MERGE sections. This has to be done after GC of
8426 sections, so that GCed sections are not merged, but before
8427 assigning dynamic symbols, since removing whole input sections
8428 is hard then. */
8429 if (!bfd_merge_sections (link_info.output_bfd, &link_info))
8430 einfo (_("%F%P: bfd_merge_sections failed: %E\n"));
8432 /* Look for a text section and set the readonly attribute in it. */
8433 found = bfd_get_section_by_name (link_info.output_bfd, ".text");
8435 if (found != NULL)
8437 if (config.text_read_only)
8438 found->flags |= SEC_READONLY;
8439 else
8440 found->flags &= ~SEC_READONLY;
8444 /* Merge together CTF sections. After this, only the symtab-dependent
8445 function and data object sections need adjustment. */
8446 lang_merge_ctf ();
8448 /* Emit the CTF, iff the emulation doesn't need to do late emission after
8449 examining things laid out late, like the strtab. */
8450 lang_write_ctf (0);
8452 /* Copy forward lma regions for output sections in same lma region. */
8453 lang_propagate_lma_regions ();
8455 /* Defining __start/__stop symbols early for --gc-sections to work
8456 around a glibc build problem can result in these symbols being
8457 defined when they should not be. Fix them now. */
8458 if (config.build_constructors)
8459 lang_undef_start_stop ();
8461 /* Define .startof./.sizeof. symbols with preliminary values before
8462 dynamic symbols are created. */
8463 if (!bfd_link_relocatable (&link_info))
8464 lang_init_startof_sizeof ();
8466 /* Do anything special before sizing sections. This is where ELF
8467 and other back-ends size dynamic sections. */
8468 ldemul_before_allocation ();
8470 /* We must record the program headers before we try to fix the
8471 section positions, since they will affect SIZEOF_HEADERS. */
8472 lang_record_phdrs ();
8474 /* Check relro sections. */
8475 if (link_info.relro && !bfd_link_relocatable (&link_info))
8476 lang_find_relro_sections ();
8478 /* Size up the sections. */
8479 lang_size_sections (NULL, !RELAXATION_ENABLED);
8481 /* See if anything special should be done now we know how big
8482 everything is. This is where relaxation is done. */
8483 ldemul_after_allocation ();
8485 /* Fix any __start, __stop, .startof. or .sizeof. symbols. */
8486 lang_finalize_start_stop ();
8488 /* Do all the assignments again, to report errors. Assignment
8489 statements are processed multiple times, updating symbols; In
8490 open_input_bfds, lang_do_assignments, and lang_size_sections.
8491 Since lang_relax_sections calls lang_do_assignments, symbols are
8492 also updated in ldemul_after_allocation. */
8493 lang_do_assignments (lang_final_phase_enum);
8495 ldemul_finish ();
8497 /* Convert absolute symbols to section relative. */
8498 ldexp_finalize_syms ();
8500 /* Make sure that the section addresses make sense. */
8501 if (command_line.check_section_addresses)
8502 lang_check_section_addresses ();
8504 if (link_info.non_contiguous_regions
8505 && link_info.non_contiguous_regions_warnings)
8506 warn_non_contiguous_discards ();
8508 /* Check any required symbols are known. */
8509 ldlang_check_require_defined_symbols ();
8511 lang_end ();
8514 void
8515 lang_add_version_string (void)
8517 if (! enable_linker_version)
8518 return;
8520 const char * str = "GNU ld ";
8521 int len = strlen (str);
8522 int i;
8524 for (i = 0 ; i < len ; i++)
8525 lang_add_data (BYTE, exp_intop (str[i]));
8527 str = BFD_VERSION_STRING;
8528 len = strlen (str);
8530 for (i = 0 ; i < len ; i++)
8531 lang_add_data (BYTE, exp_intop (str[i]));
8533 lang_add_data (BYTE, exp_intop ('\0'));
8536 /* EXPORTED TO YACC */
8538 void
8539 lang_add_wild (struct wildcard_spec *filespec,
8540 struct wildcard_list *section_list,
8541 bool keep_sections)
8543 struct wildcard_list *curr, *next;
8544 lang_wild_statement_type *new_stmt;
8545 bool any_specs_sorted = false;
8547 /* Reverse the list as the parser puts it back to front. */
8548 for (curr = section_list, section_list = NULL;
8549 curr != NULL;
8550 section_list = curr, curr = next)
8552 if (curr->spec.sorted != none && curr->spec.sorted != by_none)
8553 any_specs_sorted = true;
8554 next = curr->next;
8555 curr->next = section_list;
8558 if (filespec != NULL && filespec->name != NULL)
8560 if (strcmp (filespec->name, "*") == 0)
8561 filespec->name = NULL;
8562 else if (!wildcardp (filespec->name))
8563 lang_has_input_file = true;
8566 new_stmt = new_stat (lang_wild_statement, stat_ptr);
8567 new_stmt->filename = NULL;
8568 new_stmt->filenames_sorted = false;
8569 new_stmt->any_specs_sorted = any_specs_sorted;
8570 new_stmt->section_flag_list = NULL;
8571 new_stmt->exclude_name_list = NULL;
8572 if (filespec != NULL)
8574 new_stmt->filename = filespec->name;
8575 new_stmt->filenames_sorted = (filespec->sorted == by_name || filespec->reversed);
8576 new_stmt->section_flag_list = filespec->section_flag_list;
8577 new_stmt->exclude_name_list = filespec->exclude_name_list;
8578 new_stmt->filenames_reversed = filespec->reversed;
8580 new_stmt->section_list = section_list;
8581 new_stmt->keep_sections = keep_sections;
8582 lang_list_init (&new_stmt->children);
8583 lang_list_init (&new_stmt->matching_sections);
8584 analyze_walk_wild_section_handler (new_stmt);
8585 if (0)
8587 printf ("wild %s(", new_stmt->filename ? new_stmt->filename : "*");
8588 for (curr = new_stmt->section_list; curr; curr = curr->next)
8589 printf ("%s ", curr->spec.name ? curr->spec.name : "*");
8590 printf (")\n");
8594 void
8595 lang_section_start (const char *name, etree_type *address,
8596 const segment_type *segment)
8598 lang_address_statement_type *ad;
8600 ad = new_stat (lang_address_statement, stat_ptr);
8601 ad->section_name = name;
8602 ad->address = address;
8603 ad->segment = segment;
8606 /* Set the start symbol to NAME. CMDLINE is nonzero if this is called
8607 because of a -e argument on the command line, or zero if this is
8608 called by ENTRY in a linker script. Command line arguments take
8609 precedence. */
8611 void
8612 lang_add_entry (const char *name, bool cmdline)
8614 if (entry_symbol.name == NULL
8615 || cmdline
8616 || !entry_from_cmdline)
8618 entry_symbol.name = name;
8619 entry_from_cmdline = cmdline;
8623 /* Set the default start symbol to NAME. .em files should use this,
8624 not lang_add_entry, to override the use of "start" if neither the
8625 linker script nor the command line specifies an entry point. NAME
8626 must be permanently allocated. */
8627 void
8628 lang_default_entry (const char *name)
8630 entry_symbol_default = name;
8633 void
8634 lang_add_target (const char *name)
8636 lang_target_statement_type *new_stmt;
8638 new_stmt = new_stat (lang_target_statement, stat_ptr);
8639 new_stmt->target = name;
8642 void
8643 lang_add_map (const char *name)
8645 while (*name)
8647 switch (*name)
8649 case 'F':
8650 map_option_f = true;
8651 break;
8653 name++;
8657 void
8658 lang_add_fill (fill_type *fill)
8660 lang_fill_statement_type *new_stmt;
8662 new_stmt = new_stat (lang_fill_statement, stat_ptr);
8663 new_stmt->fill = fill;
8666 void
8667 lang_add_data (int type, union etree_union *exp)
8669 lang_data_statement_type *new_stmt;
8671 new_stmt = new_stat (lang_data_statement, stat_ptr);
8672 new_stmt->exp = exp;
8673 new_stmt->type = type;
8676 void
8677 lang_add_string (const char *s)
8679 bfd_vma len = strlen (s);
8680 bfd_vma i;
8681 bool escape = false;
8683 /* Add byte expressions until end of string. */
8684 for (i = 0 ; i < len; i++)
8686 char c = *s++;
8688 if (escape)
8690 switch (c)
8692 default:
8693 /* Ignore the escape. */
8694 break;
8696 case 'n': c = '\n'; break;
8697 case 'r': c = '\r'; break;
8698 case 't': c = '\t'; break;
8700 case '0':
8701 case '1':
8702 case '2':
8703 case '3':
8704 case '4':
8705 case '5':
8706 case '6':
8707 case '7':
8708 /* We have an octal number. */
8710 unsigned int value = c - '0';
8712 c = *s;
8713 if ((c >= '0') && (c <= '7'))
8715 value <<= 3;
8716 value += (c - '0');
8717 i++;
8718 s++;
8720 c = *s;
8721 if ((c >= '0') && (c <= '7'))
8723 value <<= 3;
8724 value += (c - '0');
8725 i++;
8726 s++;
8730 if (value > 0xff)
8732 /* octal: \777 is treated as '\077' + '7' */
8733 value >>= 3;
8734 i--;
8735 s--;
8738 c = value;
8740 break;
8743 lang_add_data (BYTE, exp_intop (c));
8744 escape = false;
8746 else
8748 if (c == '\\')
8749 escape = true;
8750 else
8751 lang_add_data (BYTE, exp_intop (c));
8755 /* Remeber to terminate the string. */
8756 lang_add_data (BYTE, exp_intop (0));
8759 /* Create a new reloc statement. RELOC is the BFD relocation type to
8760 generate. HOWTO is the corresponding howto structure (we could
8761 look this up, but the caller has already done so). SECTION is the
8762 section to generate a reloc against, or NAME is the name of the
8763 symbol to generate a reloc against. Exactly one of SECTION and
8764 NAME must be NULL. ADDEND is an expression for the addend. */
8766 void
8767 lang_add_reloc (bfd_reloc_code_real_type reloc,
8768 reloc_howto_type *howto,
8769 asection *section,
8770 const char *name,
8771 union etree_union *addend)
8773 lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
8775 p->reloc = reloc;
8776 p->howto = howto;
8777 p->section = section;
8778 p->name = name;
8779 p->addend_exp = addend;
8781 p->addend_value = 0;
8782 p->output_section = NULL;
8783 p->output_offset = 0;
8786 lang_assignment_statement_type *
8787 lang_add_assignment (etree_type *exp)
8789 lang_assignment_statement_type *new_stmt;
8791 new_stmt = new_stat (lang_assignment_statement, stat_ptr);
8792 new_stmt->exp = exp;
8793 return new_stmt;
8796 void
8797 lang_add_attribute (enum statement_enum attribute)
8799 new_statement (attribute, sizeof (lang_statement_header_type), stat_ptr);
8802 void
8803 lang_startup (const char *name)
8805 if (first_file->filename != NULL)
8807 einfo (_("%F%P: multiple STARTUP files\n"));
8809 first_file->filename = name;
8810 first_file->local_sym_name = name;
8811 first_file->flags.real = true;
8814 void
8815 lang_float (bool maybe)
8817 lang_float_flag = maybe;
8821 /* Work out the load- and run-time regions from a script statement, and
8822 store them in *LMA_REGION and *REGION respectively.
8824 MEMSPEC is the name of the run-time region, or the value of
8825 DEFAULT_MEMORY_REGION if the statement didn't specify one.
8826 LMA_MEMSPEC is the name of the load-time region, or null if the
8827 statement didn't specify one.HAVE_LMA_P is TRUE if the statement
8828 had an explicit load address.
8830 It is an error to specify both a load region and a load address. */
8832 static void
8833 lang_get_regions (lang_memory_region_type **region,
8834 lang_memory_region_type **lma_region,
8835 const char *memspec,
8836 const char *lma_memspec,
8837 bool have_lma,
8838 bool have_vma)
8840 *lma_region = lang_memory_region_lookup (lma_memspec, false);
8842 /* If no runtime region or VMA has been specified, but the load region
8843 has been specified, then use the load region for the runtime region
8844 as well. */
8845 if (lma_memspec != NULL
8846 && !have_vma
8847 && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
8848 *region = *lma_region;
8849 else
8850 *region = lang_memory_region_lookup (memspec, false);
8852 if (have_lma && lma_memspec != 0)
8853 einfo (_("%X%P:%pS: section has both a load address and a load region\n"),
8854 NULL);
8857 void
8858 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
8859 lang_output_section_phdr_list *phdrs,
8860 const char *lma_memspec)
8862 pop_stat_ptr ();
8863 if (in_section_ordering)
8864 return;
8866 lang_get_regions (&current_section->region,
8867 &current_section->lma_region,
8868 memspec, lma_memspec,
8869 current_section->load_base != NULL,
8870 current_section->addr_tree != NULL);
8872 current_section->fill = fill;
8873 current_section->phdrs = phdrs;
8876 /* Set the output format type. -oformat overrides scripts. */
8878 void
8879 lang_add_output_format (const char *format,
8880 const char *big,
8881 const char *little,
8882 int from_script)
8884 if (output_target == NULL || !from_script)
8886 if (command_line.endian == ENDIAN_BIG
8887 && big != NULL)
8888 format = big;
8889 else if (command_line.endian == ENDIAN_LITTLE
8890 && little != NULL)
8891 format = little;
8893 output_target = format;
8897 void
8898 lang_add_insert (const char *where, int is_before)
8900 lang_insert_statement_type *new_stmt;
8902 new_stmt = new_stat (lang_insert_statement, stat_ptr);
8903 new_stmt->where = where;
8904 new_stmt->is_before = is_before;
8905 saved_script_handle = previous_script_handle;
8908 /* Enter a group. This creates a new lang_group_statement, and sets
8909 stat_ptr to build new statements within the group. */
8911 void
8912 lang_enter_group (void)
8914 lang_group_statement_type *g;
8916 g = new_stat (lang_group_statement, stat_ptr);
8917 lang_list_init (&g->children);
8918 push_stat_ptr (&g->children);
8921 /* Leave a group. This just resets stat_ptr to start writing to the
8922 regular list of statements again. Note that this will not work if
8923 groups can occur inside anything else which can adjust stat_ptr,
8924 but currently they can't. */
8926 void
8927 lang_leave_group (void)
8929 pop_stat_ptr ();
8932 /* Add a new program header. This is called for each entry in a PHDRS
8933 command in a linker script. */
8935 void
8936 lang_new_phdr (const char *name,
8937 etree_type *type,
8938 bool filehdr,
8939 bool phdrs,
8940 etree_type *at,
8941 etree_type *flags)
8943 struct lang_phdr *n, **pp;
8944 bool hdrs;
8946 n = stat_alloc (sizeof (struct lang_phdr));
8947 n->next = NULL;
8948 n->name = name;
8949 n->type = exp_get_vma (type, NULL, 0, "program header type");
8950 n->filehdr = filehdr;
8951 n->phdrs = phdrs;
8952 n->at = at;
8953 n->flags = flags;
8955 hdrs = n->type == 1 && (phdrs || filehdr);
8957 for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
8958 if (hdrs
8959 && (*pp)->type == 1
8960 && !((*pp)->filehdr || (*pp)->phdrs))
8962 einfo (_("%X%P:%pS: PHDRS and FILEHDR are not supported"
8963 " when prior PT_LOAD headers lack them\n"), NULL);
8964 hdrs = false;
8967 *pp = n;
8970 /* Record the program header information in the output BFD. FIXME: We
8971 should not be calling an ELF specific function here. */
8973 static void
8974 lang_record_phdrs (void)
8976 unsigned int alc;
8977 asection **secs;
8978 lang_output_section_phdr_list *last;
8979 struct lang_phdr *l;
8980 lang_output_section_statement_type *os;
8982 alc = 10;
8983 secs = (asection **) xmalloc (alc * sizeof (asection *));
8984 last = NULL;
8986 for (l = lang_phdr_list; l != NULL; l = l->next)
8988 unsigned int c;
8989 flagword flags;
8990 bfd_vma at;
8992 c = 0;
8993 for (os = (void *) lang_os_list.head;
8994 os != NULL;
8995 os = os->next)
8997 lang_output_section_phdr_list *pl;
8999 if (os->constraint < 0)
9000 continue;
9002 pl = os->phdrs;
9003 if (pl != NULL)
9004 last = pl;
9005 else
9007 if (os->sectype == noload_section
9008 || os->bfd_section == NULL
9009 || (os->bfd_section->flags & SEC_ALLOC) == 0)
9010 continue;
9012 /* Don't add orphans to PT_INTERP header. */
9013 if (l->type == PT_INTERP)
9014 continue;
9016 if (last == NULL)
9018 lang_output_section_statement_type *tmp_os;
9020 /* If we have not run across a section with a program
9021 header assigned to it yet, then scan forwards to find
9022 one. This prevents inconsistencies in the linker's
9023 behaviour when a script has specified just a single
9024 header and there are sections in that script which are
9025 not assigned to it, and which occur before the first
9026 use of that header. See here for more details:
9027 http://sourceware.org/ml/binutils/2007-02/msg00291.html */
9028 for (tmp_os = os; tmp_os; tmp_os = tmp_os->next)
9029 if (tmp_os->phdrs)
9031 last = tmp_os->phdrs;
9032 break;
9034 if (last == NULL)
9035 einfo (_("%F%P: no sections assigned to phdrs\n"));
9037 pl = last;
9040 if (os->bfd_section == NULL)
9041 continue;
9043 for (; pl != NULL; pl = pl->next)
9045 if (strcmp (pl->name, l->name) == 0)
9047 if (c >= alc)
9049 alc *= 2;
9050 secs = (asection **) xrealloc (secs,
9051 alc * sizeof (asection *));
9053 secs[c] = os->bfd_section;
9054 ++c;
9055 pl->used = true;
9060 if (l->flags == NULL)
9061 flags = 0;
9062 else
9063 flags = exp_get_vma (l->flags, NULL, 0, "phdr flags");
9065 if (l->at == NULL)
9066 at = 0;
9067 else
9068 at = exp_get_vma (l->at, NULL, 0, "phdr load address");
9070 if (!bfd_record_phdr (link_info.output_bfd, l->type,
9071 l->flags != NULL, flags, l->at != NULL,
9072 at, l->filehdr, l->phdrs, c, secs))
9073 einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
9076 free (secs);
9078 /* Make sure all the phdr assignments succeeded. */
9079 for (os = (void *) lang_os_list.head;
9080 os != NULL;
9081 os = os->next)
9083 lang_output_section_phdr_list *pl;
9085 if (os->constraint < 0
9086 || os->bfd_section == NULL)
9087 continue;
9089 for (pl = os->phdrs;
9090 pl != NULL;
9091 pl = pl->next)
9092 if (!pl->used && strcmp (pl->name, "NONE") != 0)
9093 einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
9094 os->name, pl->name);
9098 /* Record a list of sections which may not be cross referenced. */
9100 void
9101 lang_add_nocrossref (lang_nocrossref_type *l)
9103 struct lang_nocrossrefs *n;
9105 n = (struct lang_nocrossrefs *) xmalloc (sizeof *n);
9106 n->next = nocrossref_list;
9107 n->list = l;
9108 n->onlyfirst = false;
9109 nocrossref_list = n;
9111 /* Set notice_all so that we get informed about all symbols. */
9112 link_info.notice_all = true;
9115 /* Record a section that cannot be referenced from a list of sections. */
9117 void
9118 lang_add_nocrossref_to (lang_nocrossref_type *l)
9120 lang_add_nocrossref (l);
9121 nocrossref_list->onlyfirst = true;
9124 /* Overlay handling. We handle overlays with some static variables. */
9126 /* The overlay virtual address. */
9127 static etree_type *overlay_vma;
9128 /* And subsection alignment. */
9129 static etree_type *overlay_subalign;
9131 /* An expression for the maximum section size seen so far. */
9132 static etree_type *overlay_max;
9134 /* A list of all the sections in this overlay. */
9136 struct overlay_list {
9137 struct overlay_list *next;
9138 lang_output_section_statement_type *os;
9141 static struct overlay_list *overlay_list;
9143 /* Start handling an overlay. */
9145 void
9146 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
9148 /* The grammar should prevent nested overlays from occurring. */
9149 ASSERT (overlay_vma == NULL
9150 && overlay_subalign == NULL
9151 && overlay_max == NULL);
9153 overlay_vma = vma_expr;
9154 overlay_subalign = subalign;
9157 /* Start a section in an overlay. We handle this by calling
9158 lang_enter_output_section_statement with the correct VMA.
9159 lang_leave_overlay sets up the LMA and memory regions. */
9161 void
9162 lang_enter_overlay_section (const char *name)
9164 struct overlay_list *n;
9165 etree_type *size;
9167 lang_enter_output_section_statement (name, overlay_vma, overlay_section,
9168 0, 0, overlay_subalign, 0, 0, 0);
9170 /* If this is the first section, then base the VMA of future
9171 sections on this one. This will work correctly even if `.' is
9172 used in the addresses. */
9173 if (overlay_list == NULL)
9174 overlay_vma = exp_nameop (ADDR, name);
9176 /* Remember the section. */
9177 n = (struct overlay_list *) xmalloc (sizeof *n);
9178 n->os = current_section;
9179 n->next = overlay_list;
9180 overlay_list = n;
9182 size = exp_nameop (SIZEOF, name);
9184 /* Arrange to work out the maximum section end address. */
9185 if (overlay_max == NULL)
9186 overlay_max = size;
9187 else
9188 overlay_max = exp_binop (MAX_K, overlay_max, size);
9191 /* Finish a section in an overlay. There isn't any special to do
9192 here. */
9194 void
9195 lang_leave_overlay_section (fill_type *fill,
9196 lang_output_section_phdr_list *phdrs)
9198 const char *name = current_section->name;;
9200 /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
9201 region and that no load-time region has been specified. It doesn't
9202 really matter what we say here, since lang_leave_overlay will
9203 override it. */
9204 lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
9206 /* Define the magic symbols. */
9208 char *clean = xmalloc (strlen (name) + 1);
9209 char *s2 = clean;
9210 for (const char *s1 = name; *s1 != '\0'; s1++)
9211 if (ISALNUM (*s1) || *s1 == '_')
9212 *s2++ = *s1;
9213 *s2 = '\0';
9215 char *buf = xasprintf ("__load_start_%s", clean);
9216 lang_add_assignment (exp_provide (buf,
9217 exp_nameop (LOADADDR, name),
9218 false));
9220 buf = xasprintf ("__load_stop_%s", clean);
9221 lang_add_assignment (exp_provide (buf,
9222 exp_binop ('+',
9223 exp_nameop (LOADADDR, name),
9224 exp_nameop (SIZEOF, name)),
9225 false));
9227 free (clean);
9230 /* Finish an overlay. If there are any overlay wide settings, this
9231 looks through all the sections in the overlay and sets them. */
9233 void
9234 lang_leave_overlay (etree_type *lma_expr,
9235 int nocrossrefs,
9236 fill_type *fill,
9237 const char *memspec,
9238 lang_output_section_phdr_list *phdrs,
9239 const char *lma_memspec)
9241 lang_memory_region_type *region;
9242 lang_memory_region_type *lma_region;
9243 struct overlay_list *l;
9244 lang_nocrossref_type *nocrossref;
9246 lang_get_regions (&region, &lma_region,
9247 memspec, lma_memspec,
9248 lma_expr != NULL, false);
9250 nocrossref = NULL;
9252 /* After setting the size of the last section, set '.' to end of the
9253 overlay region. */
9254 if (overlay_list != NULL)
9256 overlay_list->os->update_dot = 1;
9257 overlay_list->os->update_dot_tree
9258 = exp_assign (".", exp_binop ('+', overlay_vma, overlay_max), false);
9261 l = overlay_list;
9262 while (l != NULL)
9264 struct overlay_list *next;
9266 if (fill != NULL && l->os->fill == NULL)
9267 l->os->fill = fill;
9269 l->os->region = region;
9270 l->os->lma_region = lma_region;
9272 /* The first section has the load address specified in the
9273 OVERLAY statement. The rest are worked out from that.
9274 The base address is not needed (and should be null) if
9275 an LMA region was specified. */
9276 if (l->next == 0)
9278 l->os->load_base = lma_expr;
9279 l->os->sectype = first_overlay_section;
9281 if (phdrs != NULL && l->os->phdrs == NULL)
9282 l->os->phdrs = phdrs;
9284 if (nocrossrefs)
9286 lang_nocrossref_type *nc;
9288 nc = (lang_nocrossref_type *) xmalloc (sizeof *nc);
9289 nc->name = l->os->name;
9290 nc->next = nocrossref;
9291 nocrossref = nc;
9294 next = l->next;
9295 free (l);
9296 l = next;
9299 if (nocrossref != NULL)
9300 lang_add_nocrossref (nocrossref);
9302 overlay_vma = NULL;
9303 overlay_list = NULL;
9304 overlay_max = NULL;
9305 overlay_subalign = NULL;
9308 /* Version handling. This is only useful for ELF. */
9310 /* If PREV is NULL, return first version pattern matching particular symbol.
9311 If PREV is non-NULL, return first version pattern matching particular
9312 symbol after PREV (previously returned by lang_vers_match). */
9314 static struct bfd_elf_version_expr *
9315 lang_vers_match (struct bfd_elf_version_expr_head *head,
9316 struct bfd_elf_version_expr *prev,
9317 const char *sym)
9319 const char *c_sym;
9320 const char *cxx_sym = sym;
9321 const char *java_sym = sym;
9322 struct bfd_elf_version_expr *expr = NULL;
9323 enum demangling_styles curr_style;
9325 curr_style = CURRENT_DEMANGLING_STYLE;
9326 cplus_demangle_set_style (no_demangling);
9327 c_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_NO_OPTS);
9328 if (!c_sym)
9329 c_sym = sym;
9330 cplus_demangle_set_style (curr_style);
9332 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9334 cxx_sym = bfd_demangle (link_info.output_bfd, sym,
9335 DMGL_PARAMS | DMGL_ANSI);
9336 if (!cxx_sym)
9337 cxx_sym = sym;
9339 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9341 java_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_JAVA);
9342 if (!java_sym)
9343 java_sym = sym;
9346 if (head->htab && (prev == NULL || prev->literal))
9348 struct bfd_elf_version_expr e;
9350 switch (prev ? prev->mask : 0)
9352 case 0:
9353 if (head->mask & BFD_ELF_VERSION_C_TYPE)
9355 e.pattern = c_sym;
9356 expr = (struct bfd_elf_version_expr *)
9357 htab_find ((htab_t) head->htab, &e);
9358 while (expr && strcmp (expr->pattern, c_sym) == 0)
9359 if (expr->mask == BFD_ELF_VERSION_C_TYPE)
9360 goto out_ret;
9361 else
9362 expr = expr->next;
9364 /* Fallthrough */
9365 case BFD_ELF_VERSION_C_TYPE:
9366 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9368 e.pattern = cxx_sym;
9369 expr = (struct bfd_elf_version_expr *)
9370 htab_find ((htab_t) head->htab, &e);
9371 while (expr && strcmp (expr->pattern, cxx_sym) == 0)
9372 if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9373 goto out_ret;
9374 else
9375 expr = expr->next;
9377 /* Fallthrough */
9378 case BFD_ELF_VERSION_CXX_TYPE:
9379 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9381 e.pattern = java_sym;
9382 expr = (struct bfd_elf_version_expr *)
9383 htab_find ((htab_t) head->htab, &e);
9384 while (expr && strcmp (expr->pattern, java_sym) == 0)
9385 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9386 goto out_ret;
9387 else
9388 expr = expr->next;
9390 /* Fallthrough */
9391 default:
9392 break;
9396 /* Finally, try the wildcards. */
9397 if (prev == NULL || prev->literal)
9398 expr = head->remaining;
9399 else
9400 expr = prev->next;
9401 for (; expr; expr = expr->next)
9403 const char *s;
9405 if (!expr->pattern)
9406 continue;
9408 if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
9409 break;
9411 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9412 s = java_sym;
9413 else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9414 s = cxx_sym;
9415 else
9416 s = c_sym;
9417 if (fnmatch (expr->pattern, s, 0) == 0)
9418 break;
9421 out_ret:
9422 if (c_sym != sym)
9423 free ((char *) c_sym);
9424 if (cxx_sym != sym)
9425 free ((char *) cxx_sym);
9426 if (java_sym != sym)
9427 free ((char *) java_sym);
9428 return expr;
9431 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
9432 return a pointer to the symbol name with any backslash quotes removed. */
9434 static const char *
9435 realsymbol (const char *pattern)
9437 const char *p;
9438 bool changed = false, backslash = false;
9439 char *s, *symbol = (char *) xmalloc (strlen (pattern) + 1);
9441 for (p = pattern, s = symbol; *p != '\0'; ++p)
9443 /* It is a glob pattern only if there is no preceding
9444 backslash. */
9445 if (backslash)
9447 /* Remove the preceding backslash. */
9448 *(s - 1) = *p;
9449 backslash = false;
9450 changed = true;
9452 else
9454 if (*p == '?' || *p == '*' || *p == '[')
9456 free (symbol);
9457 return NULL;
9460 *s++ = *p;
9461 backslash = *p == '\\';
9465 if (changed)
9467 *s = '\0';
9468 return symbol;
9470 else
9472 free (symbol);
9473 return pattern;
9477 /* This is called for each variable name or match expression. NEW_NAME is
9478 the name of the symbol to match, or, if LITERAL_P is FALSE, a glob
9479 pattern to be matched against symbol names. */
9481 struct bfd_elf_version_expr *
9482 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
9483 const char *new_name,
9484 const char *lang,
9485 bool literal_p)
9487 struct bfd_elf_version_expr *ret;
9489 ret = (struct bfd_elf_version_expr *) xmalloc (sizeof *ret);
9490 ret->next = orig;
9491 ret->symver = 0;
9492 ret->script = 0;
9493 ret->literal = true;
9494 ret->pattern = literal_p ? new_name : realsymbol (new_name);
9495 if (ret->pattern == NULL)
9497 ret->pattern = new_name;
9498 ret->literal = false;
9501 if (lang == NULL || strcasecmp (lang, "C") == 0)
9502 ret->mask = BFD_ELF_VERSION_C_TYPE;
9503 else if (strcasecmp (lang, "C++") == 0)
9504 ret->mask = BFD_ELF_VERSION_CXX_TYPE;
9505 else if (strcasecmp (lang, "Java") == 0)
9506 ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
9507 else
9509 einfo (_("%X%P: unknown language `%s' in version information\n"),
9510 lang);
9511 ret->mask = BFD_ELF_VERSION_C_TYPE;
9514 return ldemul_new_vers_pattern (ret);
9517 /* This is called for each set of variable names and match
9518 expressions. */
9520 struct bfd_elf_version_tree *
9521 lang_new_vers_node (struct bfd_elf_version_expr *globals,
9522 struct bfd_elf_version_expr *locals)
9524 struct bfd_elf_version_tree *ret;
9526 ret = (struct bfd_elf_version_tree *) xcalloc (1, sizeof *ret);
9527 ret->globals.list = globals;
9528 ret->locals.list = locals;
9529 ret->match = lang_vers_match;
9530 ret->name_indx = (unsigned int) -1;
9531 return ret;
9534 /* This static variable keeps track of version indices. */
9536 static int version_index;
9538 static hashval_t
9539 version_expr_head_hash (const void *p)
9541 const struct bfd_elf_version_expr *e =
9542 (const struct bfd_elf_version_expr *) p;
9544 return htab_hash_string (e->pattern);
9547 static int
9548 version_expr_head_eq (const void *p1, const void *p2)
9550 const struct bfd_elf_version_expr *e1 =
9551 (const struct bfd_elf_version_expr *) p1;
9552 const struct bfd_elf_version_expr *e2 =
9553 (const struct bfd_elf_version_expr *) p2;
9555 return strcmp (e1->pattern, e2->pattern) == 0;
9558 static void
9559 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
9561 size_t count = 0;
9562 struct bfd_elf_version_expr *e, *next;
9563 struct bfd_elf_version_expr **list_loc, **remaining_loc;
9565 for (e = head->list; e; e = e->next)
9567 if (e->literal)
9568 count++;
9569 head->mask |= e->mask;
9572 if (count)
9574 head->htab = htab_create (count * 2, version_expr_head_hash,
9575 version_expr_head_eq, NULL);
9576 list_loc = &head->list;
9577 remaining_loc = &head->remaining;
9578 for (e = head->list; e; e = next)
9580 next = e->next;
9581 if (!e->literal)
9583 *remaining_loc = e;
9584 remaining_loc = &e->next;
9586 else
9588 void **loc = htab_find_slot ((htab_t) head->htab, e, INSERT);
9590 if (*loc)
9592 struct bfd_elf_version_expr *e1, *last;
9594 e1 = (struct bfd_elf_version_expr *) *loc;
9595 last = NULL;
9598 if (e1->mask == e->mask)
9600 last = NULL;
9601 break;
9603 last = e1;
9604 e1 = e1->next;
9606 while (e1 && strcmp (e1->pattern, e->pattern) == 0);
9608 if (last == NULL)
9610 /* This is a duplicate. */
9611 /* FIXME: Memory leak. Sometimes pattern is not
9612 xmalloced alone, but in larger chunk of memory. */
9613 /* free (e->pattern); */
9614 free (e);
9616 else
9618 e->next = last->next;
9619 last->next = e;
9622 else
9624 *loc = e;
9625 *list_loc = e;
9626 list_loc = &e->next;
9630 *remaining_loc = NULL;
9631 *list_loc = head->remaining;
9633 else
9634 head->remaining = head->list;
9637 /* This is called when we know the name and dependencies of the
9638 version. */
9640 void
9641 lang_register_vers_node (const char *name,
9642 struct bfd_elf_version_tree *version,
9643 struct bfd_elf_version_deps *deps)
9645 struct bfd_elf_version_tree *t, **pp;
9646 struct bfd_elf_version_expr *e1;
9648 if (name == NULL)
9649 name = "";
9651 if (link_info.version_info != NULL
9652 && (name[0] == '\0' || link_info.version_info->name[0] == '\0'))
9654 einfo (_("%X%P: anonymous version tag cannot be combined"
9655 " with other version tags\n"));
9656 free (version);
9657 return;
9660 /* Make sure this node has a unique name. */
9661 for (t = link_info.version_info; t != NULL; t = t->next)
9662 if (strcmp (t->name, name) == 0)
9663 einfo (_("%X%P: duplicate version tag `%s'\n"), name);
9665 lang_finalize_version_expr_head (&version->globals);
9666 lang_finalize_version_expr_head (&version->locals);
9668 /* Check the global and local match names, and make sure there
9669 aren't any duplicates. */
9671 for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
9673 for (t = link_info.version_info; t != NULL; t = t->next)
9675 struct bfd_elf_version_expr *e2;
9677 if (t->locals.htab && e1->literal)
9679 e2 = (struct bfd_elf_version_expr *)
9680 htab_find ((htab_t) t->locals.htab, e1);
9681 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9683 if (e1->mask == e2->mask)
9684 einfo (_("%X%P: duplicate expression `%s'"
9685 " in version information\n"), e1->pattern);
9686 e2 = e2->next;
9689 else if (!e1->literal)
9690 for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
9691 if (strcmp (e1->pattern, e2->pattern) == 0
9692 && e1->mask == e2->mask)
9693 einfo (_("%X%P: duplicate expression `%s'"
9694 " in version information\n"), e1->pattern);
9698 for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
9700 for (t = link_info.version_info; t != NULL; t = t->next)
9702 struct bfd_elf_version_expr *e2;
9704 if (t->globals.htab && e1->literal)
9706 e2 = (struct bfd_elf_version_expr *)
9707 htab_find ((htab_t) t->globals.htab, e1);
9708 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9710 if (e1->mask == e2->mask)
9711 einfo (_("%X%P: duplicate expression `%s'"
9712 " in version information\n"),
9713 e1->pattern);
9714 e2 = e2->next;
9717 else if (!e1->literal)
9718 for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
9719 if (strcmp (e1->pattern, e2->pattern) == 0
9720 && e1->mask == e2->mask)
9721 einfo (_("%X%P: duplicate expression `%s'"
9722 " in version information\n"), e1->pattern);
9726 version->deps = deps;
9727 version->name = name;
9728 if (name[0] != '\0')
9730 ++version_index;
9731 version->vernum = version_index;
9733 else
9734 version->vernum = 0;
9736 for (pp = &link_info.version_info; *pp != NULL; pp = &(*pp)->next)
9738 *pp = version;
9741 /* This is called when we see a version dependency. */
9743 struct bfd_elf_version_deps *
9744 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
9746 struct bfd_elf_version_deps *ret;
9747 struct bfd_elf_version_tree *t;
9749 ret = (struct bfd_elf_version_deps *) xmalloc (sizeof *ret);
9750 ret->next = list;
9752 for (t = link_info.version_info; t != NULL; t = t->next)
9754 if (strcmp (t->name, name) == 0)
9756 ret->version_needed = t;
9757 return ret;
9761 einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
9763 ret->version_needed = NULL;
9764 return ret;
9767 static void
9768 lang_do_version_exports_section (void)
9770 struct bfd_elf_version_expr *greg = NULL, *lreg;
9772 LANG_FOR_EACH_INPUT_STATEMENT (is)
9774 asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
9775 char *contents, *p;
9776 bfd_size_type len;
9778 if (sec == NULL)
9779 continue;
9781 len = sec->size;
9782 contents = (char *) xmalloc (len);
9783 if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
9784 einfo (_("%X%P: unable to read .exports section contents\n"), sec);
9786 p = contents;
9787 while (p < contents + len)
9789 greg = lang_new_vers_pattern (greg, p, NULL, false);
9790 p = strchr (p, '\0') + 1;
9793 /* Do not free the contents, as we used them creating the regex. */
9795 /* Do not include this section in the link. */
9796 sec->flags |= SEC_EXCLUDE | SEC_KEEP;
9799 lreg = lang_new_vers_pattern (NULL, "*", NULL, false);
9800 lang_register_vers_node (command_line.version_exports_section,
9801 lang_new_vers_node (greg, lreg), NULL);
9804 /* Evaluate LENGTH and ORIGIN parts of MEMORY spec. This is initially
9805 called with UPDATE_REGIONS_P set to FALSE, in this case no errors are
9806 thrown, however, references to symbols in the origin and length fields
9807 will be pushed into the symbol table, this allows PROVIDE statements to
9808 then provide these symbols. This function is called a second time with
9809 UPDATE_REGIONS_P set to TRUE, this time the we update the actual region
9810 data structures, and throw errors if missing symbols are encountered. */
9812 static void
9813 lang_do_memory_regions (bool update_regions_p)
9815 lang_memory_region_type *r = lang_memory_region_list;
9817 for (; r != NULL; r = r->next)
9819 if (r->origin_exp)
9821 exp_fold_tree_no_dot (r->origin_exp, NULL);
9822 if (update_regions_p)
9824 if (expld.result.valid_p)
9826 r->origin = expld.result.value;
9827 r->current = r->origin;
9829 else
9830 einfo (_("%P: invalid origin for memory region %s\n"),
9831 r->name_list.name);
9834 if (r->length_exp)
9836 exp_fold_tree_no_dot (r->length_exp, NULL);
9837 if (update_regions_p)
9839 if (expld.result.valid_p)
9840 r->length = expld.result.value;
9841 else
9842 einfo (_("%P: invalid length for memory region %s\n"),
9843 r->name_list.name);
9849 void
9850 lang_add_unique (const char *name)
9852 struct unique_sections *ent;
9854 for (ent = unique_section_list; ent; ent = ent->next)
9855 if (strcmp (ent->name, name) == 0)
9856 return;
9858 ent = (struct unique_sections *) xmalloc (sizeof *ent);
9859 ent->name = xstrdup (name);
9860 ent->next = unique_section_list;
9861 unique_section_list = ent;
9864 /* Append the list of dynamic symbols to the existing one. */
9866 void
9867 lang_append_dynamic_list (struct bfd_elf_dynamic_list **list_p,
9868 struct bfd_elf_version_expr *dynamic)
9870 if (*list_p)
9872 struct bfd_elf_version_expr *tail;
9873 for (tail = dynamic; tail->next != NULL; tail = tail->next)
9875 tail->next = (*list_p)->head.list;
9876 (*list_p)->head.list = dynamic;
9878 else
9880 struct bfd_elf_dynamic_list *d;
9882 d = (struct bfd_elf_dynamic_list *) xcalloc (1, sizeof *d);
9883 d->head.list = dynamic;
9884 d->match = lang_vers_match;
9885 *list_p = d;
9889 /* Append the list of C++ typeinfo dynamic symbols to the existing
9890 one. */
9892 void
9893 lang_append_dynamic_list_cpp_typeinfo (void)
9895 const char *symbols[] =
9897 "typeinfo name for*",
9898 "typeinfo for*"
9900 struct bfd_elf_version_expr *dynamic = NULL;
9901 unsigned int i;
9903 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9904 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9905 false);
9907 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9910 /* Append the list of C++ operator new and delete dynamic symbols to the
9911 existing one. */
9913 void
9914 lang_append_dynamic_list_cpp_new (void)
9916 const char *symbols[] =
9918 "operator new*",
9919 "operator delete*"
9921 struct bfd_elf_version_expr *dynamic = NULL;
9922 unsigned int i;
9924 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9925 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9926 false);
9928 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9931 /* Scan a space and/or comma separated string of features. */
9933 void
9934 lang_ld_feature (char *str)
9936 char *p, *q;
9938 p = str;
9939 while (*p)
9941 char sep;
9942 while (*p == ',' || ISSPACE (*p))
9943 ++p;
9944 if (!*p)
9945 break;
9946 q = p + 1;
9947 while (*q && *q != ',' && !ISSPACE (*q))
9948 ++q;
9949 sep = *q;
9950 *q = 0;
9951 if (strcasecmp (p, "SANE_EXPR") == 0)
9952 config.sane_expr = true;
9953 else
9954 einfo (_("%X%P: unknown feature `%s'\n"), p);
9955 *q = sep;
9956 p = q;
9960 /* Pretty print memory amount. */
9962 static void
9963 lang_print_memory_size (uint64_t sz)
9965 if (sz == 0)
9966 printf (" %10" PRIu64 " B", sz);
9967 else if ((sz & 0x3fffffff) == 0)
9968 printf ("%10" PRIu64 " GB", sz >> 30);
9969 else if ((sz & 0xfffff) == 0)
9970 printf ("%10" PRIu64 " MB", sz >> 20);
9971 else if ((sz & 0x3ff) == 0)
9972 printf ("%10" PRIu64 " KB", sz >> 10);
9973 else
9974 printf (" %10" PRIu64 " B", sz);
9977 /* Implement --print-memory-usage: disply per region memory usage. */
9979 void
9980 lang_print_memory_usage (void)
9982 lang_memory_region_type *r;
9984 printf ("Memory region Used Size Region Size %%age Used\n");
9985 for (r = lang_memory_region_list; r->next != NULL; r = r->next)
9987 bfd_vma used_length = r->current - r->origin;
9989 printf ("%16s: ",r->name_list.name);
9990 lang_print_memory_size (used_length);
9991 lang_print_memory_size (r->length);
9993 if (r->length != 0)
9995 double percent = used_length * 100.0 / r->length;
9996 printf (" %6.2f%%", percent);
9998 printf ("\n");