Add --section-ordering command line option to the bfd linker.
[binutils-gdb.git] / ld / ldlang.c
blob9e8cc224f4d0218cca759f32225104fdc957c8fa
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;
2050 for (sec = link_info.output_bfd->sections;
2051 (sec != NULL
2052 && !bfd_is_abs_section (sec));
2053 sec = sec->next)
2054 if (sec != snew
2055 && elf_section_type (sec) == SHT_NOTE
2056 && (sec->flags & SEC_LOAD) != 0)
2058 if (!first_orphan_note)
2059 first_orphan_note = sec;
2060 if (sec->alignment_power >= s->alignment_power)
2061 after_sec = sec;
2063 else if (first_orphan_note)
2065 /* Stop if there is non-note section after the first
2066 orphan note section. */
2067 break;
2070 /* If this will be the first orphan note section, it can
2071 be placed at the default location. */
2072 after_sec_note = first_orphan_note != NULL;
2073 if (after_sec == NULL && after_sec_note)
2075 /* If all output note sections have smaller
2076 alignments, place the section before all
2077 output orphan note sections. */
2078 after_sec = first_orphan_note;
2079 insert_after = false;
2082 else if (first_orphan_note)
2084 /* Don't place non-note sections in the middle of orphan
2085 note sections. */
2086 after_sec_note = true;
2087 after_sec = as;
2088 for (sec = as->next;
2089 (sec != NULL
2090 && !bfd_is_abs_section (sec));
2091 sec = sec->next)
2092 if (elf_section_type (sec) == SHT_NOTE
2093 && (sec->flags & SEC_LOAD) != 0)
2094 after_sec = sec;
2097 if (after_sec_note)
2099 if (after_sec)
2101 /* Search forward to insert OS after AFTER_SEC output
2102 statement. */
2103 lang_output_section_statement_type *stmt, *next;
2104 bool found = false;
2105 for (stmt = after; stmt != NULL; stmt = next)
2107 next = stmt->next;
2108 if (insert_after)
2110 if (stmt->bfd_section == after_sec)
2112 place_after = true;
2113 found = true;
2114 after = stmt;
2115 break;
2118 else
2120 /* If INSERT_AFTER is FALSE, place OS before
2121 AFTER_SEC output statement. */
2122 if (next && next->bfd_section == after_sec)
2124 place_after = true;
2125 found = true;
2126 after = stmt;
2127 break;
2132 /* Search backward to insert OS after AFTER_SEC output
2133 statement. */
2134 if (!found)
2135 for (stmt = after; stmt != NULL; stmt = stmt->prev)
2137 if (insert_after)
2139 if (stmt->bfd_section == after_sec)
2141 place_after = true;
2142 after = stmt;
2143 break;
2146 else
2148 /* If INSERT_AFTER is FALSE, place OS before
2149 AFTER_SEC output statement. */
2150 if (stmt->next->bfd_section == after_sec)
2152 place_after = true;
2153 after = stmt;
2154 break;
2160 if (after_sec == NULL
2161 || (insert_after && after_sec->next != snew)
2162 || (!insert_after && after_sec->prev != snew))
2164 /* Unlink the section. */
2165 bfd_section_list_remove (link_info.output_bfd, snew);
2167 /* Place SNEW after AFTER_SEC. If AFTER_SEC is NULL,
2168 prepend SNEW. */
2169 if (after_sec)
2171 if (insert_after)
2172 bfd_section_list_insert_after (link_info.output_bfd,
2173 after_sec, snew);
2174 else
2175 bfd_section_list_insert_before (link_info.output_bfd,
2176 after_sec, snew);
2178 else
2179 bfd_section_list_prepend (link_info.output_bfd, snew);
2182 else if (as != snew && as->prev != snew)
2184 /* Unlink the section. */
2185 bfd_section_list_remove (link_info.output_bfd, snew);
2187 /* Now tack it back on in the right place. */
2188 bfd_section_list_insert_before (link_info.output_bfd,
2189 as, snew);
2192 else if (as != snew && as->prev != snew)
2194 /* Unlink the section. */
2195 bfd_section_list_remove (link_info.output_bfd, snew);
2197 /* Now tack it back on in the right place. */
2198 bfd_section_list_insert_before (link_info.output_bfd, as, snew);
2201 /* Save the end of this list. Further ophans of this type will
2202 follow the one we've just added. */
2203 place->section = &snew->next;
2205 /* The following is non-cosmetic. We try to put the output
2206 statements in some sort of reasonable order here, because they
2207 determine the final load addresses of the orphan sections.
2208 In addition, placing output statements in the wrong order may
2209 require extra segments. For instance, given a typical
2210 situation of all read-only sections placed in one segment and
2211 following that a segment containing all the read-write
2212 sections, we wouldn't want to place an orphan read/write
2213 section before or amongst the read-only ones. */
2214 if (add.head != NULL)
2216 lang_output_section_statement_type *newly_added_os;
2218 /* Place OS after AFTER if AFTER_NOTE is TRUE. */
2219 if (place_after)
2221 lang_statement_union_type **where;
2223 where = insert_os_after ((lang_statement_union_type *) after);
2224 *add.tail = *where;
2225 *where = add.head;
2227 place->os_tail = &after->next;
2229 else
2231 /* Put it after the last orphan statement we added. */
2232 *add.tail = *place->stmt;
2233 *place->stmt = add.head;
2236 /* Fix the global list pointer if we happened to tack our
2237 new list at the tail. */
2238 if (*stat_ptr->tail == add.head)
2239 stat_ptr->tail = add.tail;
2241 /* Save the end of this list. */
2242 place->stmt = add.tail;
2244 /* Do the same for the list of output section statements. */
2245 newly_added_os = *os_tail;
2246 *os_tail = NULL;
2247 newly_added_os->prev = (lang_output_section_statement_type *)
2248 ((char *) place->os_tail
2249 - offsetof (lang_output_section_statement_type, next));
2250 newly_added_os->next = *place->os_tail;
2251 if (newly_added_os->next != NULL)
2252 newly_added_os->next->prev = newly_added_os;
2253 *place->os_tail = newly_added_os;
2254 place->os_tail = &newly_added_os->next;
2256 /* Fixing the global list pointer here is a little different.
2257 We added to the list in lang_enter_output_section_statement,
2258 trimmed off the new output_section_statment above when
2259 assigning *os_tail = NULL, but possibly added it back in
2260 the same place when assigning *place->os_tail. */
2261 if (*os_tail == NULL)
2262 lang_os_list.tail = (lang_statement_union_type **) os_tail;
2265 return os;
2268 static void
2269 lang_print_asneeded (void)
2271 struct asneeded_minfo *m;
2273 if (asneeded_list_head == NULL)
2274 return;
2276 minfo (_("\nAs-needed library included to satisfy reference by file (symbol)\n\n"));
2278 for (m = asneeded_list_head; m != NULL; m = m->next)
2280 int len;
2282 minfo ("%s", m->soname);
2283 len = strlen (m->soname);
2285 if (len >= 29)
2287 print_nl ();
2288 len = 0;
2290 print_spaces (30 - len);
2292 if (m->ref != NULL)
2293 minfo ("%pB ", m->ref);
2294 minfo ("(%pT)\n", m->name);
2298 static void
2299 lang_map_flags (flagword flag)
2301 if (flag & SEC_ALLOC)
2302 minfo ("a");
2304 if (flag & SEC_CODE)
2305 minfo ("x");
2307 if (flag & SEC_READONLY)
2308 minfo ("r");
2310 if (flag & SEC_DATA)
2311 minfo ("w");
2313 if (flag & SEC_LOAD)
2314 minfo ("l");
2317 void
2318 lang_map (void)
2320 lang_memory_region_type *m;
2321 bool dis_header_printed = false;
2323 ldfile_print_input_remaps ();
2325 LANG_FOR_EACH_INPUT_STATEMENT (file)
2327 asection *s;
2329 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
2330 || file->flags.just_syms)
2331 continue;
2333 if (config.print_map_discarded)
2334 for (s = file->the_bfd->sections; s != NULL; s = s->next)
2335 if ((s->output_section == NULL
2336 || s->output_section->owner != link_info.output_bfd)
2337 && (s->flags & (SEC_LINKER_CREATED | SEC_KEEP)) == 0)
2339 if (! dis_header_printed)
2341 minfo (_("\nDiscarded input sections\n\n"));
2342 dis_header_printed = true;
2345 print_input_section (s, true);
2348 if (config.print_map_discarded && ! dis_header_printed)
2349 minfo (_("\nThere are no discarded input sections\n"));
2351 minfo (_("\nMemory Configuration\n\n"));
2352 fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
2353 _("Name"), _("Origin"), _("Length"), _("Attributes"));
2355 for (m = lang_memory_region_list; m != NULL; m = m->next)
2357 fprintf (config.map_file, "%-16s", m->name_list.name);
2359 char buf[32];
2360 bfd_sprintf_vma (link_info.output_bfd, buf, m->origin);
2361 fprintf (config.map_file, " 0x%-16s", buf);
2362 bfd_sprintf_vma (link_info.output_bfd, buf, m->length);
2363 fprintf (config.map_file,
2364 " 0x%*s", m->flags || m->not_flags ? -17 : 0, buf);
2365 if (m->flags)
2366 lang_map_flags (m->flags);
2368 if (m->not_flags)
2370 minfo ("!");
2371 lang_map_flags (m->not_flags);
2374 print_nl ();
2377 minfo (_("\nLinker script and memory map\n\n"));
2379 if (!link_info.reduce_memory_overheads)
2381 obstack_begin (&map_obstack, 1000);
2382 bfd_link_hash_traverse (link_info.hash, sort_def_symbol, 0);
2384 expld.phase = lang_fixed_phase_enum;
2385 lang_statement_iteration++;
2386 print_statements ();
2388 ldemul_extra_map_file_text (link_info.output_bfd, &link_info,
2389 config.map_file);
2392 static bool
2393 sort_def_symbol (struct bfd_link_hash_entry *hash_entry,
2394 void *info ATTRIBUTE_UNUSED)
2396 if ((hash_entry->type == bfd_link_hash_defined
2397 || hash_entry->type == bfd_link_hash_defweak)
2398 && hash_entry->u.def.section->owner != link_info.output_bfd
2399 && hash_entry->u.def.section->owner != NULL)
2401 input_section_userdata_type *ud;
2402 struct map_symbol_def *def;
2404 ud = bfd_section_userdata (hash_entry->u.def.section);
2405 if (!ud)
2407 ud = stat_alloc (sizeof (*ud));
2408 bfd_set_section_userdata (hash_entry->u.def.section, ud);
2409 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2410 ud->map_symbol_def_count = 0;
2412 else if (!ud->map_symbol_def_tail)
2413 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2415 def = (struct map_symbol_def *) obstack_alloc (&map_obstack, sizeof *def);
2416 def->entry = hash_entry;
2417 *(ud->map_symbol_def_tail) = def;
2418 ud->map_symbol_def_tail = &def->next;
2419 ud->map_symbol_def_count++;
2421 return true;
2424 /* Initialize an output section. */
2426 static void
2427 init_os (lang_output_section_statement_type *s, flagword flags)
2429 if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
2430 einfo (_("%F%P: illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
2432 if (!s->dup_output)
2433 s->bfd_section = bfd_get_section_by_name (link_info.output_bfd, s->name);
2434 if (s->bfd_section == NULL)
2435 s->bfd_section = bfd_make_section_anyway_with_flags (link_info.output_bfd,
2436 s->name, flags);
2437 if (s->bfd_section == NULL)
2439 einfo (_("%F%P: output format %s cannot represent section"
2440 " called %s: %E\n"),
2441 link_info.output_bfd->xvec->name, s->name);
2443 s->bfd_section->output_section = s->bfd_section;
2444 s->bfd_section->output_offset = 0;
2446 /* Set the userdata of the output section to the output section
2447 statement to avoid lookup. */
2448 bfd_set_section_userdata (s->bfd_section, s);
2450 /* If there is a base address, make sure that any sections it might
2451 mention are initialized. */
2452 if (s->addr_tree != NULL)
2453 exp_init_os (s->addr_tree);
2455 if (s->load_base != NULL)
2456 exp_init_os (s->load_base);
2458 /* If supplied an alignment, set it. */
2459 if (s->section_alignment != NULL)
2460 s->bfd_section->alignment_power = exp_get_power (s->section_alignment, s,
2461 "section alignment");
2464 static flagword
2465 get_os_init_flag (lang_output_section_statement_type * os)
2467 if (os != NULL)
2468 switch (os->sectype)
2470 case readonly_section: return SEC_READONLY;
2471 case noload_section: return SEC_NEVER_LOAD;
2472 default: break;
2475 return 0;
2478 /* Make sure that all output sections mentioned in an expression are
2479 initialized. */
2481 static void
2482 exp_init_os (etree_type *exp)
2484 switch (exp->type.node_class)
2486 case etree_assign:
2487 case etree_provide:
2488 case etree_provided:
2489 exp_init_os (exp->assign.src);
2490 break;
2492 case etree_binary:
2493 exp_init_os (exp->binary.lhs);
2494 exp_init_os (exp->binary.rhs);
2495 break;
2497 case etree_trinary:
2498 exp_init_os (exp->trinary.cond);
2499 exp_init_os (exp->trinary.lhs);
2500 exp_init_os (exp->trinary.rhs);
2501 break;
2503 case etree_assert:
2504 exp_init_os (exp->assert_s.child);
2505 break;
2507 case etree_unary:
2508 exp_init_os (exp->unary.child);
2509 break;
2511 case etree_name:
2512 switch (exp->type.node_code)
2514 case ADDR:
2515 case LOADADDR:
2517 lang_output_section_statement_type *os;
2519 os = lang_output_section_find (exp->name.name);
2520 if (os != NULL && os->bfd_section == NULL)
2521 init_os (os, get_os_init_flag (os));
2524 break;
2526 default:
2527 break;
2531 static void
2532 section_already_linked (bfd *abfd, asection *sec, void *data)
2534 lang_input_statement_type *entry = (lang_input_statement_type *) data;
2536 /* If we are only reading symbols from this object, then we want to
2537 discard all sections. */
2538 if (entry->flags.just_syms)
2540 bfd_link_just_syms (abfd, sec, &link_info);
2541 return;
2544 /* Deal with SHF_EXCLUDE ELF sections. */
2545 if (!bfd_link_relocatable (&link_info)
2546 && (abfd->flags & BFD_PLUGIN) == 0
2547 && (sec->flags & (SEC_GROUP | SEC_KEEP | SEC_EXCLUDE)) == SEC_EXCLUDE)
2548 sec->output_section = bfd_abs_section_ptr;
2550 if (!(abfd->flags & DYNAMIC))
2551 bfd_section_already_linked (abfd, sec, &link_info);
2555 /* Returns true if SECTION is one we know will be discarded based on its
2556 section flags, otherwise returns false. */
2558 static bool
2559 lang_discard_section_p (asection *section)
2561 bool discard;
2562 flagword flags = section->flags;
2564 /* Discard sections marked with SEC_EXCLUDE. */
2565 discard = (flags & SEC_EXCLUDE) != 0;
2567 /* Discard the group descriptor sections when we're finally placing the
2568 sections from within the group. */
2569 if ((flags & SEC_GROUP) != 0
2570 && link_info.resolve_section_groups)
2571 discard = true;
2573 /* Discard debugging sections if we are stripping debugging
2574 information. */
2575 if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
2576 && (flags & SEC_DEBUGGING) != 0)
2577 discard = true;
2579 /* Discard non-alloc sections if we are stripping section headers. */
2580 else if (config.no_section_header && (flags & SEC_ALLOC) == 0)
2581 discard = true;
2583 return discard;
2586 /* Return TRUE if SECTION is never going to be added to output statement
2587 OUTPUT. lang_add_section() definitely won't do anything with SECTION
2588 if this returns TRUE. It may do something (or not) if this returns FALSE.
2590 Can be used as early-out to filter matches. This may set
2591 output_section of SECTION, if it was unset, to the abs section in case
2592 we discover SECTION to be always discarded. This may also give
2593 warning messages. */
2595 static bool
2596 wont_add_section_p (asection *section,
2597 lang_output_section_statement_type *output)
2599 bool discard;
2601 /* Is this section one we know should be discarded? */
2602 discard = lang_discard_section_p (section);
2604 /* Discard input sections which are assigned to a section named
2605 DISCARD_SECTION_NAME. */
2606 if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
2607 discard = true;
2609 if (discard)
2611 if (section->output_section == NULL)
2613 /* This prevents future calls from assigning this section or
2614 warning about it again. */
2615 section->output_section = bfd_abs_section_ptr;
2617 else if (bfd_is_abs_section (section->output_section))
2619 else if (link_info.non_contiguous_regions_warnings)
2620 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions makes "
2621 "section `%pA' from `%pB' match /DISCARD/ clause.\n"),
2622 NULL, section, section->owner);
2624 return true;
2627 if (section->output_section != NULL)
2629 if (!link_info.non_contiguous_regions)
2630 return true;
2632 /* SECTION has already been handled in a special way
2633 (eg. LINK_ONCE): skip it. */
2634 if (bfd_is_abs_section (section->output_section))
2635 return true;
2637 /* Already assigned to the same output section, do not process
2638 it again, to avoid creating loops between duplicate sections
2639 later. */
2640 if (section->output_section == output->bfd_section)
2641 return true;
2643 if (link_info.non_contiguous_regions_warnings && output->bfd_section)
2644 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions may "
2645 "change behaviour for section `%pA' from `%pB' (assigned to "
2646 "%pA, but additional match: %pA)\n"),
2647 NULL, section, section->owner, section->output_section,
2648 output->bfd_section);
2650 /* SECTION has already been assigned to an output section, but
2651 the user allows it to be mapped to another one in case it
2652 overflows. We'll later update the actual output section in
2653 size_input_section as appropriate. */
2656 return false;
2659 /* The wild routines.
2661 These expand statements like *(.text) and foo.o to a list of
2662 explicit actions, like foo.o(.text), bar.o(.text) and
2663 foo.o(.text, .data). */
2665 /* Add SECTION to the output section OUTPUT. Do this by creating a
2666 lang_input_section statement which is placed at PTR. */
2668 void
2669 lang_add_section (lang_statement_list_type *ptr,
2670 asection *section,
2671 struct wildcard_list *pattern,
2672 struct flag_info *sflag_info,
2673 lang_output_section_statement_type *output)
2675 flagword flags = section->flags;
2677 lang_input_section_type *new_section;
2678 bfd *abfd = link_info.output_bfd;
2680 if (wont_add_section_p (section, output))
2681 return;
2683 if (sflag_info)
2685 bool keep;
2687 keep = bfd_lookup_section_flags (&link_info, sflag_info, section);
2688 if (!keep)
2689 return;
2692 /* We don't copy the SEC_NEVER_LOAD flag from an input section
2693 to an output section, because we want to be able to include a
2694 SEC_NEVER_LOAD section in the middle of an otherwise loaded
2695 section (I don't know why we want to do this, but we do).
2696 build_link_order in ldwrite.c handles this case by turning
2697 the embedded SEC_NEVER_LOAD section into a fill. */
2698 flags &= ~ SEC_NEVER_LOAD;
2700 /* If final link, don't copy the SEC_LINK_ONCE flags, they've
2701 already been processed. One reason to do this is that on pe
2702 format targets, .text$foo sections go into .text and it's odd
2703 to see .text with SEC_LINK_ONCE set. */
2704 if ((flags & (SEC_LINK_ONCE | SEC_GROUP)) == (SEC_LINK_ONCE | SEC_GROUP))
2706 if (link_info.resolve_section_groups)
2707 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2708 else
2709 flags &= ~(SEC_LINK_DUPLICATES | SEC_RELOC);
2711 else if (!bfd_link_relocatable (&link_info))
2712 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2714 switch (output->sectype)
2716 case normal_section:
2717 case overlay_section:
2718 case first_overlay_section:
2719 case type_section:
2720 break;
2721 case noalloc_section:
2722 flags &= ~SEC_ALLOC;
2723 break;
2724 case typed_readonly_section:
2725 case readonly_section:
2726 flags |= SEC_READONLY;
2727 break;
2728 case noload_section:
2729 flags &= ~SEC_LOAD;
2730 flags |= SEC_NEVER_LOAD;
2731 /* Unfortunately GNU ld has managed to evolve two different
2732 meanings to NOLOAD in scripts. ELF gets a .bss style noload,
2733 alloc, no contents section. All others get a noload, noalloc
2734 section. */
2735 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
2736 flags &= ~SEC_HAS_CONTENTS;
2737 else
2738 flags &= ~SEC_ALLOC;
2739 break;
2742 if (output->bfd_section == NULL)
2743 init_os (output, flags);
2745 /* If SEC_READONLY is not set in the input section, then clear
2746 it from the output section. */
2747 output->bfd_section->flags &= flags | ~SEC_READONLY;
2749 if (output->bfd_section->linker_has_input)
2751 /* Only set SEC_READONLY flag on the first input section. */
2752 flags &= ~ SEC_READONLY;
2754 /* Keep SEC_MERGE and SEC_STRINGS only if they are the same. */
2755 if ((output->bfd_section->flags & (SEC_MERGE | SEC_STRINGS))
2756 != (flags & (SEC_MERGE | SEC_STRINGS))
2757 || ((flags & SEC_MERGE) != 0
2758 && output->bfd_section->entsize != section->entsize))
2760 output->bfd_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
2761 flags &= ~ (SEC_MERGE | SEC_STRINGS);
2764 output->bfd_section->flags |= flags;
2766 if (!output->bfd_section->linker_has_input)
2768 output->bfd_section->linker_has_input = 1;
2769 /* This must happen after flags have been updated. The output
2770 section may have been created before we saw its first input
2771 section, eg. for a data statement. */
2772 bfd_init_private_section_data (section->owner, section,
2773 link_info.output_bfd,
2774 output->bfd_section,
2775 &link_info);
2776 if ((flags & SEC_MERGE) != 0)
2777 output->bfd_section->entsize = section->entsize;
2780 if ((flags & SEC_TIC54X_BLOCK) != 0
2781 && bfd_get_arch (section->owner) == bfd_arch_tic54x)
2783 /* FIXME: This value should really be obtained from the bfd... */
2784 output->block_value = 128;
2787 /* When a .ctors section is placed in .init_array it must be copied
2788 in reverse order. Similarly for .dtors. Set that up. */
2789 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
2790 && ((startswith (section->name, ".ctors")
2791 && strcmp (output->bfd_section->name, ".init_array") == 0)
2792 || (startswith (section->name, ".dtors")
2793 && strcmp (output->bfd_section->name, ".fini_array") == 0))
2794 && (section->name[6] == 0 || section->name[6] == '.'))
2795 section->flags |= SEC_ELF_REVERSE_COPY;
2797 if (section->alignment_power > output->bfd_section->alignment_power)
2798 output->bfd_section->alignment_power = section->alignment_power;
2800 section->output_section = output->bfd_section;
2802 if (!map_head_is_link_order)
2804 asection *s = output->bfd_section->map_tail.s;
2805 output->bfd_section->map_tail.s = section;
2806 section->map_head.s = NULL;
2807 section->map_tail.s = s;
2808 if (s != NULL)
2809 s->map_head.s = section;
2810 else
2811 output->bfd_section->map_head.s = section;
2814 /* Add a section reference to the list. */
2815 new_section = new_stat (lang_input_section, ptr);
2816 new_section->section = section;
2817 new_section->pattern = pattern;
2820 /* Expand a wild statement for a particular FILE. SECTION may be
2821 NULL, in which case it is a wild card. This assumes that the
2822 wild statement doesn't need any sorting (of filenames or sections). */
2824 static void
2825 output_section_callback_nosort (lang_wild_statement_type *ptr,
2826 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2827 asection *section,
2828 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2829 void *output)
2831 lang_output_section_statement_type *os;
2833 os = (lang_output_section_statement_type *) output;
2835 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2836 if (unique_section_p (section, os))
2837 return;
2839 lang_add_section (&ptr->children, section, ptr->section_list,
2840 ptr->section_flag_list, os);
2843 /* Check if all sections in a wild statement for a particular FILE
2844 are readonly. */
2846 static void
2847 check_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
2848 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2849 asection *section,
2850 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2851 void *output)
2853 lang_output_section_statement_type *os;
2855 os = (lang_output_section_statement_type *) output;
2857 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2858 if (unique_section_p (section, os))
2859 return;
2861 if (section->output_section == NULL && (section->flags & SEC_READONLY) == 0)
2862 os->all_input_readonly = false;
2865 /* This is passed a file name which must have been seen already and
2866 added to the statement tree. We will see if it has been opened
2867 already and had its symbols read. If not then we'll read it. */
2869 static lang_input_statement_type *
2870 lookup_name (const char *name)
2872 lang_input_statement_type *search;
2874 for (search = (void *) input_file_chain.head;
2875 search != NULL;
2876 search = search->next_real_file)
2878 /* Use the local_sym_name as the name of the file that has
2879 already been loaded as filename might have been transformed
2880 via the search directory lookup mechanism. */
2881 const char *filename = search->local_sym_name;
2883 if (filename != NULL
2884 && filename_cmp (filename, name) == 0)
2885 break;
2888 if (search == NULL)
2890 /* Arrange to splice the input statement added by new_afile into
2891 statement_list after the current input_file_chain tail.
2892 We know input_file_chain is not an empty list, and that
2893 lookup_name was called via open_input_bfds. Later calls to
2894 lookup_name should always match an existing input_statement. */
2895 lang_statement_union_type **tail = stat_ptr->tail;
2896 lang_statement_union_type **after
2897 = (void *) ((char *) input_file_chain.tail
2898 - offsetof (lang_input_statement_type, next_real_file)
2899 + offsetof (lang_input_statement_type, header.next));
2900 lang_statement_union_type *rest = *after;
2901 stat_ptr->tail = after;
2902 search = new_afile (name, lang_input_file_is_search_file_enum,
2903 default_target, NULL);
2904 *stat_ptr->tail = rest;
2905 if (*tail == NULL)
2906 stat_ptr->tail = tail;
2909 /* If we have already added this file, or this file is not real
2910 don't add this file. */
2911 if (search->flags.loaded || !search->flags.real)
2912 return search;
2914 if (!load_symbols (search, NULL))
2915 return NULL;
2917 return search;
2920 /* Save LIST as a list of libraries whose symbols should not be exported. */
2922 struct excluded_lib
2924 char *name;
2925 struct excluded_lib *next;
2927 static struct excluded_lib *excluded_libs;
2929 void
2930 add_excluded_libs (const char *list)
2932 const char *p = list, *end;
2934 while (*p != '\0')
2936 struct excluded_lib *entry;
2937 end = strpbrk (p, ",:");
2938 if (end == NULL)
2939 end = p + strlen (p);
2940 entry = (struct excluded_lib *) xmalloc (sizeof (*entry));
2941 entry->next = excluded_libs;
2942 entry->name = (char *) xmalloc (end - p + 1);
2943 memcpy (entry->name, p, end - p);
2944 entry->name[end - p] = '\0';
2945 excluded_libs = entry;
2946 if (*end == '\0')
2947 break;
2948 p = end + 1;
2952 static void
2953 check_excluded_libs (bfd *abfd)
2955 struct excluded_lib *lib = excluded_libs;
2957 while (lib)
2959 int len = strlen (lib->name);
2960 const char *filename = lbasename (bfd_get_filename (abfd));
2962 if (strcmp (lib->name, "ALL") == 0)
2964 abfd->no_export = true;
2965 return;
2968 if (filename_ncmp (lib->name, filename, len) == 0
2969 && (filename[len] == '\0'
2970 || (filename[len] == '.' && filename[len + 1] == 'a'
2971 && filename[len + 2] == '\0')))
2973 abfd->no_export = true;
2974 return;
2977 lib = lib->next;
2981 /* Get the symbols for an input file. */
2983 bool
2984 load_symbols (lang_input_statement_type *entry,
2985 lang_statement_list_type *place)
2987 char **matching;
2989 if (entry->flags.loaded)
2990 return true;
2992 ldfile_open_file (entry);
2994 /* Do not process further if the file was missing. */
2995 if (entry->flags.missing_file)
2996 return true;
2998 if (trace_files || verbose)
2999 info_msg ("%pI\n", entry);
3001 if (!bfd_check_format (entry->the_bfd, bfd_archive)
3002 && !bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
3004 bfd_error_type err;
3005 struct lang_input_statement_flags save_flags;
3006 extern FILE *yyin;
3008 err = bfd_get_error ();
3010 /* See if the emulation has some special knowledge. */
3011 if (ldemul_unrecognized_file (entry))
3013 if (err == bfd_error_file_ambiguously_recognized)
3014 free (matching);
3015 return true;
3018 if (err == bfd_error_file_ambiguously_recognized)
3020 char **p;
3022 einfo (_("%P: %pB: file not recognized: %E;"
3023 " matching formats:"), entry->the_bfd);
3024 for (p = matching; *p != NULL; p++)
3025 einfo (" %s", *p);
3026 free (matching);
3027 einfo ("%F\n");
3029 else if (err != bfd_error_file_not_recognized
3030 || place == NULL)
3031 einfo (_("%F%P: %pB: file not recognized: %E\n"), entry->the_bfd);
3033 bfd_close (entry->the_bfd);
3034 entry->the_bfd = NULL;
3036 /* Try to interpret the file as a linker script. */
3037 save_flags = input_flags;
3038 ldfile_open_command_file (entry->filename);
3040 push_stat_ptr (place);
3041 input_flags.add_DT_NEEDED_for_regular
3042 = entry->flags.add_DT_NEEDED_for_regular;
3043 input_flags.add_DT_NEEDED_for_dynamic
3044 = entry->flags.add_DT_NEEDED_for_dynamic;
3045 input_flags.whole_archive = entry->flags.whole_archive;
3046 input_flags.dynamic = entry->flags.dynamic;
3048 ldfile_assumed_script = true;
3049 parser_input = input_script;
3050 current_input_file = entry->filename;
3051 yyparse ();
3052 current_input_file = NULL;
3053 ldfile_assumed_script = false;
3055 /* missing_file is sticky. sysrooted will already have been
3056 restored when seeing EOF in yyparse, but no harm to restore
3057 again. */
3058 save_flags.missing_file |= input_flags.missing_file;
3059 input_flags = save_flags;
3060 pop_stat_ptr ();
3061 fclose (yyin);
3062 yyin = NULL;
3063 entry->flags.loaded = true;
3065 return true;
3068 if (ldemul_recognized_file (entry))
3069 return true;
3071 /* We don't call ldlang_add_file for an archive. Instead, the
3072 add_symbols entry point will call ldlang_add_file, via the
3073 add_archive_element callback, for each element of the archive
3074 which is used. */
3075 switch (bfd_get_format (entry->the_bfd))
3077 default:
3078 break;
3080 case bfd_object:
3081 if (!entry->flags.reload)
3082 ldlang_add_file (entry);
3083 break;
3085 case bfd_archive:
3086 check_excluded_libs (entry->the_bfd);
3088 bfd_set_usrdata (entry->the_bfd, entry);
3089 if (entry->flags.whole_archive)
3091 bfd *member = NULL;
3092 bool loaded = true;
3094 for (;;)
3096 bfd *subsbfd;
3097 member = bfd_openr_next_archived_file (entry->the_bfd, member);
3099 if (member == NULL)
3100 break;
3102 if (!bfd_check_format (member, bfd_object))
3104 einfo (_("%F%P: %pB: member %pB in archive is not an object\n"),
3105 entry->the_bfd, member);
3106 loaded = false;
3109 subsbfd = member;
3110 if (!(*link_info.callbacks
3111 ->add_archive_element) (&link_info, member,
3112 "--whole-archive", &subsbfd))
3113 abort ();
3115 /* Potentially, the add_archive_element hook may have set a
3116 substitute BFD for us. */
3117 if (!bfd_link_add_symbols (subsbfd, &link_info))
3119 einfo (_("%F%P: %pB: error adding symbols: %E\n"), member);
3120 loaded = false;
3124 entry->flags.loaded = loaded;
3125 return loaded;
3127 break;
3130 if (bfd_link_add_symbols (entry->the_bfd, &link_info))
3131 entry->flags.loaded = true;
3132 else
3133 einfo (_("%F%P: %pB: error adding symbols: %E\n"), entry->the_bfd);
3135 return entry->flags.loaded;
3138 /* Handle a wild statement. S->FILENAME or S->SECTION_LIST or both
3139 may be NULL, indicating that it is a wildcard. Separate
3140 lang_input_section statements are created for each part of the
3141 expansion; they are added after the wild statement S. OUTPUT is
3142 the output section. */
3144 static void
3145 wild (lang_wild_statement_type *s,
3146 const char *target ATTRIBUTE_UNUSED,
3147 lang_output_section_statement_type *output)
3149 struct wildcard_list *sec;
3151 if (s->filenames_sorted || s->any_specs_sorted)
3153 lang_section_bst_type *tree;
3155 walk_wild (s, output_section_callback_sort, output);
3157 tree = s->tree;
3158 if (tree)
3160 output_section_callback_tree_to_list (s, tree, output);
3161 s->tree = NULL;
3162 s->rightmost = &s->tree;
3165 else
3166 walk_wild (s, output_section_callback_nosort, output);
3168 if (default_common_section == NULL)
3169 for (sec = s->section_list; sec != NULL; sec = sec->next)
3170 if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
3172 /* Remember the section that common is going to in case we
3173 later get something which doesn't know where to put it. */
3174 default_common_section = output;
3175 break;
3179 /* Return TRUE iff target is the sought target. */
3181 static int
3182 get_target (const bfd_target *target, void *data)
3184 const char *sought = (const char *) data;
3186 return strcmp (target->name, sought) == 0;
3189 /* Like strcpy() but convert to lower case as well. */
3191 static void
3192 stricpy (char *dest, const char *src)
3194 char c;
3196 while ((c = *src++) != 0)
3197 *dest++ = TOLOWER (c);
3199 *dest = 0;
3202 /* Remove the first occurrence of needle (if any) in haystack
3203 from haystack. */
3205 static void
3206 strcut (char *haystack, const char *needle)
3208 haystack = strstr (haystack, needle);
3210 if (haystack)
3212 char *src;
3214 for (src = haystack + strlen (needle); *src;)
3215 *haystack++ = *src++;
3217 *haystack = 0;
3221 /* Compare two target format name strings.
3222 Return a value indicating how "similar" they are. */
3224 static int
3225 name_compare (const char *first, const char *second)
3227 char *copy1;
3228 char *copy2;
3229 int result;
3231 copy1 = (char *) xmalloc (strlen (first) + 1);
3232 copy2 = (char *) xmalloc (strlen (second) + 1);
3234 /* Convert the names to lower case. */
3235 stricpy (copy1, first);
3236 stricpy (copy2, second);
3238 /* Remove size and endian strings from the name. */
3239 strcut (copy1, "big");
3240 strcut (copy1, "little");
3241 strcut (copy2, "big");
3242 strcut (copy2, "little");
3244 /* Return a value based on how many characters match,
3245 starting from the beginning. If both strings are
3246 the same then return 10 * their length. */
3247 for (result = 0; copy1[result] == copy2[result]; result++)
3248 if (copy1[result] == 0)
3250 result *= 10;
3251 break;
3254 free (copy1);
3255 free (copy2);
3257 return result;
3260 /* Set by closest_target_match() below. */
3261 static const bfd_target *winner;
3263 /* Scan all the valid bfd targets looking for one that has the endianness
3264 requirement that was specified on the command line, and is the nearest
3265 match to the original output target. */
3267 static int
3268 closest_target_match (const bfd_target *target, void *data)
3270 const bfd_target *original = (const bfd_target *) data;
3272 if (command_line.endian == ENDIAN_BIG
3273 && target->byteorder != BFD_ENDIAN_BIG)
3274 return 0;
3276 if (command_line.endian == ENDIAN_LITTLE
3277 && target->byteorder != BFD_ENDIAN_LITTLE)
3278 return 0;
3280 /* Must be the same flavour. */
3281 if (target->flavour != original->flavour)
3282 return 0;
3284 /* Ignore generic big and little endian elf vectors. */
3285 if (strcmp (target->name, "elf32-big") == 0
3286 || strcmp (target->name, "elf64-big") == 0
3287 || strcmp (target->name, "elf32-little") == 0
3288 || strcmp (target->name, "elf64-little") == 0)
3289 return 0;
3291 /* If we have not found a potential winner yet, then record this one. */
3292 if (winner == NULL)
3294 winner = target;
3295 return 0;
3298 /* Oh dear, we now have two potential candidates for a successful match.
3299 Compare their names and choose the better one. */
3300 if (name_compare (target->name, original->name)
3301 > name_compare (winner->name, original->name))
3302 winner = target;
3304 /* Keep on searching until wqe have checked them all. */
3305 return 0;
3308 /* Return the BFD target format of the first input file. */
3310 static const char *
3311 get_first_input_target (void)
3313 const char *target = NULL;
3315 LANG_FOR_EACH_INPUT_STATEMENT (s)
3317 if (s->header.type == lang_input_statement_enum
3318 && s->flags.real)
3320 ldfile_open_file (s);
3322 if (s->the_bfd != NULL
3323 && bfd_check_format (s->the_bfd, bfd_object))
3325 target = bfd_get_target (s->the_bfd);
3327 if (target != NULL)
3328 break;
3333 return target;
3336 const char *
3337 lang_get_output_target (void)
3339 const char *target;
3341 /* Has the user told us which output format to use? */
3342 if (output_target != NULL)
3343 return output_target;
3345 /* No - has the current target been set to something other than
3346 the default? */
3347 if (current_target != default_target && current_target != NULL)
3348 return current_target;
3350 /* No - can we determine the format of the first input file? */
3351 target = get_first_input_target ();
3352 if (target != NULL)
3353 return target;
3355 /* Failed - use the default output target. */
3356 return default_target;
3359 /* Open the output file. */
3361 static void
3362 open_output (const char *name)
3364 lang_input_statement_type *f;
3365 char *out = lrealpath (name);
3367 for (f = (void *) input_file_chain.head;
3368 f != NULL;
3369 f = f->next_real_file)
3370 if (f->flags.real)
3372 char *in = lrealpath (f->local_sym_name);
3373 if (filename_cmp (in, out) == 0)
3374 einfo (_("%F%P: input file '%s' is the same as output file\n"),
3375 f->filename);
3376 free (in);
3378 free (out);
3380 output_target = lang_get_output_target ();
3382 /* Has the user requested a particular endianness on the command
3383 line? */
3384 if (command_line.endian != ENDIAN_UNSET)
3386 /* Get the chosen target. */
3387 const bfd_target *target
3388 = bfd_iterate_over_targets (get_target, (void *) output_target);
3390 /* If the target is not supported, we cannot do anything. */
3391 if (target != NULL)
3393 enum bfd_endian desired_endian;
3395 if (command_line.endian == ENDIAN_BIG)
3396 desired_endian = BFD_ENDIAN_BIG;
3397 else
3398 desired_endian = BFD_ENDIAN_LITTLE;
3400 /* See if the target has the wrong endianness. This should
3401 not happen if the linker script has provided big and
3402 little endian alternatives, but some scrips don't do
3403 this. */
3404 if (target->byteorder != desired_endian)
3406 /* If it does, then see if the target provides
3407 an alternative with the correct endianness. */
3408 if (target->alternative_target != NULL
3409 && (target->alternative_target->byteorder == desired_endian))
3410 output_target = target->alternative_target->name;
3411 else
3413 /* Try to find a target as similar as possible to
3414 the default target, but which has the desired
3415 endian characteristic. */
3416 bfd_iterate_over_targets (closest_target_match,
3417 (void *) target);
3419 /* Oh dear - we could not find any targets that
3420 satisfy our requirements. */
3421 if (winner == NULL)
3422 einfo (_("%P: warning: could not find any targets"
3423 " that match endianness requirement\n"));
3424 else
3425 output_target = winner->name;
3431 link_info.output_bfd = bfd_openw (name, output_target);
3433 if (link_info.output_bfd == NULL)
3435 if (bfd_get_error () == bfd_error_invalid_target)
3436 einfo (_("%F%P: target %s not found\n"), output_target);
3438 einfo (_("%F%P: cannot open output file %s: %E\n"), name);
3441 delete_output_file_on_failure = true;
3443 if (!bfd_set_format (link_info.output_bfd, bfd_object))
3444 einfo (_("%F%P: %s: can not make object file: %E\n"), name);
3445 if (!bfd_set_arch_mach (link_info.output_bfd,
3446 ldfile_output_architecture,
3447 ldfile_output_machine))
3448 einfo (_("%F%P: %s: can not set architecture: %E\n"), name);
3450 link_info.hash = bfd_link_hash_table_create (link_info.output_bfd);
3451 if (link_info.hash == NULL)
3452 einfo (_("%F%P: can not create hash table: %E\n"));
3454 bfd_set_gp_size (link_info.output_bfd, g_switch_value);
3457 static void
3458 ldlang_open_output (lang_statement_union_type *statement)
3460 switch (statement->header.type)
3462 case lang_output_statement_enum:
3463 ASSERT (link_info.output_bfd == NULL);
3464 open_output (statement->output_statement.name);
3465 ldemul_set_output_arch ();
3466 if (config.magic_demand_paged
3467 && !bfd_link_relocatable (&link_info))
3468 link_info.output_bfd->flags |= D_PAGED;
3469 else
3470 link_info.output_bfd->flags &= ~D_PAGED;
3471 if (config.text_read_only)
3472 link_info.output_bfd->flags |= WP_TEXT;
3473 else
3474 link_info.output_bfd->flags &= ~WP_TEXT;
3475 if (link_info.traditional_format)
3476 link_info.output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
3477 else
3478 link_info.output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
3479 if (config.no_section_header)
3480 link_info.output_bfd->flags |= BFD_NO_SECTION_HEADER;
3481 else
3482 link_info.output_bfd->flags &= ~BFD_NO_SECTION_HEADER;
3483 break;
3485 case lang_target_statement_enum:
3486 current_target = statement->target_statement.target;
3487 break;
3488 default:
3489 break;
3493 static void
3494 init_opb (asection *s)
3496 unsigned int x;
3498 opb_shift = 0;
3499 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
3500 && s != NULL
3501 && (s->flags & SEC_ELF_OCTETS) != 0)
3502 return;
3504 x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3505 ldfile_output_machine);
3506 if (x > 1)
3507 while ((x & 1) == 0)
3509 x >>= 1;
3510 ++opb_shift;
3512 ASSERT (x == 1);
3515 /* Open all the input files. */
3517 enum open_bfd_mode
3519 OPEN_BFD_NORMAL = 0,
3520 OPEN_BFD_FORCE = 1,
3521 OPEN_BFD_RESCAN = 2
3523 #if BFD_SUPPORTS_PLUGINS
3524 static lang_input_statement_type *plugin_insert = NULL;
3525 static struct bfd_link_hash_entry *plugin_undefs = NULL;
3526 #endif
3528 static void
3529 open_input_bfds (lang_statement_union_type *s,
3530 lang_output_section_statement_type *os,
3531 enum open_bfd_mode mode)
3533 for (; s != NULL; s = s->header.next)
3535 switch (s->header.type)
3537 case lang_constructors_statement_enum:
3538 open_input_bfds (constructor_list.head, os, mode);
3539 break;
3540 case lang_output_section_statement_enum:
3541 os = &s->output_section_statement;
3542 open_input_bfds (os->children.head, os, mode);
3543 break;
3544 case lang_wild_statement_enum:
3545 /* Maybe we should load the file's symbols. */
3546 if ((mode & OPEN_BFD_RESCAN) == 0
3547 && s->wild_statement.filename
3548 && !wildcardp (s->wild_statement.filename)
3549 && !archive_path (s->wild_statement.filename))
3550 lookup_name (s->wild_statement.filename);
3551 open_input_bfds (s->wild_statement.children.head, os, mode);
3552 break;
3553 case lang_group_statement_enum:
3555 struct bfd_link_hash_entry *undefs;
3556 #if BFD_SUPPORTS_PLUGINS
3557 lang_input_statement_type *plugin_insert_save;
3558 #endif
3560 /* We must continually search the entries in the group
3561 until no new symbols are added to the list of undefined
3562 symbols. */
3566 #if BFD_SUPPORTS_PLUGINS
3567 plugin_insert_save = plugin_insert;
3568 #endif
3569 undefs = link_info.hash->undefs_tail;
3570 open_input_bfds (s->group_statement.children.head, os,
3571 mode | OPEN_BFD_FORCE);
3573 while (undefs != link_info.hash->undefs_tail
3574 #if BFD_SUPPORTS_PLUGINS
3575 /* Objects inserted by a plugin, which are loaded
3576 before we hit this loop, may have added new
3577 undefs. */
3578 || (plugin_insert != plugin_insert_save && plugin_undefs)
3579 #endif
3582 break;
3583 case lang_target_statement_enum:
3584 current_target = s->target_statement.target;
3585 break;
3586 case lang_input_statement_enum:
3587 if (s->input_statement.flags.real)
3589 lang_statement_union_type **os_tail;
3590 lang_statement_list_type add;
3591 bfd *abfd;
3593 s->input_statement.target = current_target;
3595 /* If we are being called from within a group, and this
3596 is an archive which has already been searched, then
3597 force it to be researched unless the whole archive
3598 has been loaded already. Do the same for a rescan.
3599 Likewise reload --as-needed shared libs. */
3600 if (mode != OPEN_BFD_NORMAL
3601 #if BFD_SUPPORTS_PLUGINS
3602 && ((mode & OPEN_BFD_RESCAN) == 0
3603 || plugin_insert == NULL)
3604 #endif
3605 && s->input_statement.flags.loaded
3606 && (abfd = s->input_statement.the_bfd) != NULL
3607 && ((bfd_get_format (abfd) == bfd_archive
3608 && !s->input_statement.flags.whole_archive)
3609 || (bfd_get_format (abfd) == bfd_object
3610 && ((abfd->flags) & DYNAMIC) != 0
3611 && s->input_statement.flags.add_DT_NEEDED_for_regular
3612 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
3613 && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)))
3615 s->input_statement.flags.loaded = false;
3616 s->input_statement.flags.reload = true;
3619 os_tail = lang_os_list.tail;
3620 lang_list_init (&add);
3622 if (!load_symbols (&s->input_statement, &add))
3623 config.make_executable = false;
3625 if (add.head != NULL)
3627 /* If this was a script with output sections then
3628 tack any added statements on to the end of the
3629 list. This avoids having to reorder the output
3630 section statement list. Very likely the user
3631 forgot -T, and whatever we do here will not meet
3632 naive user expectations. */
3633 if (os_tail != lang_os_list.tail)
3635 einfo (_("%P: warning: %s contains output sections;"
3636 " did you forget -T?\n"),
3637 s->input_statement.filename);
3638 *stat_ptr->tail = add.head;
3639 stat_ptr->tail = add.tail;
3641 else
3643 *add.tail = s->header.next;
3644 s->header.next = add.head;
3648 #if BFD_SUPPORTS_PLUGINS
3649 /* If we have found the point at which a plugin added new
3650 files, clear plugin_insert to enable archive rescan. */
3651 if (&s->input_statement == plugin_insert)
3652 plugin_insert = NULL;
3653 #endif
3654 break;
3655 case lang_assignment_statement_enum:
3656 if (s->assignment_statement.exp->type.node_class != etree_assert)
3657 exp_fold_tree_no_dot (s->assignment_statement.exp, os);
3658 break;
3659 default:
3660 break;
3664 /* Exit if any of the files were missing. */
3665 if (input_flags.missing_file)
3666 einfo ("%F");
3669 #ifdef ENABLE_LIBCTF
3670 /* Emit CTF errors and warnings. fp can be NULL to report errors/warnings
3671 that happened specifically at CTF open time. */
3672 static void
3673 lang_ctf_errs_warnings (ctf_dict_t *fp)
3675 ctf_next_t *i = NULL;
3676 char *text;
3677 int is_warning;
3678 int err;
3680 while ((text = ctf_errwarning_next (fp, &i, &is_warning, &err)) != NULL)
3682 einfo (_("%s: %s\n"), is_warning ? _("CTF warning"): _("CTF error"),
3683 text);
3684 free (text);
3686 if (err != ECTF_NEXT_END)
3688 einfo (_("CTF error: cannot get CTF errors: `%s'\n"),
3689 ctf_errmsg (err));
3692 /* `err' returns errors from the error/warning iterator in particular.
3693 These never assert. But if we have an fp, that could have recorded
3694 an assertion failure: assert if it has done so. */
3695 ASSERT (!fp || ctf_errno (fp) != ECTF_INTERNAL);
3698 /* Open the CTF sections in the input files with libctf: if any were opened,
3699 create a fake input file that we'll write the merged CTF data to later
3700 on. */
3702 static void
3703 ldlang_open_ctf (void)
3705 int any_ctf = 0;
3706 int err;
3708 LANG_FOR_EACH_INPUT_STATEMENT (file)
3710 asection *sect;
3712 /* Incoming files from the compiler have a single ctf_dict_t in them
3713 (which is presented to us by the libctf API in a ctf_archive_t
3714 wrapper): files derived from a previous relocatable link have a CTF
3715 archive containing possibly many CTF files. */
3717 if ((file->the_ctf = ctf_bfdopen (file->the_bfd, &err)) == NULL)
3719 if (err != ECTF_NOCTFDATA)
3721 lang_ctf_errs_warnings (NULL);
3722 einfo (_("%P: warning: CTF section in %pB not loaded; "
3723 "its types will be discarded: %s\n"), file->the_bfd,
3724 ctf_errmsg (err));
3726 continue;
3729 /* Prevent the contents of this section from being written, while
3730 requiring the section itself to be duplicated in the output, but only
3731 once. */
3732 /* This section must exist if ctf_bfdopen() succeeded. */
3733 sect = bfd_get_section_by_name (file->the_bfd, ".ctf");
3734 sect->size = 0;
3735 sect->flags |= SEC_NEVER_LOAD | SEC_HAS_CONTENTS | SEC_LINKER_CREATED;
3737 if (any_ctf)
3738 sect->flags |= SEC_EXCLUDE;
3739 any_ctf = 1;
3742 if (!any_ctf)
3744 ctf_output = NULL;
3745 return;
3748 if ((ctf_output = ctf_create (&err)) != NULL)
3749 return;
3751 einfo (_("%P: warning: CTF output not created: `%s'\n"),
3752 ctf_errmsg (err));
3754 LANG_FOR_EACH_INPUT_STATEMENT (errfile)
3755 ctf_close (errfile->the_ctf);
3758 /* Merge together CTF sections. After this, only the symtab-dependent
3759 function and data object sections need adjustment. */
3761 static void
3762 lang_merge_ctf (void)
3764 asection *output_sect;
3765 int flags = 0;
3767 if (!ctf_output)
3768 return;
3770 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3772 /* If the section was discarded, don't waste time merging. */
3773 if (output_sect == NULL)
3775 ctf_dict_close (ctf_output);
3776 ctf_output = NULL;
3778 LANG_FOR_EACH_INPUT_STATEMENT (file)
3780 ctf_close (file->the_ctf);
3781 file->the_ctf = NULL;
3783 return;
3786 LANG_FOR_EACH_INPUT_STATEMENT (file)
3788 if (!file->the_ctf)
3789 continue;
3791 /* Takes ownership of file->the_ctf. */
3792 if (ctf_link_add_ctf (ctf_output, file->the_ctf, file->filename) < 0)
3794 einfo (_("%P: warning: CTF section in %pB cannot be linked: `%s'\n"),
3795 file->the_bfd, ctf_errmsg (ctf_errno (ctf_output)));
3796 ctf_close (file->the_ctf);
3797 file->the_ctf = NULL;
3798 continue;
3802 if (!config.ctf_share_duplicated)
3803 flags = CTF_LINK_SHARE_UNCONFLICTED;
3804 else
3805 flags = CTF_LINK_SHARE_DUPLICATED;
3806 if (!config.ctf_variables)
3807 flags |= CTF_LINK_OMIT_VARIABLES_SECTION;
3808 if (bfd_link_relocatable (&link_info))
3809 flags |= CTF_LINK_NO_FILTER_REPORTED_SYMS;
3811 if (ctf_link (ctf_output, flags) < 0)
3813 lang_ctf_errs_warnings (ctf_output);
3814 einfo (_("%P: warning: CTF linking failed; "
3815 "output will have no CTF section: %s\n"),
3816 ctf_errmsg (ctf_errno (ctf_output)));
3817 if (output_sect)
3819 output_sect->size = 0;
3820 output_sect->flags |= SEC_EXCLUDE;
3823 /* Output any lingering errors that didn't come from ctf_link. */
3824 lang_ctf_errs_warnings (ctf_output);
3827 /* Let the emulation acquire strings from the dynamic strtab to help it optimize
3828 the CTF, if supported. */
3830 void
3831 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab)
3833 ldemul_acquire_strings_for_ctf (ctf_output, dynstrtab);
3836 /* Inform the emulation about the addition of a new dynamic symbol, in BFD
3837 internal format. */
3838 void ldlang_ctf_new_dynsym (int symidx, struct elf_internal_sym *sym)
3840 ldemul_new_dynsym_for_ctf (ctf_output, symidx, sym);
3843 /* Write out the CTF section. Called early, if the emulation isn't going to
3844 need to dedup against the strtab and symtab, then possibly called from the
3845 target linker code if the dedup has happened. */
3846 static void
3847 lang_write_ctf (int late)
3849 size_t output_size;
3850 asection *output_sect;
3852 if (!ctf_output)
3853 return;
3855 if (late)
3857 /* Emit CTF late if this emulation says it can do so. */
3858 if (ldemul_emit_ctf_early ())
3859 return;
3861 else
3863 if (!ldemul_emit_ctf_early ())
3864 return;
3867 /* Inform the emulation that all the symbols that will be received have
3868 been. */
3870 ldemul_new_dynsym_for_ctf (ctf_output, 0, NULL);
3872 /* Emit CTF. */
3874 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3875 if (output_sect)
3877 output_sect->contents = ctf_link_write (ctf_output, &output_size,
3878 CTF_COMPRESSION_THRESHOLD);
3879 output_sect->size = output_size;
3880 output_sect->flags |= SEC_IN_MEMORY | SEC_KEEP;
3882 lang_ctf_errs_warnings (ctf_output);
3883 if (!output_sect->contents)
3885 einfo (_("%P: warning: CTF section emission failed; "
3886 "output will have no CTF section: %s\n"),
3887 ctf_errmsg (ctf_errno (ctf_output)));
3888 output_sect->size = 0;
3889 output_sect->flags |= SEC_EXCLUDE;
3893 /* This also closes every CTF input file used in the link. */
3894 ctf_dict_close (ctf_output);
3895 ctf_output = NULL;
3897 LANG_FOR_EACH_INPUT_STATEMENT (file)
3898 file->the_ctf = NULL;
3901 /* Write out the CTF section late, if the emulation needs that. */
3903 void
3904 ldlang_write_ctf_late (void)
3906 /* Trigger a "late call", if the emulation needs one. */
3908 lang_write_ctf (1);
3910 #else
3911 static void
3912 ldlang_open_ctf (void)
3914 LANG_FOR_EACH_INPUT_STATEMENT (file)
3916 asection *sect;
3918 /* If built without CTF, warn and delete all CTF sections from the output.
3919 (The alternative would be to simply concatenate them, which does not
3920 yield a valid CTF section.) */
3922 if ((sect = bfd_get_section_by_name (file->the_bfd, ".ctf")) != NULL)
3924 einfo (_("%P: warning: CTF section in %pB not linkable: "
3925 "%P was built without support for CTF\n"), file->the_bfd);
3926 sect->size = 0;
3927 sect->flags |= SEC_EXCLUDE;
3932 static void lang_merge_ctf (void) {}
3933 void
3934 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab
3935 ATTRIBUTE_UNUSED) {}
3936 void
3937 ldlang_ctf_new_dynsym (int symidx ATTRIBUTE_UNUSED,
3938 struct elf_internal_sym *sym ATTRIBUTE_UNUSED) {}
3939 static void lang_write_ctf (int late ATTRIBUTE_UNUSED) {}
3940 void ldlang_write_ctf_late (void) {}
3941 #endif
3943 /* Add the supplied name to the symbol table as an undefined reference.
3944 This is a two step process as the symbol table doesn't even exist at
3945 the time the ld command line is processed. First we put the name
3946 on a list, then, once the output file has been opened, transfer the
3947 name to the symbol table. */
3949 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
3951 #define ldlang_undef_chain_list_head entry_symbol.next
3953 void
3954 ldlang_add_undef (const char *const name, bool cmdline ATTRIBUTE_UNUSED)
3956 ldlang_undef_chain_list_type *new_undef;
3958 new_undef = stat_alloc (sizeof (*new_undef));
3959 new_undef->next = ldlang_undef_chain_list_head;
3960 ldlang_undef_chain_list_head = new_undef;
3962 new_undef->name = xstrdup (name);
3964 if (link_info.output_bfd != NULL)
3965 insert_undefined (new_undef->name);
3968 /* Insert NAME as undefined in the symbol table. */
3970 static void
3971 insert_undefined (const char *name)
3973 struct bfd_link_hash_entry *h;
3975 h = bfd_link_hash_lookup (link_info.hash, name, true, false, true);
3976 if (h == NULL)
3977 einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
3978 if (h->type == bfd_link_hash_new)
3980 h->type = bfd_link_hash_undefined;
3981 h->u.undef.abfd = NULL;
3982 h->non_ir_ref_regular = true;
3983 bfd_link_add_undef (link_info.hash, h);
3987 /* Run through the list of undefineds created above and place them
3988 into the linker hash table as undefined symbols belonging to the
3989 script file. */
3991 static void
3992 lang_place_undefineds (void)
3994 ldlang_undef_chain_list_type *ptr;
3996 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
3997 insert_undefined (ptr->name);
4000 /* Mark -u symbols against garbage collection. */
4002 static void
4003 lang_mark_undefineds (void)
4005 ldlang_undef_chain_list_type *ptr;
4007 if (is_elf_hash_table (link_info.hash))
4008 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
4010 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
4011 bfd_link_hash_lookup (link_info.hash, ptr->name, false, false, true);
4012 if (h != NULL)
4013 h->mark = 1;
4017 /* Structure used to build the list of symbols that the user has required
4018 be defined. */
4020 struct require_defined_symbol
4022 const char *name;
4023 struct require_defined_symbol *next;
4026 /* The list of symbols that the user has required be defined. */
4028 static struct require_defined_symbol *require_defined_symbol_list;
4030 /* Add a new symbol NAME to the list of symbols that are required to be
4031 defined. */
4033 void
4034 ldlang_add_require_defined (const char *const name)
4036 struct require_defined_symbol *ptr;
4038 ldlang_add_undef (name, true);
4039 ptr = stat_alloc (sizeof (*ptr));
4040 ptr->next = require_defined_symbol_list;
4041 ptr->name = strdup (name);
4042 require_defined_symbol_list = ptr;
4045 /* Check that all symbols the user required to be defined, are defined,
4046 raise an error if we find a symbol that is not defined. */
4048 static void
4049 ldlang_check_require_defined_symbols (void)
4051 struct require_defined_symbol *ptr;
4053 for (ptr = require_defined_symbol_list; ptr != NULL; ptr = ptr->next)
4055 struct bfd_link_hash_entry *h;
4057 h = bfd_link_hash_lookup (link_info.hash, ptr->name,
4058 false, false, true);
4059 if (h == NULL
4060 || (h->type != bfd_link_hash_defined
4061 && h->type != bfd_link_hash_defweak))
4062 einfo(_("%X%P: required symbol `%s' not defined\n"), ptr->name);
4066 /* Check for all readonly or some readwrite sections. */
4068 static void
4069 check_input_sections
4070 (lang_statement_union_type *s,
4071 lang_output_section_statement_type *output_section_statement)
4073 for (; s != NULL; s = s->header.next)
4075 switch (s->header.type)
4077 case lang_wild_statement_enum:
4078 walk_wild (&s->wild_statement, check_section_callback,
4079 output_section_statement);
4080 if (!output_section_statement->all_input_readonly)
4081 return;
4082 break;
4083 case lang_constructors_statement_enum:
4084 check_input_sections (constructor_list.head,
4085 output_section_statement);
4086 if (!output_section_statement->all_input_readonly)
4087 return;
4088 break;
4089 case lang_group_statement_enum:
4090 check_input_sections (s->group_statement.children.head,
4091 output_section_statement);
4092 if (!output_section_statement->all_input_readonly)
4093 return;
4094 break;
4095 default:
4096 break;
4101 /* Update wildcard statements if needed. */
4103 static void
4104 update_wild_statements (lang_statement_union_type *s)
4106 struct wildcard_list *sec;
4108 switch (sort_section)
4110 default:
4111 FAIL ();
4113 case none:
4114 break;
4116 case by_name:
4117 case by_alignment:
4118 for (; s != NULL; s = s->header.next)
4120 switch (s->header.type)
4122 default:
4123 break;
4125 case lang_wild_statement_enum:
4126 for (sec = s->wild_statement.section_list; sec != NULL;
4127 sec = sec->next)
4128 /* Don't sort .init/.fini sections. */
4129 if (strcmp (sec->spec.name, ".init") != 0
4130 && strcmp (sec->spec.name, ".fini") != 0)
4132 switch (sec->spec.sorted)
4134 case none:
4135 sec->spec.sorted = sort_section;
4136 break;
4137 case by_name:
4138 if (sort_section == by_alignment)
4139 sec->spec.sorted = by_name_alignment;
4140 break;
4141 case by_alignment:
4142 if (sort_section == by_name)
4143 sec->spec.sorted = by_alignment_name;
4144 break;
4145 default:
4146 break;
4148 s->wild_statement.any_specs_sorted = true;
4150 break;
4152 case lang_constructors_statement_enum:
4153 update_wild_statements (constructor_list.head);
4154 break;
4156 case lang_output_section_statement_enum:
4157 update_wild_statements
4158 (s->output_section_statement.children.head);
4159 break;
4161 case lang_group_statement_enum:
4162 update_wild_statements (s->group_statement.children.head);
4163 break;
4166 break;
4170 /* Open input files and attach to output sections. */
4172 static void
4173 map_input_to_output_sections
4174 (lang_statement_union_type *s, const char *target,
4175 lang_output_section_statement_type *os)
4177 for (; s != NULL; s = s->header.next)
4179 lang_output_section_statement_type *tos;
4180 flagword flags;
4181 unsigned int type = 0;
4183 switch (s->header.type)
4185 case lang_wild_statement_enum:
4186 wild (&s->wild_statement, target, os);
4187 break;
4188 case lang_constructors_statement_enum:
4189 map_input_to_output_sections (constructor_list.head,
4190 target,
4191 os);
4192 break;
4193 case lang_output_section_statement_enum:
4194 tos = &s->output_section_statement;
4195 if (tos->constraint == ONLY_IF_RW
4196 || tos->constraint == ONLY_IF_RO)
4198 tos->all_input_readonly = true;
4199 check_input_sections (tos->children.head, tos);
4200 if (tos->all_input_readonly != (tos->constraint == ONLY_IF_RO))
4201 tos->constraint = -1;
4203 if (tos->constraint >= 0)
4204 map_input_to_output_sections (tos->children.head,
4205 target,
4206 tos);
4207 break;
4208 case lang_output_statement_enum:
4209 break;
4210 case lang_target_statement_enum:
4211 target = s->target_statement.target;
4212 break;
4213 case lang_group_statement_enum:
4214 map_input_to_output_sections (s->group_statement.children.head,
4215 target,
4216 os);
4217 break;
4218 case lang_data_statement_enum:
4219 if (os == NULL)
4220 /* This should never happen. */
4221 FAIL ();
4222 /* Make sure that any sections mentioned in the expression
4223 are initialized. */
4224 exp_init_os (s->data_statement.exp);
4225 /* The output section gets CONTENTS, ALLOC and LOAD, but
4226 these may be overridden by the script. */
4227 flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD;
4228 switch (os->sectype)
4230 case normal_section:
4231 case overlay_section:
4232 case first_overlay_section:
4233 break;
4234 case noalloc_section:
4235 flags = SEC_HAS_CONTENTS;
4236 break;
4237 case readonly_section:
4238 flags |= SEC_READONLY;
4239 break;
4240 case typed_readonly_section:
4241 flags |= SEC_READONLY;
4242 /* Fall through. */
4243 case type_section:
4244 if (os->sectype_value->type.node_class == etree_name
4245 && os->sectype_value->type.node_code == NAME)
4247 const char *name = os->sectype_value->name.name;
4248 if (strcmp (name, "SHT_PROGBITS") == 0)
4249 type = SHT_PROGBITS;
4250 else if (strcmp (name, "SHT_STRTAB") == 0)
4251 type = SHT_STRTAB;
4252 else if (strcmp (name, "SHT_NOTE") == 0)
4253 type = SHT_NOTE;
4254 else if (strcmp (name, "SHT_NOBITS") == 0)
4255 type = SHT_NOBITS;
4256 else if (strcmp (name, "SHT_INIT_ARRAY") == 0)
4257 type = SHT_INIT_ARRAY;
4258 else if (strcmp (name, "SHT_FINI_ARRAY") == 0)
4259 type = SHT_FINI_ARRAY;
4260 else if (strcmp (name, "SHT_PREINIT_ARRAY") == 0)
4261 type = SHT_PREINIT_ARRAY;
4262 else
4263 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4264 os->name);
4266 else
4268 exp_fold_tree_no_dot (os->sectype_value, os);
4269 if (expld.result.valid_p)
4270 type = expld.result.value;
4271 else
4272 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4273 os->name);
4275 break;
4276 case noload_section:
4277 if (bfd_get_flavour (link_info.output_bfd)
4278 == bfd_target_elf_flavour)
4279 flags = SEC_NEVER_LOAD | SEC_ALLOC;
4280 else
4281 flags = SEC_NEVER_LOAD | SEC_HAS_CONTENTS;
4282 break;
4284 if (os->bfd_section == NULL)
4285 init_os (os, flags | SEC_READONLY);
4286 else
4287 os->bfd_section->flags |= flags;
4288 os->bfd_section->type = type;
4289 break;
4290 case lang_input_section_enum:
4291 break;
4292 case lang_fill_statement_enum:
4293 case lang_object_symbols_statement_enum:
4294 case lang_reloc_statement_enum:
4295 case lang_padding_statement_enum:
4296 case lang_input_statement_enum:
4297 if (os != NULL && os->bfd_section == NULL)
4298 init_os (os, 0);
4299 break;
4301 case lang_assignment_statement_enum:
4302 if (os != NULL && os->bfd_section == NULL)
4303 init_os (os, get_os_init_flag (os));
4305 /* Make sure that any sections mentioned in the assignment
4306 are initialized. */
4307 exp_init_os (s->assignment_statement.exp);
4308 break;
4310 case lang_address_statement_enum:
4311 /* Mark the specified section with the supplied address.
4312 If this section was actually a segment marker, then the
4313 directive is ignored if the linker script explicitly
4314 processed the segment marker. Originally, the linker
4315 treated segment directives (like -Ttext on the
4316 command-line) as section directives. We honor the
4317 section directive semantics for backwards compatibility;
4318 linker scripts that do not specifically check for
4319 SEGMENT_START automatically get the old semantics. */
4320 if (!s->address_statement.segment
4321 || !s->address_statement.segment->used)
4323 const char *name = s->address_statement.section_name;
4325 /* Create the output section statement here so that
4326 orphans with a set address will be placed after other
4327 script sections. If we let the orphan placement code
4328 place them in amongst other sections then the address
4329 will affect following script sections, which is
4330 likely to surprise naive users. */
4331 tos = lang_output_section_statement_lookup (name, 0, 1);
4332 tos->addr_tree = s->address_statement.address;
4333 if (tos->bfd_section == NULL)
4334 init_os (tos, 0);
4336 break;
4337 case lang_insert_statement_enum:
4338 break;
4339 case lang_input_matcher_enum:
4340 FAIL ();
4345 /* An insert statement snips out all the linker statements from the
4346 start of the list and places them after the output section
4347 statement specified by the insert. This operation is complicated
4348 by the fact that we keep a doubly linked list of output section
4349 statements as well as the singly linked list of all statements.
4350 FIXME someday: Twiddling with the list not only moves statements
4351 from the user's script but also input and group statements that are
4352 built from command line object files and --start-group. We only
4353 get away with this because the list pointers used by file_chain
4354 and input_file_chain are not reordered, and processing via
4355 statement_list after this point mostly ignores input statements.
4356 One exception is the map file, where LOAD and START GROUP/END GROUP
4357 can end up looking odd. */
4359 static void
4360 process_insert_statements (lang_statement_union_type **start)
4362 lang_statement_union_type **s;
4363 lang_output_section_statement_type *first_os = NULL;
4364 lang_output_section_statement_type *last_os = NULL;
4365 lang_output_section_statement_type *os;
4367 s = start;
4368 while (*s != NULL)
4370 if ((*s)->header.type == lang_output_section_statement_enum)
4372 /* Keep pointers to the first and last output section
4373 statement in the sequence we may be about to move. */
4374 os = &(*s)->output_section_statement;
4376 ASSERT (last_os == NULL || last_os->next == os);
4377 last_os = os;
4379 /* Set constraint negative so that lang_output_section_find
4380 won't match this output section statement. At this
4381 stage in linking constraint has values in the range
4382 [-1, ONLY_IN_RW]. */
4383 last_os->constraint = -2 - last_os->constraint;
4384 if (first_os == NULL)
4385 first_os = last_os;
4387 else if ((*s)->header.type == lang_group_statement_enum)
4389 /* A user might put -T between --start-group and
4390 --end-group. One way this odd construct might arise is
4391 from a wrapper around ld to change library search
4392 behaviour. For example:
4393 #! /bin/sh
4394 exec real_ld --start-group "$@" --end-group
4395 This isn't completely unreasonable so go looking inside a
4396 group statement for insert statements. */
4397 process_insert_statements (&(*s)->group_statement.children.head);
4399 else if ((*s)->header.type == lang_insert_statement_enum)
4401 lang_insert_statement_type *i = &(*s)->insert_statement;
4402 lang_output_section_statement_type *where;
4403 lang_statement_union_type **ptr;
4404 lang_statement_union_type *first;
4406 if (link_info.non_contiguous_regions)
4408 einfo (_("warning: INSERT statement in linker script is "
4409 "incompatible with --enable-non-contiguous-regions.\n"));
4412 where = lang_output_section_find (i->where);
4413 if (where != NULL && i->is_before)
4416 where = where->prev;
4417 while (where != NULL && where->constraint < 0);
4419 if (where == NULL)
4421 einfo (_("%F%P: %s not found for insert\n"), i->where);
4422 return;
4425 /* Deal with reordering the output section statement list. */
4426 if (last_os != NULL)
4428 asection *first_sec, *last_sec;
4429 struct lang_output_section_statement_struct **next;
4431 /* Snip out the output sections we are moving. */
4432 first_os->prev->next = last_os->next;
4433 if (last_os->next == NULL)
4435 next = &first_os->prev->next;
4436 lang_os_list.tail = (lang_statement_union_type **) next;
4438 else
4439 last_os->next->prev = first_os->prev;
4440 /* Add them in at the new position. */
4441 last_os->next = where->next;
4442 if (where->next == NULL)
4444 next = &last_os->next;
4445 lang_os_list.tail = (lang_statement_union_type **) next;
4447 else
4448 where->next->prev = last_os;
4449 first_os->prev = where;
4450 where->next = first_os;
4452 /* Move the bfd sections in the same way. */
4453 first_sec = NULL;
4454 last_sec = NULL;
4455 for (os = first_os; os != NULL; os = os->next)
4457 os->constraint = -2 - os->constraint;
4458 if (os->bfd_section != NULL
4459 && os->bfd_section->owner != NULL)
4461 last_sec = os->bfd_section;
4462 if (first_sec == NULL)
4463 first_sec = last_sec;
4465 if (os == last_os)
4466 break;
4468 if (last_sec != NULL)
4470 asection *sec = where->bfd_section;
4471 if (sec == NULL)
4472 sec = output_prev_sec_find (where);
4474 /* The place we want to insert must come after the
4475 sections we are moving. So if we find no
4476 section or if the section is the same as our
4477 last section, then no move is needed. */
4478 if (sec != NULL && sec != last_sec)
4480 /* Trim them off. */
4481 if (first_sec->prev != NULL)
4482 first_sec->prev->next = last_sec->next;
4483 else
4484 link_info.output_bfd->sections = last_sec->next;
4485 if (last_sec->next != NULL)
4486 last_sec->next->prev = first_sec->prev;
4487 else
4488 link_info.output_bfd->section_last = first_sec->prev;
4489 /* Add back. */
4490 if (sec->owner == NULL)
4491 /* SEC is the absolute section, from the
4492 first dummy output section statement. Add
4493 back the sections we trimmed off to the
4494 start of the bfd sections. */
4495 sec = NULL;
4496 if (sec != NULL)
4497 last_sec->next = sec->next;
4498 else
4499 last_sec->next = link_info.output_bfd->sections;
4500 if (last_sec->next != NULL)
4501 last_sec->next->prev = last_sec;
4502 else
4503 link_info.output_bfd->section_last = last_sec;
4504 first_sec->prev = sec;
4505 if (first_sec->prev != NULL)
4506 first_sec->prev->next = first_sec;
4507 else
4508 link_info.output_bfd->sections = first_sec;
4513 lang_statement_union_type *after = (void *) where;
4514 if (where == &lang_os_list.head->output_section_statement
4515 && where->next == first_os)
4517 /* PR30155. Handle a corner case where the statement
4518 list is something like the following:
4519 . LOAD t.o
4520 . .data 0x0000000000000000 0x0
4521 . [0x0000000000000000] b = .
4522 . *(.data)
4523 . .data 0x0000000000000000 0x0 t.o
4524 . 0x0000000000000000 0x4 LONG 0x0
4525 . INSERT BEFORE .text.start
4526 . [0x0000000000000004] a = .
4527 . .text.start 0x0000000000000000 0x0
4528 . [0x0000000000000000] c = .
4529 . OUTPUT(a.out elf64-x86-64)
4530 Here we do not want to allow insert_os_after to
4531 choose a point inside the list we are moving.
4532 That would lose the list. Instead, let
4533 insert_os_after work from the INSERT, which in this
4534 particular example will result in inserting after
4535 the assignment "a = .". */
4536 after = *s;
4538 ptr = insert_os_after (after);
4539 /* Snip everything from the start of the list, up to and
4540 including the insert statement we are currently processing. */
4541 first = *start;
4542 *start = (*s)->header.next;
4543 /* Add them back where they belong, minus the insert. */
4544 *s = *ptr;
4545 if (*s == NULL)
4546 statement_list.tail = s;
4547 *ptr = first;
4548 s = start;
4549 first_os = NULL;
4550 last_os = NULL;
4551 continue;
4553 s = &(*s)->header.next;
4556 /* Undo constraint twiddling. */
4557 for (os = first_os; os != NULL; os = os->next)
4559 os->constraint = -2 - os->constraint;
4560 if (os == last_os)
4561 break;
4565 /* An output section might have been removed after its statement was
4566 added. For example, ldemul_before_allocation can remove dynamic
4567 sections if they turn out to be not needed. Clean them up here. */
4569 void
4570 strip_excluded_output_sections (void)
4572 lang_output_section_statement_type *os;
4574 /* Run lang_size_sections (if not already done). */
4575 if (expld.phase != lang_mark_phase_enum)
4577 expld.phase = lang_mark_phase_enum;
4578 expld.dataseg.phase = exp_seg_none;
4579 one_lang_size_sections_pass (NULL, false);
4580 lang_reset_memory_regions ();
4583 for (os = (void *) lang_os_list.head;
4584 os != NULL;
4585 os = os->next)
4587 asection *output_section;
4588 bool exclude;
4590 if (os->constraint < 0)
4591 continue;
4593 output_section = os->bfd_section;
4594 if (output_section == NULL)
4595 continue;
4597 exclude = (output_section->rawsize == 0
4598 && (output_section->flags & SEC_KEEP) == 0
4599 && !bfd_section_removed_from_list (link_info.output_bfd,
4600 output_section));
4602 /* Some sections have not yet been sized, notably .gnu.version,
4603 .dynsym, .dynstr and .hash. These all have SEC_LINKER_CREATED
4604 input sections, so don't drop output sections that have such
4605 input sections unless they are also marked SEC_EXCLUDE. */
4606 if (exclude && output_section->map_head.s != NULL)
4608 asection *s;
4610 for (s = output_section->map_head.s; s != NULL; s = s->map_head.s)
4611 if ((s->flags & SEC_EXCLUDE) == 0
4612 && ((s->flags & SEC_LINKER_CREATED) != 0
4613 || link_info.emitrelocations))
4615 exclude = false;
4616 break;
4620 if (exclude)
4622 /* We don't set bfd_section to NULL since bfd_section of the
4623 removed output section statement may still be used. */
4624 if (!os->update_dot)
4625 os->ignored = true;
4626 output_section->flags |= SEC_EXCLUDE;
4627 bfd_section_list_remove (link_info.output_bfd, output_section);
4628 link_info.output_bfd->section_count--;
4633 /* Called from ldwrite to clear out asection.map_head and
4634 asection.map_tail for use as link_orders in ldwrite. */
4636 void
4637 lang_clear_os_map (void)
4639 lang_output_section_statement_type *os;
4641 if (map_head_is_link_order)
4642 return;
4644 for (os = (void *) lang_os_list.head;
4645 os != NULL;
4646 os = os->next)
4648 asection *output_section;
4650 if (os->constraint < 0)
4651 continue;
4653 output_section = os->bfd_section;
4654 if (output_section == NULL)
4655 continue;
4657 /* TODO: Don't just junk map_head.s, turn them into link_orders. */
4658 output_section->map_head.link_order = NULL;
4659 output_section->map_tail.link_order = NULL;
4662 /* Stop future calls to lang_add_section from messing with map_head
4663 and map_tail link_order fields. */
4664 map_head_is_link_order = true;
4667 static void
4668 print_output_section_statement
4669 (lang_output_section_statement_type *output_section_statement)
4671 asection *section = output_section_statement->bfd_section;
4672 int len;
4674 if (output_section_statement != abs_output_section)
4676 minfo ("\n%s", output_section_statement->name);
4678 if (section != NULL)
4680 print_dot = section->vma;
4682 len = strlen (output_section_statement->name);
4683 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4685 print_nl ();
4686 len = 0;
4688 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4690 minfo ("0x%V %W", section->vma, TO_ADDR (section->size));
4692 if (section->vma != section->lma)
4693 minfo (_(" load address 0x%V"), section->lma);
4695 if (output_section_statement->update_dot_tree != NULL)
4696 exp_fold_tree (output_section_statement->update_dot_tree,
4697 output_section_statement,
4698 bfd_abs_section_ptr, &print_dot);
4701 print_nl ();
4704 print_statement_list (output_section_statement->children.head,
4705 output_section_statement);
4708 static void
4709 print_assignment (lang_assignment_statement_type *assignment,
4710 lang_output_section_statement_type *output_section)
4712 bool is_dot;
4713 etree_type *tree;
4714 asection *osec;
4716 print_spaces (SECTION_NAME_MAP_LENGTH);
4718 if (assignment->exp->type.node_class == etree_assert)
4720 is_dot = false;
4721 tree = assignment->exp->assert_s.child;
4723 else
4725 const char *dst = assignment->exp->assign.dst;
4727 is_dot = (dst[0] == '.' && dst[1] == 0);
4728 tree = assignment->exp;
4731 osec = output_section->bfd_section;
4732 if (osec == NULL)
4733 osec = bfd_abs_section_ptr;
4735 if (assignment->exp->type.node_class != etree_provide)
4736 exp_fold_tree (tree, output_section, osec, &print_dot);
4737 else
4738 expld.result.valid_p = false;
4740 char buf[32];
4741 const char *str = buf;
4742 if (expld.result.valid_p)
4744 bfd_vma value;
4746 if (assignment->exp->type.node_class == etree_assert
4747 || is_dot
4748 || expld.assign_name != NULL)
4750 value = expld.result.value;
4752 if (expld.result.section != NULL)
4753 value += expld.result.section->vma;
4755 buf[0] = '0';
4756 buf[1] = 'x';
4757 bfd_sprintf_vma (link_info.output_bfd, buf + 2, value);
4758 if (is_dot)
4759 print_dot = value;
4761 else
4763 struct bfd_link_hash_entry *h;
4765 h = bfd_link_hash_lookup (link_info.hash, assignment->exp->assign.dst,
4766 false, false, true);
4767 if (h != NULL
4768 && (h->type == bfd_link_hash_defined
4769 || h->type == bfd_link_hash_defweak))
4771 value = h->u.def.value;
4772 value += h->u.def.section->output_section->vma;
4773 value += h->u.def.section->output_offset;
4775 buf[0] = '[';
4776 buf[1] = '0';
4777 buf[2] = 'x';
4778 bfd_sprintf_vma (link_info.output_bfd, buf + 3, value);
4779 strcat (buf, "]");
4781 else
4782 str = "[unresolved]";
4785 else
4787 if (assignment->exp->type.node_class == etree_provide)
4788 str = "[!provide]";
4789 else
4790 str = "*undef*";
4792 expld.assign_name = NULL;
4794 fprintf (config.map_file, "%-34s", str);
4795 exp_print_tree (assignment->exp);
4796 print_nl ();
4799 static void
4800 print_input_statement (lang_input_statement_type *statm)
4802 if (statm->filename != NULL)
4803 fprintf (config.map_file, "LOAD %s\n", statm->filename);
4806 /* Print all symbols defined in a particular section. This is called
4807 via bfd_link_hash_traverse, or by print_all_symbols. */
4809 bool
4810 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
4812 asection *sec = (asection *) ptr;
4814 if ((hash_entry->type == bfd_link_hash_defined
4815 || hash_entry->type == bfd_link_hash_defweak)
4816 && sec == hash_entry->u.def.section)
4818 print_spaces (SECTION_NAME_MAP_LENGTH);
4819 minfo ("0x%V ",
4820 (hash_entry->u.def.value
4821 + hash_entry->u.def.section->output_offset
4822 + hash_entry->u.def.section->output_section->vma));
4824 minfo (" %pT\n", hash_entry->root.string);
4827 return true;
4830 static int
4831 hash_entry_addr_cmp (const void *a, const void *b)
4833 const struct bfd_link_hash_entry *l = *(const struct bfd_link_hash_entry **)a;
4834 const struct bfd_link_hash_entry *r = *(const struct bfd_link_hash_entry **)b;
4836 if (l->u.def.value < r->u.def.value)
4837 return -1;
4838 else if (l->u.def.value > r->u.def.value)
4839 return 1;
4840 else
4841 return 0;
4844 static void
4845 print_all_symbols (asection *sec)
4847 input_section_userdata_type *ud = bfd_section_userdata (sec);
4848 struct map_symbol_def *def;
4849 struct bfd_link_hash_entry **entries;
4850 unsigned int i;
4852 if (!ud)
4853 return;
4855 *ud->map_symbol_def_tail = 0;
4857 /* Sort the symbols by address. */
4858 entries = (struct bfd_link_hash_entry **)
4859 obstack_alloc (&map_obstack,
4860 ud->map_symbol_def_count * sizeof (*entries));
4862 for (i = 0, def = ud->map_symbol_def_head; def; def = def->next, i++)
4863 entries[i] = def->entry;
4865 qsort (entries, ud->map_symbol_def_count, sizeof (*entries),
4866 hash_entry_addr_cmp);
4868 /* Print the symbols. */
4869 for (i = 0; i < ud->map_symbol_def_count; i++)
4870 ldemul_print_symbol (entries[i], sec);
4872 obstack_free (&map_obstack, entries);
4875 /* Returns TRUE if SYM is a symbol suitable for printing
4876 in a linker map as a local symbol. */
4878 static bool
4879 ld_is_local_symbol (asymbol * sym)
4881 const char * name = bfd_asymbol_name (sym);
4883 if (name == NULL || *name == 0)
4884 return false;
4886 if (strcmp (name, "(null)") == 0)
4887 return false;
4889 /* Skip .Lxxx and such like. */
4890 if (bfd_is_local_label (link_info.output_bfd, sym))
4891 return false;
4893 /* FIXME: This is intended to skip ARM mapping symbols,
4894 which for some reason are not excluded by bfd_is_local_label,
4895 but maybe it is wrong for other architectures.
4896 It would be better to fix bfd_is_local_label. */
4897 if (*name == '$')
4898 return false;
4900 /* Some local symbols, eg _GLOBAL_OFFSET_TABLE_, are present
4901 in the hash table, so do not print duplicates here. */
4902 struct bfd_link_hash_entry * h;
4903 h = bfd_link_hash_lookup (link_info.hash, name, false /* create */,
4904 false /* copy */, true /* follow */);
4905 if (h == NULL)
4906 return true;
4908 /* Symbols from the plugin owned BFD will not get their own
4909 iteration of this function, but can be on the link_info
4910 list. So include them here. */
4911 if (h->u.def.section->owner != NULL
4912 && ((bfd_get_file_flags (h->u.def.section->owner) & (BFD_LINKER_CREATED | BFD_PLUGIN))
4913 == (BFD_LINKER_CREATED | BFD_PLUGIN)))
4914 return true;
4916 return false;
4919 /* Print information about an input section to the map file. */
4921 static void
4922 print_input_section (asection *i, bool is_discarded)
4924 bfd_size_type size = i->size;
4925 int len;
4926 bfd_vma addr;
4928 init_opb (i);
4930 minfo (" %s", i->name);
4932 len = 1 + strlen (i->name);
4933 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4935 print_nl ();
4936 len = 0;
4938 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4940 if (i->output_section != NULL
4941 && i->output_section->owner == link_info.output_bfd)
4942 addr = i->output_section->vma + i->output_offset;
4943 else
4945 addr = print_dot;
4946 if (!is_discarded)
4947 size = 0;
4950 char buf[32];
4951 bfd_sprintf_vma (link_info.output_bfd, buf, addr);
4952 minfo ("0x%s %W %pB\n", buf, TO_ADDR (size), i->owner);
4954 if (size != i->rawsize && i->rawsize != 0)
4956 len = SECTION_NAME_MAP_LENGTH + 3 + strlen (buf);
4957 print_spaces (len);
4958 minfo (_("%W (size before relaxing)\n"), TO_ADDR (i->rawsize));
4961 if (i->output_section != NULL
4962 && i->output_section->owner == link_info.output_bfd)
4964 if (link_info.reduce_memory_overheads)
4965 bfd_link_hash_traverse (link_info.hash, ldemul_print_symbol, i);
4966 else
4967 print_all_symbols (i);
4969 /* Update print_dot, but make sure that we do not move it
4970 backwards - this could happen if we have overlays and a
4971 later overlay is shorter than an earier one. */
4972 if (addr + TO_ADDR (size) > print_dot)
4973 print_dot = addr + TO_ADDR (size);
4975 if (config.print_map_locals)
4977 long storage_needed;
4979 /* FIXME: It would be better to cache this table, rather
4980 than recreating it for each output section. */
4981 /* FIXME: This call is not working for non-ELF based targets.
4982 Find out why. */
4983 storage_needed = bfd_get_symtab_upper_bound (link_info.output_bfd);
4984 if (storage_needed > 0)
4986 asymbol ** symbol_table;
4987 long number_of_symbols;
4988 long j;
4990 symbol_table = xmalloc (storage_needed);
4991 number_of_symbols = bfd_canonicalize_symtab (link_info.output_bfd, symbol_table);
4993 for (j = 0; j < number_of_symbols; j++)
4995 asymbol * sym = symbol_table[j];
4996 bfd_vma sym_addr = sym->value + i->output_section->vma;
4998 if (sym->section == i->output_section
4999 && (sym->flags & BSF_LOCAL) != 0
5000 && sym_addr >= addr
5001 && sym_addr < print_dot
5002 && ld_is_local_symbol (sym))
5004 print_spaces (SECTION_NAME_MAP_LENGTH);
5005 minfo ("0x%V (local) %s\n", sym_addr, bfd_asymbol_name (sym));
5009 free (symbol_table);
5015 static void
5016 print_fill_statement (lang_fill_statement_type *fill)
5018 size_t size;
5019 unsigned char *p;
5020 fputs (" FILL mask 0x", config.map_file);
5021 for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
5022 fprintf (config.map_file, "%02x", *p);
5023 fputs ("\n", config.map_file);
5026 static void
5027 print_data_statement (lang_data_statement_type *data)
5029 bfd_vma addr;
5030 bfd_size_type size;
5031 const char *name;
5033 init_opb (data->output_section);
5034 print_spaces (SECTION_NAME_MAP_LENGTH);
5036 addr = data->output_offset;
5037 if (data->output_section != NULL)
5038 addr += data->output_section->vma;
5040 switch (data->type)
5042 default:
5043 abort ();
5044 case BYTE:
5045 size = BYTE_SIZE;
5046 name = "BYTE";
5047 break;
5048 case SHORT:
5049 size = SHORT_SIZE;
5050 name = "SHORT";
5051 break;
5052 case LONG:
5053 size = LONG_SIZE;
5054 name = "LONG";
5055 break;
5056 case QUAD:
5057 size = QUAD_SIZE;
5058 name = "QUAD";
5059 break;
5060 case SQUAD:
5061 size = QUAD_SIZE;
5062 name = "SQUAD";
5063 break;
5066 if (size < TO_SIZE ((unsigned) 1))
5067 size = TO_SIZE ((unsigned) 1);
5068 minfo ("0x%V %W %s 0x%v", addr, TO_ADDR (size), name, data->value);
5070 if (data->exp->type.node_class != etree_value)
5072 print_space ();
5073 exp_print_tree (data->exp);
5076 print_nl ();
5078 print_dot = addr + TO_ADDR (size);
5081 /* Print an address statement. These are generated by options like
5082 -Ttext. */
5084 static void
5085 print_address_statement (lang_address_statement_type *address)
5087 minfo (_("Address of section %s set to "), address->section_name);
5088 exp_print_tree (address->address);
5089 print_nl ();
5092 /* Print a reloc statement. */
5094 static void
5095 print_reloc_statement (lang_reloc_statement_type *reloc)
5097 bfd_vma addr;
5098 bfd_size_type size;
5100 init_opb (reloc->output_section);
5101 print_spaces (SECTION_NAME_MAP_LENGTH);
5103 addr = reloc->output_offset;
5104 if (reloc->output_section != NULL)
5105 addr += reloc->output_section->vma;
5107 size = bfd_get_reloc_size (reloc->howto);
5109 minfo ("0x%V %W RELOC %s ", addr, TO_ADDR (size), reloc->howto->name);
5111 if (reloc->name != NULL)
5112 minfo ("%s+", reloc->name);
5113 else
5114 minfo ("%s+", reloc->section->name);
5116 exp_print_tree (reloc->addend_exp);
5118 print_nl ();
5120 print_dot = addr + TO_ADDR (size);
5123 static void
5124 print_padding_statement (lang_padding_statement_type *s)
5126 int len;
5127 bfd_vma addr;
5129 init_opb (s->output_section);
5130 minfo (" *fill*");
5132 len = sizeof " *fill*" - 1;
5133 print_spaces (SECTION_NAME_MAP_LENGTH - len);
5135 addr = s->output_offset;
5136 if (s->output_section != NULL)
5137 addr += s->output_section->vma;
5138 minfo ("0x%V %W ", addr, TO_ADDR (s->size));
5140 if (s->fill->size != 0)
5142 size_t size;
5143 unsigned char *p;
5144 for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
5145 fprintf (config.map_file, "%02x", *p);
5148 print_nl ();
5150 print_dot = addr + TO_ADDR (s->size);
5153 static void
5154 print_wild_statement (lang_wild_statement_type *w,
5155 lang_output_section_statement_type *os)
5157 struct wildcard_list *sec;
5159 print_space ();
5161 if (w->exclude_name_list)
5163 name_list *tmp;
5164 minfo ("EXCLUDE_FILE(%s", w->exclude_name_list->name);
5165 for (tmp = w->exclude_name_list->next; tmp; tmp = tmp->next)
5166 minfo (" %s", tmp->name);
5167 minfo (") ");
5170 if (w->filenames_sorted)
5171 minfo ("SORT_BY_NAME(");
5172 if (w->filenames_reversed)
5173 minfo ("REVERSE(");
5174 if (w->filename != NULL)
5175 minfo ("%s", w->filename);
5176 else
5177 minfo ("*");
5178 if (w->filenames_reversed)
5179 minfo (")");
5180 if (w->filenames_sorted)
5181 minfo (")");
5183 minfo ("(");
5184 for (sec = w->section_list; sec; sec = sec->next)
5186 int closing_paren = 0;
5188 switch (sec->spec.sorted)
5190 case none:
5191 break;
5193 case by_name:
5194 minfo ("SORT_BY_NAME(");
5195 closing_paren = 1;
5196 break;
5198 case by_alignment:
5199 minfo ("SORT_BY_ALIGNMENT(");
5200 closing_paren = 1;
5201 break;
5203 case by_name_alignment:
5204 minfo ("SORT_BY_NAME(SORT_BY_ALIGNMENT(");
5205 closing_paren = 2;
5206 break;
5208 case by_alignment_name:
5209 minfo ("SORT_BY_ALIGNMENT(SORT_BY_NAME(");
5210 closing_paren = 2;
5211 break;
5213 case by_none:
5214 minfo ("SORT_NONE(");
5215 closing_paren = 1;
5216 break;
5218 case by_init_priority:
5219 minfo ("SORT_BY_INIT_PRIORITY(");
5220 closing_paren = 1;
5221 break;
5224 if (sec->spec.reversed)
5226 minfo ("REVERSE(");
5227 closing_paren++;
5230 if (sec->spec.exclude_name_list != NULL)
5232 name_list *tmp;
5233 minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
5234 for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
5235 minfo (" %s", tmp->name);
5236 minfo (") ");
5238 if (sec->spec.name != NULL)
5239 minfo ("%s", sec->spec.name);
5240 else
5241 minfo ("*");
5242 for (;closing_paren > 0; closing_paren--)
5243 minfo (")");
5244 if (sec->next)
5245 minfo (" ");
5247 minfo (")");
5249 print_nl ();
5251 print_statement_list (w->children.head, os);
5254 /* Print a group statement. */
5256 static void
5257 print_group (lang_group_statement_type *s,
5258 lang_output_section_statement_type *os)
5260 fprintf (config.map_file, "START GROUP\n");
5261 print_statement_list (s->children.head, os);
5262 fprintf (config.map_file, "END GROUP\n");
5265 /* Print the list of statements in S.
5266 This can be called for any statement type. */
5268 static void
5269 print_statement_list (lang_statement_union_type *s,
5270 lang_output_section_statement_type *os)
5272 while (s != NULL)
5274 print_statement (s, os);
5275 s = s->header.next;
5279 /* Print the first statement in statement list S.
5280 This can be called for any statement type. */
5282 static void
5283 print_statement (lang_statement_union_type *s,
5284 lang_output_section_statement_type *os)
5286 switch (s->header.type)
5288 default:
5289 fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
5290 FAIL ();
5291 break;
5292 case lang_constructors_statement_enum:
5293 if (constructor_list.head != NULL)
5295 if (constructors_sorted)
5296 minfo (" SORT (CONSTRUCTORS)\n");
5297 else
5298 minfo (" CONSTRUCTORS\n");
5299 print_statement_list (constructor_list.head, os);
5301 break;
5302 case lang_wild_statement_enum:
5303 print_wild_statement (&s->wild_statement, os);
5304 break;
5305 case lang_address_statement_enum:
5306 print_address_statement (&s->address_statement);
5307 break;
5308 case lang_object_symbols_statement_enum:
5309 minfo (" CREATE_OBJECT_SYMBOLS\n");
5310 break;
5311 case lang_fill_statement_enum:
5312 print_fill_statement (&s->fill_statement);
5313 break;
5314 case lang_data_statement_enum:
5315 print_data_statement (&s->data_statement);
5316 break;
5317 case lang_reloc_statement_enum:
5318 print_reloc_statement (&s->reloc_statement);
5319 break;
5320 case lang_input_section_enum:
5321 print_input_section (s->input_section.section, false);
5322 break;
5323 case lang_padding_statement_enum:
5324 print_padding_statement (&s->padding_statement);
5325 break;
5326 case lang_output_section_statement_enum:
5327 print_output_section_statement (&s->output_section_statement);
5328 break;
5329 case lang_assignment_statement_enum:
5330 print_assignment (&s->assignment_statement, os);
5331 break;
5332 case lang_target_statement_enum:
5333 fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
5334 break;
5335 case lang_output_statement_enum:
5336 minfo ("OUTPUT(%s", s->output_statement.name);
5337 if (output_target != NULL)
5338 minfo (" %s", output_target);
5339 minfo (")\n");
5340 break;
5341 case lang_input_statement_enum:
5342 print_input_statement (&s->input_statement);
5343 break;
5344 case lang_group_statement_enum:
5345 print_group (&s->group_statement, os);
5346 break;
5347 case lang_insert_statement_enum:
5348 minfo ("INSERT %s %s\n",
5349 s->insert_statement.is_before ? "BEFORE" : "AFTER",
5350 s->insert_statement.where);
5351 break;
5355 static void
5356 print_statements (void)
5358 print_statement_list (statement_list.head, abs_output_section);
5361 /* Print the first N statements in statement list S to STDERR.
5362 If N == 0, nothing is printed.
5363 If N < 0, the entire list is printed.
5364 Intended to be called from GDB. */
5366 void
5367 dprint_statement (lang_statement_union_type *s, int n)
5369 FILE *map_save = config.map_file;
5371 config.map_file = stderr;
5373 if (n < 0)
5374 print_statement_list (s, abs_output_section);
5375 else
5377 while (s && --n >= 0)
5379 print_statement (s, abs_output_section);
5380 s = s->header.next;
5384 config.map_file = map_save;
5387 static void
5388 insert_pad (lang_statement_union_type **ptr,
5389 fill_type *fill,
5390 bfd_size_type alignment_needed,
5391 asection *output_section,
5392 bfd_vma dot)
5394 static fill_type zero_fill;
5395 lang_statement_union_type *pad = NULL;
5397 if (ptr != &statement_list.head)
5398 pad = ((lang_statement_union_type *)
5399 ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
5400 if (pad != NULL
5401 && pad->header.type == lang_padding_statement_enum
5402 && pad->padding_statement.output_section == output_section)
5404 /* Use the existing pad statement. */
5406 else if ((pad = *ptr) != NULL
5407 && pad->header.type == lang_padding_statement_enum
5408 && pad->padding_statement.output_section == output_section)
5410 /* Use the existing pad statement. */
5412 else
5414 /* Make a new padding statement, linked into existing chain. */
5415 pad = stat_alloc (sizeof (lang_padding_statement_type));
5416 pad->header.next = *ptr;
5417 *ptr = pad;
5418 pad->header.type = lang_padding_statement_enum;
5419 pad->padding_statement.output_section = output_section;
5420 if (fill == NULL)
5421 fill = &zero_fill;
5422 pad->padding_statement.fill = fill;
5424 pad->padding_statement.output_offset = dot - output_section->vma;
5425 pad->padding_statement.size = alignment_needed;
5426 if (!(output_section->flags & SEC_FIXED_SIZE))
5427 output_section->size = TO_SIZE (dot + TO_ADDR (alignment_needed)
5428 - output_section->vma);
5431 /* Work out how much this section will move the dot point. */
5433 static bfd_vma
5434 size_input_section
5435 (lang_statement_union_type **this_ptr,
5436 lang_output_section_statement_type *output_section_statement,
5437 fill_type *fill,
5438 bool *removed,
5439 bfd_vma dot)
5441 lang_input_section_type *is = &((*this_ptr)->input_section);
5442 asection *i = is->section;
5443 asection *o = output_section_statement->bfd_section;
5444 *removed = 0;
5446 if (link_info.non_contiguous_regions)
5448 /* If the input section I has already been successfully assigned
5449 to an output section other than O, don't bother with it and
5450 let the caller remove it from the list. Keep processing in
5451 case we have already handled O, because the repeated passes
5452 have reinitialized its size. */
5453 if (i->already_assigned && i->already_assigned != o)
5455 *removed = 1;
5456 return dot;
5460 if (i->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
5461 i->output_offset = i->vma - o->vma;
5462 else if (((i->flags & SEC_EXCLUDE) != 0)
5463 || output_section_statement->ignored)
5464 i->output_offset = dot - o->vma;
5465 else
5467 bfd_size_type alignment_needed;
5469 /* Align this section first to the input sections requirement,
5470 then to the output section's requirement. If this alignment
5471 is greater than any seen before, then record it too. Perform
5472 the alignment by inserting a magic 'padding' statement.
5473 We can force input section alignment within an output section
5474 by using SUBALIGN. The value specified overrides any alignment
5475 given by input sections, whether larger or smaller. */
5477 if (output_section_statement->subsection_alignment != NULL)
5478 o->alignment_power = i->alignment_power =
5479 exp_get_power (output_section_statement->subsection_alignment,
5480 output_section_statement,
5481 "subsection alignment");
5483 if (o->alignment_power < i->alignment_power)
5484 o->alignment_power = i->alignment_power;
5486 alignment_needed = align_power (dot, i->alignment_power) - dot;
5488 if (alignment_needed != 0)
5490 insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
5491 dot += alignment_needed;
5494 if (link_info.non_contiguous_regions)
5496 /* If I would overflow O, let the caller remove I from the
5497 list. */
5498 if (output_section_statement->region)
5500 bfd_vma end = output_section_statement->region->origin
5501 + output_section_statement->region->length;
5503 if (dot + TO_ADDR (i->size) > end)
5505 if (i->flags & SEC_LINKER_CREATED)
5506 einfo (_("%F%P: Output section `%pA' not large enough for "
5507 "the linker-created stubs section `%pA'.\n"),
5508 i->output_section, i);
5510 if (i->rawsize && i->rawsize != i->size)
5511 einfo (_("%F%P: Relaxation not supported with "
5512 "--enable-non-contiguous-regions (section `%pA' "
5513 "would overflow `%pA' after it changed size).\n"),
5514 i, i->output_section);
5516 *removed = 1;
5517 dot = end;
5518 i->output_section = NULL;
5519 return dot;
5524 /* Remember where in the output section this input section goes. */
5525 i->output_offset = dot - o->vma;
5527 /* Mark how big the output section must be to contain this now. */
5528 dot += TO_ADDR (i->size);
5529 if (!(o->flags & SEC_FIXED_SIZE))
5530 o->size = TO_SIZE (dot - o->vma);
5532 if (link_info.non_contiguous_regions)
5534 /* Record that I was successfully assigned to O, and update
5535 its actual output section too. */
5536 i->already_assigned = o;
5537 i->output_section = o;
5541 return dot;
5544 struct check_sec
5546 asection *sec;
5547 bool warned;
5550 static int
5551 sort_sections_by_lma (const void *arg1, const void *arg2)
5553 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5554 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5556 if (sec1->lma < sec2->lma)
5557 return -1;
5558 else if (sec1->lma > sec2->lma)
5559 return 1;
5560 else if (sec1->id < sec2->id)
5561 return -1;
5562 else if (sec1->id > sec2->id)
5563 return 1;
5565 return 0;
5568 static int
5569 sort_sections_by_vma (const void *arg1, const void *arg2)
5571 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5572 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5574 if (sec1->vma < sec2->vma)
5575 return -1;
5576 else if (sec1->vma > sec2->vma)
5577 return 1;
5578 else if (sec1->id < sec2->id)
5579 return -1;
5580 else if (sec1->id > sec2->id)
5581 return 1;
5583 return 0;
5586 #define IS_TBSS(s) \
5587 ((s->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == SEC_THREAD_LOCAL)
5589 #define IGNORE_SECTION(s) \
5590 ((s->flags & SEC_ALLOC) == 0 || IS_TBSS (s))
5592 /* Check to see if any allocated sections overlap with other allocated
5593 sections. This can happen if a linker script specifies the output
5594 section addresses of the two sections. Also check whether any memory
5595 region has overflowed. */
5597 static void
5598 lang_check_section_addresses (void)
5600 asection *s, *p;
5601 struct check_sec *sections;
5602 size_t i, count;
5603 bfd_vma addr_mask;
5604 bfd_vma s_start;
5605 bfd_vma s_end;
5606 bfd_vma p_start = 0;
5607 bfd_vma p_end = 0;
5608 lang_memory_region_type *m;
5609 bool overlays;
5611 /* Detect address space overflow on allocated sections. */
5612 addr_mask = ((bfd_vma) 1 <<
5613 (bfd_arch_bits_per_address (link_info.output_bfd) - 1)) - 1;
5614 addr_mask = (addr_mask << 1) + 1;
5615 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5616 if ((s->flags & SEC_ALLOC) != 0)
5618 s_end = (s->vma + s->size) & addr_mask;
5619 if (s_end != 0 && s_end < (s->vma & addr_mask))
5620 einfo (_("%X%P: section %s VMA wraps around address space\n"),
5621 s->name);
5622 else
5624 s_end = (s->lma + s->size) & addr_mask;
5625 if (s_end != 0 && s_end < (s->lma & addr_mask))
5626 einfo (_("%X%P: section %s LMA wraps around address space\n"),
5627 s->name);
5631 if (bfd_count_sections (link_info.output_bfd) <= 1)
5632 return;
5634 count = bfd_count_sections (link_info.output_bfd);
5635 sections = XNEWVEC (struct check_sec, count);
5637 /* Scan all sections in the output list. */
5638 count = 0;
5639 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5641 if (IGNORE_SECTION (s)
5642 || s->size == 0)
5643 continue;
5645 sections[count].sec = s;
5646 sections[count].warned = false;
5647 count++;
5650 if (count <= 1)
5652 free (sections);
5653 return;
5656 qsort (sections, count, sizeof (*sections), sort_sections_by_lma);
5658 /* First check section LMAs. There should be no overlap of LMAs on
5659 loadable sections, even with overlays. */
5660 for (p = NULL, i = 0; i < count; i++)
5662 s = sections[i].sec;
5663 init_opb (s);
5664 if ((s->flags & SEC_LOAD) != 0)
5666 s_start = s->lma;
5667 s_end = s_start + TO_ADDR (s->size) - 1;
5669 /* Look for an overlap. We have sorted sections by lma, so
5670 we know that s_start >= p_start. Besides the obvious
5671 case of overlap when the current section starts before
5672 the previous one ends, we also must have overlap if the
5673 previous section wraps around the address space. */
5674 if (p != NULL
5675 && (s_start <= p_end
5676 || p_end < p_start))
5678 einfo (_("%X%P: section %s LMA [%V,%V]"
5679 " overlaps section %s LMA [%V,%V]\n"),
5680 s->name, s_start, s_end, p->name, p_start, p_end);
5681 sections[i].warned = true;
5683 p = s;
5684 p_start = s_start;
5685 p_end = s_end;
5689 /* If any non-zero size allocated section (excluding tbss) starts at
5690 exactly the same VMA as another such section, then we have
5691 overlays. Overlays generated by the OVERLAY keyword will have
5692 this property. It is possible to intentionally generate overlays
5693 that fail this test, but it would be unusual. */
5694 qsort (sections, count, sizeof (*sections), sort_sections_by_vma);
5695 overlays = false;
5696 p_start = sections[0].sec->vma;
5697 for (i = 1; i < count; i++)
5699 s_start = sections[i].sec->vma;
5700 if (p_start == s_start)
5702 overlays = true;
5703 break;
5705 p_start = s_start;
5708 /* Now check section VMAs if no overlays were detected. */
5709 if (!overlays)
5711 for (p = NULL, i = 0; i < count; i++)
5713 s = sections[i].sec;
5714 init_opb (s);
5715 s_start = s->vma;
5716 s_end = s_start + TO_ADDR (s->size) - 1;
5718 if (p != NULL
5719 && !sections[i].warned
5720 && (s_start <= p_end
5721 || p_end < p_start))
5722 einfo (_("%X%P: section %s VMA [%V,%V]"
5723 " overlaps section %s VMA [%V,%V]\n"),
5724 s->name, s_start, s_end, p->name, p_start, p_end);
5725 p = s;
5726 p_start = s_start;
5727 p_end = s_end;
5731 free (sections);
5733 /* If any memory region has overflowed, report by how much.
5734 We do not issue this diagnostic for regions that had sections
5735 explicitly placed outside their bounds; os_region_check's
5736 diagnostics are adequate for that case.
5738 FIXME: It is conceivable that m->current - (m->origin + m->length)
5739 might overflow a 32-bit integer. There is, alas, no way to print
5740 a bfd_vma quantity in decimal. */
5741 for (m = lang_memory_region_list; m; m = m->next)
5742 if (m->had_full_message)
5744 unsigned long over = m->current - (m->origin + m->length);
5745 einfo (ngettext ("%X%P: region `%s' overflowed by %lu byte\n",
5746 "%X%P: region `%s' overflowed by %lu bytes\n",
5747 over),
5748 m->name_list.name, over);
5752 /* Make sure the new address is within the region. We explicitly permit the
5753 current address to be at the exact end of the region when the address is
5754 non-zero, in case the region is at the end of addressable memory and the
5755 calculation wraps around. */
5757 static void
5758 os_region_check (lang_output_section_statement_type *os,
5759 lang_memory_region_type *region,
5760 etree_type *tree,
5761 bfd_vma rbase)
5763 if ((region->current < region->origin
5764 || (region->current - region->origin > region->length))
5765 && ((region->current != region->origin + region->length)
5766 || rbase == 0))
5768 if (tree != NULL)
5770 einfo (_("%X%P: address 0x%v of %pB section `%s'"
5771 " is not within region `%s'\n"),
5772 region->current,
5773 os->bfd_section->owner,
5774 os->bfd_section->name,
5775 region->name_list.name);
5777 else if (!region->had_full_message)
5779 region->had_full_message = true;
5781 einfo (_("%X%P: %pB section `%s' will not fit in region `%s'\n"),
5782 os->bfd_section->owner,
5783 os->bfd_section->name,
5784 region->name_list.name);
5789 static void
5790 ldlang_check_relro_region (lang_statement_union_type *s)
5792 seg_align_type *seg = &expld.dataseg;
5794 if (seg->relro == exp_seg_relro_start)
5796 if (!seg->relro_start_stat)
5797 seg->relro_start_stat = s;
5798 else
5800 ASSERT (seg->relro_start_stat == s);
5803 else if (seg->relro == exp_seg_relro_end)
5805 if (!seg->relro_end_stat)
5806 seg->relro_end_stat = s;
5807 else
5809 ASSERT (seg->relro_end_stat == s);
5814 /* Set the sizes for all the output sections. */
5816 static bfd_vma
5817 lang_size_sections_1
5818 (lang_statement_union_type **prev,
5819 lang_output_section_statement_type *current_os,
5820 fill_type *fill,
5821 bfd_vma dot,
5822 bool *relax,
5823 bool check_regions)
5825 lang_statement_union_type *s;
5826 lang_statement_union_type *prev_s = NULL;
5827 bool removed_prev_s = false;
5828 lang_output_section_statement_type *os = current_os;
5830 /* Size up the sections from their constituent parts. */
5831 for (s = *prev; s != NULL; prev_s = s, s = s->header.next)
5833 bool removed = false;
5835 switch (s->header.type)
5837 case lang_output_section_statement_enum:
5839 bfd_vma newdot, after, dotdelta;
5840 lang_memory_region_type *r;
5841 int section_alignment = 0;
5843 os = &s->output_section_statement;
5844 init_opb (os->bfd_section);
5845 if (os->constraint == -1)
5846 break;
5848 /* FIXME: We shouldn't need to zero section vmas for ld -r
5849 here, in lang_insert_orphan, or in the default linker scripts.
5850 This is covering for coff backend linker bugs. See PR6945. */
5851 if (os->addr_tree == NULL
5852 && bfd_link_relocatable (&link_info)
5853 && (bfd_get_flavour (link_info.output_bfd)
5854 == bfd_target_coff_flavour))
5855 os->addr_tree = exp_intop (0);
5856 if (os->addr_tree != NULL)
5858 exp_fold_tree (os->addr_tree, os, bfd_abs_section_ptr, &dot);
5860 if (expld.result.valid_p)
5862 dot = expld.result.value;
5863 if (expld.result.section != NULL)
5864 dot += expld.result.section->vma;
5866 else if (expld.phase != lang_mark_phase_enum)
5867 einfo (_("%F%P:%pS: non constant or forward reference"
5868 " address expression for section %s\n"),
5869 os->addr_tree, os->name);
5872 if (os->bfd_section == NULL)
5873 /* This section was removed or never actually created. */
5874 break;
5876 /* If this is a COFF shared library section, use the size and
5877 address from the input section. FIXME: This is COFF
5878 specific; it would be cleaner if there were some other way
5879 to do this, but nothing simple comes to mind. */
5880 if (((bfd_get_flavour (link_info.output_bfd)
5881 == bfd_target_ecoff_flavour)
5882 || (bfd_get_flavour (link_info.output_bfd)
5883 == bfd_target_coff_flavour))
5884 && (os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
5886 asection *input;
5888 if (os->children.head == NULL
5889 || os->children.head->header.next != NULL
5890 || (os->children.head->header.type
5891 != lang_input_section_enum))
5892 einfo (_("%X%P: internal error on COFF shared library"
5893 " section %s\n"), os->name);
5895 input = os->children.head->input_section.section;
5896 bfd_set_section_vma (os->bfd_section,
5897 bfd_section_vma (input));
5898 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5899 os->bfd_section->size = input->size;
5900 break;
5903 newdot = dot;
5904 dotdelta = 0;
5905 if (bfd_is_abs_section (os->bfd_section))
5907 /* No matter what happens, an abs section starts at zero. */
5908 ASSERT (os->bfd_section->vma == 0);
5910 else
5912 if (os->addr_tree == NULL)
5914 /* No address specified for this section, get one
5915 from the region specification. */
5916 if (os->region == NULL
5917 || ((os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))
5918 && os->region->name_list.name[0] == '*'
5919 && strcmp (os->region->name_list.name,
5920 DEFAULT_MEMORY_REGION) == 0))
5922 os->region = lang_memory_default (os->bfd_section);
5925 /* If a loadable section is using the default memory
5926 region, and some non default memory regions were
5927 defined, issue an error message. */
5928 if (!os->ignored
5929 && !IGNORE_SECTION (os->bfd_section)
5930 && !bfd_link_relocatable (&link_info)
5931 && check_regions
5932 && strcmp (os->region->name_list.name,
5933 DEFAULT_MEMORY_REGION) == 0
5934 && lang_memory_region_list != NULL
5935 && (strcmp (lang_memory_region_list->name_list.name,
5936 DEFAULT_MEMORY_REGION) != 0
5937 || lang_memory_region_list->next != NULL)
5938 && lang_sizing_iteration == 1)
5940 /* By default this is an error rather than just a
5941 warning because if we allocate the section to the
5942 default memory region we can end up creating an
5943 excessively large binary, or even seg faulting when
5944 attempting to perform a negative seek. See
5945 sources.redhat.com/ml/binutils/2003-04/msg00423.html
5946 for an example of this. This behaviour can be
5947 overridden by the using the --no-check-sections
5948 switch. */
5949 if (command_line.check_section_addresses)
5950 einfo (_("%F%P: error: no memory region specified"
5951 " for loadable section `%s'\n"),
5952 bfd_section_name (os->bfd_section));
5953 else
5954 einfo (_("%P: warning: no memory region specified"
5955 " for loadable section `%s'\n"),
5956 bfd_section_name (os->bfd_section));
5959 newdot = os->region->current;
5960 section_alignment = os->bfd_section->alignment_power;
5962 else
5963 section_alignment = exp_get_power (os->section_alignment, os,
5964 "section alignment");
5966 /* Align to what the section needs. */
5967 if (section_alignment > 0)
5969 bfd_vma savedot = newdot;
5970 bfd_vma diff = 0;
5972 newdot = align_power (newdot, section_alignment);
5973 dotdelta = newdot - savedot;
5975 if (lang_sizing_iteration == 1)
5976 diff = dotdelta;
5977 else if (lang_sizing_iteration > 1)
5979 /* Only report adjustments that would change
5980 alignment from what we have already reported. */
5981 diff = newdot - os->bfd_section->vma;
5982 if (!(diff & (((bfd_vma) 1 << section_alignment) - 1)))
5983 diff = 0;
5985 if (diff != 0
5986 && (config.warn_section_align
5987 || os->addr_tree != NULL))
5988 einfo (_("%P: warning: "
5989 "start of section %s changed by %ld\n"),
5990 os->name, (long) diff);
5993 bfd_set_section_vma (os->bfd_section, newdot);
5995 os->bfd_section->output_offset = 0;
5998 lang_size_sections_1 (&os->children.head, os,
5999 os->fill, newdot, relax, check_regions);
6001 os->processed_vma = true;
6003 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
6004 /* Except for some special linker created sections,
6005 no output section should change from zero size
6006 after strip_excluded_output_sections. A non-zero
6007 size on an ignored section indicates that some
6008 input section was not sized early enough. */
6009 ASSERT (os->bfd_section->size == 0);
6010 else
6012 dot = os->bfd_section->vma;
6014 /* Put the section within the requested block size, or
6015 align at the block boundary. */
6016 after = ((dot
6017 + TO_ADDR (os->bfd_section->size)
6018 + os->block_value - 1)
6019 & - (bfd_vma) os->block_value);
6021 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
6022 os->bfd_section->size = TO_SIZE (after
6023 - os->bfd_section->vma);
6026 /* Set section lma. */
6027 r = os->region;
6028 if (r == NULL)
6029 r = lang_memory_region_lookup (DEFAULT_MEMORY_REGION, false);
6031 if (os->load_base)
6033 bfd_vma lma = exp_get_abs_int (os->load_base, 0, "load base");
6034 os->bfd_section->lma = lma;
6036 else if (os->lma_region != NULL)
6038 bfd_vma lma = os->lma_region->current;
6040 if (os->align_lma_with_input)
6041 lma += dotdelta;
6042 else
6044 /* When LMA_REGION is the same as REGION, align the LMA
6045 as we did for the VMA, possibly including alignment
6046 from the bfd section. If a different region, then
6047 only align according to the value in the output
6048 statement. */
6049 if (os->lma_region != os->region)
6050 section_alignment = exp_get_power (os->section_alignment,
6052 "section alignment");
6053 if (section_alignment > 0)
6054 lma = align_power (lma, section_alignment);
6056 os->bfd_section->lma = lma;
6058 else if (r->last_os != NULL
6059 && (os->bfd_section->flags & SEC_ALLOC) != 0)
6061 bfd_vma lma;
6062 asection *last;
6064 last = r->last_os->output_section_statement.bfd_section;
6066 /* A backwards move of dot should be accompanied by
6067 an explicit assignment to the section LMA (ie.
6068 os->load_base set) because backwards moves can
6069 create overlapping LMAs. */
6070 if (dot < last->vma
6071 && os->bfd_section->size != 0
6072 && dot + TO_ADDR (os->bfd_section->size) <= last->vma)
6074 /* If dot moved backwards then leave lma equal to
6075 vma. This is the old default lma, which might
6076 just happen to work when the backwards move is
6077 sufficiently large. Nag if this changes anything,
6078 so people can fix their linker scripts. */
6080 if (last->vma != last->lma)
6081 einfo (_("%P: warning: dot moved backwards "
6082 "before `%s'\n"), os->name);
6084 else
6086 /* If this is an overlay, set the current lma to that
6087 at the end of the previous section. */
6088 if (os->sectype == overlay_section)
6089 lma = last->lma + TO_ADDR (last->size);
6091 /* Otherwise, keep the same lma to vma relationship
6092 as the previous section. */
6093 else
6094 lma = os->bfd_section->vma + last->lma - last->vma;
6096 if (section_alignment > 0)
6097 lma = align_power (lma, section_alignment);
6098 os->bfd_section->lma = lma;
6101 os->processed_lma = true;
6103 /* Keep track of normal sections using the default
6104 lma region. We use this to set the lma for
6105 following sections. Overlays or other linker
6106 script assignment to lma might mean that the
6107 default lma == vma is incorrect.
6108 To avoid warnings about dot moving backwards when using
6109 -Ttext, don't start tracking sections until we find one
6110 of non-zero size or with lma set differently to vma.
6111 Do this tracking before we short-cut the loop so that we
6112 track changes for the case where the section size is zero,
6113 but the lma is set differently to the vma. This is
6114 important, if an orphan section is placed after an
6115 otherwise empty output section that has an explicit lma
6116 set, we want that lma reflected in the orphans lma. */
6117 if (((!IGNORE_SECTION (os->bfd_section)
6118 && (os->bfd_section->size != 0
6119 || (r->last_os == NULL
6120 && os->bfd_section->vma != os->bfd_section->lma)
6121 || (r->last_os != NULL
6122 && dot >= (r->last_os->output_section_statement
6123 .bfd_section->vma))))
6124 || os->sectype == first_overlay_section)
6125 && os->lma_region == NULL
6126 && !bfd_link_relocatable (&link_info))
6127 r->last_os = s;
6129 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
6130 break;
6132 /* .tbss sections effectively have zero size. */
6133 if (!IS_TBSS (os->bfd_section)
6134 || bfd_link_relocatable (&link_info))
6135 dotdelta = TO_ADDR (os->bfd_section->size);
6136 else
6137 dotdelta = 0;
6138 dot += dotdelta;
6140 if (os->update_dot_tree != 0)
6141 exp_fold_tree (os->update_dot_tree, os, bfd_abs_section_ptr, &dot);
6143 /* Update dot in the region ?
6144 We only do this if the section is going to be allocated,
6145 since unallocated sections do not contribute to the region's
6146 overall size in memory. */
6147 if (os->region != NULL
6148 && (os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD)))
6150 os->region->current = dot;
6152 if (check_regions)
6153 /* Make sure the new address is within the region. */
6154 os_region_check (os, os->region, os->addr_tree,
6155 os->bfd_section->vma);
6157 if (os->lma_region != NULL && os->lma_region != os->region
6158 && ((os->bfd_section->flags & SEC_LOAD)
6159 || os->align_lma_with_input))
6161 os->lma_region->current = os->bfd_section->lma + dotdelta;
6163 if (check_regions)
6164 os_region_check (os, os->lma_region, NULL,
6165 os->bfd_section->lma);
6169 break;
6171 case lang_constructors_statement_enum:
6172 dot = lang_size_sections_1 (&constructor_list.head, current_os,
6173 fill, dot, relax, check_regions);
6174 break;
6176 case lang_data_statement_enum:
6178 unsigned int size = 0;
6180 s->data_statement.output_offset = dot - current_os->bfd_section->vma;
6181 s->data_statement.output_section = current_os->bfd_section;
6183 /* We might refer to provided symbols in the expression, and
6184 need to mark them as needed. */
6185 exp_fold_tree (s->data_statement.exp, os,
6186 bfd_abs_section_ptr, &dot);
6188 switch (s->data_statement.type)
6190 default:
6191 abort ();
6192 case QUAD:
6193 case SQUAD:
6194 size = QUAD_SIZE;
6195 break;
6196 case LONG:
6197 size = LONG_SIZE;
6198 break;
6199 case SHORT:
6200 size = SHORT_SIZE;
6201 break;
6202 case BYTE:
6203 size = BYTE_SIZE;
6204 break;
6206 if (size < TO_SIZE ((unsigned) 1))
6207 size = TO_SIZE ((unsigned) 1);
6208 dot += TO_ADDR (size);
6209 if (!(current_os->bfd_section->flags & SEC_FIXED_SIZE))
6210 current_os->bfd_section->size
6211 = TO_SIZE (dot - current_os->bfd_section->vma);
6214 break;
6216 case lang_reloc_statement_enum:
6218 int size;
6220 s->reloc_statement.output_offset
6221 = dot - current_os->bfd_section->vma;
6222 s->reloc_statement.output_section
6223 = current_os->bfd_section;
6224 size = bfd_get_reloc_size (s->reloc_statement.howto);
6225 dot += TO_ADDR (size);
6226 if (!(current_os->bfd_section->flags & SEC_FIXED_SIZE))
6227 current_os->bfd_section->size
6228 = TO_SIZE (dot - current_os->bfd_section->vma);
6230 break;
6232 case lang_wild_statement_enum:
6233 dot = lang_size_sections_1 (&s->wild_statement.children.head,
6234 current_os, fill, dot, relax,
6235 check_regions);
6236 break;
6238 case lang_object_symbols_statement_enum:
6239 link_info.create_object_symbols_section = current_os->bfd_section;
6240 current_os->bfd_section->flags |= SEC_KEEP;
6241 break;
6243 case lang_output_statement_enum:
6244 case lang_target_statement_enum:
6245 break;
6247 case lang_input_section_enum:
6249 asection *i;
6251 i = s->input_section.section;
6252 if (relax)
6254 bool again;
6256 if (!bfd_relax_section (i->owner, i, &link_info, &again))
6257 einfo (_("%F%P: can't relax section: %E\n"));
6258 if (again)
6259 *relax = true;
6261 dot = size_input_section (prev, current_os, fill, &removed, dot);
6263 break;
6265 case lang_input_statement_enum:
6266 break;
6268 case lang_fill_statement_enum:
6269 s->fill_statement.output_section = current_os->bfd_section;
6271 fill = s->fill_statement.fill;
6272 break;
6274 case lang_assignment_statement_enum:
6276 bfd_vma newdot = dot;
6277 etree_type *tree = s->assignment_statement.exp;
6279 expld.dataseg.relro = exp_seg_relro_none;
6281 exp_fold_tree (tree, os, current_os->bfd_section, &newdot);
6283 ldlang_check_relro_region (s);
6285 expld.dataseg.relro = exp_seg_relro_none;
6287 /* This symbol may be relative to this section. */
6288 if ((tree->type.node_class == etree_provided
6289 || tree->type.node_class == etree_assign)
6290 && (tree->assign.dst [0] != '.'
6291 || tree->assign.dst [1] != '\0'))
6292 current_os->update_dot = 1;
6294 if (!current_os->ignored)
6296 if (current_os == abs_output_section)
6298 /* If we don't have an output section, then just adjust
6299 the default memory address. */
6300 lang_memory_region_lookup (DEFAULT_MEMORY_REGION,
6301 false)->current = newdot;
6303 else if (newdot != dot)
6305 /* Insert a pad after this statement. We can't
6306 put the pad before when relaxing, in case the
6307 assignment references dot. */
6308 insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
6309 current_os->bfd_section, dot);
6311 /* Don't neuter the pad below when relaxing. */
6312 s = s->header.next;
6314 /* If dot is advanced, this implies that the section
6315 should have space allocated to it, unless the
6316 user has explicitly stated that the section
6317 should not be allocated. */
6318 if (current_os->sectype != noalloc_section
6319 && (current_os->sectype != noload_section
6320 || (bfd_get_flavour (link_info.output_bfd)
6321 == bfd_target_elf_flavour)))
6322 current_os->bfd_section->flags |= SEC_ALLOC;
6324 dot = newdot;
6327 break;
6329 case lang_padding_statement_enum:
6330 /* If this is the first time lang_size_sections is called,
6331 we won't have any padding statements. If this is the
6332 second or later passes when relaxing, we should allow
6333 padding to shrink. If padding is needed on this pass, it
6334 will be added back in. */
6335 s->padding_statement.size = 0;
6337 /* Make sure output_offset is valid. If relaxation shrinks
6338 the section and this pad isn't needed, it's possible to
6339 have output_offset larger than the final size of the
6340 section. bfd_set_section_contents will complain even for
6341 a pad size of zero. */
6342 s->padding_statement.output_offset
6343 = dot - current_os->bfd_section->vma;
6344 break;
6346 case lang_group_statement_enum:
6347 dot = lang_size_sections_1 (&s->group_statement.children.head,
6348 current_os, fill, dot, relax,
6349 check_regions);
6350 break;
6352 case lang_insert_statement_enum:
6353 break;
6355 /* We can only get here when relaxing is turned on. */
6356 case lang_address_statement_enum:
6357 break;
6359 default:
6360 FAIL ();
6361 break;
6364 /* If an input section doesn't fit in the current output
6365 section, remove it from the list. Handle the case where we
6366 have to remove an input_section statement here: there is a
6367 special case to remove the first element of the list. */
6368 if (link_info.non_contiguous_regions && removed)
6370 /* If we removed the first element during the previous
6371 iteration, override the loop assignment of prev_s. */
6372 if (removed_prev_s)
6373 prev_s = NULL;
6375 if (prev_s)
6377 /* If there was a real previous input section, just skip
6378 the current one. */
6379 prev_s->header.next=s->header.next;
6380 s = prev_s;
6381 removed_prev_s = false;
6383 else
6385 /* Remove the first input section of the list. */
6386 *prev = s->header.next;
6387 removed_prev_s = true;
6390 /* Move to next element, unless we removed the head of the
6391 list. */
6392 if (!removed_prev_s)
6393 prev = &s->header.next;
6395 else
6397 prev = &s->header.next;
6398 removed_prev_s = false;
6401 return dot;
6404 /* Callback routine that is used in _bfd_elf_map_sections_to_segments.
6405 The BFD library has set NEW_SEGMENT to TRUE iff it thinks that
6406 CURRENT_SECTION and PREVIOUS_SECTION ought to be placed into different
6407 segments. We are allowed an opportunity to override this decision. */
6409 bool
6410 ldlang_override_segment_assignment (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6411 bfd *abfd ATTRIBUTE_UNUSED,
6412 asection *current_section,
6413 asection *previous_section,
6414 bool new_segment)
6416 lang_output_section_statement_type *cur;
6417 lang_output_section_statement_type *prev;
6419 /* The checks below are only necessary when the BFD library has decided
6420 that the two sections ought to be placed into the same segment. */
6421 if (new_segment)
6422 return true;
6424 /* Paranoia checks. */
6425 if (current_section == NULL || previous_section == NULL)
6426 return new_segment;
6428 /* If this flag is set, the target never wants code and non-code
6429 sections comingled in the same segment. */
6430 if (config.separate_code
6431 && ((current_section->flags ^ previous_section->flags) & SEC_CODE))
6432 return true;
6434 /* Find the memory regions associated with the two sections.
6435 We call lang_output_section_find() here rather than scanning the list
6436 of output sections looking for a matching section pointer because if
6437 we have a large number of sections then a hash lookup is faster. */
6438 cur = lang_output_section_find (current_section->name);
6439 prev = lang_output_section_find (previous_section->name);
6441 /* More paranoia. */
6442 if (cur == NULL || prev == NULL)
6443 return new_segment;
6445 /* If the regions are different then force the sections to live in
6446 different segments. See the email thread starting at the following
6447 URL for the reasons why this is necessary:
6448 http://sourceware.org/ml/binutils/2007-02/msg00216.html */
6449 return cur->region != prev->region;
6452 void
6453 one_lang_size_sections_pass (bool *relax, bool check_regions)
6455 lang_statement_iteration++;
6456 if (expld.phase != lang_mark_phase_enum)
6457 lang_sizing_iteration++;
6458 lang_size_sections_1 (&statement_list.head, abs_output_section,
6459 0, 0, relax, check_regions);
6462 static bool
6463 lang_size_segment (void)
6465 /* If XXX_SEGMENT_ALIGN XXX_SEGMENT_END pair was seen, check whether
6466 a page could be saved in the data segment. */
6467 seg_align_type *seg = &expld.dataseg;
6468 bfd_vma first, last;
6470 first = -seg->base & (seg->commonpagesize - 1);
6471 last = seg->end & (seg->commonpagesize - 1);
6472 if (first && last
6473 && ((seg->base & ~(seg->commonpagesize - 1))
6474 != (seg->end & ~(seg->commonpagesize - 1)))
6475 && first + last <= seg->commonpagesize)
6477 seg->phase = exp_seg_adjust;
6478 return true;
6481 seg->phase = exp_seg_done;
6482 return false;
6485 static bfd_vma
6486 lang_size_relro_segment_1 (void)
6488 seg_align_type *seg = &expld.dataseg;
6489 bfd_vma relro_end, desired_end;
6490 asection *sec;
6492 /* Compute the expected PT_GNU_RELRO/PT_LOAD segment end. */
6493 relro_end = (seg->relro_end + seg->relropagesize - 1) & -seg->relropagesize;
6495 /* Adjust by the offset arg of XXX_SEGMENT_RELRO_END. */
6496 desired_end = relro_end - seg->relro_offset;
6498 /* For sections in the relro segment.. */
6499 for (sec = link_info.output_bfd->section_last; sec; sec = sec->prev)
6500 if ((sec->flags & SEC_ALLOC) != 0
6501 && sec->vma >= seg->base
6502 && sec->vma < seg->relro_end - seg->relro_offset)
6504 /* Where do we want to put this section so that it ends as
6505 desired? */
6506 bfd_vma start, end, bump;
6508 end = start = sec->vma;
6509 if (!IS_TBSS (sec))
6510 end += TO_ADDR (sec->size);
6511 bump = desired_end - end;
6512 /* We'd like to increase START by BUMP, but we must heed
6513 alignment so the increase might be less than optimum. */
6514 start += bump;
6515 start &= ~(((bfd_vma) 1 << sec->alignment_power) - 1);
6516 /* This is now the desired end for the previous section. */
6517 desired_end = start;
6520 seg->phase = exp_seg_relro_adjust;
6521 ASSERT (desired_end >= seg->base);
6522 seg->base = desired_end;
6523 return relro_end;
6526 static bool
6527 lang_size_relro_segment (bool *relax, bool check_regions)
6529 bool do_reset = false;
6531 if (link_info.relro && expld.dataseg.relro_end)
6533 bfd_vma data_initial_base = expld.dataseg.base;
6534 bfd_vma data_relro_end = lang_size_relro_segment_1 ();
6536 lang_reset_memory_regions ();
6537 one_lang_size_sections_pass (relax, check_regions);
6539 /* Assignments to dot, or to output section address in a user
6540 script have increased padding over the original. Revert. */
6541 if (expld.dataseg.relro_end > data_relro_end)
6543 expld.dataseg.base = data_initial_base;
6544 do_reset = true;
6547 else if (lang_size_segment ())
6548 do_reset = true;
6550 return do_reset;
6553 void
6554 lang_size_sections (bool *relax, bool check_regions)
6556 expld.phase = lang_allocating_phase_enum;
6557 expld.dataseg.phase = exp_seg_none;
6559 one_lang_size_sections_pass (relax, check_regions);
6561 if (expld.dataseg.phase != exp_seg_end_seen)
6562 expld.dataseg.phase = exp_seg_done;
6564 if (expld.dataseg.phase == exp_seg_end_seen)
6566 bool do_reset
6567 = lang_size_relro_segment (relax, check_regions);
6569 if (do_reset)
6571 lang_reset_memory_regions ();
6572 one_lang_size_sections_pass (relax, check_regions);
6575 if (link_info.relro && expld.dataseg.relro_end)
6577 link_info.relro_start = expld.dataseg.base;
6578 link_info.relro_end = expld.dataseg.relro_end;
6583 static lang_output_section_statement_type *current_section;
6584 static lang_assignment_statement_type *current_assign;
6585 static bool prefer_next_section;
6587 /* Worker function for lang_do_assignments. Recursiveness goes here. */
6589 static bfd_vma
6590 lang_do_assignments_1 (lang_statement_union_type *s,
6591 lang_output_section_statement_type *current_os,
6592 fill_type *fill,
6593 bfd_vma dot,
6594 bool *found_end)
6596 lang_output_section_statement_type *os = current_os;
6598 for (; s != NULL; s = s->header.next)
6600 switch (s->header.type)
6602 case lang_constructors_statement_enum:
6603 dot = lang_do_assignments_1 (constructor_list.head,
6604 current_os, fill, dot, found_end);
6605 break;
6607 case lang_output_section_statement_enum:
6609 bfd_vma newdot;
6611 os = &s->output_section_statement;
6612 os->after_end = *found_end;
6613 init_opb (os->bfd_section);
6614 newdot = dot;
6615 if (os->bfd_section != NULL)
6617 if (!os->ignored && (os->bfd_section->flags & SEC_ALLOC) != 0)
6619 current_section = os;
6620 prefer_next_section = false;
6622 newdot = os->bfd_section->vma;
6624 newdot = lang_do_assignments_1 (os->children.head,
6625 os, os->fill, newdot, found_end);
6626 if (!os->ignored)
6628 if (os->bfd_section != NULL)
6630 newdot = os->bfd_section->vma;
6632 /* .tbss sections effectively have zero size. */
6633 if (!IS_TBSS (os->bfd_section)
6634 || bfd_link_relocatable (&link_info))
6635 newdot += TO_ADDR (os->bfd_section->size);
6637 if (os->update_dot_tree != NULL)
6638 exp_fold_tree (os->update_dot_tree, os,
6639 bfd_abs_section_ptr, &newdot);
6641 dot = newdot;
6644 break;
6646 case lang_wild_statement_enum:
6648 dot = lang_do_assignments_1 (s->wild_statement.children.head,
6649 current_os, fill, dot, found_end);
6650 break;
6652 case lang_object_symbols_statement_enum:
6653 case lang_output_statement_enum:
6654 case lang_target_statement_enum:
6655 break;
6657 case lang_data_statement_enum:
6658 exp_fold_tree (s->data_statement.exp, os, bfd_abs_section_ptr, &dot);
6659 if (expld.result.valid_p)
6661 s->data_statement.value = expld.result.value;
6662 if (expld.result.section != NULL)
6663 s->data_statement.value += expld.result.section->vma;
6665 else if (expld.phase == lang_final_phase_enum)
6666 einfo (_("%F%P: invalid data statement\n"));
6668 unsigned int size;
6669 switch (s->data_statement.type)
6671 default:
6672 abort ();
6673 case QUAD:
6674 case SQUAD:
6675 size = QUAD_SIZE;
6676 break;
6677 case LONG:
6678 size = LONG_SIZE;
6679 break;
6680 case SHORT:
6681 size = SHORT_SIZE;
6682 break;
6683 case BYTE:
6684 size = BYTE_SIZE;
6685 break;
6687 if (size < TO_SIZE ((unsigned) 1))
6688 size = TO_SIZE ((unsigned) 1);
6689 dot += TO_ADDR (size);
6691 break;
6693 case lang_reloc_statement_enum:
6694 exp_fold_tree (s->reloc_statement.addend_exp, os,
6695 bfd_abs_section_ptr, &dot);
6696 if (expld.result.valid_p)
6697 s->reloc_statement.addend_value = expld.result.value;
6698 else if (expld.phase == lang_final_phase_enum)
6699 einfo (_("%F%P: invalid reloc statement\n"));
6700 dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
6701 break;
6703 case lang_input_section_enum:
6705 asection *in = s->input_section.section;
6707 if ((in->flags & SEC_EXCLUDE) == 0)
6708 dot += TO_ADDR (in->size);
6710 break;
6712 case lang_input_statement_enum:
6713 break;
6715 case lang_fill_statement_enum:
6716 fill = s->fill_statement.fill;
6717 break;
6719 case lang_assignment_statement_enum:
6720 current_assign = &s->assignment_statement;
6721 if (current_assign->exp->type.node_class != etree_assert)
6723 const char *p = current_assign->exp->assign.dst;
6725 if (current_os == abs_output_section && p[0] == '.' && p[1] == 0)
6726 prefer_next_section = true;
6728 while (*p == '_')
6729 ++p;
6730 if (strcmp (p, "end") == 0)
6731 *found_end = true;
6733 exp_fold_tree (s->assignment_statement.exp, os,
6734 (current_os->bfd_section != NULL
6735 ? current_os->bfd_section : bfd_und_section_ptr),
6736 &dot);
6737 break;
6739 case lang_padding_statement_enum:
6740 dot += TO_ADDR (s->padding_statement.size);
6741 break;
6743 case lang_group_statement_enum:
6744 dot = lang_do_assignments_1 (s->group_statement.children.head,
6745 current_os, fill, dot, found_end);
6746 break;
6748 case lang_insert_statement_enum:
6749 break;
6751 case lang_address_statement_enum:
6752 break;
6754 default:
6755 FAIL ();
6756 break;
6759 return dot;
6762 void
6763 lang_do_assignments (lang_phase_type phase)
6765 bool found_end = false;
6767 current_section = NULL;
6768 prefer_next_section = false;
6769 expld.phase = phase;
6770 lang_statement_iteration++;
6771 lang_do_assignments_1 (statement_list.head,
6772 abs_output_section, NULL, 0, &found_end);
6775 /* For an assignment statement outside of an output section statement,
6776 choose the best of neighbouring output sections to use for values
6777 of "dot". */
6779 asection *
6780 section_for_dot (void)
6782 asection *s;
6784 /* Assignments belong to the previous output section, unless there
6785 has been an assignment to "dot", in which case following
6786 assignments belong to the next output section. (The assumption
6787 is that an assignment to "dot" is setting up the address for the
6788 next output section.) Except that past the assignment to "_end"
6789 we always associate with the previous section. This exception is
6790 for targets like SH that define an alloc .stack or other
6791 weirdness after non-alloc sections. */
6792 if (current_section == NULL || prefer_next_section)
6794 lang_statement_union_type *stmt;
6795 lang_output_section_statement_type *os;
6797 for (stmt = (lang_statement_union_type *) current_assign;
6798 stmt != NULL;
6799 stmt = stmt->header.next)
6800 if (stmt->header.type == lang_output_section_statement_enum)
6801 break;
6803 os = stmt ? &stmt->output_section_statement : NULL;
6804 while (os != NULL
6805 && !os->after_end
6806 && (os->bfd_section == NULL
6807 || (os->bfd_section->flags & SEC_EXCLUDE) != 0
6808 || bfd_section_removed_from_list (link_info.output_bfd,
6809 os->bfd_section)))
6810 os = os->next;
6812 if (current_section == NULL || os == NULL || !os->after_end)
6814 if (os != NULL)
6815 s = os->bfd_section;
6816 else
6817 s = link_info.output_bfd->section_last;
6818 while (s != NULL
6819 && ((s->flags & SEC_ALLOC) == 0
6820 || (s->flags & SEC_THREAD_LOCAL) != 0))
6821 s = s->prev;
6822 if (s != NULL)
6823 return s;
6825 return bfd_abs_section_ptr;
6829 s = current_section->bfd_section;
6831 /* The section may have been stripped. */
6832 while (s != NULL
6833 && ((s->flags & SEC_EXCLUDE) != 0
6834 || (s->flags & SEC_ALLOC) == 0
6835 || (s->flags & SEC_THREAD_LOCAL) != 0
6836 || bfd_section_removed_from_list (link_info.output_bfd, s)))
6837 s = s->prev;
6838 if (s == NULL)
6839 s = link_info.output_bfd->sections;
6840 while (s != NULL
6841 && ((s->flags & SEC_ALLOC) == 0
6842 || (s->flags & SEC_THREAD_LOCAL) != 0))
6843 s = s->next;
6844 if (s != NULL)
6845 return s;
6847 return bfd_abs_section_ptr;
6850 /* Array of __start/__stop/.startof./.sizeof/ symbols. */
6852 static struct bfd_link_hash_entry **start_stop_syms;
6853 static size_t start_stop_count = 0;
6854 static size_t start_stop_alloc = 0;
6856 /* Give start/stop SYMBOL for SEC a preliminary definition, and add it
6857 to start_stop_syms. */
6859 static void
6860 lang_define_start_stop (const char *symbol, asection *sec)
6862 struct bfd_link_hash_entry *h;
6864 h = bfd_define_start_stop (link_info.output_bfd, &link_info, symbol, sec);
6865 if (h != NULL)
6867 if (start_stop_count == start_stop_alloc)
6869 start_stop_alloc = 2 * start_stop_alloc + 10;
6870 start_stop_syms
6871 = xrealloc (start_stop_syms,
6872 start_stop_alloc * sizeof (*start_stop_syms));
6874 start_stop_syms[start_stop_count++] = h;
6878 /* Check for input sections whose names match references to
6879 __start_SECNAME or __stop_SECNAME symbols. Give the symbols
6880 preliminary definitions. */
6882 static void
6883 lang_init_start_stop (void)
6885 bfd *abfd;
6886 asection *s;
6887 char leading_char = bfd_get_symbol_leading_char (link_info.output_bfd);
6889 for (abfd = link_info.input_bfds; abfd != NULL; abfd = abfd->link.next)
6890 for (s = abfd->sections; s != NULL; s = s->next)
6892 const char *ps;
6893 const char *secname = s->name;
6895 for (ps = secname; *ps != '\0'; ps++)
6896 if (!ISALNUM ((unsigned char) *ps) && *ps != '_')
6897 break;
6898 if (*ps == '\0')
6900 char *symbol = (char *) xmalloc (10 + strlen (secname));
6902 symbol[0] = leading_char;
6903 sprintf (symbol + (leading_char != 0), "__start_%s", secname);
6904 lang_define_start_stop (symbol, s);
6906 symbol[1] = leading_char;
6907 memcpy (symbol + 1 + (leading_char != 0), "__stop", 6);
6908 lang_define_start_stop (symbol + 1, s);
6910 free (symbol);
6915 /* Iterate over start_stop_syms. */
6917 static void
6918 foreach_start_stop (void (*func) (struct bfd_link_hash_entry *))
6920 size_t i;
6922 for (i = 0; i < start_stop_count; ++i)
6923 func (start_stop_syms[i]);
6926 /* __start and __stop symbols are only supposed to be defined by the
6927 linker for orphan sections, but we now extend that to sections that
6928 map to an output section of the same name. The symbols were
6929 defined early for --gc-sections, before we mapped input to output
6930 sections, so undo those that don't satisfy this rule. */
6932 static void
6933 undef_start_stop (struct bfd_link_hash_entry *h)
6935 if (h->ldscript_def)
6936 return;
6938 if (h->u.def.section->output_section == NULL
6939 || h->u.def.section->output_section->owner != link_info.output_bfd
6940 || strcmp (h->u.def.section->name,
6941 h->u.def.section->output_section->name) != 0)
6943 asection *sec = bfd_get_section_by_name (link_info.output_bfd,
6944 h->u.def.section->name);
6945 if (sec != NULL)
6947 /* When there are more than one input sections with the same
6948 section name, SECNAME, linker picks the first one to define
6949 __start_SECNAME and __stop_SECNAME symbols. When the first
6950 input section is removed by comdat group, we need to check
6951 if there is still an output section with section name
6952 SECNAME. */
6953 asection *i;
6954 for (i = sec->map_head.s; i != NULL; i = i->map_head.s)
6955 if (strcmp (h->u.def.section->name, i->name) == 0)
6957 h->u.def.section = i;
6958 return;
6961 h->type = bfd_link_hash_undefined;
6962 h->u.undef.abfd = NULL;
6963 if (is_elf_hash_table (link_info.hash))
6965 const struct elf_backend_data *bed;
6966 struct elf_link_hash_entry *eh = (struct elf_link_hash_entry *) h;
6967 unsigned int was_forced = eh->forced_local;
6969 bed = get_elf_backend_data (link_info.output_bfd);
6970 (*bed->elf_backend_hide_symbol) (&link_info, eh, true);
6971 if (!eh->ref_regular_nonweak)
6972 h->type = bfd_link_hash_undefweak;
6973 eh->def_regular = 0;
6974 eh->forced_local = was_forced;
6979 static void
6980 lang_undef_start_stop (void)
6982 foreach_start_stop (undef_start_stop);
6985 /* Check for output sections whose names match references to
6986 .startof.SECNAME or .sizeof.SECNAME symbols. Give the symbols
6987 preliminary definitions. */
6989 static void
6990 lang_init_startof_sizeof (void)
6992 asection *s;
6994 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
6996 const char *secname = s->name;
6997 char *symbol = (char *) xmalloc (10 + strlen (secname));
6999 sprintf (symbol, ".startof.%s", secname);
7000 lang_define_start_stop (symbol, s);
7002 memcpy (symbol + 1, ".size", 5);
7003 lang_define_start_stop (symbol + 1, s);
7004 free (symbol);
7008 /* Set .startof., .sizeof., __start and __stop symbols final values. */
7010 static void
7011 set_start_stop (struct bfd_link_hash_entry *h)
7013 if (h->ldscript_def
7014 || h->type != bfd_link_hash_defined)
7015 return;
7017 if (h->root.string[0] == '.')
7019 /* .startof. or .sizeof. symbol.
7020 .startof. already has final value. */
7021 if (h->root.string[2] == 'i')
7023 /* .sizeof. */
7024 h->u.def.value = TO_ADDR (h->u.def.section->size);
7025 h->u.def.section = bfd_abs_section_ptr;
7028 else
7030 /* __start or __stop symbol. */
7031 int has_lead = bfd_get_symbol_leading_char (link_info.output_bfd) != 0;
7033 h->u.def.section = h->u.def.section->output_section;
7034 if (h->root.string[4 + has_lead] == 'o')
7036 /* __stop_ */
7037 h->u.def.value = TO_ADDR (h->u.def.section->size);
7042 static void
7043 lang_finalize_start_stop (void)
7045 foreach_start_stop (set_start_stop);
7048 static void
7049 lang_symbol_tweaks (void)
7051 /* Give initial values for __start and __stop symbols, so that ELF
7052 gc_sections will keep sections referenced by these symbols. Must
7053 be done before lang_do_assignments. */
7054 if (config.build_constructors)
7055 lang_init_start_stop ();
7057 /* Make __ehdr_start hidden, and set def_regular even though it is
7058 likely undefined at this stage. For lang_check_relocs. */
7059 if (is_elf_hash_table (link_info.hash)
7060 && !bfd_link_relocatable (&link_info))
7062 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
7063 bfd_link_hash_lookup (link_info.hash, "__ehdr_start",
7064 false, false, true);
7066 /* Only adjust the export class if the symbol was referenced
7067 and not defined, otherwise leave it alone. */
7068 if (h != NULL
7069 && (h->root.type == bfd_link_hash_new
7070 || h->root.type == bfd_link_hash_undefined
7071 || h->root.type == bfd_link_hash_undefweak
7072 || h->root.type == bfd_link_hash_common))
7074 const struct elf_backend_data *bed;
7075 bed = get_elf_backend_data (link_info.output_bfd);
7076 (*bed->elf_backend_hide_symbol) (&link_info, h, true);
7077 if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
7078 h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
7079 h->def_regular = 1;
7080 h->root.linker_def = 1;
7081 h->root.rel_from_abs = 1;
7086 static void
7087 lang_end (void)
7089 struct bfd_link_hash_entry *h;
7090 bool warn;
7092 if ((bfd_link_relocatable (&link_info) && !link_info.gc_sections)
7093 || bfd_link_dll (&link_info))
7094 warn = entry_from_cmdline;
7095 else
7096 warn = true;
7098 /* Force the user to specify a root when generating a relocatable with
7099 --gc-sections, unless --gc-keep-exported was also given. */
7100 if (bfd_link_relocatable (&link_info)
7101 && link_info.gc_sections
7102 && !link_info.gc_keep_exported)
7104 struct bfd_sym_chain *sym;
7106 for (sym = link_info.gc_sym_list; sym != NULL; sym = sym->next)
7108 h = bfd_link_hash_lookup (link_info.hash, sym->name,
7109 false, false, false);
7110 if (h != NULL
7111 && (h->type == bfd_link_hash_defined
7112 || h->type == bfd_link_hash_defweak)
7113 && !bfd_is_const_section (h->u.def.section))
7114 break;
7116 if (!sym)
7117 einfo (_("%F%P: --gc-sections requires a defined symbol root "
7118 "specified by -e or -u\n"));
7121 if (entry_symbol.name == NULL)
7123 /* No entry has been specified. Look for the default entry, but
7124 don't warn if we don't find it. */
7125 entry_symbol.name = entry_symbol_default;
7126 warn = false;
7129 h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
7130 false, false, true);
7131 if (h != NULL
7132 && (h->type == bfd_link_hash_defined
7133 || h->type == bfd_link_hash_defweak)
7134 && h->u.def.section->output_section != NULL)
7136 bfd_vma val;
7138 val = (h->u.def.value
7139 + bfd_section_vma (h->u.def.section->output_section)
7140 + h->u.def.section->output_offset);
7141 if (!bfd_set_start_address (link_info.output_bfd, val))
7142 einfo (_("%F%P: %s: can't set start address\n"), entry_symbol.name);
7144 else
7146 bfd_vma val;
7147 const char *send;
7149 /* We couldn't find the entry symbol. Try parsing it as a
7150 number. */
7151 val = bfd_scan_vma (entry_symbol.name, &send, 0);
7152 if (*send == '\0')
7154 if (!bfd_set_start_address (link_info.output_bfd, val))
7155 einfo (_("%F%P: can't set start address\n"));
7157 /* BZ 2004952: Only use the start of the entry section for executables. */
7158 else if bfd_link_executable (&link_info)
7160 asection *ts;
7162 /* Can't find the entry symbol, and it's not a number. Use
7163 the first address in the text section. */
7164 ts = bfd_get_section_by_name (link_info.output_bfd, entry_section);
7165 if (ts != NULL)
7167 if (warn)
7168 einfo (_("%P: warning: cannot find entry symbol %s;"
7169 " defaulting to %V\n"),
7170 entry_symbol.name,
7171 bfd_section_vma (ts));
7172 if (!bfd_set_start_address (link_info.output_bfd,
7173 bfd_section_vma (ts)))
7174 einfo (_("%F%P: can't set start address\n"));
7176 else
7178 if (warn)
7179 einfo (_("%P: warning: cannot find entry symbol %s;"
7180 " not setting start address\n"),
7181 entry_symbol.name);
7184 else
7186 if (warn)
7187 einfo (_("%P: warning: cannot find entry symbol %s;"
7188 " not setting start address\n"),
7189 entry_symbol.name);
7194 /* This is a small function used when we want to ignore errors from
7195 BFD. */
7197 static void
7198 ignore_bfd_errors (const char *fmt ATTRIBUTE_UNUSED,
7199 va_list ap ATTRIBUTE_UNUSED)
7201 /* Don't do anything. */
7204 /* Check that the architecture of all the input files is compatible
7205 with the output file. Also call the backend to let it do any
7206 other checking that is needed. */
7208 static void
7209 lang_check (void)
7211 lang_input_statement_type *file;
7212 bfd *input_bfd;
7213 const bfd_arch_info_type *compatible;
7215 for (file = (void *) file_chain.head;
7216 file != NULL;
7217 file = file->next)
7219 #if BFD_SUPPORTS_PLUGINS
7220 /* Don't check format of files claimed by plugin. */
7221 if (file->flags.claimed)
7222 continue;
7223 #endif /* BFD_SUPPORTS_PLUGINS */
7224 input_bfd = file->the_bfd;
7225 compatible
7226 = bfd_arch_get_compatible (input_bfd, link_info.output_bfd,
7227 command_line.accept_unknown_input_arch);
7229 /* In general it is not possible to perform a relocatable
7230 link between differing object formats when the input
7231 file has relocations, because the relocations in the
7232 input format may not have equivalent representations in
7233 the output format (and besides BFD does not translate
7234 relocs for other link purposes than a final link). */
7235 if (!file->flags.just_syms
7236 && (bfd_link_relocatable (&link_info)
7237 || link_info.emitrelocations)
7238 && (compatible == NULL
7239 || (bfd_get_flavour (input_bfd)
7240 != bfd_get_flavour (link_info.output_bfd)))
7241 && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
7243 einfo (_("%F%P: relocatable linking with relocations from"
7244 " format %s (%pB) to format %s (%pB) is not supported\n"),
7245 bfd_get_target (input_bfd), input_bfd,
7246 bfd_get_target (link_info.output_bfd), link_info.output_bfd);
7247 /* einfo with %F exits. */
7250 if (compatible == NULL)
7252 if (command_line.warn_mismatch)
7253 einfo (_("%X%P: %s architecture of input file `%pB'"
7254 " is incompatible with %s output\n"),
7255 bfd_printable_name (input_bfd), input_bfd,
7256 bfd_printable_name (link_info.output_bfd));
7259 /* If the input bfd has no contents, it shouldn't set the
7260 private data of the output bfd. */
7261 else if (!file->flags.just_syms
7262 && ((input_bfd->flags & DYNAMIC) != 0
7263 || bfd_count_sections (input_bfd) != 0))
7265 bfd_error_handler_type pfn = NULL;
7267 /* If we aren't supposed to warn about mismatched input
7268 files, temporarily set the BFD error handler to a
7269 function which will do nothing. We still want to call
7270 bfd_merge_private_bfd_data, since it may set up
7271 information which is needed in the output file. */
7272 if (!command_line.warn_mismatch)
7273 pfn = bfd_set_error_handler (ignore_bfd_errors);
7274 if (!bfd_merge_private_bfd_data (input_bfd, &link_info))
7276 if (command_line.warn_mismatch)
7277 einfo (_("%X%P: failed to merge target specific data"
7278 " of file %pB\n"), input_bfd);
7280 if (!command_line.warn_mismatch)
7281 bfd_set_error_handler (pfn);
7286 /* Look through all the global common symbols and attach them to the
7287 correct section. The -sort-common command line switch may be used
7288 to roughly sort the entries by alignment. */
7290 static void
7291 lang_common (void)
7293 if (link_info.inhibit_common_definition)
7294 return;
7295 if (bfd_link_relocatable (&link_info)
7296 && !command_line.force_common_definition)
7297 return;
7299 if (!config.sort_common)
7300 bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
7301 else
7303 unsigned int power;
7305 if (config.sort_common == sort_descending)
7307 for (power = 4; power > 0; power--)
7308 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7310 power = 0;
7311 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7313 else
7315 for (power = 0; power <= 4; power++)
7316 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7318 power = (unsigned int) -1;
7319 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7324 /* Place one common symbol in the correct section. */
7326 static bool
7327 lang_one_common (struct bfd_link_hash_entry *h, void *info)
7329 unsigned int power_of_two;
7330 bfd_vma size;
7331 asection *section;
7333 if (h->type != bfd_link_hash_common)
7334 return true;
7336 size = h->u.c.size;
7337 power_of_two = h->u.c.p->alignment_power;
7339 if (config.sort_common == sort_descending
7340 && power_of_two < *(unsigned int *) info)
7341 return true;
7342 else if (config.sort_common == sort_ascending
7343 && power_of_two > *(unsigned int *) info)
7344 return true;
7346 section = h->u.c.p->section;
7347 if (!bfd_define_common_symbol (link_info.output_bfd, &link_info, h))
7348 einfo (_("%F%P: could not define common symbol `%pT': %E\n"),
7349 h->root.string);
7351 if (config.map_file != NULL)
7353 static bool header_printed;
7354 int len;
7355 char *name;
7356 char buf[32];
7358 if (!header_printed)
7360 minfo (_("\nAllocating common symbols\n"));
7361 minfo (_("Common symbol size file\n\n"));
7362 header_printed = true;
7365 name = bfd_demangle (link_info.output_bfd, h->root.string,
7366 DMGL_ANSI | DMGL_PARAMS);
7367 if (name == NULL)
7369 minfo ("%s", h->root.string);
7370 len = strlen (h->root.string);
7372 else
7374 minfo ("%s", name);
7375 len = strlen (name);
7376 free (name);
7379 if (len >= 19)
7381 print_nl ();
7382 len = 0;
7385 sprintf (buf, "%" PRIx64, (uint64_t) size);
7386 fprintf (config.map_file, "%*s0x%-16s", 20 - len, "", buf);
7388 minfo ("%pB\n", section->owner);
7391 return true;
7394 /* Handle a single orphan section S, placing the orphan into an appropriate
7395 output section. The effects of the --orphan-handling command line
7396 option are handled here. */
7398 static void
7399 ldlang_place_orphan (asection *s)
7401 if (config.orphan_handling == orphan_handling_discard)
7403 lang_output_section_statement_type *os;
7404 os = lang_output_section_statement_lookup (DISCARD_SECTION_NAME, 0, 1);
7405 if (os->addr_tree == NULL
7406 && (bfd_link_relocatable (&link_info)
7407 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7408 os->addr_tree = exp_intop (0);
7409 lang_add_section (&os->children, s, NULL, NULL, os);
7411 else
7413 lang_output_section_statement_type *os;
7414 const char *name = s->name;
7415 int constraint = 0;
7417 if (config.orphan_handling == orphan_handling_error)
7418 einfo (_("%X%P: error: unplaced orphan section `%pA' from `%pB'\n"),
7419 s, s->owner);
7421 if (config.unique_orphan_sections || unique_section_p (s, NULL))
7422 constraint = SPECIAL;
7424 os = ldemul_place_orphan (s, name, constraint);
7425 if (os == NULL)
7427 os = lang_output_section_statement_lookup (name, constraint, 1);
7428 if (os->addr_tree == NULL
7429 && (bfd_link_relocatable (&link_info)
7430 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7431 os->addr_tree = exp_intop (0);
7432 lang_add_section (&os->children, s, NULL, NULL, os);
7435 if (config.orphan_handling == orphan_handling_warn)
7436 einfo (_("%P: warning: orphan section `%pA' from `%pB' being "
7437 "placed in section `%s'\n"),
7438 s, s->owner, os->name);
7442 /* Run through the input files and ensure that every input section has
7443 somewhere to go. If one is found without a destination then create
7444 an input request and place it into the statement tree. */
7446 static void
7447 lang_place_orphans (void)
7449 LANG_FOR_EACH_INPUT_STATEMENT (file)
7451 asection *s;
7453 for (s = file->the_bfd->sections; s != NULL; s = s->next)
7455 if (s->output_section == NULL)
7457 /* This section of the file is not attached, root
7458 around for a sensible place for it to go. */
7460 if (file->flags.just_syms)
7461 bfd_link_just_syms (file->the_bfd, s, &link_info);
7462 else if (lang_discard_section_p (s))
7463 s->output_section = bfd_abs_section_ptr;
7464 else if (strcmp (s->name, "COMMON") == 0)
7466 /* This is a lonely common section which must have
7467 come from an archive. We attach to the section
7468 with the wildcard. */
7469 if (!bfd_link_relocatable (&link_info)
7470 || command_line.force_common_definition)
7472 if (default_common_section == NULL)
7473 default_common_section
7474 = lang_output_section_statement_lookup (".bss", 0, 1);
7475 lang_add_section (&default_common_section->children, s,
7476 NULL, NULL, default_common_section);
7479 else
7480 ldlang_place_orphan (s);
7486 void
7487 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
7489 flagword *ptr_flags;
7491 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7493 while (*flags)
7495 switch (*flags)
7497 /* PR 17900: An exclamation mark in the attributes reverses
7498 the sense of any of the attributes that follow. */
7499 case '!':
7500 invert = !invert;
7501 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7502 break;
7504 case 'A': case 'a':
7505 *ptr_flags |= SEC_ALLOC;
7506 break;
7508 case 'R': case 'r':
7509 *ptr_flags |= SEC_READONLY;
7510 break;
7512 case 'W': case 'w':
7513 *ptr_flags |= SEC_DATA;
7514 break;
7516 case 'X': case 'x':
7517 *ptr_flags |= SEC_CODE;
7518 break;
7520 case 'L': case 'l':
7521 case 'I': case 'i':
7522 *ptr_flags |= SEC_LOAD;
7523 break;
7525 default:
7526 einfo (_("%F%P: invalid character %c (%d) in flags\n"),
7527 *flags, *flags);
7528 break;
7530 flags++;
7534 /* Call a function on each real input file. This function will be
7535 called on an archive, but not on the elements. */
7537 void
7538 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
7540 lang_input_statement_type *f;
7542 for (f = (void *) input_file_chain.head;
7543 f != NULL;
7544 f = f->next_real_file)
7545 if (f->flags.real)
7546 func (f);
7549 /* Call a function on each real file. The function will be called on
7550 all the elements of an archive which are included in the link, but
7551 will not be called on the archive file itself. */
7553 void
7554 lang_for_each_file (void (*func) (lang_input_statement_type *))
7556 LANG_FOR_EACH_INPUT_STATEMENT (f)
7558 if (f->flags.real)
7559 func (f);
7563 void
7564 ldlang_add_file (lang_input_statement_type *entry)
7566 lang_statement_append (&file_chain, entry, &entry->next);
7568 /* The BFD linker needs to have a list of all input BFDs involved in
7569 a link. */
7570 ASSERT (link_info.input_bfds_tail != &entry->the_bfd->link.next
7571 && entry->the_bfd->link.next == NULL);
7572 ASSERT (entry->the_bfd != link_info.output_bfd);
7574 *link_info.input_bfds_tail = entry->the_bfd;
7575 link_info.input_bfds_tail = &entry->the_bfd->link.next;
7576 bfd_set_usrdata (entry->the_bfd, entry);
7577 bfd_set_gp_size (entry->the_bfd, g_switch_value);
7579 /* Look through the sections and check for any which should not be
7580 included in the link. We need to do this now, so that we can
7581 notice when the backend linker tries to report multiple
7582 definition errors for symbols which are in sections we aren't
7583 going to link. FIXME: It might be better to entirely ignore
7584 symbols which are defined in sections which are going to be
7585 discarded. This would require modifying the backend linker for
7586 each backend which might set the SEC_LINK_ONCE flag. If we do
7587 this, we should probably handle SEC_EXCLUDE in the same way. */
7589 bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
7592 void
7593 lang_add_output (const char *name, int from_script)
7595 /* Make -o on command line override OUTPUT in script. */
7596 if (!had_output_filename || !from_script)
7598 output_filename = name;
7599 had_output_filename = true;
7603 lang_output_section_statement_type *
7604 lang_enter_output_section_statement (const char *output_section_statement_name,
7605 etree_type *address_exp,
7606 enum section_type sectype,
7607 etree_type *sectype_value,
7608 etree_type *align,
7609 etree_type *subalign,
7610 etree_type *ebase,
7611 int constraint,
7612 int align_with_input)
7614 lang_output_section_statement_type *os;
7616 os = lang_output_section_statement_lookup (output_section_statement_name,
7617 constraint,
7618 in_section_ordering ? 0 : 2);
7619 if (os == NULL) /* && in_section_ordering */
7620 einfo (_("%F%P:%pS: error: output section '%s' must already exist\n"),
7621 NULL, output_section_statement_name);
7622 current_section = os;
7624 /* Make next things chain into subchain of this. */
7625 push_stat_ptr (in_section_ordering ? &os->sort_children : &os->children);
7627 if (in_section_ordering)
7628 return os;
7630 if (os->addr_tree == NULL)
7631 os->addr_tree = address_exp;
7633 os->sectype = sectype;
7634 if (sectype == type_section || sectype == typed_readonly_section)
7635 os->sectype_value = sectype_value;
7636 else if (sectype == noload_section)
7637 os->flags = SEC_NEVER_LOAD;
7638 else
7639 os->flags = SEC_NO_FLAGS;
7640 os->block_value = 1;
7642 os->align_lma_with_input = align_with_input == ALIGN_WITH_INPUT;
7643 if (os->align_lma_with_input && align != NULL)
7644 einfo (_("%F%P:%pS: error: align with input and explicit align specified\n"),
7645 NULL);
7647 os->subsection_alignment = subalign;
7648 os->section_alignment = align;
7650 os->load_base = ebase;
7651 return os;
7654 void
7655 lang_final (void)
7657 lang_output_statement_type *new_stmt;
7659 new_stmt = new_stat (lang_output_statement, stat_ptr);
7660 new_stmt->name = output_filename;
7663 /* Reset the current counters in the regions. */
7665 void
7666 lang_reset_memory_regions (void)
7668 lang_memory_region_type *p = lang_memory_region_list;
7669 asection *o;
7670 lang_output_section_statement_type *os;
7672 for (p = lang_memory_region_list; p != NULL; p = p->next)
7674 p->current = p->origin;
7675 p->last_os = NULL;
7678 for (os = (void *) lang_os_list.head;
7679 os != NULL;
7680 os = os->next)
7682 os->processed_vma = false;
7683 os->processed_lma = false;
7686 for (o = link_info.output_bfd->sections; o != NULL; o = o->next)
7688 /* Save the last size for possible use by bfd_relax_section. */
7689 o->rawsize = o->size;
7690 if (!(o->flags & SEC_FIXED_SIZE))
7691 o->size = 0;
7695 /* Worker for lang_gc_sections_1. */
7697 static void
7698 gc_section_callback (lang_wild_statement_type *ptr,
7699 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7700 asection *section,
7701 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7702 void *data ATTRIBUTE_UNUSED)
7704 /* If the wild pattern was marked KEEP, the member sections
7705 should be as well. */
7706 if (ptr->keep_sections)
7707 section->flags |= SEC_KEEP;
7710 /* Iterate over sections marking them against GC. */
7712 static void
7713 lang_gc_sections_1 (lang_statement_union_type *s)
7715 for (; s != NULL; s = s->header.next)
7717 switch (s->header.type)
7719 case lang_wild_statement_enum:
7720 walk_wild (&s->wild_statement, gc_section_callback, NULL);
7721 break;
7722 case lang_constructors_statement_enum:
7723 lang_gc_sections_1 (constructor_list.head);
7724 break;
7725 case lang_output_section_statement_enum:
7726 lang_gc_sections_1 (s->output_section_statement.children.head);
7727 break;
7728 case lang_group_statement_enum:
7729 lang_gc_sections_1 (s->group_statement.children.head);
7730 break;
7731 default:
7732 break;
7737 static void
7738 lang_gc_sections (void)
7740 /* Keep all sections so marked in the link script. */
7741 lang_gc_sections_1 (statement_list.head);
7743 /* SEC_EXCLUDE is ignored when doing a relocatable link, except in
7744 the special case of .stabstr debug info. (See bfd/stabs.c)
7745 Twiddle the flag here, to simplify later linker code. */
7746 if (bfd_link_relocatable (&link_info))
7748 LANG_FOR_EACH_INPUT_STATEMENT (f)
7750 asection *sec;
7751 #if BFD_SUPPORTS_PLUGINS
7752 if (f->flags.claimed)
7753 continue;
7754 #endif
7755 for (sec = f->the_bfd->sections; sec != NULL; sec = sec->next)
7756 if ((sec->flags & SEC_DEBUGGING) == 0
7757 || strcmp (sec->name, ".stabstr") != 0)
7758 sec->flags &= ~SEC_EXCLUDE;
7762 if (link_info.gc_sections)
7763 bfd_gc_sections (link_info.output_bfd, &link_info);
7766 /* Worker for lang_find_relro_sections_1. */
7768 static void
7769 find_relro_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
7770 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7771 asection *section,
7772 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7773 void *data)
7775 /* Discarded, excluded and ignored sections effectively have zero
7776 size. */
7777 if (section->output_section != NULL
7778 && section->output_section->owner == link_info.output_bfd
7779 && (section->output_section->flags & SEC_EXCLUDE) == 0
7780 && !IGNORE_SECTION (section)
7781 && section->size != 0)
7783 bool *has_relro_section = (bool *) data;
7784 *has_relro_section = true;
7788 /* Iterate over sections for relro sections. */
7790 static void
7791 lang_find_relro_sections_1 (lang_statement_union_type *s,
7792 bool *has_relro_section)
7794 if (*has_relro_section)
7795 return;
7797 for (; s != NULL; s = s->header.next)
7799 if (s == expld.dataseg.relro_end_stat)
7800 break;
7802 switch (s->header.type)
7804 case lang_wild_statement_enum:
7805 walk_wild (&s->wild_statement,
7806 find_relro_section_callback,
7807 has_relro_section);
7808 break;
7809 case lang_constructors_statement_enum:
7810 lang_find_relro_sections_1 (constructor_list.head,
7811 has_relro_section);
7812 break;
7813 case lang_output_section_statement_enum:
7814 lang_find_relro_sections_1 (s->output_section_statement.children.head,
7815 has_relro_section);
7816 break;
7817 case lang_group_statement_enum:
7818 lang_find_relro_sections_1 (s->group_statement.children.head,
7819 has_relro_section);
7820 break;
7821 default:
7822 break;
7827 static void
7828 lang_find_relro_sections (void)
7830 bool has_relro_section = false;
7832 /* Check all sections in the link script. */
7834 lang_find_relro_sections_1 (expld.dataseg.relro_start_stat,
7835 &has_relro_section);
7837 if (!has_relro_section)
7838 link_info.relro = false;
7841 /* Relax all sections until bfd_relax_section gives up. */
7843 void
7844 lang_relax_sections (bool need_layout)
7846 /* NB: Also enable relaxation to layout sections for DT_RELR. */
7847 if (RELAXATION_ENABLED || link_info.enable_dt_relr)
7849 /* We may need more than one relaxation pass. */
7850 int i = link_info.relax_pass;
7852 /* The backend can use it to determine the current pass. */
7853 link_info.relax_pass = 0;
7855 while (i--)
7857 /* Keep relaxing until bfd_relax_section gives up. */
7858 bool relax_again;
7860 link_info.relax_trip = -1;
7863 link_info.relax_trip++;
7865 /* Note: pe-dll.c does something like this also. If you find
7866 you need to change this code, you probably need to change
7867 pe-dll.c also. DJ */
7869 /* Do all the assignments with our current guesses as to
7870 section sizes. */
7871 lang_do_assignments (lang_assigning_phase_enum);
7873 /* We must do this after lang_do_assignments, because it uses
7874 size. */
7875 lang_reset_memory_regions ();
7877 /* Perform another relax pass - this time we know where the
7878 globals are, so can make a better guess. */
7879 relax_again = false;
7880 lang_size_sections (&relax_again, false);
7882 while (relax_again);
7884 link_info.relax_pass++;
7886 need_layout = true;
7889 if (need_layout)
7891 /* Final extra sizing to report errors. */
7892 lang_do_assignments (lang_assigning_phase_enum);
7893 lang_reset_memory_regions ();
7894 lang_size_sections (NULL, true);
7898 #if BFD_SUPPORTS_PLUGINS
7899 /* Find the insert point for the plugin's replacement files. We
7900 place them after the first claimed real object file, or if the
7901 first claimed object is an archive member, after the last real
7902 object file immediately preceding the archive. In the event
7903 no objects have been claimed at all, we return the first dummy
7904 object file on the list as the insert point; that works, but
7905 the callee must be careful when relinking the file_chain as it
7906 is not actually on that chain, only the statement_list and the
7907 input_file list; in that case, the replacement files must be
7908 inserted at the head of the file_chain. */
7910 static lang_input_statement_type *
7911 find_replacements_insert_point (bool *before)
7913 lang_input_statement_type *claim1, *lastobject;
7914 lastobject = (void *) input_file_chain.head;
7915 for (claim1 = (void *) file_chain.head;
7916 claim1 != NULL;
7917 claim1 = claim1->next)
7919 if (claim1->flags.claimed)
7921 *before = claim1->flags.claim_archive;
7922 return claim1->flags.claim_archive ? lastobject : claim1;
7924 /* Update lastobject if this is a real object file. */
7925 if (claim1->the_bfd != NULL && claim1->the_bfd->my_archive == NULL)
7926 lastobject = claim1;
7928 /* No files were claimed by the plugin. Choose the last object
7929 file found on the list (maybe the first, dummy entry) as the
7930 insert point. */
7931 *before = false;
7932 return lastobject;
7935 /* Find where to insert ADD, an archive element or shared library
7936 added during a rescan. */
7938 static lang_input_statement_type **
7939 find_rescan_insertion (lang_input_statement_type *add)
7941 bfd *add_bfd = add->the_bfd;
7942 lang_input_statement_type *f;
7943 lang_input_statement_type *last_loaded = NULL;
7944 lang_input_statement_type *before = NULL;
7945 lang_input_statement_type **iter = NULL;
7947 if (add_bfd->my_archive != NULL)
7948 add_bfd = add_bfd->my_archive;
7950 /* First look through the input file chain, to find an object file
7951 before the one we've rescanned. Normal object files always
7952 appear on both the input file chain and the file chain, so this
7953 lets us get quickly to somewhere near the correct place on the
7954 file chain if it is full of archive elements. Archives don't
7955 appear on the file chain, but if an element has been extracted
7956 then their input_statement->next points at it. */
7957 for (f = (void *) input_file_chain.head;
7958 f != NULL;
7959 f = f->next_real_file)
7961 if (f->the_bfd == add_bfd)
7963 before = last_loaded;
7964 if (f->next != NULL)
7965 return &f->next->next;
7967 if (f->the_bfd != NULL && f->next != NULL)
7968 last_loaded = f;
7971 for (iter = before ? &before->next : &file_chain.head->input_statement.next;
7972 *iter != NULL;
7973 iter = &(*iter)->next)
7974 if (!(*iter)->flags.claim_archive
7975 && (*iter)->the_bfd->my_archive == NULL)
7976 break;
7978 return iter;
7981 /* Detach new nodes added to DESTLIST since the time ORIGLIST
7982 was taken as a copy of it and leave them in ORIGLIST. */
7984 static void
7985 lang_list_remove_tail (lang_statement_list_type *destlist,
7986 lang_statement_list_type *origlist)
7988 union lang_statement_union **savetail;
7989 /* Check that ORIGLIST really is an earlier state of DESTLIST. */
7990 ASSERT (origlist->head == destlist->head);
7991 savetail = origlist->tail;
7992 origlist->head = *(savetail);
7993 origlist->tail = destlist->tail;
7994 destlist->tail = savetail;
7995 *savetail = NULL;
7998 static lang_statement_union_type **
7999 find_next_input_statement (lang_statement_union_type **s)
8001 for ( ; *s; s = &(*s)->header.next)
8003 lang_statement_union_type **t;
8004 switch ((*s)->header.type)
8006 case lang_input_statement_enum:
8007 return s;
8008 case lang_wild_statement_enum:
8009 t = &(*s)->wild_statement.children.head;
8010 break;
8011 case lang_group_statement_enum:
8012 t = &(*s)->group_statement.children.head;
8013 break;
8014 case lang_output_section_statement_enum:
8015 t = &(*s)->output_section_statement.children.head;
8016 break;
8017 default:
8018 continue;
8020 t = find_next_input_statement (t);
8021 if (*t)
8022 return t;
8024 return s;
8026 #endif /* BFD_SUPPORTS_PLUGINS */
8028 /* Insert SRCLIST into DESTLIST after given element by chaining
8029 on FIELD as the next-pointer. (Counterintuitively does not need
8030 a pointer to the actual after-node itself, just its chain field.) */
8032 static void
8033 lang_list_insert_after (lang_statement_list_type *destlist,
8034 lang_statement_list_type *srclist,
8035 lang_statement_union_type **field)
8037 *(srclist->tail) = *field;
8038 *field = srclist->head;
8039 if (destlist->tail == field)
8040 destlist->tail = srclist->tail;
8043 /* Add NAME to the list of garbage collection entry points. */
8045 void
8046 lang_add_gc_name (const char *name)
8048 struct bfd_sym_chain *sym;
8050 if (name == NULL)
8051 return;
8053 sym = stat_alloc (sizeof (*sym));
8055 sym->next = link_info.gc_sym_list;
8056 sym->name = name;
8057 link_info.gc_sym_list = sym;
8060 /* Check relocations. */
8062 static void
8063 lang_check_relocs (void)
8065 if (link_info.check_relocs_after_open_input)
8067 bfd *abfd;
8069 for (abfd = link_info.input_bfds;
8070 abfd != (bfd *) NULL; abfd = abfd->link.next)
8071 if (!bfd_link_check_relocs (abfd, &link_info))
8073 /* No object output, fail return. */
8074 config.make_executable = false;
8075 /* Note: we do not abort the loop, but rather
8076 continue the scan in case there are other
8077 bad relocations to report. */
8082 /* Look through all output sections looking for places where we can
8083 propagate forward the lma region. */
8085 static void
8086 lang_propagate_lma_regions (void)
8088 lang_output_section_statement_type *os;
8090 for (os = (void *) lang_os_list.head;
8091 os != NULL;
8092 os = os->next)
8094 if (os->prev != NULL
8095 && os->lma_region == NULL
8096 && os->load_base == NULL
8097 && os->addr_tree == NULL
8098 && os->region == os->prev->region)
8099 os->lma_region = os->prev->lma_region;
8103 static void
8104 warn_non_contiguous_discards (void)
8106 LANG_FOR_EACH_INPUT_STATEMENT (file)
8108 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
8109 || file->flags.just_syms)
8110 continue;
8112 for (asection *s = file->the_bfd->sections; s != NULL; s = s->next)
8113 if (s->output_section == NULL
8114 && (s->flags & SEC_LINKER_CREATED) == 0)
8115 einfo (_("%P: warning: --enable-non-contiguous-regions "
8116 "discards section `%pA' from `%pB'\n"),
8117 s, file->the_bfd);
8121 static void
8122 reset_one_wild (lang_statement_union_type *statement)
8124 if (statement->header.type == lang_wild_statement_enum)
8126 lang_wild_statement_type *stmt = &statement->wild_statement;
8127 lang_list_init (&stmt->matching_sections);
8131 static void
8132 reset_resolved_wilds (void)
8134 lang_for_each_statement (reset_one_wild);
8137 /* For each output section statement, splice any entries on the
8138 sort_children list before the first wild statement on the children
8139 list. */
8141 static void
8142 lang_os_merge_sort_children (void)
8144 lang_output_section_statement_type *os;
8145 for (os = (void *) lang_os_list.head; os != NULL; os = os->next)
8147 if (os->sort_children.head != NULL)
8149 lang_statement_union_type **where;
8150 for (where = &os->children.head;
8151 *where != NULL;
8152 where = &(*where)->header.next)
8153 if ((*where)->header.type == lang_wild_statement_enum)
8154 break;
8155 lang_list_insert_after (&os->children, &os->sort_children, where);
8160 void
8161 lang_process (void)
8163 lang_os_merge_sort_children ();
8165 /* Finalize dynamic list. */
8166 if (link_info.dynamic_list)
8167 lang_finalize_version_expr_head (&link_info.dynamic_list->head);
8169 current_target = default_target;
8171 /* Open the output file. */
8172 lang_for_each_statement (ldlang_open_output);
8173 init_opb (NULL);
8175 ldemul_create_output_section_statements ();
8177 /* Add to the hash table all undefineds on the command line. */
8178 lang_place_undefineds ();
8180 if (!bfd_section_already_linked_table_init ())
8181 einfo (_("%F%P: can not create hash table: %E\n"));
8183 /* A first pass through the memory regions ensures that if any region
8184 references a symbol for its origin or length then this symbol will be
8185 added to the symbol table. Having these symbols in the symbol table
8186 means that when we call open_input_bfds PROVIDE statements will
8187 trigger to provide any needed symbols. The regions origins and
8188 lengths are not assigned as a result of this call. */
8189 lang_do_memory_regions (false);
8191 /* Create a bfd for each input file. */
8192 current_target = default_target;
8193 lang_statement_iteration++;
8194 open_input_bfds (statement_list.head, NULL, OPEN_BFD_NORMAL);
8196 /* Now that open_input_bfds has processed assignments and provide
8197 statements we can give values to symbolic origin/length now. */
8198 lang_do_memory_regions (true);
8200 ldemul_before_plugin_all_symbols_read ();
8202 #if BFD_SUPPORTS_PLUGINS
8203 if (link_info.lto_plugin_active)
8205 lang_statement_list_type added;
8206 lang_statement_list_type files, inputfiles;
8208 /* Now all files are read, let the plugin(s) decide if there
8209 are any more to be added to the link before we call the
8210 emulation's after_open hook. We create a private list of
8211 input statements for this purpose, which we will eventually
8212 insert into the global statement list after the first claimed
8213 file. */
8214 added = *stat_ptr;
8215 /* We need to manipulate all three chains in synchrony. */
8216 files = file_chain;
8217 inputfiles = input_file_chain;
8218 if (plugin_call_all_symbols_read ())
8219 einfo (_("%F%P: %s: plugin reported error after all symbols read\n"),
8220 plugin_error_plugin ());
8221 link_info.lto_all_symbols_read = true;
8222 /* Open any newly added files, updating the file chains. */
8223 plugin_undefs = link_info.hash->undefs_tail;
8224 lang_output_section_statement_type *last_os = NULL;
8225 if (lang_os_list.head != NULL)
8226 last_os = ((lang_output_section_statement_type *)
8227 ((char *) lang_os_list.tail
8228 - offsetof (lang_output_section_statement_type, next)));
8229 open_input_bfds (*added.tail, last_os, OPEN_BFD_NORMAL);
8230 if (plugin_undefs == link_info.hash->undefs_tail)
8231 plugin_undefs = NULL;
8232 /* Restore the global list pointer now they have all been added. */
8233 lang_list_remove_tail (stat_ptr, &added);
8234 /* And detach the fresh ends of the file lists. */
8235 lang_list_remove_tail (&file_chain, &files);
8236 lang_list_remove_tail (&input_file_chain, &inputfiles);
8237 /* Were any new files added? */
8238 if (added.head != NULL)
8240 /* If so, we will insert them into the statement list immediately
8241 after the first input file that was claimed by the plugin,
8242 unless that file was an archive in which case it is inserted
8243 immediately before. */
8244 bool before;
8245 lang_statement_union_type **prev;
8246 plugin_insert = find_replacements_insert_point (&before);
8247 /* If a plugin adds input files without having claimed any, we
8248 don't really have a good idea where to place them. Just putting
8249 them at the start or end of the list is liable to leave them
8250 outside the crtbegin...crtend range. */
8251 ASSERT (plugin_insert != NULL);
8252 /* Splice the new statement list into the old one. */
8253 prev = &plugin_insert->header.next;
8254 if (before)
8256 prev = find_next_input_statement (prev);
8257 if (*prev != (void *) plugin_insert->next_real_file)
8259 /* We didn't find the expected input statement.
8260 Fall back to adding after plugin_insert. */
8261 prev = &plugin_insert->header.next;
8264 lang_list_insert_after (stat_ptr, &added, prev);
8265 /* Likewise for the file chains. */
8266 lang_list_insert_after (&input_file_chain, &inputfiles,
8267 (void *) &plugin_insert->next_real_file);
8268 /* We must be careful when relinking file_chain; we may need to
8269 insert the new files at the head of the list if the insert
8270 point chosen is the dummy first input file. */
8271 if (plugin_insert->filename)
8272 lang_list_insert_after (&file_chain, &files,
8273 (void *) &plugin_insert->next);
8274 else
8275 lang_list_insert_after (&file_chain, &files, &file_chain.head);
8277 /* Rescan archives in case new undefined symbols have appeared. */
8278 files = file_chain;
8279 lang_statement_iteration++;
8280 open_input_bfds (statement_list.head, NULL, OPEN_BFD_RESCAN);
8281 lang_list_remove_tail (&file_chain, &files);
8282 while (files.head != NULL)
8284 lang_input_statement_type **insert;
8285 lang_input_statement_type **iter, *temp;
8286 bfd *my_arch;
8288 insert = find_rescan_insertion (&files.head->input_statement);
8289 /* All elements from an archive can be added at once. */
8290 iter = &files.head->input_statement.next;
8291 my_arch = files.head->input_statement.the_bfd->my_archive;
8292 if (my_arch != NULL)
8293 for (; *iter != NULL; iter = &(*iter)->next)
8294 if ((*iter)->the_bfd->my_archive != my_arch)
8295 break;
8296 temp = *insert;
8297 *insert = &files.head->input_statement;
8298 files.head = (lang_statement_union_type *) *iter;
8299 *iter = temp;
8300 if (file_chain.tail == (lang_statement_union_type **) insert)
8301 file_chain.tail = (lang_statement_union_type **) iter;
8302 if (my_arch != NULL)
8304 lang_input_statement_type *parent = bfd_usrdata (my_arch);
8305 if (parent != NULL)
8306 parent->next = (lang_input_statement_type *)
8307 ((char *) iter
8308 - offsetof (lang_input_statement_type, next));
8313 #endif /* BFD_SUPPORTS_PLUGINS */
8315 struct bfd_sym_chain **sym = &link_info.gc_sym_list;
8316 while (*sym)
8317 sym = &(*sym)->next;
8319 *sym = &entry_symbol;
8321 if (entry_symbol.name == NULL)
8323 *sym = ldlang_undef_chain_list_head;
8325 /* entry_symbol is normally initialised by an ENTRY definition in the
8326 linker script or the -e command line option. But if neither of
8327 these have been used, the target specific backend may still have
8328 provided an entry symbol via a call to lang_default_entry().
8329 Unfortunately this value will not be processed until lang_end()
8330 is called, long after this function has finished. So detect this
8331 case here and add the target's entry symbol to the list of starting
8332 points for garbage collection resolution. */
8333 lang_add_gc_name (entry_symbol_default);
8336 lang_add_gc_name (link_info.init_function);
8337 lang_add_gc_name (link_info.fini_function);
8339 ldemul_after_open ();
8340 if (config.map_file != NULL)
8341 lang_print_asneeded ();
8343 ldlang_open_ctf ();
8345 bfd_section_already_linked_table_free ();
8347 /* Make sure that we're not mixing architectures. We call this
8348 after all the input files have been opened, but before we do any
8349 other processing, so that any operations merge_private_bfd_data
8350 does on the output file will be known during the rest of the
8351 link. */
8352 lang_check ();
8354 /* Handle .exports instead of a version script if we're told to do so. */
8355 if (command_line.version_exports_section)
8356 lang_do_version_exports_section ();
8358 /* Build all sets based on the information gathered from the input
8359 files. */
8360 ldctor_build_sets ();
8362 lang_symbol_tweaks ();
8364 /* PR 13683: We must rerun the assignments prior to running garbage
8365 collection in order to make sure that all symbol aliases are resolved. */
8366 lang_do_assignments (lang_mark_phase_enum);
8367 expld.phase = lang_first_phase_enum;
8369 /* Size up the common data. */
8370 lang_common ();
8372 if (0)
8373 debug_prefix_tree ();
8375 resolve_wilds ();
8377 /* Remove unreferenced sections if asked to. */
8378 lang_gc_sections ();
8380 lang_mark_undefineds ();
8382 /* Check relocations. */
8383 lang_check_relocs ();
8385 ldemul_after_check_relocs ();
8387 /* There might have been new sections created (e.g. as result of
8388 checking relocs to need a .got, or suchlike), so to properly order
8389 them into our lists of matching sections reset them here. */
8390 reset_resolved_wilds ();
8391 resolve_wilds ();
8393 /* Update wild statements in case the user gave --sort-section.
8394 Note how the option might have come after the linker script and
8395 so couldn't have been set when the wild statements were created. */
8396 update_wild_statements (statement_list.head);
8398 /* Run through the contours of the script and attach input sections
8399 to the correct output sections. */
8400 lang_statement_iteration++;
8401 map_input_to_output_sections (statement_list.head, NULL, NULL);
8403 /* Start at the statement immediately after the special abs_section
8404 output statement, so that it isn't reordered. */
8405 process_insert_statements (&lang_os_list.head->header.next);
8407 ldemul_before_place_orphans ();
8409 /* Find any sections not attached explicitly and handle them. */
8410 lang_place_orphans ();
8412 if (!bfd_link_relocatable (&link_info))
8414 asection *found;
8416 /* Merge SEC_MERGE sections. This has to be done after GC of
8417 sections, so that GCed sections are not merged, but before
8418 assigning dynamic symbols, since removing whole input sections
8419 is hard then. */
8420 bfd_merge_sections (link_info.output_bfd, &link_info);
8422 /* Look for a text section and set the readonly attribute in it. */
8423 found = bfd_get_section_by_name (link_info.output_bfd, ".text");
8425 if (found != NULL)
8427 if (config.text_read_only)
8428 found->flags |= SEC_READONLY;
8429 else
8430 found->flags &= ~SEC_READONLY;
8434 /* Merge together CTF sections. After this, only the symtab-dependent
8435 function and data object sections need adjustment. */
8436 lang_merge_ctf ();
8438 /* Emit the CTF, iff the emulation doesn't need to do late emission after
8439 examining things laid out late, like the strtab. */
8440 lang_write_ctf (0);
8442 /* Copy forward lma regions for output sections in same lma region. */
8443 lang_propagate_lma_regions ();
8445 /* Defining __start/__stop symbols early for --gc-sections to work
8446 around a glibc build problem can result in these symbols being
8447 defined when they should not be. Fix them now. */
8448 if (config.build_constructors)
8449 lang_undef_start_stop ();
8451 /* Define .startof./.sizeof. symbols with preliminary values before
8452 dynamic symbols are created. */
8453 if (!bfd_link_relocatable (&link_info))
8454 lang_init_startof_sizeof ();
8456 /* Do anything special before sizing sections. This is where ELF
8457 and other back-ends size dynamic sections. */
8458 ldemul_before_allocation ();
8460 /* We must record the program headers before we try to fix the
8461 section positions, since they will affect SIZEOF_HEADERS. */
8462 lang_record_phdrs ();
8464 /* Check relro sections. */
8465 if (link_info.relro && !bfd_link_relocatable (&link_info))
8466 lang_find_relro_sections ();
8468 /* Size up the sections. */
8469 lang_size_sections (NULL, !RELAXATION_ENABLED);
8471 /* See if anything special should be done now we know how big
8472 everything is. This is where relaxation is done. */
8473 ldemul_after_allocation ();
8475 /* Fix any __start, __stop, .startof. or .sizeof. symbols. */
8476 lang_finalize_start_stop ();
8478 /* Do all the assignments again, to report errors. Assignment
8479 statements are processed multiple times, updating symbols; In
8480 open_input_bfds, lang_do_assignments, and lang_size_sections.
8481 Since lang_relax_sections calls lang_do_assignments, symbols are
8482 also updated in ldemul_after_allocation. */
8483 lang_do_assignments (lang_final_phase_enum);
8485 ldemul_finish ();
8487 /* Convert absolute symbols to section relative. */
8488 ldexp_finalize_syms ();
8490 /* Make sure that the section addresses make sense. */
8491 if (command_line.check_section_addresses)
8492 lang_check_section_addresses ();
8494 if (link_info.non_contiguous_regions
8495 && link_info.non_contiguous_regions_warnings)
8496 warn_non_contiguous_discards ();
8498 /* Check any required symbols are known. */
8499 ldlang_check_require_defined_symbols ();
8501 lang_end ();
8504 void
8505 lang_add_version_string (void)
8507 if (! enable_linker_version)
8508 return;
8510 const char * str = "GNU ld ";
8511 int len = strlen (str);
8512 int i;
8514 for (i = 0 ; i < len ; i++)
8515 lang_add_data (BYTE, exp_intop (str[i]));
8517 str = BFD_VERSION_STRING;
8518 len = strlen (str);
8520 for (i = 0 ; i < len ; i++)
8521 lang_add_data (BYTE, exp_intop (str[i]));
8523 lang_add_data (BYTE, exp_intop ('\0'));
8526 /* EXPORTED TO YACC */
8528 void
8529 lang_add_wild (struct wildcard_spec *filespec,
8530 struct wildcard_list *section_list,
8531 bool keep_sections)
8533 struct wildcard_list *curr, *next;
8534 lang_wild_statement_type *new_stmt;
8535 bool any_specs_sorted = false;
8537 /* Reverse the list as the parser puts it back to front. */
8538 for (curr = section_list, section_list = NULL;
8539 curr != NULL;
8540 section_list = curr, curr = next)
8542 if (curr->spec.sorted != none && curr->spec.sorted != by_none)
8543 any_specs_sorted = true;
8544 next = curr->next;
8545 curr->next = section_list;
8548 if (filespec != NULL && filespec->name != NULL)
8550 if (strcmp (filespec->name, "*") == 0)
8551 filespec->name = NULL;
8552 else if (!wildcardp (filespec->name))
8553 lang_has_input_file = true;
8556 new_stmt = new_stat (lang_wild_statement, stat_ptr);
8557 new_stmt->filename = NULL;
8558 new_stmt->filenames_sorted = false;
8559 new_stmt->any_specs_sorted = any_specs_sorted;
8560 new_stmt->section_flag_list = NULL;
8561 new_stmt->exclude_name_list = NULL;
8562 if (filespec != NULL)
8564 new_stmt->filename = filespec->name;
8565 new_stmt->filenames_sorted = (filespec->sorted == by_name || filespec->reversed);
8566 new_stmt->section_flag_list = filespec->section_flag_list;
8567 new_stmt->exclude_name_list = filespec->exclude_name_list;
8568 new_stmt->filenames_reversed = filespec->reversed;
8570 new_stmt->section_list = section_list;
8571 new_stmt->keep_sections = keep_sections;
8572 lang_list_init (&new_stmt->children);
8573 lang_list_init (&new_stmt->matching_sections);
8574 analyze_walk_wild_section_handler (new_stmt);
8575 if (0)
8577 printf ("wild %s(", new_stmt->filename ? new_stmt->filename : "*");
8578 for (curr = new_stmt->section_list; curr; curr = curr->next)
8579 printf ("%s ", curr->spec.name ? curr->spec.name : "*");
8580 printf (")\n");
8584 void
8585 lang_section_start (const char *name, etree_type *address,
8586 const segment_type *segment)
8588 lang_address_statement_type *ad;
8590 ad = new_stat (lang_address_statement, stat_ptr);
8591 ad->section_name = name;
8592 ad->address = address;
8593 ad->segment = segment;
8596 /* Set the start symbol to NAME. CMDLINE is nonzero if this is called
8597 because of a -e argument on the command line, or zero if this is
8598 called by ENTRY in a linker script. Command line arguments take
8599 precedence. */
8601 void
8602 lang_add_entry (const char *name, bool cmdline)
8604 if (entry_symbol.name == NULL
8605 || cmdline
8606 || !entry_from_cmdline)
8608 entry_symbol.name = name;
8609 entry_from_cmdline = cmdline;
8613 /* Set the default start symbol to NAME. .em files should use this,
8614 not lang_add_entry, to override the use of "start" if neither the
8615 linker script nor the command line specifies an entry point. NAME
8616 must be permanently allocated. */
8617 void
8618 lang_default_entry (const char *name)
8620 entry_symbol_default = name;
8623 void
8624 lang_add_target (const char *name)
8626 lang_target_statement_type *new_stmt;
8628 new_stmt = new_stat (lang_target_statement, stat_ptr);
8629 new_stmt->target = name;
8632 void
8633 lang_add_map (const char *name)
8635 while (*name)
8637 switch (*name)
8639 case 'F':
8640 map_option_f = true;
8641 break;
8643 name++;
8647 void
8648 lang_add_fill (fill_type *fill)
8650 lang_fill_statement_type *new_stmt;
8652 new_stmt = new_stat (lang_fill_statement, stat_ptr);
8653 new_stmt->fill = fill;
8656 void
8657 lang_add_data (int type, union etree_union *exp)
8659 lang_data_statement_type *new_stmt;
8661 new_stmt = new_stat (lang_data_statement, stat_ptr);
8662 new_stmt->exp = exp;
8663 new_stmt->type = type;
8666 void
8667 lang_add_string (const char *s)
8669 bfd_vma len = strlen (s);
8670 bfd_vma i;
8671 bool escape = false;
8673 /* Add byte expressions until end of string. */
8674 for (i = 0 ; i < len; i++)
8676 char c = *s++;
8678 if (escape)
8680 switch (c)
8682 default:
8683 /* Ignore the escape. */
8684 break;
8686 case 'n': c = '\n'; break;
8687 case 'r': c = '\r'; break;
8688 case 't': c = '\t'; break;
8690 case '0':
8691 case '1':
8692 case '2':
8693 case '3':
8694 case '4':
8695 case '5':
8696 case '6':
8697 case '7':
8698 /* We have an octal number. */
8700 unsigned int value = c - '0';
8702 c = *s;
8703 if ((c >= '0') && (c <= '7'))
8705 value <<= 3;
8706 value += (c - '0');
8707 i++;
8708 s++;
8710 c = *s;
8711 if ((c >= '0') && (c <= '7'))
8713 value <<= 3;
8714 value += (c - '0');
8715 i++;
8716 s++;
8720 if (value > 0xff)
8722 /* octal: \777 is treated as '\077' + '7' */
8723 value >>= 3;
8724 i--;
8725 s--;
8728 c = value;
8730 break;
8733 lang_add_data (BYTE, exp_intop (c));
8734 escape = false;
8736 else
8738 if (c == '\\')
8739 escape = true;
8740 else
8741 lang_add_data (BYTE, exp_intop (c));
8745 /* Remeber to terminate the string. */
8746 lang_add_data (BYTE, exp_intop (0));
8749 /* Create a new reloc statement. RELOC is the BFD relocation type to
8750 generate. HOWTO is the corresponding howto structure (we could
8751 look this up, but the caller has already done so). SECTION is the
8752 section to generate a reloc against, or NAME is the name of the
8753 symbol to generate a reloc against. Exactly one of SECTION and
8754 NAME must be NULL. ADDEND is an expression for the addend. */
8756 void
8757 lang_add_reloc (bfd_reloc_code_real_type reloc,
8758 reloc_howto_type *howto,
8759 asection *section,
8760 const char *name,
8761 union etree_union *addend)
8763 lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
8765 p->reloc = reloc;
8766 p->howto = howto;
8767 p->section = section;
8768 p->name = name;
8769 p->addend_exp = addend;
8771 p->addend_value = 0;
8772 p->output_section = NULL;
8773 p->output_offset = 0;
8776 lang_assignment_statement_type *
8777 lang_add_assignment (etree_type *exp)
8779 lang_assignment_statement_type *new_stmt;
8781 new_stmt = new_stat (lang_assignment_statement, stat_ptr);
8782 new_stmt->exp = exp;
8783 return new_stmt;
8786 void
8787 lang_add_attribute (enum statement_enum attribute)
8789 new_statement (attribute, sizeof (lang_statement_header_type), stat_ptr);
8792 void
8793 lang_startup (const char *name)
8795 if (first_file->filename != NULL)
8797 einfo (_("%F%P: multiple STARTUP files\n"));
8799 first_file->filename = name;
8800 first_file->local_sym_name = name;
8801 first_file->flags.real = true;
8804 void
8805 lang_float (bool maybe)
8807 lang_float_flag = maybe;
8811 /* Work out the load- and run-time regions from a script statement, and
8812 store them in *LMA_REGION and *REGION respectively.
8814 MEMSPEC is the name of the run-time region, or the value of
8815 DEFAULT_MEMORY_REGION if the statement didn't specify one.
8816 LMA_MEMSPEC is the name of the load-time region, or null if the
8817 statement didn't specify one.HAVE_LMA_P is TRUE if the statement
8818 had an explicit load address.
8820 It is an error to specify both a load region and a load address. */
8822 static void
8823 lang_get_regions (lang_memory_region_type **region,
8824 lang_memory_region_type **lma_region,
8825 const char *memspec,
8826 const char *lma_memspec,
8827 bool have_lma,
8828 bool have_vma)
8830 *lma_region = lang_memory_region_lookup (lma_memspec, false);
8832 /* If no runtime region or VMA has been specified, but the load region
8833 has been specified, then use the load region for the runtime region
8834 as well. */
8835 if (lma_memspec != NULL
8836 && !have_vma
8837 && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
8838 *region = *lma_region;
8839 else
8840 *region = lang_memory_region_lookup (memspec, false);
8842 if (have_lma && lma_memspec != 0)
8843 einfo (_("%X%P:%pS: section has both a load address and a load region\n"),
8844 NULL);
8847 void
8848 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
8849 lang_output_section_phdr_list *phdrs,
8850 const char *lma_memspec)
8852 pop_stat_ptr ();
8853 if (in_section_ordering)
8854 return;
8856 lang_get_regions (&current_section->region,
8857 &current_section->lma_region,
8858 memspec, lma_memspec,
8859 current_section->load_base != NULL,
8860 current_section->addr_tree != NULL);
8862 current_section->fill = fill;
8863 current_section->phdrs = phdrs;
8866 /* Set the output format type. -oformat overrides scripts. */
8868 void
8869 lang_add_output_format (const char *format,
8870 const char *big,
8871 const char *little,
8872 int from_script)
8874 if (output_target == NULL || !from_script)
8876 if (command_line.endian == ENDIAN_BIG
8877 && big != NULL)
8878 format = big;
8879 else if (command_line.endian == ENDIAN_LITTLE
8880 && little != NULL)
8881 format = little;
8883 output_target = format;
8887 void
8888 lang_add_insert (const char *where, int is_before)
8890 lang_insert_statement_type *new_stmt;
8892 new_stmt = new_stat (lang_insert_statement, stat_ptr);
8893 new_stmt->where = where;
8894 new_stmt->is_before = is_before;
8895 saved_script_handle = previous_script_handle;
8898 /* Enter a group. This creates a new lang_group_statement, and sets
8899 stat_ptr to build new statements within the group. */
8901 void
8902 lang_enter_group (void)
8904 lang_group_statement_type *g;
8906 g = new_stat (lang_group_statement, stat_ptr);
8907 lang_list_init (&g->children);
8908 push_stat_ptr (&g->children);
8911 /* Leave a group. This just resets stat_ptr to start writing to the
8912 regular list of statements again. Note that this will not work if
8913 groups can occur inside anything else which can adjust stat_ptr,
8914 but currently they can't. */
8916 void
8917 lang_leave_group (void)
8919 pop_stat_ptr ();
8922 /* Add a new program header. This is called for each entry in a PHDRS
8923 command in a linker script. */
8925 void
8926 lang_new_phdr (const char *name,
8927 etree_type *type,
8928 bool filehdr,
8929 bool phdrs,
8930 etree_type *at,
8931 etree_type *flags)
8933 struct lang_phdr *n, **pp;
8934 bool hdrs;
8936 n = stat_alloc (sizeof (struct lang_phdr));
8937 n->next = NULL;
8938 n->name = name;
8939 n->type = exp_get_vma (type, NULL, 0, "program header type");
8940 n->filehdr = filehdr;
8941 n->phdrs = phdrs;
8942 n->at = at;
8943 n->flags = flags;
8945 hdrs = n->type == 1 && (phdrs || filehdr);
8947 for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
8948 if (hdrs
8949 && (*pp)->type == 1
8950 && !((*pp)->filehdr || (*pp)->phdrs))
8952 einfo (_("%X%P:%pS: PHDRS and FILEHDR are not supported"
8953 " when prior PT_LOAD headers lack them\n"), NULL);
8954 hdrs = false;
8957 *pp = n;
8960 /* Record the program header information in the output BFD. FIXME: We
8961 should not be calling an ELF specific function here. */
8963 static void
8964 lang_record_phdrs (void)
8966 unsigned int alc;
8967 asection **secs;
8968 lang_output_section_phdr_list *last;
8969 struct lang_phdr *l;
8970 lang_output_section_statement_type *os;
8972 alc = 10;
8973 secs = (asection **) xmalloc (alc * sizeof (asection *));
8974 last = NULL;
8976 for (l = lang_phdr_list; l != NULL; l = l->next)
8978 unsigned int c;
8979 flagword flags;
8980 bfd_vma at;
8982 c = 0;
8983 for (os = (void *) lang_os_list.head;
8984 os != NULL;
8985 os = os->next)
8987 lang_output_section_phdr_list *pl;
8989 if (os->constraint < 0)
8990 continue;
8992 pl = os->phdrs;
8993 if (pl != NULL)
8994 last = pl;
8995 else
8997 if (os->sectype == noload_section
8998 || os->bfd_section == NULL
8999 || (os->bfd_section->flags & SEC_ALLOC) == 0)
9000 continue;
9002 /* Don't add orphans to PT_INTERP header. */
9003 if (l->type == 3)
9004 continue;
9006 if (last == NULL)
9008 lang_output_section_statement_type *tmp_os;
9010 /* If we have not run across a section with a program
9011 header assigned to it yet, then scan forwards to find
9012 one. This prevents inconsistencies in the linker's
9013 behaviour when a script has specified just a single
9014 header and there are sections in that script which are
9015 not assigned to it, and which occur before the first
9016 use of that header. See here for more details:
9017 http://sourceware.org/ml/binutils/2007-02/msg00291.html */
9018 for (tmp_os = os; tmp_os; tmp_os = tmp_os->next)
9019 if (tmp_os->phdrs)
9021 last = tmp_os->phdrs;
9022 break;
9024 if (last == NULL)
9025 einfo (_("%F%P: no sections assigned to phdrs\n"));
9027 pl = last;
9030 if (os->bfd_section == NULL)
9031 continue;
9033 for (; pl != NULL; pl = pl->next)
9035 if (strcmp (pl->name, l->name) == 0)
9037 if (c >= alc)
9039 alc *= 2;
9040 secs = (asection **) xrealloc (secs,
9041 alc * sizeof (asection *));
9043 secs[c] = os->bfd_section;
9044 ++c;
9045 pl->used = true;
9050 if (l->flags == NULL)
9051 flags = 0;
9052 else
9053 flags = exp_get_vma (l->flags, NULL, 0, "phdr flags");
9055 if (l->at == NULL)
9056 at = 0;
9057 else
9058 at = exp_get_vma (l->at, NULL, 0, "phdr load address");
9060 if (!bfd_record_phdr (link_info.output_bfd, l->type,
9061 l->flags != NULL, flags, l->at != NULL,
9062 at, l->filehdr, l->phdrs, c, secs))
9063 einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
9066 free (secs);
9068 /* Make sure all the phdr assignments succeeded. */
9069 for (os = (void *) lang_os_list.head;
9070 os != NULL;
9071 os = os->next)
9073 lang_output_section_phdr_list *pl;
9075 if (os->constraint < 0
9076 || os->bfd_section == NULL)
9077 continue;
9079 for (pl = os->phdrs;
9080 pl != NULL;
9081 pl = pl->next)
9082 if (!pl->used && strcmp (pl->name, "NONE") != 0)
9083 einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
9084 os->name, pl->name);
9088 /* Record a list of sections which may not be cross referenced. */
9090 void
9091 lang_add_nocrossref (lang_nocrossref_type *l)
9093 struct lang_nocrossrefs *n;
9095 n = (struct lang_nocrossrefs *) xmalloc (sizeof *n);
9096 n->next = nocrossref_list;
9097 n->list = l;
9098 n->onlyfirst = false;
9099 nocrossref_list = n;
9101 /* Set notice_all so that we get informed about all symbols. */
9102 link_info.notice_all = true;
9105 /* Record a section that cannot be referenced from a list of sections. */
9107 void
9108 lang_add_nocrossref_to (lang_nocrossref_type *l)
9110 lang_add_nocrossref (l);
9111 nocrossref_list->onlyfirst = true;
9114 /* Overlay handling. We handle overlays with some static variables. */
9116 /* The overlay virtual address. */
9117 static etree_type *overlay_vma;
9118 /* And subsection alignment. */
9119 static etree_type *overlay_subalign;
9121 /* An expression for the maximum section size seen so far. */
9122 static etree_type *overlay_max;
9124 /* A list of all the sections in this overlay. */
9126 struct overlay_list {
9127 struct overlay_list *next;
9128 lang_output_section_statement_type *os;
9131 static struct overlay_list *overlay_list;
9133 /* Start handling an overlay. */
9135 void
9136 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
9138 /* The grammar should prevent nested overlays from occurring. */
9139 ASSERT (overlay_vma == NULL
9140 && overlay_subalign == NULL
9141 && overlay_max == NULL);
9143 overlay_vma = vma_expr;
9144 overlay_subalign = subalign;
9147 /* Start a section in an overlay. We handle this by calling
9148 lang_enter_output_section_statement with the correct VMA.
9149 lang_leave_overlay sets up the LMA and memory regions. */
9151 void
9152 lang_enter_overlay_section (const char *name)
9154 struct overlay_list *n;
9155 etree_type *size;
9157 lang_enter_output_section_statement (name, overlay_vma, overlay_section,
9158 0, 0, overlay_subalign, 0, 0, 0);
9160 /* If this is the first section, then base the VMA of future
9161 sections on this one. This will work correctly even if `.' is
9162 used in the addresses. */
9163 if (overlay_list == NULL)
9164 overlay_vma = exp_nameop (ADDR, name);
9166 /* Remember the section. */
9167 n = (struct overlay_list *) xmalloc (sizeof *n);
9168 n->os = current_section;
9169 n->next = overlay_list;
9170 overlay_list = n;
9172 size = exp_nameop (SIZEOF, name);
9174 /* Arrange to work out the maximum section end address. */
9175 if (overlay_max == NULL)
9176 overlay_max = size;
9177 else
9178 overlay_max = exp_binop (MAX_K, overlay_max, size);
9181 /* Finish a section in an overlay. There isn't any special to do
9182 here. */
9184 void
9185 lang_leave_overlay_section (fill_type *fill,
9186 lang_output_section_phdr_list *phdrs)
9188 const char *name;
9189 char *clean, *s2;
9190 const char *s1;
9191 char *buf;
9193 name = current_section->name;
9195 /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
9196 region and that no load-time region has been specified. It doesn't
9197 really matter what we say here, since lang_leave_overlay will
9198 override it. */
9199 lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
9201 /* Define the magic symbols. */
9203 clean = (char *) xmalloc (strlen (name) + 1);
9204 s2 = clean;
9205 for (s1 = name; *s1 != '\0'; s1++)
9206 if (ISALNUM (*s1) || *s1 == '_')
9207 *s2++ = *s1;
9208 *s2 = '\0';
9210 buf = (char *) xmalloc (strlen (clean) + sizeof "__load_start_");
9211 sprintf (buf, "__load_start_%s", clean);
9212 lang_add_assignment (exp_provide (buf,
9213 exp_nameop (LOADADDR, name),
9214 false));
9216 buf = (char *) xmalloc (strlen (clean) + sizeof "__load_stop_");
9217 sprintf (buf, "__load_stop_%s", clean);
9218 lang_add_assignment (exp_provide (buf,
9219 exp_binop ('+',
9220 exp_nameop (LOADADDR, name),
9221 exp_nameop (SIZEOF, name)),
9222 false));
9224 free (clean);
9227 /* Finish an overlay. If there are any overlay wide settings, this
9228 looks through all the sections in the overlay and sets them. */
9230 void
9231 lang_leave_overlay (etree_type *lma_expr,
9232 int nocrossrefs,
9233 fill_type *fill,
9234 const char *memspec,
9235 lang_output_section_phdr_list *phdrs,
9236 const char *lma_memspec)
9238 lang_memory_region_type *region;
9239 lang_memory_region_type *lma_region;
9240 struct overlay_list *l;
9241 lang_nocrossref_type *nocrossref;
9243 lang_get_regions (&region, &lma_region,
9244 memspec, lma_memspec,
9245 lma_expr != NULL, false);
9247 nocrossref = NULL;
9249 /* After setting the size of the last section, set '.' to end of the
9250 overlay region. */
9251 if (overlay_list != NULL)
9253 overlay_list->os->update_dot = 1;
9254 overlay_list->os->update_dot_tree
9255 = exp_assign (".", exp_binop ('+', overlay_vma, overlay_max), false);
9258 l = overlay_list;
9259 while (l != NULL)
9261 struct overlay_list *next;
9263 if (fill != NULL && l->os->fill == NULL)
9264 l->os->fill = fill;
9266 l->os->region = region;
9267 l->os->lma_region = lma_region;
9269 /* The first section has the load address specified in the
9270 OVERLAY statement. The rest are worked out from that.
9271 The base address is not needed (and should be null) if
9272 an LMA region was specified. */
9273 if (l->next == 0)
9275 l->os->load_base = lma_expr;
9276 l->os->sectype = first_overlay_section;
9278 if (phdrs != NULL && l->os->phdrs == NULL)
9279 l->os->phdrs = phdrs;
9281 if (nocrossrefs)
9283 lang_nocrossref_type *nc;
9285 nc = (lang_nocrossref_type *) xmalloc (sizeof *nc);
9286 nc->name = l->os->name;
9287 nc->next = nocrossref;
9288 nocrossref = nc;
9291 next = l->next;
9292 free (l);
9293 l = next;
9296 if (nocrossref != NULL)
9297 lang_add_nocrossref (nocrossref);
9299 overlay_vma = NULL;
9300 overlay_list = NULL;
9301 overlay_max = NULL;
9302 overlay_subalign = NULL;
9305 /* Version handling. This is only useful for ELF. */
9307 /* If PREV is NULL, return first version pattern matching particular symbol.
9308 If PREV is non-NULL, return first version pattern matching particular
9309 symbol after PREV (previously returned by lang_vers_match). */
9311 static struct bfd_elf_version_expr *
9312 lang_vers_match (struct bfd_elf_version_expr_head *head,
9313 struct bfd_elf_version_expr *prev,
9314 const char *sym)
9316 const char *c_sym;
9317 const char *cxx_sym = sym;
9318 const char *java_sym = sym;
9319 struct bfd_elf_version_expr *expr = NULL;
9320 enum demangling_styles curr_style;
9322 curr_style = CURRENT_DEMANGLING_STYLE;
9323 cplus_demangle_set_style (no_demangling);
9324 c_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_NO_OPTS);
9325 if (!c_sym)
9326 c_sym = sym;
9327 cplus_demangle_set_style (curr_style);
9329 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9331 cxx_sym = bfd_demangle (link_info.output_bfd, sym,
9332 DMGL_PARAMS | DMGL_ANSI);
9333 if (!cxx_sym)
9334 cxx_sym = sym;
9336 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9338 java_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_JAVA);
9339 if (!java_sym)
9340 java_sym = sym;
9343 if (head->htab && (prev == NULL || prev->literal))
9345 struct bfd_elf_version_expr e;
9347 switch (prev ? prev->mask : 0)
9349 case 0:
9350 if (head->mask & BFD_ELF_VERSION_C_TYPE)
9352 e.pattern = c_sym;
9353 expr = (struct bfd_elf_version_expr *)
9354 htab_find ((htab_t) head->htab, &e);
9355 while (expr && strcmp (expr->pattern, c_sym) == 0)
9356 if (expr->mask == BFD_ELF_VERSION_C_TYPE)
9357 goto out_ret;
9358 else
9359 expr = expr->next;
9361 /* Fallthrough */
9362 case BFD_ELF_VERSION_C_TYPE:
9363 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9365 e.pattern = cxx_sym;
9366 expr = (struct bfd_elf_version_expr *)
9367 htab_find ((htab_t) head->htab, &e);
9368 while (expr && strcmp (expr->pattern, cxx_sym) == 0)
9369 if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9370 goto out_ret;
9371 else
9372 expr = expr->next;
9374 /* Fallthrough */
9375 case BFD_ELF_VERSION_CXX_TYPE:
9376 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9378 e.pattern = java_sym;
9379 expr = (struct bfd_elf_version_expr *)
9380 htab_find ((htab_t) head->htab, &e);
9381 while (expr && strcmp (expr->pattern, java_sym) == 0)
9382 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9383 goto out_ret;
9384 else
9385 expr = expr->next;
9387 /* Fallthrough */
9388 default:
9389 break;
9393 /* Finally, try the wildcards. */
9394 if (prev == NULL || prev->literal)
9395 expr = head->remaining;
9396 else
9397 expr = prev->next;
9398 for (; expr; expr = expr->next)
9400 const char *s;
9402 if (!expr->pattern)
9403 continue;
9405 if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
9406 break;
9408 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9409 s = java_sym;
9410 else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9411 s = cxx_sym;
9412 else
9413 s = c_sym;
9414 if (fnmatch (expr->pattern, s, 0) == 0)
9415 break;
9418 out_ret:
9419 if (c_sym != sym)
9420 free ((char *) c_sym);
9421 if (cxx_sym != sym)
9422 free ((char *) cxx_sym);
9423 if (java_sym != sym)
9424 free ((char *) java_sym);
9425 return expr;
9428 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
9429 return a pointer to the symbol name with any backslash quotes removed. */
9431 static const char *
9432 realsymbol (const char *pattern)
9434 const char *p;
9435 bool changed = false, backslash = false;
9436 char *s, *symbol = (char *) xmalloc (strlen (pattern) + 1);
9438 for (p = pattern, s = symbol; *p != '\0'; ++p)
9440 /* It is a glob pattern only if there is no preceding
9441 backslash. */
9442 if (backslash)
9444 /* Remove the preceding backslash. */
9445 *(s - 1) = *p;
9446 backslash = false;
9447 changed = true;
9449 else
9451 if (*p == '?' || *p == '*' || *p == '[')
9453 free (symbol);
9454 return NULL;
9457 *s++ = *p;
9458 backslash = *p == '\\';
9462 if (changed)
9464 *s = '\0';
9465 return symbol;
9467 else
9469 free (symbol);
9470 return pattern;
9474 /* This is called for each variable name or match expression. NEW_NAME is
9475 the name of the symbol to match, or, if LITERAL_P is FALSE, a glob
9476 pattern to be matched against symbol names. */
9478 struct bfd_elf_version_expr *
9479 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
9480 const char *new_name,
9481 const char *lang,
9482 bool literal_p)
9484 struct bfd_elf_version_expr *ret;
9486 ret = (struct bfd_elf_version_expr *) xmalloc (sizeof *ret);
9487 ret->next = orig;
9488 ret->symver = 0;
9489 ret->script = 0;
9490 ret->literal = true;
9491 ret->pattern = literal_p ? new_name : realsymbol (new_name);
9492 if (ret->pattern == NULL)
9494 ret->pattern = new_name;
9495 ret->literal = false;
9498 if (lang == NULL || strcasecmp (lang, "C") == 0)
9499 ret->mask = BFD_ELF_VERSION_C_TYPE;
9500 else if (strcasecmp (lang, "C++") == 0)
9501 ret->mask = BFD_ELF_VERSION_CXX_TYPE;
9502 else if (strcasecmp (lang, "Java") == 0)
9503 ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
9504 else
9506 einfo (_("%X%P: unknown language `%s' in version information\n"),
9507 lang);
9508 ret->mask = BFD_ELF_VERSION_C_TYPE;
9511 return ldemul_new_vers_pattern (ret);
9514 /* This is called for each set of variable names and match
9515 expressions. */
9517 struct bfd_elf_version_tree *
9518 lang_new_vers_node (struct bfd_elf_version_expr *globals,
9519 struct bfd_elf_version_expr *locals)
9521 struct bfd_elf_version_tree *ret;
9523 ret = (struct bfd_elf_version_tree *) xcalloc (1, sizeof *ret);
9524 ret->globals.list = globals;
9525 ret->locals.list = locals;
9526 ret->match = lang_vers_match;
9527 ret->name_indx = (unsigned int) -1;
9528 return ret;
9531 /* This static variable keeps track of version indices. */
9533 static int version_index;
9535 static hashval_t
9536 version_expr_head_hash (const void *p)
9538 const struct bfd_elf_version_expr *e =
9539 (const struct bfd_elf_version_expr *) p;
9541 return htab_hash_string (e->pattern);
9544 static int
9545 version_expr_head_eq (const void *p1, const void *p2)
9547 const struct bfd_elf_version_expr *e1 =
9548 (const struct bfd_elf_version_expr *) p1;
9549 const struct bfd_elf_version_expr *e2 =
9550 (const struct bfd_elf_version_expr *) p2;
9552 return strcmp (e1->pattern, e2->pattern) == 0;
9555 static void
9556 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
9558 size_t count = 0;
9559 struct bfd_elf_version_expr *e, *next;
9560 struct bfd_elf_version_expr **list_loc, **remaining_loc;
9562 for (e = head->list; e; e = e->next)
9564 if (e->literal)
9565 count++;
9566 head->mask |= e->mask;
9569 if (count)
9571 head->htab = htab_create (count * 2, version_expr_head_hash,
9572 version_expr_head_eq, NULL);
9573 list_loc = &head->list;
9574 remaining_loc = &head->remaining;
9575 for (e = head->list; e; e = next)
9577 next = e->next;
9578 if (!e->literal)
9580 *remaining_loc = e;
9581 remaining_loc = &e->next;
9583 else
9585 void **loc = htab_find_slot ((htab_t) head->htab, e, INSERT);
9587 if (*loc)
9589 struct bfd_elf_version_expr *e1, *last;
9591 e1 = (struct bfd_elf_version_expr *) *loc;
9592 last = NULL;
9595 if (e1->mask == e->mask)
9597 last = NULL;
9598 break;
9600 last = e1;
9601 e1 = e1->next;
9603 while (e1 && strcmp (e1->pattern, e->pattern) == 0);
9605 if (last == NULL)
9607 /* This is a duplicate. */
9608 /* FIXME: Memory leak. Sometimes pattern is not
9609 xmalloced alone, but in larger chunk of memory. */
9610 /* free (e->pattern); */
9611 free (e);
9613 else
9615 e->next = last->next;
9616 last->next = e;
9619 else
9621 *loc = e;
9622 *list_loc = e;
9623 list_loc = &e->next;
9627 *remaining_loc = NULL;
9628 *list_loc = head->remaining;
9630 else
9631 head->remaining = head->list;
9634 /* This is called when we know the name and dependencies of the
9635 version. */
9637 void
9638 lang_register_vers_node (const char *name,
9639 struct bfd_elf_version_tree *version,
9640 struct bfd_elf_version_deps *deps)
9642 struct bfd_elf_version_tree *t, **pp;
9643 struct bfd_elf_version_expr *e1;
9645 if (name == NULL)
9646 name = "";
9648 if (link_info.version_info != NULL
9649 && (name[0] == '\0' || link_info.version_info->name[0] == '\0'))
9651 einfo (_("%X%P: anonymous version tag cannot be combined"
9652 " with other version tags\n"));
9653 free (version);
9654 return;
9657 /* Make sure this node has a unique name. */
9658 for (t = link_info.version_info; t != NULL; t = t->next)
9659 if (strcmp (t->name, name) == 0)
9660 einfo (_("%X%P: duplicate version tag `%s'\n"), name);
9662 lang_finalize_version_expr_head (&version->globals);
9663 lang_finalize_version_expr_head (&version->locals);
9665 /* Check the global and local match names, and make sure there
9666 aren't any duplicates. */
9668 for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
9670 for (t = link_info.version_info; t != NULL; t = t->next)
9672 struct bfd_elf_version_expr *e2;
9674 if (t->locals.htab && e1->literal)
9676 e2 = (struct bfd_elf_version_expr *)
9677 htab_find ((htab_t) t->locals.htab, e1);
9678 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9680 if (e1->mask == e2->mask)
9681 einfo (_("%X%P: duplicate expression `%s'"
9682 " in version information\n"), e1->pattern);
9683 e2 = e2->next;
9686 else if (!e1->literal)
9687 for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
9688 if (strcmp (e1->pattern, e2->pattern) == 0
9689 && e1->mask == e2->mask)
9690 einfo (_("%X%P: duplicate expression `%s'"
9691 " in version information\n"), e1->pattern);
9695 for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
9697 for (t = link_info.version_info; t != NULL; t = t->next)
9699 struct bfd_elf_version_expr *e2;
9701 if (t->globals.htab && e1->literal)
9703 e2 = (struct bfd_elf_version_expr *)
9704 htab_find ((htab_t) t->globals.htab, e1);
9705 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9707 if (e1->mask == e2->mask)
9708 einfo (_("%X%P: duplicate expression `%s'"
9709 " in version information\n"),
9710 e1->pattern);
9711 e2 = e2->next;
9714 else if (!e1->literal)
9715 for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
9716 if (strcmp (e1->pattern, e2->pattern) == 0
9717 && e1->mask == e2->mask)
9718 einfo (_("%X%P: duplicate expression `%s'"
9719 " in version information\n"), e1->pattern);
9723 version->deps = deps;
9724 version->name = name;
9725 if (name[0] != '\0')
9727 ++version_index;
9728 version->vernum = version_index;
9730 else
9731 version->vernum = 0;
9733 for (pp = &link_info.version_info; *pp != NULL; pp = &(*pp)->next)
9735 *pp = version;
9738 /* This is called when we see a version dependency. */
9740 struct bfd_elf_version_deps *
9741 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
9743 struct bfd_elf_version_deps *ret;
9744 struct bfd_elf_version_tree *t;
9746 ret = (struct bfd_elf_version_deps *) xmalloc (sizeof *ret);
9747 ret->next = list;
9749 for (t = link_info.version_info; t != NULL; t = t->next)
9751 if (strcmp (t->name, name) == 0)
9753 ret->version_needed = t;
9754 return ret;
9758 einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
9760 ret->version_needed = NULL;
9761 return ret;
9764 static void
9765 lang_do_version_exports_section (void)
9767 struct bfd_elf_version_expr *greg = NULL, *lreg;
9769 LANG_FOR_EACH_INPUT_STATEMENT (is)
9771 asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
9772 char *contents, *p;
9773 bfd_size_type len;
9775 if (sec == NULL)
9776 continue;
9778 len = sec->size;
9779 contents = (char *) xmalloc (len);
9780 if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
9781 einfo (_("%X%P: unable to read .exports section contents\n"), sec);
9783 p = contents;
9784 while (p < contents + len)
9786 greg = lang_new_vers_pattern (greg, p, NULL, false);
9787 p = strchr (p, '\0') + 1;
9790 /* Do not free the contents, as we used them creating the regex. */
9792 /* Do not include this section in the link. */
9793 sec->flags |= SEC_EXCLUDE | SEC_KEEP;
9796 lreg = lang_new_vers_pattern (NULL, "*", NULL, false);
9797 lang_register_vers_node (command_line.version_exports_section,
9798 lang_new_vers_node (greg, lreg), NULL);
9801 /* Evaluate LENGTH and ORIGIN parts of MEMORY spec. This is initially
9802 called with UPDATE_REGIONS_P set to FALSE, in this case no errors are
9803 thrown, however, references to symbols in the origin and length fields
9804 will be pushed into the symbol table, this allows PROVIDE statements to
9805 then provide these symbols. This function is called a second time with
9806 UPDATE_REGIONS_P set to TRUE, this time the we update the actual region
9807 data structures, and throw errors if missing symbols are encountered. */
9809 static void
9810 lang_do_memory_regions (bool update_regions_p)
9812 lang_memory_region_type *r = lang_memory_region_list;
9814 for (; r != NULL; r = r->next)
9816 if (r->origin_exp)
9818 exp_fold_tree_no_dot (r->origin_exp, NULL);
9819 if (update_regions_p)
9821 if (expld.result.valid_p)
9823 r->origin = expld.result.value;
9824 r->current = r->origin;
9826 else
9827 einfo (_("%P: invalid origin for memory region %s\n"),
9828 r->name_list.name);
9831 if (r->length_exp)
9833 exp_fold_tree_no_dot (r->length_exp, NULL);
9834 if (update_regions_p)
9836 if (expld.result.valid_p)
9837 r->length = expld.result.value;
9838 else
9839 einfo (_("%P: invalid length for memory region %s\n"),
9840 r->name_list.name);
9846 void
9847 lang_add_unique (const char *name)
9849 struct unique_sections *ent;
9851 for (ent = unique_section_list; ent; ent = ent->next)
9852 if (strcmp (ent->name, name) == 0)
9853 return;
9855 ent = (struct unique_sections *) xmalloc (sizeof *ent);
9856 ent->name = xstrdup (name);
9857 ent->next = unique_section_list;
9858 unique_section_list = ent;
9861 /* Append the list of dynamic symbols to the existing one. */
9863 void
9864 lang_append_dynamic_list (struct bfd_elf_dynamic_list **list_p,
9865 struct bfd_elf_version_expr *dynamic)
9867 if (*list_p)
9869 struct bfd_elf_version_expr *tail;
9870 for (tail = dynamic; tail->next != NULL; tail = tail->next)
9872 tail->next = (*list_p)->head.list;
9873 (*list_p)->head.list = dynamic;
9875 else
9877 struct bfd_elf_dynamic_list *d;
9879 d = (struct bfd_elf_dynamic_list *) xcalloc (1, sizeof *d);
9880 d->head.list = dynamic;
9881 d->match = lang_vers_match;
9882 *list_p = d;
9886 /* Append the list of C++ typeinfo dynamic symbols to the existing
9887 one. */
9889 void
9890 lang_append_dynamic_list_cpp_typeinfo (void)
9892 const char *symbols[] =
9894 "typeinfo name for*",
9895 "typeinfo for*"
9897 struct bfd_elf_version_expr *dynamic = NULL;
9898 unsigned int i;
9900 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9901 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9902 false);
9904 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9907 /* Append the list of C++ operator new and delete dynamic symbols to the
9908 existing one. */
9910 void
9911 lang_append_dynamic_list_cpp_new (void)
9913 const char *symbols[] =
9915 "operator new*",
9916 "operator delete*"
9918 struct bfd_elf_version_expr *dynamic = NULL;
9919 unsigned int i;
9921 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9922 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9923 false);
9925 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9928 /* Scan a space and/or comma separated string of features. */
9930 void
9931 lang_ld_feature (char *str)
9933 char *p, *q;
9935 p = str;
9936 while (*p)
9938 char sep;
9939 while (*p == ',' || ISSPACE (*p))
9940 ++p;
9941 if (!*p)
9942 break;
9943 q = p + 1;
9944 while (*q && *q != ',' && !ISSPACE (*q))
9945 ++q;
9946 sep = *q;
9947 *q = 0;
9948 if (strcasecmp (p, "SANE_EXPR") == 0)
9949 config.sane_expr = true;
9950 else
9951 einfo (_("%X%P: unknown feature `%s'\n"), p);
9952 *q = sep;
9953 p = q;
9957 /* Pretty print memory amount. */
9959 static void
9960 lang_print_memory_size (uint64_t sz)
9962 if (sz == 0)
9963 printf (" %10" PRIu64 " B", sz);
9964 else if ((sz & 0x3fffffff) == 0)
9965 printf ("%10" PRIu64 " GB", sz >> 30);
9966 else if ((sz & 0xfffff) == 0)
9967 printf ("%10" PRIu64 " MB", sz >> 20);
9968 else if ((sz & 0x3ff) == 0)
9969 printf ("%10" PRIu64 " KB", sz >> 10);
9970 else
9971 printf (" %10" PRIu64 " B", sz);
9974 /* Implement --print-memory-usage: disply per region memory usage. */
9976 void
9977 lang_print_memory_usage (void)
9979 lang_memory_region_type *r;
9981 printf ("Memory region Used Size Region Size %%age Used\n");
9982 for (r = lang_memory_region_list; r->next != NULL; r = r->next)
9984 bfd_vma used_length = r->current - r->origin;
9986 printf ("%16s: ",r->name_list.name);
9987 lang_print_memory_size (used_length);
9988 lang_print_memory_size (r->length);
9990 if (r->length != 0)
9992 double percent = used_length * 100.0 / r->length;
9993 printf (" %6.2f%%", percent);
9995 printf ("\n");