Fix PR30358, performance with --sort-section
[binutils-gdb.git] / ld / ldlang.c
1 /* Linker command language support.
2 Copyright (C) 1991-2023 Free Software Foundation, Inc.
3
4 This file is part of the GNU Binutils.
5
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.
10
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.
15
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. */
20
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"
45
46 #if BFD_SUPPORTS_PLUGINS
47 #include "plugin.h"
48 #endif
49
50 #ifndef offsetof
51 #define offsetof(TYPE, MEMBER) ((size_t) & (((TYPE*) 0)->MEMBER))
52 #endif
53
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)
59
60 /* Local variables. */
61 static struct obstack stat_obstack;
62 static struct obstack map_obstack;
63 static struct obstack pt_obstack;
64
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;
79
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);
102
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
144
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;
148
149 /* Count times through one_lang_size_sections_pass after mark phase. */
150 static int lang_sizing_iteration = 0;
151
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)
158
159 #define new_stat(x, y) \
160 (x##_type *) new_statement (x##_enum, sizeof (x##_type), y)
161
162 #define outside_section_address(q) \
163 ((q)->output_offset + (q)->output_section->vma)
164
165 #define outside_symbol_address(q) \
166 ((q)->value + outside_section_address (q->section))
167
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
173
174 void *
175 stat_alloc (size_t size)
176 {
177 return obstack_alloc (&stat_obstack, size);
178 }
179
180 /* Code for handling simple wildcards without going through fnmatch,
181 which can be expensive because of charset translations etc. */
182
183 /* A simple wild is a literal string followed by a single '*',
184 where the literal part is at least 4 characters long. */
185
186 static bool
187 is_simple_wild (const char *name)
188 {
189 size_t len = strcspn (name, "*?[");
190 return len >= 4 && name[len] == '*' && name[len + 1] == '\0';
191 }
192
193 static bool
194 match_simple_wild (const char *pattern, const char *name)
195 {
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;
201
202 pattern += 4;
203 name += 4;
204 while (*pattern != '*')
205 if (*name++ != *pattern++)
206 return false;
207
208 return true;
209 }
210
211 static int
212 name_match (const char *pattern, const char *name)
213 {
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);
219 }
220
221 /* Given an analyzed wildcard_spec SPEC, match it against NAME,
222 returns zero on a match, non-zero if there's no match. */
223
224 static int
225 spec_match (const struct wildcard_spec *spec, const char *name)
226 {
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;
232
233 if (pl)
234 {
235 if (inputlen < pl)
236 return 1;
237
238 r = memcmp (spec->name, name, pl);
239 if (r)
240 return r;
241 }
242
243 if (sl)
244 {
245 if (inputlen < sl)
246 return 1;
247
248 r = memcmp (spec->name + nl - sl, name + inputlen - sl, sl);
249 if (r)
250 return r;
251 }
252
253 if (nl == pl + sl + 1 && spec->name[pl] == '*')
254 return 0;
255
256 if (nl > pl)
257 return fnmatch (spec->name + pl, name + pl, 0);
258
259 if (inputlen >= nl)
260 return name[nl];
261
262 return 0;
263 }
264
265 static char *
266 ldirname (const char *name)
267 {
268 const char *base = lbasename (name);
269 char *dirname;
270
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;
278 }
279
280 /* If PATTERN is of the form archive:file, return a pointer to the
281 separator. If not, return NULL. */
282
283 static char *
284 archive_path (const char *pattern)
285 {
286 char *p = NULL;
287
288 if (link_info.path_separator == 0)
289 return p;
290
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;
295
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;
302 }
303
304 /* Given that FILE_SPEC results in a non-NULL SEP result from archive_path,
305 return whether F matches FILE_SPEC. */
306
307 static bool
308 input_statement_is_archive_path (const char *file_spec, char *sep,
309 lang_input_statement_type *f)
310 {
311 bool match = false;
312
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)))
317 {
318 match = true;
319
320 if (sep != file_spec)
321 {
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;
326 }
327 }
328 return match;
329 }
330
331 static bool
332 unique_section_p (const asection *sec,
333 const lang_output_section_statement_type *os)
334 {
335 struct unique_sections *unam;
336 const char *secnam;
337
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);
343
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;
348
349 return false;
350 }
351
352 /* Generic traversal routines for finding matching sections. */
353
354 /* Return true if FILE matches a pattern in EXCLUDE_LIST, otherwise return
355 false. */
356
357 static bool
358 walk_wild_file_in_exclude_list (struct name_list *exclude_list,
359 lang_input_statement_type *file)
360 {
361 struct name_list *list_tmp;
362
363 for (list_tmp = exclude_list;
364 list_tmp;
365 list_tmp = list_tmp->next)
366 {
367 char *p = archive_path (list_tmp->name);
368
369 if (p != NULL)
370 {
371 if (input_statement_is_archive_path (list_tmp->name, p, file))
372 return true;
373 }
374
375 else if (name_match (list_tmp->name, file->filename) == 0)
376 return true;
377
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;
386 }
387
388 return false;
389 }
390
391 /* Add SECTION (from input FILE) to the list of matching sections
392 within PTR (the matching wildcard is SEC). */
393
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)
399 {
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;
406 }
407
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. */
413
414 static void
415 walk_wild_section_match (lang_wild_statement_type *ptr,
416 lang_input_statement_type *file,
417 asection *s)
418 {
419 struct wildcard_list *sec;
420 const char *file_spec = ptr->filename;
421 char *p;
422
423 /* Check if filenames match. */
424 if (file_spec == NULL)
425 ;
426 else if ((p = archive_path (file_spec)) != NULL)
427 {
428 if (!input_statement_is_archive_path (file_spec, p, file))
429 return;
430 }
431 else if (wildcardp (file_spec))
432 {
433 if (fnmatch (file_spec, file->filename, 0) != 0)
434 return;
435 }
436 else
437 {
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 if (filename == NULL
449 || filename_cmp (filename, file_spec) != 0)
450 return;
451 }
452
453 /* If filename is excluded we're done. */
454 if (walk_wild_file_in_exclude_list (ptr->exclude_name_list, file))
455 return;
456
457 /* Check section name against each wildcard spec. If there's no
458 wildcard all sections match. */
459 sec = ptr->section_list;
460 if (sec == NULL)
461 add_matching_section (ptr, sec, s, file);
462 else
463 {
464 const char *sname = bfd_section_name (s);
465 for (; sec != NULL; sec = sec->next)
466 {
467 if (sec->spec.name != NULL
468 && spec_match (&sec->spec, sname) != 0)
469 continue;
470
471 /* Don't process sections from files which were excluded. */
472 if (!walk_wild_file_in_exclude_list (sec->spec.exclude_name_list,
473 file))
474 add_matching_section (ptr, sec, s, file);
475 }
476 }
477 }
478
479 /* Return the numerical value of the init_priority attribute from
480 section name NAME. */
481
482 static int
483 get_init_priority (const asection *sec)
484 {
485 const char *name = bfd_section_name (sec);
486 const char *dot;
487
488 /* GCC uses the following section names for the init_priority
489 attribute with numerical values 101 to 65535 inclusive. A
490 lower value means a higher priority.
491
492 1: .init_array.NNNNN/.fini_array.NNNNN: Where NNNNN is the
493 decimal numerical value of the init_priority attribute.
494 The order of execution in .init_array is forward and
495 .fini_array is backward.
496 2: .ctors.NNNNN/.dtors.NNNNN: Where NNNNN is 65535 minus the
497 decimal numerical value of the init_priority attribute.
498 The order of execution in .ctors is backward and .dtors
499 is forward.
500
501 .init_array.NNNNN sections would normally be placed in an output
502 .init_array section, .fini_array.NNNNN in .fini_array,
503 .ctors.NNNNN in .ctors, and .dtors.NNNNN in .dtors. This means
504 we should sort by increasing number (and could just use
505 SORT_BY_NAME in scripts). However if .ctors.NNNNN sections are
506 being placed in .init_array (which may also contain
507 .init_array.NNNNN sections) or .dtors.NNNNN sections are being
508 placed in .fini_array then we need to extract the init_priority
509 attribute and sort on that. */
510 dot = strrchr (name, '.');
511 if (dot != NULL && ISDIGIT (dot[1]))
512 {
513 char *end;
514 unsigned long init_priority = strtoul (dot + 1, &end, 10);
515 if (*end == 0)
516 {
517 if (dot == name + 6
518 && (strncmp (name, ".ctors", 6) == 0
519 || strncmp (name, ".dtors", 6) == 0))
520 init_priority = 65535 - init_priority;
521 if (init_priority <= INT_MAX)
522 return init_priority;
523 }
524 }
525 return -1;
526 }
527
528 /* Compare sections ASEC and BSEC according to SORT. */
529
530 static int
531 compare_section (sort_type sort, asection *asec, asection *bsec)
532 {
533 int ret;
534 int a_priority, b_priority;
535
536 switch (sort)
537 {
538 default:
539 abort ();
540
541 case by_init_priority:
542 a_priority = get_init_priority (asec);
543 b_priority = get_init_priority (bsec);
544 if (a_priority < 0 || b_priority < 0)
545 goto sort_by_name;
546 ret = a_priority - b_priority;
547 if (ret)
548 break;
549 else
550 goto sort_by_name;
551
552 case by_alignment_name:
553 ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
554 if (ret)
555 break;
556 /* Fall through. */
557
558 case by_name:
559 sort_by_name:
560 ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
561 break;
562
563 case by_name_alignment:
564 ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
565 if (ret)
566 break;
567 /* Fall through. */
568
569 case by_alignment:
570 ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
571 break;
572 }
573
574 return ret;
575 }
576
577 /* PE puts the sort key in the input statement. */
578
579 static const char *
580 sort_filename (bfd *abfd)
581 {
582 lang_input_statement_type *is = bfd_usrdata (abfd);
583 if (is->sort_key)
584 return is->sort_key;
585 return bfd_get_filename (abfd);
586 }
587
588 /* Handle wildcard sorting. This returns the place in a binary search tree
589 where this FILE:SECTION should be inserted for wild statement WILD where
590 the spec SEC was the matching one. The tree is later linearized. */
591
592 static lang_section_bst_type **
593 wild_sort (lang_wild_statement_type *wild,
594 struct wildcard_list *sec,
595 lang_input_statement_type *file,
596 asection *section)
597 {
598 lang_section_bst_type **tree;
599
600 if (!wild->filenames_sorted
601 && (sec == NULL || sec->spec.sorted == none
602 || sec->spec.sorted == by_none))
603 {
604 /* We might be called even if _this_ spec doesn't need sorting,
605 in which case we simply append at the right end of tree. */
606 return wild->rightmost;
607 }
608
609 tree = &wild->tree;
610 while (*tree)
611 {
612 /* Sorting by filename takes precedence over sorting by section
613 name. */
614
615 if (wild->filenames_sorted)
616 {
617 const char *fn, *ln;
618 bool fa, la;
619 int i;
620 asection *lsec = (*tree)->section;
621
622 /* The PE support for the .idata section as generated by
623 dlltool assumes that files will be sorted by the name of
624 the archive and then the name of the file within the
625 archive. */
626
627 fa = file->the_bfd->my_archive != NULL;
628 if (fa)
629 fn = sort_filename (file->the_bfd->my_archive);
630 else
631 fn = sort_filename (file->the_bfd);
632
633 la = lsec->owner->my_archive != NULL;
634 if (la)
635 ln = sort_filename (lsec->owner->my_archive);
636 else
637 ln = sort_filename (lsec->owner);
638
639 i = filename_cmp (fn, ln);
640 if (i > 0)
641 { tree = &((*tree)->right); continue; }
642 else if (i < 0)
643 { tree = &((*tree)->left); continue; }
644
645 if (fa || la)
646 {
647 if (fa)
648 fn = sort_filename (file->the_bfd);
649 if (la)
650 ln = sort_filename (lsec->owner);
651
652 i = filename_cmp (fn, ln);
653 if (i > 0)
654 { tree = &((*tree)->right); continue; }
655 else if (i < 0)
656 { tree = &((*tree)->left); continue; }
657 }
658 }
659
660 /* Here either the files are not sorted by name, or we are
661 looking at the sections for this file. */
662
663 /* Find the correct node to append this section. */
664 if (sec && sec->spec.sorted != none && sec->spec.sorted != by_none
665 && compare_section (sec->spec.sorted, section, (*tree)->section) < 0)
666 tree = &((*tree)->left);
667 else
668 tree = &((*tree)->right);
669 }
670
671 return tree;
672 }
673
674 /* Use wild_sort to build a BST to sort sections. */
675
676 static void
677 output_section_callback_sort (lang_wild_statement_type *ptr,
678 struct wildcard_list *sec,
679 asection *section,
680 lang_input_statement_type *file,
681 void *output)
682 {
683 lang_section_bst_type *node;
684 lang_section_bst_type **tree;
685 lang_output_section_statement_type *os;
686
687 os = (lang_output_section_statement_type *) output;
688
689 if (unique_section_p (section, os))
690 return;
691
692 /* Don't add sections to the tree when we already know that
693 lang_add_section won't do anything with it. */
694 if (wont_add_section_p (section, os))
695 return;
696
697 node = (lang_section_bst_type *) xmalloc (sizeof (lang_section_bst_type));
698 node->left = 0;
699 node->right = 0;
700 node->section = section;
701 node->pattern = ptr->section_list;
702
703 tree = wild_sort (ptr, sec, file, section);
704 if (tree != NULL)
705 {
706 *tree = node;
707 if (tree == ptr->rightmost)
708 ptr->rightmost = &node->right;
709 }
710 }
711
712 /* Convert a sorted sections' BST back to list form. */
713
714 static void
715 output_section_callback_tree_to_list (lang_wild_statement_type *ptr,
716 lang_section_bst_type *tree,
717 void *output)
718 {
719 if (tree->left)
720 output_section_callback_tree_to_list (ptr, tree->left, output);
721
722 lang_add_section (&ptr->children, tree->section, tree->pattern,
723 ptr->section_flag_list,
724 (lang_output_section_statement_type *) output);
725
726 if (tree->right)
727 output_section_callback_tree_to_list (ptr, tree->right, output);
728
729 free (tree);
730 }
731
732 \f
733 /* Sections are matched against wildcard statements via a prefix tree.
734 The prefix tree holds prefixes of all matching patterns (up to the first
735 wildcard character), and the wild statement from which those patterns
736 came. When matching a section name against the tree we're walking through
737 the tree character by character. Each statement we hit is one that
738 potentially matches. This is checked by actually going through the
739 (glob) matching routines.
740
741 When the section name turns out to actually match we record that section
742 in the wild statements list of matching sections. */
743
744 /* A prefix can be matched by multiple statement, so we need a list of them. */
745 struct wild_stmt_list
746 {
747 lang_wild_statement_type *stmt;
748 struct wild_stmt_list *next;
749 };
750
751 /* The prefix tree itself. */
752 struct prefixtree
753 {
754 /* The list of all children (linked via .next). */
755 struct prefixtree *child;
756 struct prefixtree *next;
757 /* This tree node is responsible for the prefix of parent plus 'c'. */
758 char c;
759 /* The statements that potentially can match this prefix. */
760 struct wild_stmt_list *stmt;
761 };
762
763 /* We always have a root node in the prefix tree. It corresponds to the
764 empty prefix. E.g. a glob like "*" would sit in this root. */
765 static struct prefixtree the_root, *ptroot = &the_root;
766
767 /* Given a prefix tree in *TREE, corresponding to prefix P, find or
768 INSERT the tree node corresponding to prefix P+C. */
769
770 static struct prefixtree *
771 get_prefix_tree (struct prefixtree **tree, char c, bool insert)
772 {
773 struct prefixtree *t;
774 for (t = *tree; t; t = t->next)
775 if (t->c == c)
776 return t;
777 if (!insert)
778 return NULL;
779 t = (struct prefixtree *) obstack_alloc (&pt_obstack, sizeof *t);
780 t->child = NULL;
781 t->next = *tree;
782 t->c = c;
783 t->stmt = NULL;
784 *tree = t;
785 return t;
786 }
787
788 /* Add STMT to the set of statements that can be matched by the prefix
789 corresponding to prefix tree T. */
790
791 static void
792 pt_add_stmt (struct prefixtree *t, lang_wild_statement_type *stmt)
793 {
794 struct wild_stmt_list *sl, **psl;
795 sl = (struct wild_stmt_list *) obstack_alloc (&pt_obstack, sizeof *sl);
796 sl->stmt = stmt;
797 sl->next = NULL;
798 psl = &t->stmt;
799 while (*psl)
800 psl = &(*psl)->next;
801 *psl = sl;
802 }
803
804 /* Insert STMT into the global prefix tree. */
805
806 static void
807 insert_prefix_tree (lang_wild_statement_type *stmt)
808 {
809 struct wildcard_list *sec;
810 struct prefixtree *t;
811
812 if (!stmt->section_list)
813 {
814 /* If we have no section_list (no wildcards in the wild STMT),
815 then every section name will match, so add this to the root. */
816 pt_add_stmt (ptroot, stmt);
817 return;
818 }
819
820 for (sec = stmt->section_list; sec; sec = sec->next)
821 {
822 const char *name = sec->spec.name ? sec->spec.name : "*";
823 char c;
824 t = ptroot;
825 for (; (c = *name); name++)
826 {
827 if (c == '*' || c == '[' || c == '?')
828 break;
829 t = get_prefix_tree (&t->child, c, true);
830 }
831 /* If we hit a glob character, the matching prefix is what we saw
832 until now. If we hit the end of pattern (hence it's no glob) then
833 we can do better: we only need to record a match when a section name
834 completely matches, not merely a prefix, so record the trailing 0
835 as well. */
836 if (!c)
837 t = get_prefix_tree (&t->child, 0, true);
838 pt_add_stmt (t, stmt);
839 }
840 }
841
842 /* Dump T indented by INDENT spaces. */
843
844 static void
845 debug_prefix_tree_rec (struct prefixtree *t, int indent)
846 {
847 for (; t; t = t->next)
848 {
849 struct wild_stmt_list *sl;
850 printf ("%*s %c", indent, "", t->c);
851 for (sl = t->stmt; sl; sl = sl->next)
852 {
853 struct wildcard_list *curr;
854 printf (" %p ", sl->stmt);
855 for (curr = sl->stmt->section_list; curr; curr = curr->next)
856 printf ("%s ", curr->spec.name ? curr->spec.name : "*");
857 }
858 printf ("\n");
859 debug_prefix_tree_rec (t->child, indent + 2);
860 }
861 }
862
863 /* Dump the global prefix tree. */
864
865 static void
866 debug_prefix_tree (void)
867 {
868 debug_prefix_tree_rec (ptroot, 2);
869 }
870
871 /* Like strcspn() but start to look from the end to beginning of
872 S. Returns the length of the suffix of S consisting entirely
873 of characters not in REJECT. */
874
875 static size_t
876 rstrcspn (const char *s, const char *reject)
877 {
878 size_t len = strlen (s), sufflen = 0;
879 while (len--)
880 {
881 char c = s[len];
882 if (strchr (reject, c) != 0)
883 break;
884 sufflen++;
885 }
886 return sufflen;
887 }
888
889 /* Analyze the wildcards in wild statement PTR to setup various
890 things for quick matching. */
891
892 static void
893 analyze_walk_wild_section_handler (lang_wild_statement_type *ptr)
894 {
895 struct wildcard_list *sec;
896
897 ptr->tree = NULL;
898 ptr->rightmost = &ptr->tree;
899
900 for (sec = ptr->section_list; sec != NULL; sec = sec->next)
901 {
902 if (sec->spec.name)
903 {
904 sec->spec.namelen = strlen (sec->spec.name);
905 sec->spec.prefixlen = strcspn (sec->spec.name, "?*[");
906 sec->spec.suffixlen = rstrcspn (sec->spec.name + sec->spec.prefixlen,
907 "?*]");
908 }
909 else
910 sec->spec.namelen = sec->spec.prefixlen = sec->spec.suffixlen = 0;
911 }
912
913 insert_prefix_tree (ptr);
914 }
915
916 /* Match all sections from FILE against the global prefix tree,
917 and record them into each wild statement that has a match. */
918
919 static void
920 resolve_wild_sections (lang_input_statement_type *file)
921 {
922 asection *s;
923
924 if (file->flags.just_syms)
925 return;
926
927 for (s = file->the_bfd->sections; s != NULL; s = s->next)
928 {
929 const char *sname = bfd_section_name (s);
930 char c = 1;
931 struct prefixtree *t = ptroot;
932 //printf (" YYY consider %s of %s\n", sname, file->the_bfd->filename);
933 do
934 {
935 if (t->stmt)
936 {
937 struct wild_stmt_list *sl;
938 for (sl = t->stmt; sl; sl = sl->next)
939 {
940 walk_wild_section_match (sl->stmt, file, s);
941 //printf (" ZZZ maybe place into %p\n", sl->stmt);
942 }
943 }
944 if (!c)
945 break;
946 c = *sname++;
947 t = get_prefix_tree (&t->child, c, false);
948 }
949 while (t);
950 }
951 }
952
953 /* Match all sections from all input files against the global prefix tree. */
954
955 static void
956 resolve_wilds (void)
957 {
958 LANG_FOR_EACH_INPUT_STATEMENT (f)
959 {
960 //printf("XXX %s\n", f->filename);
961 if (f->the_bfd == NULL
962 || !bfd_check_format (f->the_bfd, bfd_archive))
963 resolve_wild_sections (f);
964 else
965 {
966 bfd *member;
967
968 /* This is an archive file. We must map each member of the
969 archive separately. */
970 member = bfd_openr_next_archived_file (f->the_bfd, NULL);
971 while (member != NULL)
972 {
973 /* When lookup_name is called, it will call the add_symbols
974 entry point for the archive. For each element of the
975 archive which is included, BFD will call ldlang_add_file,
976 which will set the usrdata field of the member to the
977 lang_input_statement. */
978 if (bfd_usrdata (member) != NULL)
979 resolve_wild_sections (bfd_usrdata (member));
980
981 member = bfd_openr_next_archived_file (f->the_bfd, member);
982 }
983 }
984 }
985 }
986
987 /* For each input section that matches wild statement S calls
988 CALLBACK with DATA. */
989
990 static void
991 walk_wild (lang_wild_statement_type *s, callback_t callback, void *data)
992 {
993 lang_statement_union_type *l;
994
995 for (l = s->matching_sections.head; l; l = l->header.next)
996 {
997 (*callback) (s, l->input_matcher.pattern, l->input_matcher.section,
998 l->input_matcher.input_stmt, data);
999 }
1000 }
1001
1002 /* lang_for_each_statement walks the parse tree and calls the provided
1003 function for each node, except those inside output section statements
1004 with constraint set to -1. */
1005
1006 void
1007 lang_for_each_statement_worker (void (*func) (lang_statement_union_type *),
1008 lang_statement_union_type *s)
1009 {
1010 for (; s != NULL; s = s->header.next)
1011 {
1012 func (s);
1013
1014 switch (s->header.type)
1015 {
1016 case lang_constructors_statement_enum:
1017 lang_for_each_statement_worker (func, constructor_list.head);
1018 break;
1019 case lang_output_section_statement_enum:
1020 if (s->output_section_statement.constraint != -1)
1021 lang_for_each_statement_worker
1022 (func, s->output_section_statement.children.head);
1023 break;
1024 case lang_wild_statement_enum:
1025 lang_for_each_statement_worker (func,
1026 s->wild_statement.children.head);
1027 break;
1028 case lang_group_statement_enum:
1029 lang_for_each_statement_worker (func,
1030 s->group_statement.children.head);
1031 break;
1032 case lang_data_statement_enum:
1033 case lang_reloc_statement_enum:
1034 case lang_object_symbols_statement_enum:
1035 case lang_output_statement_enum:
1036 case lang_target_statement_enum:
1037 case lang_input_section_enum:
1038 case lang_input_statement_enum:
1039 case lang_assignment_statement_enum:
1040 case lang_padding_statement_enum:
1041 case lang_address_statement_enum:
1042 case lang_fill_statement_enum:
1043 case lang_insert_statement_enum:
1044 break;
1045 default:
1046 FAIL ();
1047 break;
1048 }
1049 }
1050 }
1051
1052 void
1053 lang_for_each_statement (void (*func) (lang_statement_union_type *))
1054 {
1055 lang_for_each_statement_worker (func, statement_list.head);
1056 }
1057
1058 /*----------------------------------------------------------------------*/
1059
1060 void
1061 lang_list_init (lang_statement_list_type *list)
1062 {
1063 list->head = NULL;
1064 list->tail = &list->head;
1065 }
1066
1067 static void
1068 lang_statement_append (lang_statement_list_type *list,
1069 void *element,
1070 void *field)
1071 {
1072 *(list->tail) = element;
1073 list->tail = field;
1074 }
1075
1076 void
1077 push_stat_ptr (lang_statement_list_type *new_ptr)
1078 {
1079 if (stat_save_ptr >= stat_save + sizeof (stat_save) / sizeof (stat_save[0]))
1080 abort ();
1081 *stat_save_ptr++ = stat_ptr;
1082 stat_ptr = new_ptr;
1083 }
1084
1085 void
1086 pop_stat_ptr (void)
1087 {
1088 if (stat_save_ptr <= stat_save)
1089 abort ();
1090 stat_ptr = *--stat_save_ptr;
1091 }
1092
1093 /* Build a new statement node for the parse tree. */
1094
1095 static lang_statement_union_type *
1096 new_statement (enum statement_enum type,
1097 size_t size,
1098 lang_statement_list_type *list)
1099 {
1100 lang_statement_union_type *new_stmt;
1101
1102 new_stmt = stat_alloc (size);
1103 new_stmt->header.type = type;
1104 new_stmt->header.next = NULL;
1105 lang_statement_append (list, new_stmt, &new_stmt->header.next);
1106 return new_stmt;
1107 }
1108
1109 /* Build a new input file node for the language. There are several
1110 ways in which we treat an input file, eg, we only look at symbols,
1111 or prefix it with a -l etc.
1112
1113 We can be supplied with requests for input files more than once;
1114 they may, for example be split over several lines like foo.o(.text)
1115 foo.o(.data) etc, so when asked for a file we check that we haven't
1116 got it already so we don't duplicate the bfd. */
1117
1118 static lang_input_statement_type *
1119 new_afile (const char *name,
1120 lang_input_file_enum_type file_type,
1121 const char *target,
1122 const char *from_filename)
1123 {
1124 lang_input_statement_type *p;
1125
1126 lang_has_input_file = true;
1127
1128 p = new_stat (lang_input_statement, stat_ptr);
1129 memset (&p->the_bfd, 0,
1130 sizeof (*p) - offsetof (lang_input_statement_type, the_bfd));
1131 p->extra_search_path = NULL;
1132 p->target = target;
1133 p->flags.dynamic = input_flags.dynamic;
1134 p->flags.add_DT_NEEDED_for_dynamic = input_flags.add_DT_NEEDED_for_dynamic;
1135 p->flags.add_DT_NEEDED_for_regular = input_flags.add_DT_NEEDED_for_regular;
1136 p->flags.whole_archive = input_flags.whole_archive;
1137 p->flags.sysrooted = input_flags.sysrooted;
1138 p->sort_key = NULL;
1139
1140 switch (file_type)
1141 {
1142 case lang_input_file_is_symbols_only_enum:
1143 p->filename = name;
1144 p->local_sym_name = name;
1145 p->flags.real = true;
1146 p->flags.just_syms = true;
1147 break;
1148 case lang_input_file_is_fake_enum:
1149 p->filename = name;
1150 p->local_sym_name = name;
1151 break;
1152 case lang_input_file_is_l_enum:
1153 if (name[0] == ':' && name[1] != '\0')
1154 {
1155 p->filename = name + 1;
1156 p->flags.full_name_provided = true;
1157 }
1158 else
1159 p->filename = name;
1160 p->local_sym_name = concat ("-l", name, (const char *) NULL);
1161 p->flags.maybe_archive = true;
1162 p->flags.real = true;
1163 p->flags.search_dirs = true;
1164 break;
1165 case lang_input_file_is_marker_enum:
1166 p->filename = name;
1167 p->local_sym_name = name;
1168 p->flags.search_dirs = true;
1169 break;
1170 case lang_input_file_is_search_file_enum:
1171 p->filename = name;
1172 p->local_sym_name = name;
1173 /* If name is a relative path, search the directory of the current linker
1174 script first. */
1175 if (from_filename && !IS_ABSOLUTE_PATH (name))
1176 p->extra_search_path = ldirname (from_filename);
1177 p->flags.real = true;
1178 p->flags.search_dirs = true;
1179 break;
1180 case lang_input_file_is_file_enum:
1181 p->filename = name;
1182 p->local_sym_name = name;
1183 p->flags.real = true;
1184 break;
1185 default:
1186 FAIL ();
1187 }
1188
1189 lang_statement_append (&input_file_chain, p, &p->next_real_file);
1190 return p;
1191 }
1192
1193 lang_input_statement_type *
1194 lang_add_input_file (const char *name,
1195 lang_input_file_enum_type file_type,
1196 const char *target)
1197 {
1198 if (name != NULL
1199 && (*name == '=' || startswith (name, "$SYSROOT")))
1200 {
1201 lang_input_statement_type *ret;
1202 char *sysrooted_name
1203 = concat (ld_sysroot,
1204 name + (*name == '=' ? 1 : strlen ("$SYSROOT")),
1205 (const char *) NULL);
1206
1207 /* We've now forcibly prepended the sysroot, making the input
1208 file independent of the context. Therefore, temporarily
1209 force a non-sysrooted context for this statement, so it won't
1210 get the sysroot prepended again when opened. (N.B. if it's a
1211 script, any child nodes with input files starting with "/"
1212 will be handled as "sysrooted" as they'll be found to be
1213 within the sysroot subdirectory.) */
1214 unsigned int outer_sysrooted = input_flags.sysrooted;
1215 input_flags.sysrooted = 0;
1216 ret = new_afile (sysrooted_name, file_type, target, NULL);
1217 input_flags.sysrooted = outer_sysrooted;
1218 return ret;
1219 }
1220
1221 return new_afile (name, file_type, target, current_input_file);
1222 }
1223
1224 struct out_section_hash_entry
1225 {
1226 struct bfd_hash_entry root;
1227 lang_statement_union_type s;
1228 };
1229
1230 /* The hash table. */
1231
1232 static struct bfd_hash_table output_section_statement_table;
1233
1234 /* Support routines for the hash table used by lang_output_section_find,
1235 initialize the table, fill in an entry and remove the table. */
1236
1237 static struct bfd_hash_entry *
1238 output_section_statement_newfunc (struct bfd_hash_entry *entry,
1239 struct bfd_hash_table *table,
1240 const char *string)
1241 {
1242 lang_output_section_statement_type **nextp;
1243 struct out_section_hash_entry *ret;
1244
1245 if (entry == NULL)
1246 {
1247 entry = (struct bfd_hash_entry *) bfd_hash_allocate (table,
1248 sizeof (*ret));
1249 if (entry == NULL)
1250 return entry;
1251 }
1252
1253 entry = bfd_hash_newfunc (entry, table, string);
1254 if (entry == NULL)
1255 return entry;
1256
1257 ret = (struct out_section_hash_entry *) entry;
1258 memset (&ret->s, 0, sizeof (ret->s));
1259 ret->s.header.type = lang_output_section_statement_enum;
1260 ret->s.output_section_statement.subsection_alignment = NULL;
1261 ret->s.output_section_statement.section_alignment = NULL;
1262 ret->s.output_section_statement.block_value = 1;
1263 lang_list_init (&ret->s.output_section_statement.children);
1264 lang_statement_append (stat_ptr, &ret->s, &ret->s.header.next);
1265
1266 /* For every output section statement added to the list, except the
1267 first one, lang_os_list.tail points to the "next"
1268 field of the last element of the list. */
1269 if (lang_os_list.head != NULL)
1270 ret->s.output_section_statement.prev
1271 = ((lang_output_section_statement_type *)
1272 ((char *) lang_os_list.tail
1273 - offsetof (lang_output_section_statement_type, next)));
1274
1275 /* GCC's strict aliasing rules prevent us from just casting the
1276 address, so we store the pointer in a variable and cast that
1277 instead. */
1278 nextp = &ret->s.output_section_statement.next;
1279 lang_statement_append (&lang_os_list, &ret->s, nextp);
1280 return &ret->root;
1281 }
1282
1283 static void
1284 output_section_statement_table_init (void)
1285 {
1286 if (!bfd_hash_table_init_n (&output_section_statement_table,
1287 output_section_statement_newfunc,
1288 sizeof (struct out_section_hash_entry),
1289 61))
1290 einfo (_("%F%P: can not create hash table: %E\n"));
1291 }
1292
1293 static void
1294 output_section_statement_table_free (void)
1295 {
1296 bfd_hash_table_free (&output_section_statement_table);
1297 }
1298
1299 /* Build enough state so that the parser can build its tree. */
1300
1301 void
1302 lang_init (void)
1303 {
1304 obstack_begin (&stat_obstack, 1000);
1305 obstack_init (&pt_obstack);
1306
1307 stat_ptr = &statement_list;
1308
1309 output_section_statement_table_init ();
1310
1311 lang_list_init (stat_ptr);
1312
1313 lang_list_init (&input_file_chain);
1314 lang_list_init (&lang_os_list);
1315 lang_list_init (&file_chain);
1316 first_file = lang_add_input_file (NULL, lang_input_file_is_marker_enum,
1317 NULL);
1318 abs_output_section =
1319 lang_output_section_statement_lookup (BFD_ABS_SECTION_NAME, 0, 1);
1320
1321 abs_output_section->bfd_section = bfd_abs_section_ptr;
1322
1323 asneeded_list_head = NULL;
1324 asneeded_list_tail = &asneeded_list_head;
1325 }
1326
1327 void
1328 lang_finish (void)
1329 {
1330 output_section_statement_table_free ();
1331 }
1332
1333 /*----------------------------------------------------------------------
1334 A region is an area of memory declared with the
1335 MEMORY { name:org=exp, len=exp ... }
1336 syntax.
1337
1338 We maintain a list of all the regions here.
1339
1340 If no regions are specified in the script, then the default is used
1341 which is created when looked up to be the entire data space.
1342
1343 If create is true we are creating a region inside a MEMORY block.
1344 In this case it is probably an error to create a region that has
1345 already been created. If we are not inside a MEMORY block it is
1346 dubious to use an undeclared region name (except DEFAULT_MEMORY_REGION)
1347 and so we issue a warning.
1348
1349 Each region has at least one name. The first name is either
1350 DEFAULT_MEMORY_REGION or the name given in the MEMORY block. You can add
1351 alias names to an existing region within a script with
1352 REGION_ALIAS (alias, region_name). Each name corresponds to at most one
1353 region. */
1354
1355 static lang_memory_region_type *lang_memory_region_list;
1356 static lang_memory_region_type **lang_memory_region_list_tail
1357 = &lang_memory_region_list;
1358
1359 lang_memory_region_type *
1360 lang_memory_region_lookup (const char *const name, bool create)
1361 {
1362 lang_memory_region_name *n;
1363 lang_memory_region_type *r;
1364 lang_memory_region_type *new_region;
1365
1366 /* NAME is NULL for LMA memspecs if no region was specified. */
1367 if (name == NULL)
1368 return NULL;
1369
1370 for (r = lang_memory_region_list; r != NULL; r = r->next)
1371 for (n = &r->name_list; n != NULL; n = n->next)
1372 if (strcmp (n->name, name) == 0)
1373 {
1374 if (create)
1375 einfo (_("%P:%pS: warning: redeclaration of memory region `%s'\n"),
1376 NULL, name);
1377 return r;
1378 }
1379
1380 if (!create && strcmp (name, DEFAULT_MEMORY_REGION))
1381 einfo (_("%P:%pS: warning: memory region `%s' not declared\n"),
1382 NULL, name);
1383
1384 new_region = stat_alloc (sizeof (lang_memory_region_type));
1385
1386 new_region->name_list.name = xstrdup (name);
1387 new_region->name_list.next = NULL;
1388 new_region->next = NULL;
1389 new_region->origin_exp = NULL;
1390 new_region->origin = 0;
1391 new_region->length_exp = NULL;
1392 new_region->length = ~(bfd_size_type) 0;
1393 new_region->current = 0;
1394 new_region->last_os = NULL;
1395 new_region->flags = 0;
1396 new_region->not_flags = 0;
1397 new_region->had_full_message = false;
1398
1399 *lang_memory_region_list_tail = new_region;
1400 lang_memory_region_list_tail = &new_region->next;
1401
1402 return new_region;
1403 }
1404
1405 void
1406 lang_memory_region_alias (const char *alias, const char *region_name)
1407 {
1408 lang_memory_region_name *n;
1409 lang_memory_region_type *r;
1410 lang_memory_region_type *region;
1411
1412 /* The default region must be unique. This ensures that it is not necessary
1413 to iterate through the name list if someone wants the check if a region is
1414 the default memory region. */
1415 if (strcmp (region_name, DEFAULT_MEMORY_REGION) == 0
1416 || strcmp (alias, DEFAULT_MEMORY_REGION) == 0)
1417 einfo (_("%F%P:%pS: error: alias for default memory region\n"), NULL);
1418
1419 /* Look for the target region and check if the alias is not already
1420 in use. */
1421 region = NULL;
1422 for (r = lang_memory_region_list; r != NULL; r = r->next)
1423 for (n = &r->name_list; n != NULL; n = n->next)
1424 {
1425 if (region == NULL && strcmp (n->name, region_name) == 0)
1426 region = r;
1427 if (strcmp (n->name, alias) == 0)
1428 einfo (_("%F%P:%pS: error: redefinition of memory region "
1429 "alias `%s'\n"),
1430 NULL, alias);
1431 }
1432
1433 /* Check if the target region exists. */
1434 if (region == NULL)
1435 einfo (_("%F%P:%pS: error: memory region `%s' "
1436 "for alias `%s' does not exist\n"),
1437 NULL, region_name, alias);
1438
1439 /* Add alias to region name list. */
1440 n = stat_alloc (sizeof (lang_memory_region_name));
1441 n->name = xstrdup (alias);
1442 n->next = region->name_list.next;
1443 region->name_list.next = n;
1444 }
1445
1446 static lang_memory_region_type *
1447 lang_memory_default (asection *section)
1448 {
1449 lang_memory_region_type *p;
1450
1451 flagword sec_flags = section->flags;
1452
1453 /* Override SEC_DATA to mean a writable section. */
1454 if ((sec_flags & (SEC_ALLOC | SEC_READONLY | SEC_CODE)) == SEC_ALLOC)
1455 sec_flags |= SEC_DATA;
1456
1457 for (p = lang_memory_region_list; p != NULL; p = p->next)
1458 {
1459 if ((p->flags & sec_flags) != 0
1460 && (p->not_flags & sec_flags) == 0)
1461 {
1462 return p;
1463 }
1464 }
1465 return lang_memory_region_lookup (DEFAULT_MEMORY_REGION, false);
1466 }
1467
1468 /* Get the output section statement directly from the userdata. */
1469
1470 lang_output_section_statement_type *
1471 lang_output_section_get (const asection *output_section)
1472 {
1473 return bfd_section_userdata (output_section);
1474 }
1475
1476 /* Find or create an output_section_statement with the given NAME.
1477 If CONSTRAINT is non-zero match one with that constraint, otherwise
1478 match any non-negative constraint. If CREATE is 0 return NULL when
1479 no match exists. If CREATE is 1, create an output_section_statement
1480 when no match exists or if CONSTRAINT is SPECIAL. If CREATE is 2,
1481 always make a new output_section_statement. */
1482
1483 lang_output_section_statement_type *
1484 lang_output_section_statement_lookup (const char *name,
1485 int constraint,
1486 int create)
1487 {
1488 struct out_section_hash_entry *entry;
1489
1490 entry = ((struct out_section_hash_entry *)
1491 bfd_hash_lookup (&output_section_statement_table, name,
1492 create != 0, false));
1493 if (entry == NULL)
1494 {
1495 if (create)
1496 einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1497 return NULL;
1498 }
1499
1500 if (entry->s.output_section_statement.name != NULL)
1501 {
1502 /* We have a section of this name, but it might not have the correct
1503 constraint. */
1504 struct out_section_hash_entry *last_ent;
1505
1506 name = entry->s.output_section_statement.name;
1507 do
1508 {
1509 if (create != 2
1510 && !(create && constraint == SPECIAL)
1511 && (constraint == entry->s.output_section_statement.constraint
1512 || (constraint == 0
1513 && entry->s.output_section_statement.constraint >= 0)))
1514 return &entry->s.output_section_statement;
1515 last_ent = entry;
1516 entry = (struct out_section_hash_entry *) entry->root.next;
1517 }
1518 while (entry != NULL
1519 && name == entry->s.output_section_statement.name);
1520
1521 if (!create)
1522 return NULL;
1523
1524 entry
1525 = ((struct out_section_hash_entry *)
1526 output_section_statement_newfunc (NULL,
1527 &output_section_statement_table,
1528 name));
1529 if (entry == NULL)
1530 {
1531 einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1532 return NULL;
1533 }
1534 entry->root = last_ent->root;
1535 last_ent->root.next = &entry->root;
1536 }
1537
1538 entry->s.output_section_statement.name = name;
1539 entry->s.output_section_statement.constraint = constraint;
1540 entry->s.output_section_statement.dup_output = (create == 2
1541 || constraint == SPECIAL);
1542 return &entry->s.output_section_statement;
1543 }
1544
1545 /* Find the next output_section_statement with the same name as OS.
1546 If CONSTRAINT is non-zero, find one with that constraint otherwise
1547 match any non-negative constraint. */
1548
1549 lang_output_section_statement_type *
1550 next_matching_output_section_statement (lang_output_section_statement_type *os,
1551 int constraint)
1552 {
1553 /* All output_section_statements are actually part of a
1554 struct out_section_hash_entry. */
1555 struct out_section_hash_entry *entry = (struct out_section_hash_entry *)
1556 ((char *) os
1557 - offsetof (struct out_section_hash_entry, s.output_section_statement));
1558 const char *name = os->name;
1559
1560 ASSERT (name == entry->root.string);
1561 do
1562 {
1563 entry = (struct out_section_hash_entry *) entry->root.next;
1564 if (entry == NULL
1565 || name != entry->s.output_section_statement.name)
1566 return NULL;
1567 }
1568 while (constraint != entry->s.output_section_statement.constraint
1569 && (constraint != 0
1570 || entry->s.output_section_statement.constraint < 0));
1571
1572 return &entry->s.output_section_statement;
1573 }
1574
1575 /* A variant of lang_output_section_find used by place_orphan.
1576 Returns the output statement that should precede a new output
1577 statement for SEC. If an exact match is found on certain flags,
1578 sets *EXACT too. */
1579
1580 lang_output_section_statement_type *
1581 lang_output_section_find_by_flags (const asection *sec,
1582 flagword sec_flags,
1583 lang_output_section_statement_type **exact,
1584 lang_match_sec_type_func match_type)
1585 {
1586 lang_output_section_statement_type *first, *look, *found;
1587 flagword look_flags, differ;
1588
1589 /* We know the first statement on this list is *ABS*. May as well
1590 skip it. */
1591 first = (void *) lang_os_list.head;
1592 first = first->next;
1593
1594 /* First try for an exact match. */
1595 found = NULL;
1596 for (look = first; look; look = look->next)
1597 {
1598 look_flags = look->flags;
1599 if (look->bfd_section != NULL)
1600 {
1601 look_flags = look->bfd_section->flags;
1602 if (match_type && !match_type (link_info.output_bfd,
1603 look->bfd_section,
1604 sec->owner, sec))
1605 continue;
1606 }
1607 differ = look_flags ^ sec_flags;
1608 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY
1609 | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1610 found = look;
1611 }
1612 if (found != NULL)
1613 {
1614 if (exact != NULL)
1615 *exact = found;
1616 return found;
1617 }
1618
1619 if ((sec_flags & SEC_CODE) != 0
1620 && (sec_flags & SEC_ALLOC) != 0)
1621 {
1622 /* Try for a rw code section. */
1623 for (look = first; look; look = look->next)
1624 {
1625 look_flags = look->flags;
1626 if (look->bfd_section != NULL)
1627 {
1628 look_flags = look->bfd_section->flags;
1629 if (match_type && !match_type (link_info.output_bfd,
1630 look->bfd_section,
1631 sec->owner, sec))
1632 continue;
1633 }
1634 differ = look_flags ^ sec_flags;
1635 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1636 | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1637 found = look;
1638 }
1639 }
1640 else if ((sec_flags & SEC_READONLY) != 0
1641 && (sec_flags & SEC_ALLOC) != 0)
1642 {
1643 /* .rodata can go after .text, .sdata2 after .rodata. */
1644 for (look = first; look; look = look->next)
1645 {
1646 look_flags = look->flags;
1647 if (look->bfd_section != NULL)
1648 {
1649 look_flags = look->bfd_section->flags;
1650 if (match_type && !match_type (link_info.output_bfd,
1651 look->bfd_section,
1652 sec->owner, sec))
1653 continue;
1654 }
1655 differ = look_flags ^ sec_flags;
1656 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1657 | SEC_READONLY | SEC_SMALL_DATA))
1658 || (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1659 | SEC_READONLY))
1660 && !(look_flags & SEC_SMALL_DATA)))
1661 found = look;
1662 }
1663 }
1664 else if ((sec_flags & SEC_THREAD_LOCAL) != 0
1665 && (sec_flags & SEC_ALLOC) != 0)
1666 {
1667 /* .tdata can go after .data, .tbss after .tdata. Treat .tbss
1668 as if it were a loaded section, and don't use match_type. */
1669 bool seen_thread_local = false;
1670
1671 match_type = NULL;
1672 for (look = first; look; look = look->next)
1673 {
1674 look_flags = look->flags;
1675 if (look->bfd_section != NULL)
1676 look_flags = look->bfd_section->flags;
1677
1678 differ = look_flags ^ (sec_flags | SEC_LOAD | SEC_HAS_CONTENTS);
1679 if (!(differ & (SEC_THREAD_LOCAL | SEC_ALLOC)))
1680 {
1681 /* .tdata and .tbss must be adjacent and in that order. */
1682 if (!(look_flags & SEC_LOAD)
1683 && (sec_flags & SEC_LOAD))
1684 /* ..so if we're at a .tbss section and we're placing
1685 a .tdata section stop looking and return the
1686 previous section. */
1687 break;
1688 found = look;
1689 seen_thread_local = true;
1690 }
1691 else if (seen_thread_local)
1692 break;
1693 else if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD)))
1694 found = look;
1695 }
1696 }
1697 else if ((sec_flags & SEC_SMALL_DATA) != 0
1698 && (sec_flags & SEC_ALLOC) != 0)
1699 {
1700 /* .sdata goes after .data, .sbss after .sdata. */
1701 for (look = first; look; look = look->next)
1702 {
1703 look_flags = look->flags;
1704 if (look->bfd_section != NULL)
1705 {
1706 look_flags = look->bfd_section->flags;
1707 if (match_type && !match_type (link_info.output_bfd,
1708 look->bfd_section,
1709 sec->owner, sec))
1710 continue;
1711 }
1712 differ = look_flags ^ sec_flags;
1713 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1714 | SEC_THREAD_LOCAL))
1715 || ((look_flags & SEC_SMALL_DATA)
1716 && !(sec_flags & SEC_HAS_CONTENTS)))
1717 found = look;
1718 }
1719 }
1720 else if ((sec_flags & SEC_HAS_CONTENTS) != 0
1721 && (sec_flags & SEC_ALLOC) != 0)
1722 {
1723 /* .data goes after .rodata. */
1724 for (look = first; look; look = look->next)
1725 {
1726 look_flags = look->flags;
1727 if (look->bfd_section != NULL)
1728 {
1729 look_flags = look->bfd_section->flags;
1730 if (match_type && !match_type (link_info.output_bfd,
1731 look->bfd_section,
1732 sec->owner, sec))
1733 continue;
1734 }
1735 differ = look_flags ^ sec_flags;
1736 if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1737 | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1738 found = look;
1739 }
1740 }
1741 else if ((sec_flags & SEC_ALLOC) != 0)
1742 {
1743 /* .bss goes after any other alloc section. */
1744 for (look = first; look; look = look->next)
1745 {
1746 look_flags = look->flags;
1747 if (look->bfd_section != NULL)
1748 {
1749 look_flags = look->bfd_section->flags;
1750 if (match_type && !match_type (link_info.output_bfd,
1751 look->bfd_section,
1752 sec->owner, sec))
1753 continue;
1754 }
1755 differ = look_flags ^ sec_flags;
1756 if (!(differ & SEC_ALLOC))
1757 found = look;
1758 }
1759 }
1760 else
1761 {
1762 /* non-alloc go last. */
1763 for (look = first; look; look = look->next)
1764 {
1765 look_flags = look->flags;
1766 if (look->bfd_section != NULL)
1767 look_flags = look->bfd_section->flags;
1768 differ = look_flags ^ sec_flags;
1769 if (!(differ & SEC_DEBUGGING))
1770 found = look;
1771 }
1772 return found;
1773 }
1774
1775 if (found || !match_type)
1776 return found;
1777
1778 return lang_output_section_find_by_flags (sec, sec_flags, NULL, NULL);
1779 }
1780
1781 /* Find the last output section before given output statement.
1782 Used by place_orphan. */
1783
1784 static asection *
1785 output_prev_sec_find (lang_output_section_statement_type *os)
1786 {
1787 lang_output_section_statement_type *lookup;
1788
1789 for (lookup = os->prev; lookup != NULL; lookup = lookup->prev)
1790 {
1791 if (lookup->constraint < 0)
1792 continue;
1793
1794 if (lookup->bfd_section != NULL)
1795 return lookup->bfd_section;
1796 }
1797
1798 return NULL;
1799 }
1800
1801 /* Look for a suitable place for a new output section statement. The
1802 idea is to skip over anything that might be inside a SECTIONS {}
1803 statement in a script, before we find another output section
1804 statement. Assignments to "dot" before an output section statement
1805 are assumed to belong to it, except in two cases; The first
1806 assignment to dot, and assignments before non-alloc sections.
1807 Otherwise we might put an orphan before . = . + SIZEOF_HEADERS or
1808 similar assignments that set the initial address, or we might
1809 insert non-alloc note sections among assignments setting end of
1810 image symbols. */
1811
1812 static lang_statement_union_type **
1813 insert_os_after (lang_statement_union_type *after)
1814 {
1815 lang_statement_union_type **where;
1816 lang_statement_union_type **assign = NULL;
1817 bool ignore_first;
1818
1819 ignore_first = after == lang_os_list.head;
1820
1821 for (where = &after->header.next;
1822 *where != NULL;
1823 where = &(*where)->header.next)
1824 {
1825 switch ((*where)->header.type)
1826 {
1827 case lang_assignment_statement_enum:
1828 if (assign == NULL)
1829 {
1830 lang_assignment_statement_type *ass;
1831
1832 ass = &(*where)->assignment_statement;
1833 if (ass->exp->type.node_class != etree_assert
1834 && ass->exp->assign.dst[0] == '.'
1835 && ass->exp->assign.dst[1] == 0)
1836 {
1837 if (!ignore_first)
1838 assign = where;
1839 ignore_first = false;
1840 }
1841 }
1842 continue;
1843 case lang_wild_statement_enum:
1844 case lang_input_section_enum:
1845 case lang_object_symbols_statement_enum:
1846 case lang_fill_statement_enum:
1847 case lang_data_statement_enum:
1848 case lang_reloc_statement_enum:
1849 case lang_padding_statement_enum:
1850 case lang_constructors_statement_enum:
1851 assign = NULL;
1852 ignore_first = false;
1853 continue;
1854 case lang_output_section_statement_enum:
1855 if (assign != NULL)
1856 {
1857 asection *s = (*where)->output_section_statement.bfd_section;
1858
1859 if (s == NULL
1860 || s->map_head.s == NULL
1861 || (s->flags & SEC_ALLOC) != 0)
1862 where = assign;
1863 }
1864 break;
1865 case lang_input_statement_enum:
1866 case lang_address_statement_enum:
1867 case lang_target_statement_enum:
1868 case lang_output_statement_enum:
1869 case lang_group_statement_enum:
1870 case lang_insert_statement_enum:
1871 continue;
1872 case lang_input_matcher_enum:
1873 FAIL ();
1874 }
1875 break;
1876 }
1877
1878 return where;
1879 }
1880
1881 lang_output_section_statement_type *
1882 lang_insert_orphan (asection *s,
1883 const char *secname,
1884 int constraint,
1885 lang_output_section_statement_type *after,
1886 struct orphan_save *place,
1887 etree_type *address,
1888 lang_statement_list_type *add_child)
1889 {
1890 lang_statement_list_type add;
1891 lang_output_section_statement_type *os;
1892 lang_output_section_statement_type **os_tail;
1893
1894 /* If we have found an appropriate place for the output section
1895 statements for this orphan, add them to our own private list,
1896 inserting them later into the global statement list. */
1897 if (after != NULL)
1898 {
1899 lang_list_init (&add);
1900 push_stat_ptr (&add);
1901 }
1902
1903 if (bfd_link_relocatable (&link_info)
1904 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0)
1905 address = exp_intop (0);
1906
1907 os_tail = (lang_output_section_statement_type **) lang_os_list.tail;
1908 os = lang_enter_output_section_statement (
1909 secname, address, normal_section, 0, NULL, NULL, NULL, constraint, 0);
1910
1911 if (add_child == NULL)
1912 add_child = &os->children;
1913 lang_add_section (add_child, s, NULL, NULL, os);
1914
1915 if (after && (s->flags & (SEC_LOAD | SEC_ALLOC)) != 0)
1916 {
1917 const char *region = (after->region
1918 ? after->region->name_list.name
1919 : DEFAULT_MEMORY_REGION);
1920 const char *lma_region = (after->lma_region
1921 ? after->lma_region->name_list.name
1922 : NULL);
1923 lang_leave_output_section_statement (NULL, region, after->phdrs,
1924 lma_region);
1925 }
1926 else
1927 lang_leave_output_section_statement (NULL, DEFAULT_MEMORY_REGION, NULL,
1928 NULL);
1929
1930 /* Restore the global list pointer. */
1931 if (after != NULL)
1932 pop_stat_ptr ();
1933
1934 if (after != NULL && os->bfd_section != NULL)
1935 {
1936 asection *snew, *as;
1937 bool place_after = place->stmt == NULL;
1938 bool insert_after = true;
1939
1940 snew = os->bfd_section;
1941
1942 /* Shuffle the bfd section list to make the output file look
1943 neater. This is really only cosmetic. */
1944 if (place->section == NULL
1945 && after != (void *) lang_os_list.head)
1946 {
1947 asection *bfd_section = after->bfd_section;
1948
1949 /* If the output statement hasn't been used to place any input
1950 sections (and thus doesn't have an output bfd_section),
1951 look for the closest prior output statement having an
1952 output section. */
1953 if (bfd_section == NULL)
1954 bfd_section = output_prev_sec_find (after);
1955
1956 if (bfd_section != NULL
1957 && bfd_section->owner != NULL
1958 && bfd_section != snew)
1959 place->section = &bfd_section->next;
1960 }
1961
1962 if (place->section == NULL)
1963 place->section = &link_info.output_bfd->sections;
1964
1965 as = *place->section;
1966
1967 if (!as)
1968 {
1969 /* Put the section at the end of the list. */
1970
1971 /* Unlink the section. */
1972 bfd_section_list_remove (link_info.output_bfd, snew);
1973
1974 /* Now tack it back on in the right place. */
1975 bfd_section_list_append (link_info.output_bfd, snew);
1976 }
1977 else if ((bfd_get_flavour (link_info.output_bfd)
1978 == bfd_target_elf_flavour)
1979 && (bfd_get_flavour (s->owner)
1980 == bfd_target_elf_flavour)
1981 && ((elf_section_type (s) == SHT_NOTE
1982 && (s->flags & SEC_LOAD) != 0)
1983 || (elf_section_type (as) == SHT_NOTE
1984 && (as->flags & SEC_LOAD) != 0)))
1985 {
1986 /* Make sure that output note sections are grouped and sorted
1987 by alignments when inserting a note section or insert a
1988 section after a note section, */
1989 asection *sec;
1990 /* A specific section after which the output note section
1991 should be placed. */
1992 asection *after_sec;
1993 /* True if we need to insert the orphan section after a
1994 specific section to maintain output note section order. */
1995 bool after_sec_note = false;
1996
1997 static asection *first_orphan_note = NULL;
1998
1999 /* Group and sort output note section by alignments in
2000 ascending order. */
2001 after_sec = NULL;
2002 if (elf_section_type (s) == SHT_NOTE
2003 && (s->flags & SEC_LOAD) != 0)
2004 {
2005 /* Search from the beginning for the last output note
2006 section with equal or larger alignments. NB: Don't
2007 place orphan note section after non-note sections. */
2008
2009 first_orphan_note = NULL;
2010 for (sec = link_info.output_bfd->sections;
2011 (sec != NULL
2012 && !bfd_is_abs_section (sec));
2013 sec = sec->next)
2014 if (sec != snew
2015 && elf_section_type (sec) == SHT_NOTE
2016 && (sec->flags & SEC_LOAD) != 0)
2017 {
2018 if (!first_orphan_note)
2019 first_orphan_note = sec;
2020 if (sec->alignment_power >= s->alignment_power)
2021 after_sec = sec;
2022 }
2023 else if (first_orphan_note)
2024 {
2025 /* Stop if there is non-note section after the first
2026 orphan note section. */
2027 break;
2028 }
2029
2030 /* If this will be the first orphan note section, it can
2031 be placed at the default location. */
2032 after_sec_note = first_orphan_note != NULL;
2033 if (after_sec == NULL && after_sec_note)
2034 {
2035 /* If all output note sections have smaller
2036 alignments, place the section before all
2037 output orphan note sections. */
2038 after_sec = first_orphan_note;
2039 insert_after = false;
2040 }
2041 }
2042 else if (first_orphan_note)
2043 {
2044 /* Don't place non-note sections in the middle of orphan
2045 note sections. */
2046 after_sec_note = true;
2047 after_sec = as;
2048 for (sec = as->next;
2049 (sec != NULL
2050 && !bfd_is_abs_section (sec));
2051 sec = sec->next)
2052 if (elf_section_type (sec) == SHT_NOTE
2053 && (sec->flags & SEC_LOAD) != 0)
2054 after_sec = sec;
2055 }
2056
2057 if (after_sec_note)
2058 {
2059 if (after_sec)
2060 {
2061 /* Search forward to insert OS after AFTER_SEC output
2062 statement. */
2063 lang_output_section_statement_type *stmt, *next;
2064 bool found = false;
2065 for (stmt = after; stmt != NULL; stmt = next)
2066 {
2067 next = stmt->next;
2068 if (insert_after)
2069 {
2070 if (stmt->bfd_section == after_sec)
2071 {
2072 place_after = true;
2073 found = true;
2074 after = stmt;
2075 break;
2076 }
2077 }
2078 else
2079 {
2080 /* If INSERT_AFTER is FALSE, place OS before
2081 AFTER_SEC output statement. */
2082 if (next && next->bfd_section == after_sec)
2083 {
2084 place_after = true;
2085 found = true;
2086 after = stmt;
2087 break;
2088 }
2089 }
2090 }
2091
2092 /* Search backward to insert OS after AFTER_SEC output
2093 statement. */
2094 if (!found)
2095 for (stmt = after; stmt != NULL; stmt = stmt->prev)
2096 {
2097 if (insert_after)
2098 {
2099 if (stmt->bfd_section == after_sec)
2100 {
2101 place_after = true;
2102 after = stmt;
2103 break;
2104 }
2105 }
2106 else
2107 {
2108 /* If INSERT_AFTER is FALSE, place OS before
2109 AFTER_SEC output statement. */
2110 if (stmt->next->bfd_section == after_sec)
2111 {
2112 place_after = true;
2113 after = stmt;
2114 break;
2115 }
2116 }
2117 }
2118 }
2119
2120 if (after_sec == NULL
2121 || (insert_after && after_sec->next != snew)
2122 || (!insert_after && after_sec->prev != snew))
2123 {
2124 /* Unlink the section. */
2125 bfd_section_list_remove (link_info.output_bfd, snew);
2126
2127 /* Place SNEW after AFTER_SEC. If AFTER_SEC is NULL,
2128 prepend SNEW. */
2129 if (after_sec)
2130 {
2131 if (insert_after)
2132 bfd_section_list_insert_after (link_info.output_bfd,
2133 after_sec, snew);
2134 else
2135 bfd_section_list_insert_before (link_info.output_bfd,
2136 after_sec, snew);
2137 }
2138 else
2139 bfd_section_list_prepend (link_info.output_bfd, snew);
2140 }
2141 }
2142 else if (as != snew && as->prev != snew)
2143 {
2144 /* Unlink the section. */
2145 bfd_section_list_remove (link_info.output_bfd, snew);
2146
2147 /* Now tack it back on in the right place. */
2148 bfd_section_list_insert_before (link_info.output_bfd,
2149 as, snew);
2150 }
2151 }
2152 else if (as != snew && as->prev != snew)
2153 {
2154 /* Unlink the section. */
2155 bfd_section_list_remove (link_info.output_bfd, snew);
2156
2157 /* Now tack it back on in the right place. */
2158 bfd_section_list_insert_before (link_info.output_bfd, as, snew);
2159 }
2160
2161 /* Save the end of this list. Further ophans of this type will
2162 follow the one we've just added. */
2163 place->section = &snew->next;
2164
2165 /* The following is non-cosmetic. We try to put the output
2166 statements in some sort of reasonable order here, because they
2167 determine the final load addresses of the orphan sections.
2168 In addition, placing output statements in the wrong order may
2169 require extra segments. For instance, given a typical
2170 situation of all read-only sections placed in one segment and
2171 following that a segment containing all the read-write
2172 sections, we wouldn't want to place an orphan read/write
2173 section before or amongst the read-only ones. */
2174 if (add.head != NULL)
2175 {
2176 lang_output_section_statement_type *newly_added_os;
2177
2178 /* Place OS after AFTER if AFTER_NOTE is TRUE. */
2179 if (place_after)
2180 {
2181 lang_statement_union_type **where;
2182
2183 where = insert_os_after ((lang_statement_union_type *) after);
2184 *add.tail = *where;
2185 *where = add.head;
2186
2187 place->os_tail = &after->next;
2188 }
2189 else
2190 {
2191 /* Put it after the last orphan statement we added. */
2192 *add.tail = *place->stmt;
2193 *place->stmt = add.head;
2194 }
2195
2196 /* Fix the global list pointer if we happened to tack our
2197 new list at the tail. */
2198 if (*stat_ptr->tail == add.head)
2199 stat_ptr->tail = add.tail;
2200
2201 /* Save the end of this list. */
2202 place->stmt = add.tail;
2203
2204 /* Do the same for the list of output section statements. */
2205 newly_added_os = *os_tail;
2206 *os_tail = NULL;
2207 newly_added_os->prev = (lang_output_section_statement_type *)
2208 ((char *) place->os_tail
2209 - offsetof (lang_output_section_statement_type, next));
2210 newly_added_os->next = *place->os_tail;
2211 if (newly_added_os->next != NULL)
2212 newly_added_os->next->prev = newly_added_os;
2213 *place->os_tail = newly_added_os;
2214 place->os_tail = &newly_added_os->next;
2215
2216 /* Fixing the global list pointer here is a little different.
2217 We added to the list in lang_enter_output_section_statement,
2218 trimmed off the new output_section_statment above when
2219 assigning *os_tail = NULL, but possibly added it back in
2220 the same place when assigning *place->os_tail. */
2221 if (*os_tail == NULL)
2222 lang_os_list.tail = (lang_statement_union_type **) os_tail;
2223 }
2224 }
2225 return os;
2226 }
2227
2228 static void
2229 lang_print_asneeded (void)
2230 {
2231 struct asneeded_minfo *m;
2232
2233 if (asneeded_list_head == NULL)
2234 return;
2235
2236 minfo (_("\nAs-needed library included to satisfy reference by file (symbol)\n\n"));
2237
2238 for (m = asneeded_list_head; m != NULL; m = m->next)
2239 {
2240 int len;
2241
2242 minfo ("%s", m->soname);
2243 len = strlen (m->soname);
2244
2245 if (len >= 29)
2246 {
2247 print_nl ();
2248 len = 0;
2249 }
2250 print_spaces (30 - len);
2251
2252 if (m->ref != NULL)
2253 minfo ("%pB ", m->ref);
2254 minfo ("(%pT)\n", m->name);
2255 }
2256 }
2257
2258 static void
2259 lang_map_flags (flagword flag)
2260 {
2261 if (flag & SEC_ALLOC)
2262 minfo ("a");
2263
2264 if (flag & SEC_CODE)
2265 minfo ("x");
2266
2267 if (flag & SEC_READONLY)
2268 minfo ("r");
2269
2270 if (flag & SEC_DATA)
2271 minfo ("w");
2272
2273 if (flag & SEC_LOAD)
2274 minfo ("l");
2275 }
2276
2277 void
2278 lang_map (void)
2279 {
2280 lang_memory_region_type *m;
2281 bool dis_header_printed = false;
2282
2283 LANG_FOR_EACH_INPUT_STATEMENT (file)
2284 {
2285 asection *s;
2286
2287 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
2288 || file->flags.just_syms)
2289 continue;
2290
2291 if (config.print_map_discarded)
2292 for (s = file->the_bfd->sections; s != NULL; s = s->next)
2293 if ((s->output_section == NULL
2294 || s->output_section->owner != link_info.output_bfd)
2295 && (s->flags & (SEC_LINKER_CREATED | SEC_KEEP)) == 0)
2296 {
2297 if (! dis_header_printed)
2298 {
2299 fprintf (config.map_file, _("\nDiscarded input sections\n\n"));
2300 dis_header_printed = true;
2301 }
2302
2303 print_input_section (s, true);
2304 }
2305 }
2306
2307 minfo (_("\nMemory Configuration\n\n"));
2308 fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
2309 _("Name"), _("Origin"), _("Length"), _("Attributes"));
2310
2311 for (m = lang_memory_region_list; m != NULL; m = m->next)
2312 {
2313 fprintf (config.map_file, "%-16s", m->name_list.name);
2314
2315 char buf[32];
2316 bfd_sprintf_vma (link_info.output_bfd, buf, m->origin);
2317 fprintf (config.map_file, " 0x%-16s", buf);
2318 bfd_sprintf_vma (link_info.output_bfd, buf, m->length);
2319 fprintf (config.map_file,
2320 " 0x%*s", m->flags || m->not_flags ? -17 : 0, buf);
2321 if (m->flags)
2322 lang_map_flags (m->flags);
2323
2324 if (m->not_flags)
2325 {
2326 minfo ("!");
2327 lang_map_flags (m->not_flags);
2328 }
2329
2330 print_nl ();
2331 }
2332
2333 fprintf (config.map_file, _("\nLinker script and memory map\n\n"));
2334
2335 if (!link_info.reduce_memory_overheads)
2336 {
2337 obstack_begin (&map_obstack, 1000);
2338 bfd_link_hash_traverse (link_info.hash, sort_def_symbol, 0);
2339 }
2340 expld.phase = lang_fixed_phase_enum;
2341 lang_statement_iteration++;
2342 print_statements ();
2343
2344 ldemul_extra_map_file_text (link_info.output_bfd, &link_info,
2345 config.map_file);
2346 }
2347
2348 static bool
2349 sort_def_symbol (struct bfd_link_hash_entry *hash_entry,
2350 void *info ATTRIBUTE_UNUSED)
2351 {
2352 if ((hash_entry->type == bfd_link_hash_defined
2353 || hash_entry->type == bfd_link_hash_defweak)
2354 && hash_entry->u.def.section->owner != link_info.output_bfd
2355 && hash_entry->u.def.section->owner != NULL)
2356 {
2357 input_section_userdata_type *ud;
2358 struct map_symbol_def *def;
2359
2360 ud = bfd_section_userdata (hash_entry->u.def.section);
2361 if (!ud)
2362 {
2363 ud = stat_alloc (sizeof (*ud));
2364 bfd_set_section_userdata (hash_entry->u.def.section, ud);
2365 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2366 ud->map_symbol_def_count = 0;
2367 }
2368 else if (!ud->map_symbol_def_tail)
2369 ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2370
2371 def = (struct map_symbol_def *) obstack_alloc (&map_obstack, sizeof *def);
2372 def->entry = hash_entry;
2373 *(ud->map_symbol_def_tail) = def;
2374 ud->map_symbol_def_tail = &def->next;
2375 ud->map_symbol_def_count++;
2376 }
2377 return true;
2378 }
2379
2380 /* Initialize an output section. */
2381
2382 static void
2383 init_os (lang_output_section_statement_type *s, flagword flags)
2384 {
2385 if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
2386 einfo (_("%F%P: illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
2387
2388 if (!s->dup_output)
2389 s->bfd_section = bfd_get_section_by_name (link_info.output_bfd, s->name);
2390 if (s->bfd_section == NULL)
2391 s->bfd_section = bfd_make_section_anyway_with_flags (link_info.output_bfd,
2392 s->name, flags);
2393 if (s->bfd_section == NULL)
2394 {
2395 einfo (_("%F%P: output format %s cannot represent section"
2396 " called %s: %E\n"),
2397 link_info.output_bfd->xvec->name, s->name);
2398 }
2399 s->bfd_section->output_section = s->bfd_section;
2400 s->bfd_section->output_offset = 0;
2401
2402 /* Set the userdata of the output section to the output section
2403 statement to avoid lookup. */
2404 bfd_set_section_userdata (s->bfd_section, s);
2405
2406 /* If there is a base address, make sure that any sections it might
2407 mention are initialized. */
2408 if (s->addr_tree != NULL)
2409 exp_init_os (s->addr_tree);
2410
2411 if (s->load_base != NULL)
2412 exp_init_os (s->load_base);
2413
2414 /* If supplied an alignment, set it. */
2415 if (s->section_alignment != NULL)
2416 s->bfd_section->alignment_power = exp_get_power (s->section_alignment,
2417 "section alignment");
2418 }
2419
2420 /* Make sure that all output sections mentioned in an expression are
2421 initialized. */
2422
2423 static void
2424 exp_init_os (etree_type *exp)
2425 {
2426 switch (exp->type.node_class)
2427 {
2428 case etree_assign:
2429 case etree_provide:
2430 case etree_provided:
2431 exp_init_os (exp->assign.src);
2432 break;
2433
2434 case etree_binary:
2435 exp_init_os (exp->binary.lhs);
2436 exp_init_os (exp->binary.rhs);
2437 break;
2438
2439 case etree_trinary:
2440 exp_init_os (exp->trinary.cond);
2441 exp_init_os (exp->trinary.lhs);
2442 exp_init_os (exp->trinary.rhs);
2443 break;
2444
2445 case etree_assert:
2446 exp_init_os (exp->assert_s.child);
2447 break;
2448
2449 case etree_unary:
2450 exp_init_os (exp->unary.child);
2451 break;
2452
2453 case etree_name:
2454 switch (exp->type.node_code)
2455 {
2456 case ADDR:
2457 case LOADADDR:
2458 {
2459 lang_output_section_statement_type *os;
2460
2461 os = lang_output_section_find (exp->name.name);
2462 if (os != NULL && os->bfd_section == NULL)
2463 init_os (os, 0);
2464 }
2465 }
2466 break;
2467
2468 default:
2469 break;
2470 }
2471 }
2472 \f
2473 static void
2474 section_already_linked (bfd *abfd, asection *sec, void *data)
2475 {
2476 lang_input_statement_type *entry = (lang_input_statement_type *) data;
2477
2478 /* If we are only reading symbols from this object, then we want to
2479 discard all sections. */
2480 if (entry->flags.just_syms)
2481 {
2482 bfd_link_just_syms (abfd, sec, &link_info);
2483 return;
2484 }
2485
2486 /* Deal with SHF_EXCLUDE ELF sections. */
2487 if (!bfd_link_relocatable (&link_info)
2488 && (abfd->flags & BFD_PLUGIN) == 0
2489 && (sec->flags & (SEC_GROUP | SEC_KEEP | SEC_EXCLUDE)) == SEC_EXCLUDE)
2490 sec->output_section = bfd_abs_section_ptr;
2491
2492 if (!(abfd->flags & DYNAMIC))
2493 bfd_section_already_linked (abfd, sec, &link_info);
2494 }
2495 \f
2496
2497 /* Returns true if SECTION is one we know will be discarded based on its
2498 section flags, otherwise returns false. */
2499
2500 static bool
2501 lang_discard_section_p (asection *section)
2502 {
2503 bool discard;
2504 flagword flags = section->flags;
2505
2506 /* Discard sections marked with SEC_EXCLUDE. */
2507 discard = (flags & SEC_EXCLUDE) != 0;
2508
2509 /* Discard the group descriptor sections when we're finally placing the
2510 sections from within the group. */
2511 if ((flags & SEC_GROUP) != 0
2512 && link_info.resolve_section_groups)
2513 discard = true;
2514
2515 /* Discard debugging sections if we are stripping debugging
2516 information. */
2517 if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
2518 && (flags & SEC_DEBUGGING) != 0)
2519 discard = true;
2520
2521 return discard;
2522 }
2523
2524 /* Return TRUE if SECTION is never going to be added to output statement
2525 OUTPUT. lang_add_section() definitely won't do anything with SECTION
2526 if this returns TRUE. It may do something (or not) if this returns FALSE.
2527
2528 Can be used as early-out to filter matches. This may set
2529 output_section of SECTION, if it was unset, to the abs section in case
2530 we discover SECTION to be always discarded. This may also give
2531 warning messages. */
2532
2533 static bool
2534 wont_add_section_p (asection *section,
2535 lang_output_section_statement_type *output)
2536 {
2537 bool discard;
2538
2539 /* Is this section one we know should be discarded? */
2540 discard = lang_discard_section_p (section);
2541
2542 /* Discard input sections which are assigned to a section named
2543 DISCARD_SECTION_NAME. */
2544 if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
2545 discard = true;
2546
2547 if (discard)
2548 {
2549 if (section->output_section == NULL)
2550 {
2551 /* This prevents future calls from assigning this section or
2552 warning about it again. */
2553 section->output_section = bfd_abs_section_ptr;
2554 }
2555 else if (bfd_is_abs_section (section->output_section))
2556 ;
2557 else if (link_info.non_contiguous_regions_warnings)
2558 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions makes "
2559 "section `%pA' from `%pB' match /DISCARD/ clause.\n"),
2560 NULL, section, section->owner);
2561
2562 return true;
2563 }
2564
2565 if (section->output_section != NULL)
2566 {
2567 if (!link_info.non_contiguous_regions)
2568 return true;
2569
2570 /* SECTION has already been handled in a special way
2571 (eg. LINK_ONCE): skip it. */
2572 if (bfd_is_abs_section (section->output_section))
2573 return true;
2574
2575 /* Already assigned to the same output section, do not process
2576 it again, to avoid creating loops between duplicate sections
2577 later. */
2578 if (section->output_section == output->bfd_section)
2579 return true;
2580
2581 if (link_info.non_contiguous_regions_warnings && output->bfd_section)
2582 einfo (_("%P:%pS: warning: --enable-non-contiguous-regions may "
2583 "change behaviour for section `%pA' from `%pB' (assigned to "
2584 "%pA, but additional match: %pA)\n"),
2585 NULL, section, section->owner, section->output_section,
2586 output->bfd_section);
2587
2588 /* SECTION has already been assigned to an output section, but
2589 the user allows it to be mapped to another one in case it
2590 overflows. We'll later update the actual output section in
2591 size_input_section as appropriate. */
2592 }
2593
2594 return false;
2595 }
2596
2597 /* The wild routines.
2598
2599 These expand statements like *(.text) and foo.o to a list of
2600 explicit actions, like foo.o(.text), bar.o(.text) and
2601 foo.o(.text, .data). */
2602
2603 /* Add SECTION to the output section OUTPUT. Do this by creating a
2604 lang_input_section statement which is placed at PTR. */
2605
2606 void
2607 lang_add_section (lang_statement_list_type *ptr,
2608 asection *section,
2609 struct wildcard_list *pattern,
2610 struct flag_info *sflag_info,
2611 lang_output_section_statement_type *output)
2612 {
2613 flagword flags = section->flags;
2614
2615 lang_input_section_type *new_section;
2616 bfd *abfd = link_info.output_bfd;
2617
2618 if (wont_add_section_p (section, output))
2619 return;
2620
2621 if (sflag_info)
2622 {
2623 bool keep;
2624
2625 keep = bfd_lookup_section_flags (&link_info, sflag_info, section);
2626 if (!keep)
2627 return;
2628 }
2629
2630 /* We don't copy the SEC_NEVER_LOAD flag from an input section
2631 to an output section, because we want to be able to include a
2632 SEC_NEVER_LOAD section in the middle of an otherwise loaded
2633 section (I don't know why we want to do this, but we do).
2634 build_link_order in ldwrite.c handles this case by turning
2635 the embedded SEC_NEVER_LOAD section into a fill. */
2636 flags &= ~ SEC_NEVER_LOAD;
2637
2638 /* If final link, don't copy the SEC_LINK_ONCE flags, they've
2639 already been processed. One reason to do this is that on pe
2640 format targets, .text$foo sections go into .text and it's odd
2641 to see .text with SEC_LINK_ONCE set. */
2642 if ((flags & (SEC_LINK_ONCE | SEC_GROUP)) == (SEC_LINK_ONCE | SEC_GROUP))
2643 {
2644 if (link_info.resolve_section_groups)
2645 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2646 else
2647 flags &= ~(SEC_LINK_DUPLICATES | SEC_RELOC);
2648 }
2649 else if (!bfd_link_relocatable (&link_info))
2650 flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2651
2652 switch (output->sectype)
2653 {
2654 case normal_section:
2655 case overlay_section:
2656 case first_overlay_section:
2657 case type_section:
2658 break;
2659 case noalloc_section:
2660 flags &= ~SEC_ALLOC;
2661 break;
2662 case typed_readonly_section:
2663 case readonly_section:
2664 flags |= SEC_READONLY;
2665 break;
2666 case noload_section:
2667 flags &= ~SEC_LOAD;
2668 flags |= SEC_NEVER_LOAD;
2669 /* Unfortunately GNU ld has managed to evolve two different
2670 meanings to NOLOAD in scripts. ELF gets a .bss style noload,
2671 alloc, no contents section. All others get a noload, noalloc
2672 section. */
2673 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
2674 flags &= ~SEC_HAS_CONTENTS;
2675 else
2676 flags &= ~SEC_ALLOC;
2677 break;
2678 }
2679
2680 if (output->bfd_section == NULL)
2681 init_os (output, flags);
2682
2683 /* If SEC_READONLY is not set in the input section, then clear
2684 it from the output section. */
2685 output->bfd_section->flags &= flags | ~SEC_READONLY;
2686
2687 if (output->bfd_section->linker_has_input)
2688 {
2689 /* Only set SEC_READONLY flag on the first input section. */
2690 flags &= ~ SEC_READONLY;
2691
2692 /* Keep SEC_MERGE and SEC_STRINGS only if they are the same. */
2693 if ((output->bfd_section->flags & (SEC_MERGE | SEC_STRINGS))
2694 != (flags & (SEC_MERGE | SEC_STRINGS))
2695 || ((flags & SEC_MERGE) != 0
2696 && output->bfd_section->entsize != section->entsize))
2697 {
2698 output->bfd_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
2699 flags &= ~ (SEC_MERGE | SEC_STRINGS);
2700 }
2701 }
2702 output->bfd_section->flags |= flags;
2703
2704 if (!output->bfd_section->linker_has_input)
2705 {
2706 output->bfd_section->linker_has_input = 1;
2707 /* This must happen after flags have been updated. The output
2708 section may have been created before we saw its first input
2709 section, eg. for a data statement. */
2710 bfd_init_private_section_data (section->owner, section,
2711 link_info.output_bfd,
2712 output->bfd_section,
2713 &link_info);
2714 if ((flags & SEC_MERGE) != 0)
2715 output->bfd_section->entsize = section->entsize;
2716 }
2717
2718 if ((flags & SEC_TIC54X_BLOCK) != 0
2719 && bfd_get_arch (section->owner) == bfd_arch_tic54x)
2720 {
2721 /* FIXME: This value should really be obtained from the bfd... */
2722 output->block_value = 128;
2723 }
2724
2725 /* When a .ctors section is placed in .init_array it must be copied
2726 in reverse order. Similarly for .dtors. Set that up. */
2727 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
2728 && ((startswith (section->name, ".ctors")
2729 && strcmp (output->bfd_section->name, ".init_array") == 0)
2730 || (startswith (section->name, ".dtors")
2731 && strcmp (output->bfd_section->name, ".fini_array") == 0))
2732 && (section->name[6] == 0 || section->name[6] == '.'))
2733 section->flags |= SEC_ELF_REVERSE_COPY;
2734
2735 if (section->alignment_power > output->bfd_section->alignment_power)
2736 output->bfd_section->alignment_power = section->alignment_power;
2737
2738 section->output_section = output->bfd_section;
2739
2740 if (!map_head_is_link_order)
2741 {
2742 asection *s = output->bfd_section->map_tail.s;
2743 output->bfd_section->map_tail.s = section;
2744 section->map_head.s = NULL;
2745 section->map_tail.s = s;
2746 if (s != NULL)
2747 s->map_head.s = section;
2748 else
2749 output->bfd_section->map_head.s = section;
2750 }
2751
2752 /* Add a section reference to the list. */
2753 new_section = new_stat (lang_input_section, ptr);
2754 new_section->section = section;
2755 new_section->pattern = pattern;
2756 }
2757
2758 /* Expand a wild statement for a particular FILE. SECTION may be
2759 NULL, in which case it is a wild card. This assumes that the
2760 wild statement doesn't need any sorting (of filenames or sections). */
2761
2762 static void
2763 output_section_callback_nosort (lang_wild_statement_type *ptr,
2764 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2765 asection *section,
2766 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2767 void *output)
2768 {
2769 lang_output_section_statement_type *os;
2770
2771 os = (lang_output_section_statement_type *) output;
2772
2773 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2774 if (unique_section_p (section, os))
2775 return;
2776
2777 lang_add_section (&ptr->children, section, ptr->section_list,
2778 ptr->section_flag_list, os);
2779 }
2780
2781 /* Check if all sections in a wild statement for a particular FILE
2782 are readonly. */
2783
2784 static void
2785 check_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
2786 struct wildcard_list *sec ATTRIBUTE_UNUSED,
2787 asection *section,
2788 lang_input_statement_type *file ATTRIBUTE_UNUSED,
2789 void *output)
2790 {
2791 lang_output_section_statement_type *os;
2792
2793 os = (lang_output_section_statement_type *) output;
2794
2795 /* Exclude sections that match UNIQUE_SECTION_LIST. */
2796 if (unique_section_p (section, os))
2797 return;
2798
2799 if (section->output_section == NULL && (section->flags & SEC_READONLY) == 0)
2800 os->all_input_readonly = false;
2801 }
2802
2803 /* This is passed a file name which must have been seen already and
2804 added to the statement tree. We will see if it has been opened
2805 already and had its symbols read. If not then we'll read it. */
2806
2807 static lang_input_statement_type *
2808 lookup_name (const char *name)
2809 {
2810 lang_input_statement_type *search;
2811
2812 for (search = (void *) input_file_chain.head;
2813 search != NULL;
2814 search = search->next_real_file)
2815 {
2816 /* Use the local_sym_name as the name of the file that has
2817 already been loaded as filename might have been transformed
2818 via the search directory lookup mechanism. */
2819 const char *filename = search->local_sym_name;
2820
2821 if (filename != NULL
2822 && filename_cmp (filename, name) == 0)
2823 break;
2824 }
2825
2826 if (search == NULL)
2827 {
2828 /* Arrange to splice the input statement added by new_afile into
2829 statement_list after the current input_file_chain tail.
2830 We know input_file_chain is not an empty list, and that
2831 lookup_name was called via open_input_bfds. Later calls to
2832 lookup_name should always match an existing input_statement. */
2833 lang_statement_union_type **tail = stat_ptr->tail;
2834 lang_statement_union_type **after
2835 = (void *) ((char *) input_file_chain.tail
2836 - offsetof (lang_input_statement_type, next_real_file)
2837 + offsetof (lang_input_statement_type, header.next));
2838 lang_statement_union_type *rest = *after;
2839 stat_ptr->tail = after;
2840 search = new_afile (name, lang_input_file_is_search_file_enum,
2841 default_target, NULL);
2842 *stat_ptr->tail = rest;
2843 if (*tail == NULL)
2844 stat_ptr->tail = tail;
2845 }
2846
2847 /* If we have already added this file, or this file is not real
2848 don't add this file. */
2849 if (search->flags.loaded || !search->flags.real)
2850 return search;
2851
2852 if (!load_symbols (search, NULL))
2853 return NULL;
2854
2855 return search;
2856 }
2857
2858 /* Save LIST as a list of libraries whose symbols should not be exported. */
2859
2860 struct excluded_lib
2861 {
2862 char *name;
2863 struct excluded_lib *next;
2864 };
2865 static struct excluded_lib *excluded_libs;
2866
2867 void
2868 add_excluded_libs (const char *list)
2869 {
2870 const char *p = list, *end;
2871
2872 while (*p != '\0')
2873 {
2874 struct excluded_lib *entry;
2875 end = strpbrk (p, ",:");
2876 if (end == NULL)
2877 end = p + strlen (p);
2878 entry = (struct excluded_lib *) xmalloc (sizeof (*entry));
2879 entry->next = excluded_libs;
2880 entry->name = (char *) xmalloc (end - p + 1);
2881 memcpy (entry->name, p, end - p);
2882 entry->name[end - p] = '\0';
2883 excluded_libs = entry;
2884 if (*end == '\0')
2885 break;
2886 p = end + 1;
2887 }
2888 }
2889
2890 static void
2891 check_excluded_libs (bfd *abfd)
2892 {
2893 struct excluded_lib *lib = excluded_libs;
2894
2895 while (lib)
2896 {
2897 int len = strlen (lib->name);
2898 const char *filename = lbasename (bfd_get_filename (abfd));
2899
2900 if (strcmp (lib->name, "ALL") == 0)
2901 {
2902 abfd->no_export = true;
2903 return;
2904 }
2905
2906 if (filename_ncmp (lib->name, filename, len) == 0
2907 && (filename[len] == '\0'
2908 || (filename[len] == '.' && filename[len + 1] == 'a'
2909 && filename[len + 2] == '\0')))
2910 {
2911 abfd->no_export = true;
2912 return;
2913 }
2914
2915 lib = lib->next;
2916 }
2917 }
2918
2919 /* Get the symbols for an input file. */
2920
2921 bool
2922 load_symbols (lang_input_statement_type *entry,
2923 lang_statement_list_type *place)
2924 {
2925 char **matching;
2926
2927 if (entry->flags.loaded)
2928 return true;
2929
2930 ldfile_open_file (entry);
2931
2932 /* Do not process further if the file was missing. */
2933 if (entry->flags.missing_file)
2934 return true;
2935
2936 if (trace_files || verbose)
2937 info_msg ("%pI\n", entry);
2938
2939 if (!bfd_check_format (entry->the_bfd, bfd_archive)
2940 && !bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
2941 {
2942 bfd_error_type err;
2943 struct lang_input_statement_flags save_flags;
2944 extern FILE *yyin;
2945
2946 err = bfd_get_error ();
2947
2948 /* See if the emulation has some special knowledge. */
2949 if (ldemul_unrecognized_file (entry))
2950 {
2951 if (err == bfd_error_file_ambiguously_recognized)
2952 free (matching);
2953 return true;
2954 }
2955
2956 if (err == bfd_error_file_ambiguously_recognized)
2957 {
2958 char **p;
2959
2960 einfo (_("%P: %pB: file not recognized: %E;"
2961 " matching formats:"), entry->the_bfd);
2962 for (p = matching; *p != NULL; p++)
2963 einfo (" %s", *p);
2964 free (matching);
2965 einfo ("%F\n");
2966 }
2967 else if (err != bfd_error_file_not_recognized
2968 || place == NULL)
2969 einfo (_("%F%P: %pB: file not recognized: %E\n"), entry->the_bfd);
2970
2971 bfd_close (entry->the_bfd);
2972 entry->the_bfd = NULL;
2973
2974 /* Try to interpret the file as a linker script. */
2975 save_flags = input_flags;
2976 ldfile_open_command_file (entry->filename);
2977
2978 push_stat_ptr (place);
2979 input_flags.add_DT_NEEDED_for_regular
2980 = entry->flags.add_DT_NEEDED_for_regular;
2981 input_flags.add_DT_NEEDED_for_dynamic
2982 = entry->flags.add_DT_NEEDED_for_dynamic;
2983 input_flags.whole_archive = entry->flags.whole_archive;
2984 input_flags.dynamic = entry->flags.dynamic;
2985
2986 ldfile_assumed_script = true;
2987 parser_input = input_script;
2988 current_input_file = entry->filename;
2989 yyparse ();
2990 current_input_file = NULL;
2991 ldfile_assumed_script = false;
2992
2993 /* missing_file is sticky. sysrooted will already have been
2994 restored when seeing EOF in yyparse, but no harm to restore
2995 again. */
2996 save_flags.missing_file |= input_flags.missing_file;
2997 input_flags = save_flags;
2998 pop_stat_ptr ();
2999 fclose (yyin);
3000 yyin = NULL;
3001 entry->flags.loaded = true;
3002
3003 return true;
3004 }
3005
3006 if (ldemul_recognized_file (entry))
3007 return true;
3008
3009 /* We don't call ldlang_add_file for an archive. Instead, the
3010 add_symbols entry point will call ldlang_add_file, via the
3011 add_archive_element callback, for each element of the archive
3012 which is used. */
3013 switch (bfd_get_format (entry->the_bfd))
3014 {
3015 default:
3016 break;
3017
3018 case bfd_object:
3019 if (!entry->flags.reload)
3020 ldlang_add_file (entry);
3021 break;
3022
3023 case bfd_archive:
3024 check_excluded_libs (entry->the_bfd);
3025
3026 bfd_set_usrdata (entry->the_bfd, entry);
3027 if (entry->flags.whole_archive)
3028 {
3029 bfd *member = NULL;
3030 bool loaded = true;
3031
3032 for (;;)
3033 {
3034 bfd *subsbfd;
3035 member = bfd_openr_next_archived_file (entry->the_bfd, member);
3036
3037 if (member == NULL)
3038 break;
3039
3040 if (!bfd_check_format (member, bfd_object))
3041 {
3042 einfo (_("%F%P: %pB: member %pB in archive is not an object\n"),
3043 entry->the_bfd, member);
3044 loaded = false;
3045 }
3046
3047 subsbfd = member;
3048 if (!(*link_info.callbacks
3049 ->add_archive_element) (&link_info, member,
3050 "--whole-archive", &subsbfd))
3051 abort ();
3052
3053 /* Potentially, the add_archive_element hook may have set a
3054 substitute BFD for us. */
3055 if (!bfd_link_add_symbols (subsbfd, &link_info))
3056 {
3057 einfo (_("%F%P: %pB: error adding symbols: %E\n"), member);
3058 loaded = false;
3059 }
3060 }
3061
3062 entry->flags.loaded = loaded;
3063 return loaded;
3064 }
3065 break;
3066 }
3067
3068 if (bfd_link_add_symbols (entry->the_bfd, &link_info))
3069 entry->flags.loaded = true;
3070 else
3071 einfo (_("%F%P: %pB: error adding symbols: %E\n"), entry->the_bfd);
3072
3073 return entry->flags.loaded;
3074 }
3075
3076 /* Handle a wild statement. S->FILENAME or S->SECTION_LIST or both
3077 may be NULL, indicating that it is a wildcard. Separate
3078 lang_input_section statements are created for each part of the
3079 expansion; they are added after the wild statement S. OUTPUT is
3080 the output section. */
3081
3082 static void
3083 wild (lang_wild_statement_type *s,
3084 const char *target ATTRIBUTE_UNUSED,
3085 lang_output_section_statement_type *output)
3086 {
3087 struct wildcard_list *sec;
3088
3089 if (s->filenames_sorted || s->any_specs_sorted)
3090 {
3091 lang_section_bst_type *tree;
3092
3093 walk_wild (s, output_section_callback_sort, output);
3094
3095 tree = s->tree;
3096 if (tree)
3097 {
3098 output_section_callback_tree_to_list (s, tree, output);
3099 s->tree = NULL;
3100 s->rightmost = &s->tree;
3101 }
3102 }
3103 else
3104 walk_wild (s, output_section_callback_nosort, output);
3105
3106 if (default_common_section == NULL)
3107 for (sec = s->section_list; sec != NULL; sec = sec->next)
3108 if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
3109 {
3110 /* Remember the section that common is going to in case we
3111 later get something which doesn't know where to put it. */
3112 default_common_section = output;
3113 break;
3114 }
3115 }
3116
3117 /* Return TRUE iff target is the sought target. */
3118
3119 static int
3120 get_target (const bfd_target *target, void *data)
3121 {
3122 const char *sought = (const char *) data;
3123
3124 return strcmp (target->name, sought) == 0;
3125 }
3126
3127 /* Like strcpy() but convert to lower case as well. */
3128
3129 static void
3130 stricpy (char *dest, const char *src)
3131 {
3132 char c;
3133
3134 while ((c = *src++) != 0)
3135 *dest++ = TOLOWER (c);
3136
3137 *dest = 0;
3138 }
3139
3140 /* Remove the first occurrence of needle (if any) in haystack
3141 from haystack. */
3142
3143 static void
3144 strcut (char *haystack, const char *needle)
3145 {
3146 haystack = strstr (haystack, needle);
3147
3148 if (haystack)
3149 {
3150 char *src;
3151
3152 for (src = haystack + strlen (needle); *src;)
3153 *haystack++ = *src++;
3154
3155 *haystack = 0;
3156 }
3157 }
3158
3159 /* Compare two target format name strings.
3160 Return a value indicating how "similar" they are. */
3161
3162 static int
3163 name_compare (const char *first, const char *second)
3164 {
3165 char *copy1;
3166 char *copy2;
3167 int result;
3168
3169 copy1 = (char *) xmalloc (strlen (first) + 1);
3170 copy2 = (char *) xmalloc (strlen (second) + 1);
3171
3172 /* Convert the names to lower case. */
3173 stricpy (copy1, first);
3174 stricpy (copy2, second);
3175
3176 /* Remove size and endian strings from the name. */
3177 strcut (copy1, "big");
3178 strcut (copy1, "little");
3179 strcut (copy2, "big");
3180 strcut (copy2, "little");
3181
3182 /* Return a value based on how many characters match,
3183 starting from the beginning. If both strings are
3184 the same then return 10 * their length. */
3185 for (result = 0; copy1[result] == copy2[result]; result++)
3186 if (copy1[result] == 0)
3187 {
3188 result *= 10;
3189 break;
3190 }
3191
3192 free (copy1);
3193 free (copy2);
3194
3195 return result;
3196 }
3197
3198 /* Set by closest_target_match() below. */
3199 static const bfd_target *winner;
3200
3201 /* Scan all the valid bfd targets looking for one that has the endianness
3202 requirement that was specified on the command line, and is the nearest
3203 match to the original output target. */
3204
3205 static int
3206 closest_target_match (const bfd_target *target, void *data)
3207 {
3208 const bfd_target *original = (const bfd_target *) data;
3209
3210 if (command_line.endian == ENDIAN_BIG
3211 && target->byteorder != BFD_ENDIAN_BIG)
3212 return 0;
3213
3214 if (command_line.endian == ENDIAN_LITTLE
3215 && target->byteorder != BFD_ENDIAN_LITTLE)
3216 return 0;
3217
3218 /* Must be the same flavour. */
3219 if (target->flavour != original->flavour)
3220 return 0;
3221
3222 /* Ignore generic big and little endian elf vectors. */
3223 if (strcmp (target->name, "elf32-big") == 0
3224 || strcmp (target->name, "elf64-big") == 0
3225 || strcmp (target->name, "elf32-little") == 0
3226 || strcmp (target->name, "elf64-little") == 0)
3227 return 0;
3228
3229 /* If we have not found a potential winner yet, then record this one. */
3230 if (winner == NULL)
3231 {
3232 winner = target;
3233 return 0;
3234 }
3235
3236 /* Oh dear, we now have two potential candidates for a successful match.
3237 Compare their names and choose the better one. */
3238 if (name_compare (target->name, original->name)
3239 > name_compare (winner->name, original->name))
3240 winner = target;
3241
3242 /* Keep on searching until wqe have checked them all. */
3243 return 0;
3244 }
3245
3246 /* Return the BFD target format of the first input file. */
3247
3248 static const char *
3249 get_first_input_target (void)
3250 {
3251 const char *target = NULL;
3252
3253 LANG_FOR_EACH_INPUT_STATEMENT (s)
3254 {
3255 if (s->header.type == lang_input_statement_enum
3256 && s->flags.real)
3257 {
3258 ldfile_open_file (s);
3259
3260 if (s->the_bfd != NULL
3261 && bfd_check_format (s->the_bfd, bfd_object))
3262 {
3263 target = bfd_get_target (s->the_bfd);
3264
3265 if (target != NULL)
3266 break;
3267 }
3268 }
3269 }
3270
3271 return target;
3272 }
3273
3274 const char *
3275 lang_get_output_target (void)
3276 {
3277 const char *target;
3278
3279 /* Has the user told us which output format to use? */
3280 if (output_target != NULL)
3281 return output_target;
3282
3283 /* No - has the current target been set to something other than
3284 the default? */
3285 if (current_target != default_target && current_target != NULL)
3286 return current_target;
3287
3288 /* No - can we determine the format of the first input file? */
3289 target = get_first_input_target ();
3290 if (target != NULL)
3291 return target;
3292
3293 /* Failed - use the default output target. */
3294 return default_target;
3295 }
3296
3297 /* Open the output file. */
3298
3299 static void
3300 open_output (const char *name)
3301 {
3302 lang_input_statement_type *f;
3303 char *out = lrealpath (name);
3304
3305 for (f = (void *) input_file_chain.head;
3306 f != NULL;
3307 f = f->next_real_file)
3308 if (f->flags.real)
3309 {
3310 char *in = lrealpath (f->local_sym_name);
3311 if (filename_cmp (in, out) == 0)
3312 einfo (_("%F%P: input file '%s' is the same as output file\n"),
3313 f->filename);
3314 free (in);
3315 }
3316 free (out);
3317
3318 output_target = lang_get_output_target ();
3319
3320 /* Has the user requested a particular endianness on the command
3321 line? */
3322 if (command_line.endian != ENDIAN_UNSET)
3323 {
3324 /* Get the chosen target. */
3325 const bfd_target *target
3326 = bfd_iterate_over_targets (get_target, (void *) output_target);
3327
3328 /* If the target is not supported, we cannot do anything. */
3329 if (target != NULL)
3330 {
3331 enum bfd_endian desired_endian;
3332
3333 if (command_line.endian == ENDIAN_BIG)
3334 desired_endian = BFD_ENDIAN_BIG;
3335 else
3336 desired_endian = BFD_ENDIAN_LITTLE;
3337
3338 /* See if the target has the wrong endianness. This should
3339 not happen if the linker script has provided big and
3340 little endian alternatives, but some scrips don't do
3341 this. */
3342 if (target->byteorder != desired_endian)
3343 {
3344 /* If it does, then see if the target provides
3345 an alternative with the correct endianness. */
3346 if (target->alternative_target != NULL
3347 && (target->alternative_target->byteorder == desired_endian))
3348 output_target = target->alternative_target->name;
3349 else
3350 {
3351 /* Try to find a target as similar as possible to
3352 the default target, but which has the desired
3353 endian characteristic. */
3354 bfd_iterate_over_targets (closest_target_match,
3355 (void *) target);
3356
3357 /* Oh dear - we could not find any targets that
3358 satisfy our requirements. */
3359 if (winner == NULL)
3360 einfo (_("%P: warning: could not find any targets"
3361 " that match endianness requirement\n"));
3362 else
3363 output_target = winner->name;
3364 }
3365 }
3366 }
3367 }
3368
3369 link_info.output_bfd = bfd_openw (name, output_target);
3370
3371 if (link_info.output_bfd == NULL)
3372 {
3373 if (bfd_get_error () == bfd_error_invalid_target)
3374 einfo (_("%F%P: target %s not found\n"), output_target);
3375
3376 einfo (_("%F%P: cannot open output file %s: %E\n"), name);
3377 }
3378
3379 delete_output_file_on_failure = true;
3380
3381 if (!bfd_set_format (link_info.output_bfd, bfd_object))
3382 einfo (_("%F%P: %s: can not make object file: %E\n"), name);
3383 if (!bfd_set_arch_mach (link_info.output_bfd,
3384 ldfile_output_architecture,
3385 ldfile_output_machine))
3386 einfo (_("%F%P: %s: can not set architecture: %E\n"), name);
3387
3388 link_info.hash = bfd_link_hash_table_create (link_info.output_bfd);
3389 if (link_info.hash == NULL)
3390 einfo (_("%F%P: can not create hash table: %E\n"));
3391
3392 bfd_set_gp_size (link_info.output_bfd, g_switch_value);
3393 }
3394
3395 static void
3396 ldlang_open_output (lang_statement_union_type *statement)
3397 {
3398 switch (statement->header.type)
3399 {
3400 case lang_output_statement_enum:
3401 ASSERT (link_info.output_bfd == NULL);
3402 open_output (statement->output_statement.name);
3403 ldemul_set_output_arch ();
3404 if (config.magic_demand_paged
3405 && !bfd_link_relocatable (&link_info))
3406 link_info.output_bfd->flags |= D_PAGED;
3407 else
3408 link_info.output_bfd->flags &= ~D_PAGED;
3409 if (config.text_read_only)
3410 link_info.output_bfd->flags |= WP_TEXT;
3411 else
3412 link_info.output_bfd->flags &= ~WP_TEXT;
3413 if (link_info.traditional_format)
3414 link_info.output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
3415 else
3416 link_info.output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
3417 break;
3418
3419 case lang_target_statement_enum:
3420 current_target = statement->target_statement.target;
3421 break;
3422 default:
3423 break;
3424 }
3425 }
3426
3427 static void
3428 init_opb (asection *s)
3429 {
3430 unsigned int x;
3431
3432 opb_shift = 0;
3433 if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
3434 && s != NULL
3435 && (s->flags & SEC_ELF_OCTETS) != 0)
3436 return;
3437
3438 x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3439 ldfile_output_machine);
3440 if (x > 1)
3441 while ((x & 1) == 0)
3442 {
3443 x >>= 1;
3444 ++opb_shift;
3445 }
3446 ASSERT (x == 1);
3447 }
3448
3449 /* Open all the input files. */
3450
3451 enum open_bfd_mode
3452 {
3453 OPEN_BFD_NORMAL = 0,
3454 OPEN_BFD_FORCE = 1,
3455 OPEN_BFD_RESCAN = 2
3456 };
3457 #if BFD_SUPPORTS_PLUGINS
3458 static lang_input_statement_type *plugin_insert = NULL;
3459 static struct bfd_link_hash_entry *plugin_undefs = NULL;
3460 #endif
3461
3462 static void
3463 open_input_bfds (lang_statement_union_type *s, enum open_bfd_mode mode)
3464 {
3465 for (; s != NULL; s = s->header.next)
3466 {
3467 switch (s->header.type)
3468 {
3469 case lang_constructors_statement_enum:
3470 open_input_bfds (constructor_list.head, mode);
3471 break;
3472 case lang_output_section_statement_enum:
3473 open_input_bfds (s->output_section_statement.children.head, mode);
3474 break;
3475 case lang_wild_statement_enum:
3476 /* Maybe we should load the file's symbols. */
3477 if ((mode & OPEN_BFD_RESCAN) == 0
3478 && s->wild_statement.filename
3479 && !wildcardp (s->wild_statement.filename)
3480 && !archive_path (s->wild_statement.filename))
3481 lookup_name (s->wild_statement.filename);
3482 open_input_bfds (s->wild_statement.children.head, mode);
3483 break;
3484 case lang_group_statement_enum:
3485 {
3486 struct bfd_link_hash_entry *undefs;
3487 #if BFD_SUPPORTS_PLUGINS
3488 lang_input_statement_type *plugin_insert_save;
3489 #endif
3490
3491 /* We must continually search the entries in the group
3492 until no new symbols are added to the list of undefined
3493 symbols. */
3494
3495 do
3496 {
3497 #if BFD_SUPPORTS_PLUGINS
3498 plugin_insert_save = plugin_insert;
3499 #endif
3500 undefs = link_info.hash->undefs_tail;
3501 open_input_bfds (s->group_statement.children.head,
3502 mode | OPEN_BFD_FORCE);
3503 }
3504 while (undefs != link_info.hash->undefs_tail
3505 #if BFD_SUPPORTS_PLUGINS
3506 /* Objects inserted by a plugin, which are loaded
3507 before we hit this loop, may have added new
3508 undefs. */
3509 || (plugin_insert != plugin_insert_save && plugin_undefs)
3510 #endif
3511 );
3512 }
3513 break;
3514 case lang_target_statement_enum:
3515 current_target = s->target_statement.target;
3516 break;
3517 case lang_input_statement_enum:
3518 if (s->input_statement.flags.real)
3519 {
3520 lang_statement_union_type **os_tail;
3521 lang_statement_list_type add;
3522 bfd *abfd;
3523
3524 s->input_statement.target = current_target;
3525
3526 /* If we are being called from within a group, and this
3527 is an archive which has already been searched, then
3528 force it to be researched unless the whole archive
3529 has been loaded already. Do the same for a rescan.
3530 Likewise reload --as-needed shared libs. */
3531 if (mode != OPEN_BFD_NORMAL
3532 #if BFD_SUPPORTS_PLUGINS
3533 && ((mode & OPEN_BFD_RESCAN) == 0
3534 || plugin_insert == NULL)
3535 #endif
3536 && s->input_statement.flags.loaded
3537 && (abfd = s->input_statement.the_bfd) != NULL
3538 && ((bfd_get_format (abfd) == bfd_archive
3539 && !s->input_statement.flags.whole_archive)
3540 || (bfd_get_format (abfd) == bfd_object
3541 && ((abfd->flags) & DYNAMIC) != 0
3542 && s->input_statement.flags.add_DT_NEEDED_for_regular
3543 && bfd_get_flavour (abfd) == bfd_target_elf_flavour
3544 && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)))
3545 {
3546 s->input_statement.flags.loaded = false;
3547 s->input_statement.flags.reload = true;
3548 }
3549
3550 os_tail = lang_os_list.tail;
3551 lang_list_init (&add);
3552
3553 if (!load_symbols (&s->input_statement, &add))
3554 config.make_executable = false;
3555
3556 if (add.head != NULL)
3557 {
3558 /* If this was a script with output sections then
3559 tack any added statements on to the end of the
3560 list. This avoids having to reorder the output
3561 section statement list. Very likely the user
3562 forgot -T, and whatever we do here will not meet
3563 naive user expectations. */
3564 if (os_tail != lang_os_list.tail)
3565 {
3566 einfo (_("%P: warning: %s contains output sections;"
3567 " did you forget -T?\n"),
3568 s->input_statement.filename);
3569 *stat_ptr->tail = add.head;
3570 stat_ptr->tail = add.tail;
3571 }
3572 else
3573 {
3574 *add.tail = s->header.next;
3575 s->header.next = add.head;
3576 }
3577 }
3578 }
3579 #if BFD_SUPPORTS_PLUGINS
3580 /* If we have found the point at which a plugin added new
3581 files, clear plugin_insert to enable archive rescan. */
3582 if (&s->input_statement == plugin_insert)
3583 plugin_insert = NULL;
3584 #endif
3585 break;
3586 case lang_assignment_statement_enum:
3587 if (s->assignment_statement.exp->type.node_class != etree_assert)
3588 exp_fold_tree_no_dot (s->assignment_statement.exp);
3589 break;
3590 default:
3591 break;
3592 }
3593 }
3594
3595 /* Exit if any of the files were missing. */
3596 if (input_flags.missing_file)
3597 einfo ("%F");
3598 }
3599
3600 #ifdef ENABLE_LIBCTF
3601 /* Emit CTF errors and warnings. fp can be NULL to report errors/warnings
3602 that happened specifically at CTF open time. */
3603 static void
3604 lang_ctf_errs_warnings (ctf_dict_t *fp)
3605 {
3606 ctf_next_t *i = NULL;
3607 char *text;
3608 int is_warning;
3609 int err;
3610
3611 while ((text = ctf_errwarning_next (fp, &i, &is_warning, &err)) != NULL)
3612 {
3613 einfo (_("%s: %s\n"), is_warning ? _("CTF warning"): _("CTF error"),
3614 text);
3615 free (text);
3616 }
3617 if (err != ECTF_NEXT_END)
3618 {
3619 einfo (_("CTF error: cannot get CTF errors: `%s'\n"),
3620 ctf_errmsg (err));
3621 }
3622
3623 /* `err' returns errors from the error/warning iterator in particular.
3624 These never assert. But if we have an fp, that could have recorded
3625 an assertion failure: assert if it has done so. */
3626 ASSERT (!fp || ctf_errno (fp) != ECTF_INTERNAL);
3627 }
3628
3629 /* Open the CTF sections in the input files with libctf: if any were opened,
3630 create a fake input file that we'll write the merged CTF data to later
3631 on. */
3632
3633 static void
3634 ldlang_open_ctf (void)
3635 {
3636 int any_ctf = 0;
3637 int err;
3638
3639 LANG_FOR_EACH_INPUT_STATEMENT (file)
3640 {
3641 asection *sect;
3642
3643 /* Incoming files from the compiler have a single ctf_dict_t in them
3644 (which is presented to us by the libctf API in a ctf_archive_t
3645 wrapper): files derived from a previous relocatable link have a CTF
3646 archive containing possibly many CTF files. */
3647
3648 if ((file->the_ctf = ctf_bfdopen (file->the_bfd, &err)) == NULL)
3649 {
3650 if (err != ECTF_NOCTFDATA)
3651 {
3652 lang_ctf_errs_warnings (NULL);
3653 einfo (_("%P: warning: CTF section in %pB not loaded; "
3654 "its types will be discarded: %s\n"), file->the_bfd,
3655 ctf_errmsg (err));
3656 }
3657 continue;
3658 }
3659
3660 /* Prevent the contents of this section from being written, while
3661 requiring the section itself to be duplicated in the output, but only
3662 once. */
3663 /* This section must exist if ctf_bfdopen() succeeded. */
3664 sect = bfd_get_section_by_name (file->the_bfd, ".ctf");
3665 sect->size = 0;
3666 sect->flags |= SEC_NEVER_LOAD | SEC_HAS_CONTENTS | SEC_LINKER_CREATED;
3667
3668 if (any_ctf)
3669 sect->flags |= SEC_EXCLUDE;
3670 any_ctf = 1;
3671 }
3672
3673 if (!any_ctf)
3674 {
3675 ctf_output = NULL;
3676 return;
3677 }
3678
3679 if ((ctf_output = ctf_create (&err)) != NULL)
3680 return;
3681
3682 einfo (_("%P: warning: CTF output not created: `%s'\n"),
3683 ctf_errmsg (err));
3684
3685 LANG_FOR_EACH_INPUT_STATEMENT (errfile)
3686 ctf_close (errfile->the_ctf);
3687 }
3688
3689 /* Merge together CTF sections. After this, only the symtab-dependent
3690 function and data object sections need adjustment. */
3691
3692 static void
3693 lang_merge_ctf (void)
3694 {
3695 asection *output_sect;
3696 int flags = 0;
3697
3698 if (!ctf_output)
3699 return;
3700
3701 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3702
3703 /* If the section was discarded, don't waste time merging. */
3704 if (output_sect == NULL)
3705 {
3706 ctf_dict_close (ctf_output);
3707 ctf_output = NULL;
3708
3709 LANG_FOR_EACH_INPUT_STATEMENT (file)
3710 {
3711 ctf_close (file->the_ctf);
3712 file->the_ctf = NULL;
3713 }
3714 return;
3715 }
3716
3717 LANG_FOR_EACH_INPUT_STATEMENT (file)
3718 {
3719 if (!file->the_ctf)
3720 continue;
3721
3722 /* Takes ownership of file->the_ctf. */
3723 if (ctf_link_add_ctf (ctf_output, file->the_ctf, file->filename) < 0)
3724 {
3725 einfo (_("%P: warning: CTF section in %pB cannot be linked: `%s'\n"),
3726 file->the_bfd, ctf_errmsg (ctf_errno (ctf_output)));
3727 ctf_close (file->the_ctf);
3728 file->the_ctf = NULL;
3729 continue;
3730 }
3731 }
3732
3733 if (!config.ctf_share_duplicated)
3734 flags = CTF_LINK_SHARE_UNCONFLICTED;
3735 else
3736 flags = CTF_LINK_SHARE_DUPLICATED;
3737 if (!config.ctf_variables)
3738 flags |= CTF_LINK_OMIT_VARIABLES_SECTION;
3739 if (bfd_link_relocatable (&link_info))
3740 flags |= CTF_LINK_NO_FILTER_REPORTED_SYMS;
3741
3742 if (ctf_link (ctf_output, flags) < 0)
3743 {
3744 lang_ctf_errs_warnings (ctf_output);
3745 einfo (_("%P: warning: CTF linking failed; "
3746 "output will have no CTF section: %s\n"),
3747 ctf_errmsg (ctf_errno (ctf_output)));
3748 if (output_sect)
3749 {
3750 output_sect->size = 0;
3751 output_sect->flags |= SEC_EXCLUDE;
3752 }
3753 }
3754 /* Output any lingering errors that didn't come from ctf_link. */
3755 lang_ctf_errs_warnings (ctf_output);
3756 }
3757
3758 /* Let the emulation acquire strings from the dynamic strtab to help it optimize
3759 the CTF, if supported. */
3760
3761 void
3762 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab)
3763 {
3764 ldemul_acquire_strings_for_ctf (ctf_output, dynstrtab);
3765 }
3766
3767 /* Inform the emulation about the addition of a new dynamic symbol, in BFD
3768 internal format. */
3769 void ldlang_ctf_new_dynsym (int symidx, struct elf_internal_sym *sym)
3770 {
3771 ldemul_new_dynsym_for_ctf (ctf_output, symidx, sym);
3772 }
3773
3774 /* Write out the CTF section. Called early, if the emulation isn't going to
3775 need to dedup against the strtab and symtab, then possibly called from the
3776 target linker code if the dedup has happened. */
3777 static void
3778 lang_write_ctf (int late)
3779 {
3780 size_t output_size;
3781 asection *output_sect;
3782
3783 if (!ctf_output)
3784 return;
3785
3786 if (late)
3787 {
3788 /* Emit CTF late if this emulation says it can do so. */
3789 if (ldemul_emit_ctf_early ())
3790 return;
3791 }
3792 else
3793 {
3794 if (!ldemul_emit_ctf_early ())
3795 return;
3796 }
3797
3798 /* Inform the emulation that all the symbols that will be received have
3799 been. */
3800
3801 ldemul_new_dynsym_for_ctf (ctf_output, 0, NULL);
3802
3803 /* Emit CTF. */
3804
3805 output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3806 if (output_sect)
3807 {
3808 output_sect->contents = ctf_link_write (ctf_output, &output_size,
3809 CTF_COMPRESSION_THRESHOLD);
3810 output_sect->size = output_size;
3811 output_sect->flags |= SEC_IN_MEMORY | SEC_KEEP;
3812
3813 lang_ctf_errs_warnings (ctf_output);
3814 if (!output_sect->contents)
3815 {
3816 einfo (_("%P: warning: CTF section emission failed; "
3817 "output will have no CTF section: %s\n"),
3818 ctf_errmsg (ctf_errno (ctf_output)));
3819 output_sect->size = 0;
3820 output_sect->flags |= SEC_EXCLUDE;
3821 }
3822 }
3823
3824 /* This also closes every CTF input file used in the link. */
3825 ctf_dict_close (ctf_output);
3826 ctf_output = NULL;
3827
3828 LANG_FOR_EACH_INPUT_STATEMENT (file)
3829 file->the_ctf = NULL;
3830 }
3831
3832 /* Write out the CTF section late, if the emulation needs that. */
3833
3834 void
3835 ldlang_write_ctf_late (void)
3836 {
3837 /* Trigger a "late call", if the emulation needs one. */
3838
3839 lang_write_ctf (1);
3840 }
3841 #else
3842 static void
3843 ldlang_open_ctf (void)
3844 {
3845 LANG_FOR_EACH_INPUT_STATEMENT (file)
3846 {
3847 asection *sect;
3848
3849 /* If built without CTF, warn and delete all CTF sections from the output.
3850 (The alternative would be to simply concatenate them, which does not
3851 yield a valid CTF section.) */
3852
3853 if ((sect = bfd_get_section_by_name (file->the_bfd, ".ctf")) != NULL)
3854 {
3855 einfo (_("%P: warning: CTF section in %pB not linkable: "
3856 "%P was built without support for CTF\n"), file->the_bfd);
3857 sect->size = 0;
3858 sect->flags |= SEC_EXCLUDE;
3859 }
3860 }
3861 }
3862
3863 static void lang_merge_ctf (void) {}
3864 void
3865 ldlang_ctf_acquire_strings (struct elf_strtab_hash *dynstrtab
3866 ATTRIBUTE_UNUSED) {}
3867 void
3868 ldlang_ctf_new_dynsym (int symidx ATTRIBUTE_UNUSED,
3869 struct elf_internal_sym *sym ATTRIBUTE_UNUSED) {}
3870 static void lang_write_ctf (int late ATTRIBUTE_UNUSED) {}
3871 void ldlang_write_ctf_late (void) {}
3872 #endif
3873
3874 /* Add the supplied name to the symbol table as an undefined reference.
3875 This is a two step process as the symbol table doesn't even exist at
3876 the time the ld command line is processed. First we put the name
3877 on a list, then, once the output file has been opened, transfer the
3878 name to the symbol table. */
3879
3880 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
3881
3882 #define ldlang_undef_chain_list_head entry_symbol.next
3883
3884 void
3885 ldlang_add_undef (const char *const name, bool cmdline ATTRIBUTE_UNUSED)
3886 {
3887 ldlang_undef_chain_list_type *new_undef;
3888
3889 new_undef = stat_alloc (sizeof (*new_undef));
3890 new_undef->next = ldlang_undef_chain_list_head;
3891 ldlang_undef_chain_list_head = new_undef;
3892
3893 new_undef->name = xstrdup (name);
3894
3895 if (link_info.output_bfd != NULL)
3896 insert_undefined (new_undef->name);
3897 }
3898
3899 /* Insert NAME as undefined in the symbol table. */
3900
3901 static void
3902 insert_undefined (const char *name)
3903 {
3904 struct bfd_link_hash_entry *h;
3905
3906 h = bfd_link_hash_lookup (link_info.hash, name, true, false, true);
3907 if (h == NULL)
3908 einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
3909 if (h->type == bfd_link_hash_new)
3910 {
3911 h->type = bfd_link_hash_undefined;
3912 h->u.undef.abfd = NULL;
3913 h->non_ir_ref_regular = true;
3914 bfd_link_add_undef (link_info.hash, h);
3915 }
3916 }
3917
3918 /* Run through the list of undefineds created above and place them
3919 into the linker hash table as undefined symbols belonging to the
3920 script file. */
3921
3922 static void
3923 lang_place_undefineds (void)
3924 {
3925 ldlang_undef_chain_list_type *ptr;
3926
3927 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
3928 insert_undefined (ptr->name);
3929 }
3930
3931 /* Mark -u symbols against garbage collection. */
3932
3933 static void
3934 lang_mark_undefineds (void)
3935 {
3936 ldlang_undef_chain_list_type *ptr;
3937
3938 if (is_elf_hash_table (link_info.hash))
3939 for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
3940 {
3941 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
3942 bfd_link_hash_lookup (link_info.hash, ptr->name, false, false, true);
3943 if (h != NULL)
3944 h->mark = 1;
3945 }
3946 }
3947
3948 /* Structure used to build the list of symbols that the user has required
3949 be defined. */
3950
3951 struct require_defined_symbol
3952 {
3953 const char *name;
3954 struct require_defined_symbol *next;
3955 };
3956
3957 /* The list of symbols that the user has required be defined. */
3958
3959 static struct require_defined_symbol *require_defined_symbol_list;
3960
3961 /* Add a new symbol NAME to the list of symbols that are required to be
3962 defined. */
3963
3964 void
3965 ldlang_add_require_defined (const char *const name)
3966 {
3967 struct require_defined_symbol *ptr;
3968
3969 ldlang_add_undef (name, true);
3970 ptr = stat_alloc (sizeof (*ptr));
3971 ptr->next = require_defined_symbol_list;
3972 ptr->name = strdup (name);
3973 require_defined_symbol_list = ptr;
3974 }
3975
3976 /* Check that all symbols the user required to be defined, are defined,
3977 raise an error if we find a symbol that is not defined. */
3978
3979 static void
3980 ldlang_check_require_defined_symbols (void)
3981 {
3982 struct require_defined_symbol *ptr;
3983
3984 for (ptr = require_defined_symbol_list; ptr != NULL; ptr = ptr->next)
3985 {
3986 struct bfd_link_hash_entry *h;
3987
3988 h = bfd_link_hash_lookup (link_info.hash, ptr->name,
3989 false, false, true);
3990 if (h == NULL
3991 || (h->type != bfd_link_hash_defined
3992 && h->type != bfd_link_hash_defweak))
3993 einfo(_("%X%P: required symbol `%s' not defined\n"), ptr->name);
3994 }
3995 }
3996
3997 /* Check for all readonly or some readwrite sections. */
3998
3999 static void
4000 check_input_sections
4001 (lang_statement_union_type *s,
4002 lang_output_section_statement_type *output_section_statement)
4003 {
4004 for (; s != NULL; s = s->header.next)
4005 {
4006 switch (s->header.type)
4007 {
4008 case lang_wild_statement_enum:
4009 walk_wild (&s->wild_statement, check_section_callback,
4010 output_section_statement);
4011 if (!output_section_statement->all_input_readonly)
4012 return;
4013 break;
4014 case lang_constructors_statement_enum:
4015 check_input_sections (constructor_list.head,
4016 output_section_statement);
4017 if (!output_section_statement->all_input_readonly)
4018 return;
4019 break;
4020 case lang_group_statement_enum:
4021 check_input_sections (s->group_statement.children.head,
4022 output_section_statement);
4023 if (!output_section_statement->all_input_readonly)
4024 return;
4025 break;
4026 default:
4027 break;
4028 }
4029 }
4030 }
4031
4032 /* Update wildcard statements if needed. */
4033
4034 static void
4035 update_wild_statements (lang_statement_union_type *s)
4036 {
4037 struct wildcard_list *sec;
4038
4039 switch (sort_section)
4040 {
4041 default:
4042 FAIL ();
4043
4044 case none:
4045 break;
4046
4047 case by_name:
4048 case by_alignment:
4049 for (; s != NULL; s = s->header.next)
4050 {
4051 switch (s->header.type)
4052 {
4053 default:
4054 break;
4055
4056 case lang_wild_statement_enum:
4057 for (sec = s->wild_statement.section_list; sec != NULL;
4058 sec = sec->next)
4059 /* Don't sort .init/.fini sections. */
4060 if (strcmp (sec->spec.name, ".init") != 0
4061 && strcmp (sec->spec.name, ".fini") != 0)
4062 {
4063 switch (sec->spec.sorted)
4064 {
4065 case none:
4066 sec->spec.sorted = sort_section;
4067 break;
4068 case by_name:
4069 if (sort_section == by_alignment)
4070 sec->spec.sorted = by_name_alignment;
4071 break;
4072 case by_alignment:
4073 if (sort_section == by_name)
4074 sec->spec.sorted = by_alignment_name;
4075 break;
4076 default:
4077 break;
4078 }
4079 s->wild_statement.any_specs_sorted = true;
4080 }
4081 break;
4082
4083 case lang_constructors_statement_enum:
4084 update_wild_statements (constructor_list.head);
4085 break;
4086
4087 case lang_output_section_statement_enum:
4088 update_wild_statements
4089 (s->output_section_statement.children.head);
4090 break;
4091
4092 case lang_group_statement_enum:
4093 update_wild_statements (s->group_statement.children.head);
4094 break;
4095 }
4096 }
4097 break;
4098 }
4099 }
4100
4101 /* Open input files and attach to output sections. */
4102
4103 static void
4104 map_input_to_output_sections
4105 (lang_statement_union_type *s, const char *target,
4106 lang_output_section_statement_type *os)
4107 {
4108 for (; s != NULL; s = s->header.next)
4109 {
4110 lang_output_section_statement_type *tos;
4111 flagword flags;
4112 unsigned int type = 0;
4113
4114 switch (s->header.type)
4115 {
4116 case lang_wild_statement_enum:
4117 wild (&s->wild_statement, target, os);
4118 break;
4119 case lang_constructors_statement_enum:
4120 map_input_to_output_sections (constructor_list.head,
4121 target,
4122 os);
4123 break;
4124 case lang_output_section_statement_enum:
4125 tos = &s->output_section_statement;
4126 if (tos->constraint == ONLY_IF_RW
4127 || tos->constraint == ONLY_IF_RO)
4128 {
4129 tos->all_input_readonly = true;
4130 check_input_sections (tos->children.head, tos);
4131 if (tos->all_input_readonly != (tos->constraint == ONLY_IF_RO))
4132 tos->constraint = -1;
4133 }
4134 if (tos->constraint >= 0)
4135 map_input_to_output_sections (tos->children.head,
4136 target,
4137 tos);
4138 break;
4139 case lang_output_statement_enum:
4140 break;
4141 case lang_target_statement_enum:
4142 target = s->target_statement.target;
4143 break;
4144 case lang_group_statement_enum:
4145 map_input_to_output_sections (s->group_statement.children.head,
4146 target,
4147 os);
4148 break;
4149 case lang_data_statement_enum:
4150 /* Make sure that any sections mentioned in the expression
4151 are initialized. */
4152 exp_init_os (s->data_statement.exp);
4153 /* The output section gets CONTENTS, ALLOC and LOAD, but
4154 these may be overridden by the script. */
4155 flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD;
4156 switch (os->sectype)
4157 {
4158 case normal_section:
4159 case overlay_section:
4160 case first_overlay_section:
4161 break;
4162 case noalloc_section:
4163 flags = SEC_HAS_CONTENTS;
4164 break;
4165 case readonly_section:
4166 flags |= SEC_READONLY;
4167 break;
4168 case typed_readonly_section:
4169 flags |= SEC_READONLY;
4170 /* Fall through. */
4171 case type_section:
4172 if (os->sectype_value->type.node_class == etree_name
4173 && os->sectype_value->type.node_code == NAME)
4174 {
4175 const char *name = os->sectype_value->name.name;
4176 if (strcmp (name, "SHT_PROGBITS") == 0)
4177 type = SHT_PROGBITS;
4178 else if (strcmp (name, "SHT_STRTAB") == 0)
4179 type = SHT_STRTAB;
4180 else if (strcmp (name, "SHT_NOTE") == 0)
4181 type = SHT_NOTE;
4182 else if (strcmp (name, "SHT_NOBITS") == 0)
4183 type = SHT_NOBITS;
4184 else if (strcmp (name, "SHT_INIT_ARRAY") == 0)
4185 type = SHT_INIT_ARRAY;
4186 else if (strcmp (name, "SHT_FINI_ARRAY") == 0)
4187 type = SHT_FINI_ARRAY;
4188 else if (strcmp (name, "SHT_PREINIT_ARRAY") == 0)
4189 type = SHT_PREINIT_ARRAY;
4190 else
4191 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4192 os->name);
4193 }
4194 else
4195 {
4196 exp_fold_tree_no_dot (os->sectype_value);
4197 if (expld.result.valid_p)
4198 type = expld.result.value;
4199 else
4200 einfo (_ ("%F%P: invalid type for output section `%s'\n"),
4201 os->name);
4202 }
4203 break;
4204 case noload_section:
4205 if (bfd_get_flavour (link_info.output_bfd)
4206 == bfd_target_elf_flavour)
4207 flags = SEC_NEVER_LOAD | SEC_ALLOC;
4208 else
4209 flags = SEC_NEVER_LOAD | SEC_HAS_CONTENTS;
4210 break;
4211 }
4212 if (os->bfd_section == NULL)
4213 init_os (os, flags | SEC_READONLY);
4214 else
4215 os->bfd_section->flags |= flags;
4216 os->bfd_section->type = type;
4217 break;
4218 case lang_input_section_enum:
4219 break;
4220 case lang_fill_statement_enum:
4221 case lang_object_symbols_statement_enum:
4222 case lang_reloc_statement_enum:
4223 case lang_padding_statement_enum:
4224 case lang_input_statement_enum:
4225 if (os != NULL && os->bfd_section == NULL)
4226 init_os (os, 0);
4227 break;
4228 case lang_assignment_statement_enum:
4229 if (os != NULL && os->bfd_section == NULL)
4230 init_os (os, 0);
4231
4232 /* Make sure that any sections mentioned in the assignment
4233 are initialized. */
4234 exp_init_os (s->assignment_statement.exp);
4235 break;
4236 case lang_address_statement_enum:
4237 /* Mark the specified section with the supplied address.
4238 If this section was actually a segment marker, then the
4239 directive is ignored if the linker script explicitly
4240 processed the segment marker. Originally, the linker
4241 treated segment directives (like -Ttext on the
4242 command-line) as section directives. We honor the
4243 section directive semantics for backwards compatibility;
4244 linker scripts that do not specifically check for
4245 SEGMENT_START automatically get the old semantics. */
4246 if (!s->address_statement.segment
4247 || !s->address_statement.segment->used)
4248 {
4249 const char *name = s->address_statement.section_name;
4250
4251 /* Create the output section statement here so that
4252 orphans with a set address will be placed after other
4253 script sections. If we let the orphan placement code
4254 place them in amongst other sections then the address
4255 will affect following script sections, which is
4256 likely to surprise naive users. */
4257 tos = lang_output_section_statement_lookup (name, 0, 1);
4258 tos->addr_tree = s->address_statement.address;
4259 if (tos->bfd_section == NULL)
4260 init_os (tos, 0);
4261 }
4262 break;
4263 case lang_insert_statement_enum:
4264 break;
4265 case lang_input_matcher_enum:
4266 FAIL ();
4267 }
4268 }
4269 }
4270
4271 /* An insert statement snips out all the linker statements from the
4272 start of the list and places them after the output section
4273 statement specified by the insert. This operation is complicated
4274 by the fact that we keep a doubly linked list of output section
4275 statements as well as the singly linked list of all statements.
4276 FIXME someday: Twiddling with the list not only moves statements
4277 from the user's script but also input and group statements that are
4278 built from command line object files and --start-group. We only
4279 get away with this because the list pointers used by file_chain
4280 and input_file_chain are not reordered, and processing via
4281 statement_list after this point mostly ignores input statements.
4282 One exception is the map file, where LOAD and START GROUP/END GROUP
4283 can end up looking odd. */
4284
4285 static void
4286 process_insert_statements (lang_statement_union_type **start)
4287 {
4288 lang_statement_union_type **s;
4289 lang_output_section_statement_type *first_os = NULL;
4290 lang_output_section_statement_type *last_os = NULL;
4291 lang_output_section_statement_type *os;
4292
4293 s = start;
4294 while (*s != NULL)
4295 {
4296 if ((*s)->header.type == lang_output_section_statement_enum)
4297 {
4298 /* Keep pointers to the first and last output section
4299 statement in the sequence we may be about to move. */
4300 os = &(*s)->output_section_statement;
4301
4302 ASSERT (last_os == NULL || last_os->next == os);
4303 last_os = os;
4304
4305 /* Set constraint negative so that lang_output_section_find
4306 won't match this output section statement. At this
4307 stage in linking constraint has values in the range
4308 [-1, ONLY_IN_RW]. */
4309 last_os->constraint = -2 - last_os->constraint;
4310 if (first_os == NULL)
4311 first_os = last_os;
4312 }
4313 else if ((*s)->header.type == lang_group_statement_enum)
4314 {
4315 /* A user might put -T between --start-group and
4316 --end-group. One way this odd construct might arise is
4317 from a wrapper around ld to change library search
4318 behaviour. For example:
4319 #! /bin/sh
4320 exec real_ld --start-group "$@" --end-group
4321 This isn't completely unreasonable so go looking inside a
4322 group statement for insert statements. */
4323 process_insert_statements (&(*s)->group_statement.children.head);
4324 }
4325 else if ((*s)->header.type == lang_insert_statement_enum)
4326 {
4327 lang_insert_statement_type *i = &(*s)->insert_statement;
4328 lang_output_section_statement_type *where;
4329 lang_statement_union_type **ptr;
4330 lang_statement_union_type *first;
4331
4332 if (link_info.non_contiguous_regions)
4333 {
4334 einfo (_("warning: INSERT statement in linker script is "
4335 "incompatible with --enable-non-contiguous-regions.\n"));
4336 }
4337
4338 where = lang_output_section_find (i->where);
4339 if (where != NULL && i->is_before)
4340 {
4341 do
4342 where = where->prev;
4343 while (where != NULL && where->constraint < 0);
4344 }
4345 if (where == NULL)
4346 {
4347 einfo (_("%F%P: %s not found for insert\n"), i->where);
4348 return;
4349 }
4350
4351 /* Deal with reordering the output section statement list. */
4352 if (last_os != NULL)
4353 {
4354 asection *first_sec, *last_sec;
4355 struct lang_output_section_statement_struct **next;
4356
4357 /* Snip out the output sections we are moving. */
4358 first_os->prev->next = last_os->next;
4359 if (last_os->next == NULL)
4360 {
4361 next = &first_os->prev->next;
4362 lang_os_list.tail = (lang_statement_union_type **) next;
4363 }
4364 else
4365 last_os->next->prev = first_os->prev;
4366 /* Add them in at the new position. */
4367 last_os->next = where->next;
4368 if (where->next == NULL)
4369 {
4370 next = &last_os->next;
4371 lang_os_list.tail = (lang_statement_union_type **) next;
4372 }
4373 else
4374 where->next->prev = last_os;
4375 first_os->prev = where;
4376 where->next = first_os;
4377
4378 /* Move the bfd sections in the same way. */
4379 first_sec = NULL;
4380 last_sec = NULL;
4381 for (os = first_os; os != NULL; os = os->next)
4382 {
4383 os->constraint = -2 - os->constraint;
4384 if (os->bfd_section != NULL
4385 && os->bfd_section->owner != NULL)
4386 {
4387 last_sec = os->bfd_section;
4388 if (first_sec == NULL)
4389 first_sec = last_sec;
4390 }
4391 if (os == last_os)
4392 break;
4393 }
4394 if (last_sec != NULL)
4395 {
4396 asection *sec = where->bfd_section;
4397 if (sec == NULL)
4398 sec = output_prev_sec_find (where);
4399
4400 /* The place we want to insert must come after the
4401 sections we are moving. So if we find no
4402 section or if the section is the same as our
4403 last section, then no move is needed. */
4404 if (sec != NULL && sec != last_sec)
4405 {
4406 /* Trim them off. */
4407 if (first_sec->prev != NULL)
4408 first_sec->prev->next = last_sec->next;
4409 else
4410 link_info.output_bfd->sections = last_sec->next;
4411 if (last_sec->next != NULL)
4412 last_sec->next->prev = first_sec->prev;
4413 else
4414 link_info.output_bfd->section_last = first_sec->prev;
4415 /* Add back. */
4416 if (sec->owner == NULL)
4417 /* SEC is the absolute section, from the
4418 first dummy output section statement. Add
4419 back the sections we trimmed off to the
4420 start of the bfd sections. */
4421 sec = NULL;
4422 if (sec != NULL)
4423 last_sec->next = sec->next;
4424 else
4425 last_sec->next = link_info.output_bfd->sections;
4426 if (last_sec->next != NULL)
4427 last_sec->next->prev = last_sec;
4428 else
4429 link_info.output_bfd->section_last = last_sec;
4430 first_sec->prev = sec;
4431 if (first_sec->prev != NULL)
4432 first_sec->prev->next = first_sec;
4433 else
4434 link_info.output_bfd->sections = first_sec;
4435 }
4436 }
4437 }
4438
4439 lang_statement_union_type *after = (void *) where;
4440 if (where == &lang_os_list.head->output_section_statement
4441 && where->next == first_os)
4442 {
4443 /* PR30155. Handle a corner case where the statement
4444 list is something like the following:
4445 . LOAD t.o
4446 . .data 0x0000000000000000 0x0
4447 . [0x0000000000000000] b = .
4448 . *(.data)
4449 . .data 0x0000000000000000 0x0 t.o
4450 . 0x0000000000000000 0x4 LONG 0x0
4451 . INSERT BEFORE .text.start
4452 . [0x0000000000000004] a = .
4453 . .text.start 0x0000000000000000 0x0
4454 . [0x0000000000000000] c = .
4455 . OUTPUT(a.out elf64-x86-64)
4456 Here we do not want to allow insert_os_after to
4457 choose a point inside the list we are moving.
4458 That would lose the list. Instead, let
4459 insert_os_after work from the INSERT, which in this
4460 particular example will result in inserting after
4461 the assignment "a = .". */
4462 after = *s;
4463 }
4464 ptr = insert_os_after (after);
4465 /* Snip everything from the start of the list, up to and
4466 including the insert statement we are currently processing. */
4467 first = *start;
4468 *start = (*s)->header.next;
4469 /* Add them back where they belong, minus the insert. */
4470 *s = *ptr;
4471 if (*s == NULL)
4472 statement_list.tail = s;
4473 *ptr = first;
4474 s = start;
4475 first_os = NULL;
4476 last_os = NULL;
4477 continue;
4478 }
4479 s = &(*s)->header.next;
4480 }
4481
4482 /* Undo constraint twiddling. */
4483 for (os = first_os; os != NULL; os = os->next)
4484 {
4485 os->constraint = -2 - os->constraint;
4486 if (os == last_os)
4487 break;
4488 }
4489 }
4490
4491 /* An output section might have been removed after its statement was
4492 added. For example, ldemul_before_allocation can remove dynamic
4493 sections if they turn out to be not needed. Clean them up here. */
4494
4495 void
4496 strip_excluded_output_sections (void)
4497 {
4498 lang_output_section_statement_type *os;
4499
4500 /* Run lang_size_sections (if not already done). */
4501 if (expld.phase != lang_mark_phase_enum)
4502 {
4503 expld.phase = lang_mark_phase_enum;
4504 expld.dataseg.phase = exp_seg_none;
4505 one_lang_size_sections_pass (NULL, false);
4506 lang_reset_memory_regions ();
4507 }
4508
4509 for (os = (void *) lang_os_list.head;
4510 os != NULL;
4511 os = os->next)
4512 {
4513 asection *output_section;
4514 bool exclude;
4515
4516 if (os->constraint < 0)
4517 continue;
4518
4519 output_section = os->bfd_section;
4520 if (output_section == NULL)
4521 continue;
4522
4523 exclude = (output_section->rawsize == 0
4524 && (output_section->flags & SEC_KEEP) == 0
4525 && !bfd_section_removed_from_list (link_info.output_bfd,
4526 output_section));
4527
4528 /* Some sections have not yet been sized, notably .gnu.version,
4529 .dynsym, .dynstr and .hash. These all have SEC_LINKER_CREATED
4530 input sections, so don't drop output sections that have such
4531 input sections unless they are also marked SEC_EXCLUDE. */
4532 if (exclude && output_section->map_head.s != NULL)
4533 {
4534 asection *s;
4535
4536 for (s = output_section->map_head.s; s != NULL; s = s->map_head.s)
4537 if ((s->flags & SEC_EXCLUDE) == 0
4538 && ((s->flags & SEC_LINKER_CREATED) != 0
4539 || link_info.emitrelocations))
4540 {
4541 exclude = false;
4542 break;
4543 }
4544 }
4545
4546 if (exclude)
4547 {
4548 /* We don't set bfd_section to NULL since bfd_section of the
4549 removed output section statement may still be used. */
4550 if (!os->update_dot)
4551 os->ignored = true;
4552 output_section->flags |= SEC_EXCLUDE;
4553 bfd_section_list_remove (link_info.output_bfd, output_section);
4554 link_info.output_bfd->section_count--;
4555 }
4556 }
4557 }
4558
4559 /* Called from ldwrite to clear out asection.map_head and
4560 asection.map_tail for use as link_orders in ldwrite. */
4561
4562 void
4563 lang_clear_os_map (void)
4564 {
4565 lang_output_section_statement_type *os;
4566
4567 if (map_head_is_link_order)
4568 return;
4569
4570 for (os = (void *) lang_os_list.head;
4571 os != NULL;
4572 os = os->next)
4573 {
4574 asection *output_section;
4575
4576 if (os->constraint < 0)
4577 continue;
4578
4579 output_section = os->bfd_section;
4580 if (output_section == NULL)
4581 continue;
4582
4583 /* TODO: Don't just junk map_head.s, turn them into link_orders. */
4584 output_section->map_head.link_order = NULL;
4585 output_section->map_tail.link_order = NULL;
4586 }
4587
4588 /* Stop future calls to lang_add_section from messing with map_head
4589 and map_tail link_order fields. */
4590 map_head_is_link_order = true;
4591 }
4592
4593 static void
4594 print_output_section_statement
4595 (lang_output_section_statement_type *output_section_statement)
4596 {
4597 asection *section = output_section_statement->bfd_section;
4598 int len;
4599
4600 if (output_section_statement != abs_output_section)
4601 {
4602 minfo ("\n%s", output_section_statement->name);
4603
4604 if (section != NULL)
4605 {
4606 print_dot = section->vma;
4607
4608 len = strlen (output_section_statement->name);
4609 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4610 {
4611 print_nl ();
4612 len = 0;
4613 }
4614 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4615
4616 minfo ("0x%V %W", section->vma, TO_ADDR (section->size));
4617
4618 if (section->vma != section->lma)
4619 minfo (_(" load address 0x%V"), section->lma);
4620
4621 if (output_section_statement->update_dot_tree != NULL)
4622 exp_fold_tree (output_section_statement->update_dot_tree,
4623 bfd_abs_section_ptr, &print_dot);
4624 }
4625
4626 print_nl ();
4627 }
4628
4629 print_statement_list (output_section_statement->children.head,
4630 output_section_statement);
4631 }
4632
4633 static void
4634 print_assignment (lang_assignment_statement_type *assignment,
4635 lang_output_section_statement_type *output_section)
4636 {
4637 bool is_dot;
4638 etree_type *tree;
4639 asection *osec;
4640
4641 print_spaces (SECTION_NAME_MAP_LENGTH);
4642
4643 if (assignment->exp->type.node_class == etree_assert)
4644 {
4645 is_dot = false;
4646 tree = assignment->exp->assert_s.child;
4647 }
4648 else
4649 {
4650 const char *dst = assignment->exp->assign.dst;
4651
4652 is_dot = (dst[0] == '.' && dst[1] == 0);
4653 tree = assignment->exp;
4654 }
4655
4656 osec = output_section->bfd_section;
4657 if (osec == NULL)
4658 osec = bfd_abs_section_ptr;
4659
4660 if (assignment->exp->type.node_class != etree_provide)
4661 exp_fold_tree (tree, osec, &print_dot);
4662 else
4663 expld.result.valid_p = false;
4664
4665 char buf[32];
4666 const char *str = buf;
4667 if (expld.result.valid_p)
4668 {
4669 bfd_vma value;
4670
4671 if (assignment->exp->type.node_class == etree_assert
4672 || is_dot
4673 || expld.assign_name != NULL)
4674 {
4675 value = expld.result.value;
4676
4677 if (expld.result.section != NULL)
4678 value += expld.result.section->vma;
4679
4680 buf[0] = '0';
4681 buf[1] = 'x';
4682 bfd_sprintf_vma (link_info.output_bfd, buf + 2, value);
4683 if (is_dot)
4684 print_dot = value;
4685 }
4686 else
4687 {
4688 struct bfd_link_hash_entry *h;
4689
4690 h = bfd_link_hash_lookup (link_info.hash, assignment->exp->assign.dst,
4691 false, false, true);
4692 if (h != NULL
4693 && (h->type == bfd_link_hash_defined
4694 || h->type == bfd_link_hash_defweak))
4695 {
4696 value = h->u.def.value;
4697 value += h->u.def.section->output_section->vma;
4698 value += h->u.def.section->output_offset;
4699
4700 buf[0] = '[';
4701 buf[1] = '0';
4702 buf[2] = 'x';
4703 bfd_sprintf_vma (link_info.output_bfd, buf + 3, value);
4704 strcat (buf, "]");
4705 }
4706 else
4707 str = "[unresolved]";
4708 }
4709 }
4710 else
4711 {
4712 if (assignment->exp->type.node_class == etree_provide)
4713 str = "[!provide]";
4714 else
4715 str = "*undef*";
4716 }
4717 expld.assign_name = NULL;
4718
4719 fprintf (config.map_file, "%-34s", str);
4720 exp_print_tree (assignment->exp);
4721 print_nl ();
4722 }
4723
4724 static void
4725 print_input_statement (lang_input_statement_type *statm)
4726 {
4727 if (statm->filename != NULL)
4728 fprintf (config.map_file, "LOAD %s\n", statm->filename);
4729 }
4730
4731 /* Print all symbols defined in a particular section. This is called
4732 via bfd_link_hash_traverse, or by print_all_symbols. */
4733
4734 bool
4735 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
4736 {
4737 asection *sec = (asection *) ptr;
4738
4739 if ((hash_entry->type == bfd_link_hash_defined
4740 || hash_entry->type == bfd_link_hash_defweak)
4741 && sec == hash_entry->u.def.section)
4742 {
4743 print_spaces (SECTION_NAME_MAP_LENGTH);
4744 minfo ("0x%V ",
4745 (hash_entry->u.def.value
4746 + hash_entry->u.def.section->output_offset
4747 + hash_entry->u.def.section->output_section->vma));
4748
4749 minfo (" %pT\n", hash_entry->root.string);
4750 }
4751
4752 return true;
4753 }
4754
4755 static int
4756 hash_entry_addr_cmp (const void *a, const void *b)
4757 {
4758 const struct bfd_link_hash_entry *l = *(const struct bfd_link_hash_entry **)a;
4759 const struct bfd_link_hash_entry *r = *(const struct bfd_link_hash_entry **)b;
4760
4761 if (l->u.def.value < r->u.def.value)
4762 return -1;
4763 else if (l->u.def.value > r->u.def.value)
4764 return 1;
4765 else
4766 return 0;
4767 }
4768
4769 static void
4770 print_all_symbols (asection *sec)
4771 {
4772 input_section_userdata_type *ud = bfd_section_userdata (sec);
4773 struct map_symbol_def *def;
4774 struct bfd_link_hash_entry **entries;
4775 unsigned int i;
4776
4777 if (!ud)
4778 return;
4779
4780 *ud->map_symbol_def_tail = 0;
4781
4782 /* Sort the symbols by address. */
4783 entries = (struct bfd_link_hash_entry **)
4784 obstack_alloc (&map_obstack,
4785 ud->map_symbol_def_count * sizeof (*entries));
4786
4787 for (i = 0, def = ud->map_symbol_def_head; def; def = def->next, i++)
4788 entries[i] = def->entry;
4789
4790 qsort (entries, ud->map_symbol_def_count, sizeof (*entries),
4791 hash_entry_addr_cmp);
4792
4793 /* Print the symbols. */
4794 for (i = 0; i < ud->map_symbol_def_count; i++)
4795 ldemul_print_symbol (entries[i], sec);
4796
4797 obstack_free (&map_obstack, entries);
4798 }
4799
4800 /* Print information about an input section to the map file. */
4801
4802 static void
4803 print_input_section (asection *i, bool is_discarded)
4804 {
4805 bfd_size_type size = i->size;
4806 int len;
4807 bfd_vma addr;
4808
4809 init_opb (i);
4810
4811 minfo (" %s", i->name);
4812
4813 len = 1 + strlen (i->name);
4814 if (len >= SECTION_NAME_MAP_LENGTH - 1)
4815 {
4816 print_nl ();
4817 len = 0;
4818 }
4819 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4820
4821 if (i->output_section != NULL
4822 && i->output_section->owner == link_info.output_bfd)
4823 addr = i->output_section->vma + i->output_offset;
4824 else
4825 {
4826 addr = print_dot;
4827 if (!is_discarded)
4828 size = 0;
4829 }
4830
4831 char buf[32];
4832 bfd_sprintf_vma (link_info.output_bfd, buf, addr);
4833 minfo ("0x%s %W %pB\n", buf, TO_ADDR (size), i->owner);
4834
4835 if (size != i->rawsize && i->rawsize != 0)
4836 {
4837 len = SECTION_NAME_MAP_LENGTH + 3 + strlen (buf);
4838 print_spaces (len);
4839 minfo (_("%W (size before relaxing)\n"), TO_ADDR (i->rawsize));
4840 }
4841
4842 if (i->output_section != NULL
4843 && i->output_section->owner == link_info.output_bfd)
4844 {
4845 if (link_info.reduce_memory_overheads)
4846 bfd_link_hash_traverse (link_info.hash, ldemul_print_symbol, i);
4847 else
4848 print_all_symbols (i);
4849
4850 /* Update print_dot, but make sure that we do not move it
4851 backwards - this could happen if we have overlays and a
4852 later overlay is shorter than an earier one. */
4853 if (addr + TO_ADDR (size) > print_dot)
4854 print_dot = addr + TO_ADDR (size);
4855 }
4856 }
4857
4858 static void
4859 print_fill_statement (lang_fill_statement_type *fill)
4860 {
4861 size_t size;
4862 unsigned char *p;
4863 fputs (" FILL mask 0x", config.map_file);
4864 for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
4865 fprintf (config.map_file, "%02x", *p);
4866 fputs ("\n", config.map_file);
4867 }
4868
4869 static void
4870 print_data_statement (lang_data_statement_type *data)
4871 {
4872 bfd_vma addr;
4873 bfd_size_type size;
4874 const char *name;
4875
4876 init_opb (data->output_section);
4877 print_spaces (SECTION_NAME_MAP_LENGTH);
4878
4879 addr = data->output_offset;
4880 if (data->output_section != NULL)
4881 addr += data->output_section->vma;
4882
4883 switch (data->type)
4884 {
4885 default:
4886 abort ();
4887 case BYTE:
4888 size = BYTE_SIZE;
4889 name = "BYTE";
4890 break;
4891 case SHORT:
4892 size = SHORT_SIZE;
4893 name = "SHORT";
4894 break;
4895 case LONG:
4896 size = LONG_SIZE;
4897 name = "LONG";
4898 break;
4899 case QUAD:
4900 size = QUAD_SIZE;
4901 name = "QUAD";
4902 break;
4903 case SQUAD:
4904 size = QUAD_SIZE;
4905 name = "SQUAD";
4906 break;
4907 }
4908
4909 if (size < TO_SIZE ((unsigned) 1))
4910 size = TO_SIZE ((unsigned) 1);
4911 minfo ("0x%V %W %s 0x%v", addr, TO_ADDR (size), name, data->value);
4912
4913 if (data->exp->type.node_class != etree_value)
4914 {
4915 print_space ();
4916 exp_print_tree (data->exp);
4917 }
4918
4919 print_nl ();
4920
4921 print_dot = addr + TO_ADDR (size);
4922 }
4923
4924 /* Print an address statement. These are generated by options like
4925 -Ttext. */
4926
4927 static void
4928 print_address_statement (lang_address_statement_type *address)
4929 {
4930 minfo (_("Address of section %s set to "), address->section_name);
4931 exp_print_tree (address->address);
4932 print_nl ();
4933 }
4934
4935 /* Print a reloc statement. */
4936
4937 static void
4938 print_reloc_statement (lang_reloc_statement_type *reloc)
4939 {
4940 bfd_vma addr;
4941 bfd_size_type size;
4942
4943 init_opb (reloc->output_section);
4944 print_spaces (SECTION_NAME_MAP_LENGTH);
4945
4946 addr = reloc->output_offset;
4947 if (reloc->output_section != NULL)
4948 addr += reloc->output_section->vma;
4949
4950 size = bfd_get_reloc_size (reloc->howto);
4951
4952 minfo ("0x%V %W RELOC %s ", addr, TO_ADDR (size), reloc->howto->name);
4953
4954 if (reloc->name != NULL)
4955 minfo ("%s+", reloc->name);
4956 else
4957 minfo ("%s+", reloc->section->name);
4958
4959 exp_print_tree (reloc->addend_exp);
4960
4961 print_nl ();
4962
4963 print_dot = addr + TO_ADDR (size);
4964 }
4965
4966 static void
4967 print_padding_statement (lang_padding_statement_type *s)
4968 {
4969 int len;
4970 bfd_vma addr;
4971
4972 init_opb (s->output_section);
4973 minfo (" *fill*");
4974
4975 len = sizeof " *fill*" - 1;
4976 print_spaces (SECTION_NAME_MAP_LENGTH - len);
4977
4978 addr = s->output_offset;
4979 if (s->output_section != NULL)
4980 addr += s->output_section->vma;
4981 minfo ("0x%V %W ", addr, TO_ADDR (s->size));
4982
4983 if (s->fill->size != 0)
4984 {
4985 size_t size;
4986 unsigned char *p;
4987 for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
4988 fprintf (config.map_file, "%02x", *p);
4989 }
4990
4991 print_nl ();
4992
4993 print_dot = addr + TO_ADDR (s->size);
4994 }
4995
4996 static void
4997 print_wild_statement (lang_wild_statement_type *w,
4998 lang_output_section_statement_type *os)
4999 {
5000 struct wildcard_list *sec;
5001
5002 print_space ();
5003
5004 if (w->exclude_name_list)
5005 {
5006 name_list *tmp;
5007 minfo ("EXCLUDE_FILE(%s", w->exclude_name_list->name);
5008 for (tmp = w->exclude_name_list->next; tmp; tmp = tmp->next)
5009 minfo (" %s", tmp->name);
5010 minfo (") ");
5011 }
5012
5013 if (w->filenames_sorted)
5014 minfo ("SORT_BY_NAME(");
5015 if (w->filename != NULL)
5016 minfo ("%s", w->filename);
5017 else
5018 minfo ("*");
5019 if (w->filenames_sorted)
5020 minfo (")");
5021
5022 minfo ("(");
5023 for (sec = w->section_list; sec; sec = sec->next)
5024 {
5025 int closing_paren = 0;
5026
5027 switch (sec->spec.sorted)
5028 {
5029 case none:
5030 break;
5031
5032 case by_name:
5033 minfo ("SORT_BY_NAME(");
5034 closing_paren = 1;
5035 break;
5036
5037 case by_alignment:
5038 minfo ("SORT_BY_ALIGNMENT(");
5039 closing_paren = 1;
5040 break;
5041
5042 case by_name_alignment:
5043 minfo ("SORT_BY_NAME(SORT_BY_ALIGNMENT(");
5044 closing_paren = 2;
5045 break;
5046
5047 case by_alignment_name:
5048 minfo ("SORT_BY_ALIGNMENT(SORT_BY_NAME(");
5049 closing_paren = 2;
5050 break;
5051
5052 case by_none:
5053 minfo ("SORT_NONE(");
5054 closing_paren = 1;
5055 break;
5056
5057 case by_init_priority:
5058 minfo ("SORT_BY_INIT_PRIORITY(");
5059 closing_paren = 1;
5060 break;
5061 }
5062
5063 if (sec->spec.exclude_name_list != NULL)
5064 {
5065 name_list *tmp;
5066 minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
5067 for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
5068 minfo (" %s", tmp->name);
5069 minfo (") ");
5070 }
5071 if (sec->spec.name != NULL)
5072 minfo ("%s", sec->spec.name);
5073 else
5074 minfo ("*");
5075 for (;closing_paren > 0; closing_paren--)
5076 minfo (")");
5077 if (sec->next)
5078 minfo (" ");
5079 }
5080 minfo (")");
5081
5082 print_nl ();
5083
5084 print_statement_list (w->children.head, os);
5085 }
5086
5087 /* Print a group statement. */
5088
5089 static void
5090 print_group (lang_group_statement_type *s,
5091 lang_output_section_statement_type *os)
5092 {
5093 fprintf (config.map_file, "START GROUP\n");
5094 print_statement_list (s->children.head, os);
5095 fprintf (config.map_file, "END GROUP\n");
5096 }
5097
5098 /* Print the list of statements in S.
5099 This can be called for any statement type. */
5100
5101 static void
5102 print_statement_list (lang_statement_union_type *s,
5103 lang_output_section_statement_type *os)
5104 {
5105 while (s != NULL)
5106 {
5107 print_statement (s, os);
5108 s = s->header.next;
5109 }
5110 }
5111
5112 /* Print the first statement in statement list S.
5113 This can be called for any statement type. */
5114
5115 static void
5116 print_statement (lang_statement_union_type *s,
5117 lang_output_section_statement_type *os)
5118 {
5119 switch (s->header.type)
5120 {
5121 default:
5122 fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
5123 FAIL ();
5124 break;
5125 case lang_constructors_statement_enum:
5126 if (constructor_list.head != NULL)
5127 {
5128 if (constructors_sorted)
5129 minfo (" SORT (CONSTRUCTORS)\n");
5130 else
5131 minfo (" CONSTRUCTORS\n");
5132 print_statement_list (constructor_list.head, os);
5133 }
5134 break;
5135 case lang_wild_statement_enum:
5136 print_wild_statement (&s->wild_statement, os);
5137 break;
5138 case lang_address_statement_enum:
5139 print_address_statement (&s->address_statement);
5140 break;
5141 case lang_object_symbols_statement_enum:
5142 minfo (" CREATE_OBJECT_SYMBOLS\n");
5143 break;
5144 case lang_fill_statement_enum:
5145 print_fill_statement (&s->fill_statement);
5146 break;
5147 case lang_data_statement_enum:
5148 print_data_statement (&s->data_statement);
5149 break;
5150 case lang_reloc_statement_enum:
5151 print_reloc_statement (&s->reloc_statement);
5152 break;
5153 case lang_input_section_enum:
5154 print_input_section (s->input_section.section, false);
5155 break;
5156 case lang_padding_statement_enum:
5157 print_padding_statement (&s->padding_statement);
5158 break;
5159 case lang_output_section_statement_enum:
5160 print_output_section_statement (&s->output_section_statement);
5161 break;
5162 case lang_assignment_statement_enum:
5163 print_assignment (&s->assignment_statement, os);
5164 break;
5165 case lang_target_statement_enum:
5166 fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
5167 break;
5168 case lang_output_statement_enum:
5169 minfo ("OUTPUT(%s", s->output_statement.name);
5170 if (output_target != NULL)
5171 minfo (" %s", output_target);
5172 minfo (")\n");
5173 break;
5174 case lang_input_statement_enum:
5175 print_input_statement (&s->input_statement);
5176 break;
5177 case lang_group_statement_enum:
5178 print_group (&s->group_statement, os);
5179 break;
5180 case lang_insert_statement_enum:
5181 minfo ("INSERT %s %s\n",
5182 s->insert_statement.is_before ? "BEFORE" : "AFTER",
5183 s->insert_statement.where);
5184 break;
5185 }
5186 }
5187
5188 static void
5189 print_statements (void)
5190 {
5191 print_statement_list (statement_list.head, abs_output_section);
5192 }
5193
5194 /* Print the first N statements in statement list S to STDERR.
5195 If N == 0, nothing is printed.
5196 If N < 0, the entire list is printed.
5197 Intended to be called from GDB. */
5198
5199 void
5200 dprint_statement (lang_statement_union_type *s, int n)
5201 {
5202 FILE *map_save = config.map_file;
5203
5204 config.map_file = stderr;
5205
5206 if (n < 0)
5207 print_statement_list (s, abs_output_section);
5208 else
5209 {
5210 while (s && --n >= 0)
5211 {
5212 print_statement (s, abs_output_section);
5213 s = s->header.next;
5214 }
5215 }
5216
5217 config.map_file = map_save;
5218 }
5219
5220 static void
5221 insert_pad (lang_statement_union_type **ptr,
5222 fill_type *fill,
5223 bfd_size_type alignment_needed,
5224 asection *output_section,
5225 bfd_vma dot)
5226 {
5227 static fill_type zero_fill;
5228 lang_statement_union_type *pad = NULL;
5229
5230 if (ptr != &statement_list.head)
5231 pad = ((lang_statement_union_type *)
5232 ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
5233 if (pad != NULL
5234 && pad->header.type == lang_padding_statement_enum
5235 && pad->padding_statement.output_section == output_section)
5236 {
5237 /* Use the existing pad statement. */
5238 }
5239 else if ((pad = *ptr) != NULL
5240 && pad->header.type == lang_padding_statement_enum
5241 && pad->padding_statement.output_section == output_section)
5242 {
5243 /* Use the existing pad statement. */
5244 }
5245 else
5246 {
5247 /* Make a new padding statement, linked into existing chain. */
5248 pad = stat_alloc (sizeof (lang_padding_statement_type));
5249 pad->header.next = *ptr;
5250 *ptr = pad;
5251 pad->header.type = lang_padding_statement_enum;
5252 pad->padding_statement.output_section = output_section;
5253 if (fill == NULL)
5254 fill = &zero_fill;
5255 pad->padding_statement.fill = fill;
5256 }
5257 pad->padding_statement.output_offset = dot - output_section->vma;
5258 pad->padding_statement.size = alignment_needed;
5259 if (!(output_section->flags & SEC_FIXED_SIZE))
5260 output_section->size = TO_SIZE (dot + TO_ADDR (alignment_needed)
5261 - output_section->vma);
5262 }
5263
5264 /* Work out how much this section will move the dot point. */
5265
5266 static bfd_vma
5267 size_input_section
5268 (lang_statement_union_type **this_ptr,
5269 lang_output_section_statement_type *output_section_statement,
5270 fill_type *fill,
5271 bool *removed,
5272 bfd_vma dot)
5273 {
5274 lang_input_section_type *is = &((*this_ptr)->input_section);
5275 asection *i = is->section;
5276 asection *o = output_section_statement->bfd_section;
5277 *removed = 0;
5278
5279 if (link_info.non_contiguous_regions)
5280 {
5281 /* If the input section I has already been successfully assigned
5282 to an output section other than O, don't bother with it and
5283 let the caller remove it from the list. Keep processing in
5284 case we have already handled O, because the repeated passes
5285 have reinitialized its size. */
5286 if (i->already_assigned && i->already_assigned != o)
5287 {
5288 *removed = 1;
5289 return dot;
5290 }
5291 }
5292
5293 if (i->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
5294 i->output_offset = i->vma - o->vma;
5295 else if (((i->flags & SEC_EXCLUDE) != 0)
5296 || output_section_statement->ignored)
5297 i->output_offset = dot - o->vma;
5298 else
5299 {
5300 bfd_size_type alignment_needed;
5301
5302 /* Align this section first to the input sections requirement,
5303 then to the output section's requirement. If this alignment
5304 is greater than any seen before, then record it too. Perform
5305 the alignment by inserting a magic 'padding' statement. */
5306
5307 if (output_section_statement->subsection_alignment != NULL)
5308 i->alignment_power
5309 = exp_get_power (output_section_statement->subsection_alignment,
5310 "subsection alignment");
5311
5312 if (o->alignment_power < i->alignment_power)
5313 o->alignment_power = i->alignment_power;
5314
5315 alignment_needed = align_power (dot, i->alignment_power) - dot;
5316
5317 if (alignment_needed != 0)
5318 {
5319 insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
5320 dot += alignment_needed;
5321 }
5322
5323 if (link_info.non_contiguous_regions)
5324 {
5325 /* If I would overflow O, let the caller remove I from the
5326 list. */
5327 if (output_section_statement->region)
5328 {
5329 bfd_vma end = output_section_statement->region->origin
5330 + output_section_statement->region->length;
5331
5332 if (dot + TO_ADDR (i->size) > end)
5333 {
5334 if (i->flags & SEC_LINKER_CREATED)
5335 einfo (_("%F%P: Output section `%pA' not large enough for "
5336 "the linker-created stubs section `%pA'.\n"),
5337 i->output_section, i);
5338
5339 if (i->rawsize && i->rawsize != i->size)
5340 einfo (_("%F%P: Relaxation not supported with "
5341 "--enable-non-contiguous-regions (section `%pA' "
5342 "would overflow `%pA' after it changed size).\n"),
5343 i, i->output_section);
5344
5345 *removed = 1;
5346 dot = end;
5347 i->output_section = NULL;
5348 return dot;
5349 }
5350 }
5351 }
5352
5353 /* Remember where in the output section this input section goes. */
5354 i->output_offset = dot - o->vma;
5355
5356 /* Mark how big the output section must be to contain this now. */
5357 dot += TO_ADDR (i->size);
5358 if (!(o->flags & SEC_FIXED_SIZE))
5359 o->size = TO_SIZE (dot - o->vma);
5360
5361 if (link_info.non_contiguous_regions)
5362 {
5363 /* Record that I was successfully assigned to O, and update
5364 its actual output section too. */
5365 i->already_assigned = o;
5366 i->output_section = o;
5367 }
5368 }
5369
5370 return dot;
5371 }
5372
5373 struct check_sec
5374 {
5375 asection *sec;
5376 bool warned;
5377 };
5378
5379 static int
5380 sort_sections_by_lma (const void *arg1, const void *arg2)
5381 {
5382 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5383 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5384
5385 if (sec1->lma < sec2->lma)
5386 return -1;
5387 else if (sec1->lma > sec2->lma)
5388 return 1;
5389 else if (sec1->id < sec2->id)
5390 return -1;
5391 else if (sec1->id > sec2->id)
5392 return 1;
5393
5394 return 0;
5395 }
5396
5397 static int
5398 sort_sections_by_vma (const void *arg1, const void *arg2)
5399 {
5400 const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5401 const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5402
5403 if (sec1->vma < sec2->vma)
5404 return -1;
5405 else if (sec1->vma > sec2->vma)
5406 return 1;
5407 else if (sec1->id < sec2->id)
5408 return -1;
5409 else if (sec1->id > sec2->id)
5410 return 1;
5411
5412 return 0;
5413 }
5414
5415 #define IS_TBSS(s) \
5416 ((s->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == SEC_THREAD_LOCAL)
5417
5418 #define IGNORE_SECTION(s) \
5419 ((s->flags & SEC_ALLOC) == 0 || IS_TBSS (s))
5420
5421 /* Check to see if any allocated sections overlap with other allocated
5422 sections. This can happen if a linker script specifies the output
5423 section addresses of the two sections. Also check whether any memory
5424 region has overflowed. */
5425
5426 static void
5427 lang_check_section_addresses (void)
5428 {
5429 asection *s, *p;
5430 struct check_sec *sections;
5431 size_t i, count;
5432 bfd_vma addr_mask;
5433 bfd_vma s_start;
5434 bfd_vma s_end;
5435 bfd_vma p_start = 0;
5436 bfd_vma p_end = 0;
5437 lang_memory_region_type *m;
5438 bool overlays;
5439
5440 /* Detect address space overflow on allocated sections. */
5441 addr_mask = ((bfd_vma) 1 <<
5442 (bfd_arch_bits_per_address (link_info.output_bfd) - 1)) - 1;
5443 addr_mask = (addr_mask << 1) + 1;
5444 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5445 if ((s->flags & SEC_ALLOC) != 0)
5446 {
5447 s_end = (s->vma + s->size) & addr_mask;
5448 if (s_end != 0 && s_end < (s->vma & addr_mask))
5449 einfo (_("%X%P: section %s VMA wraps around address space\n"),
5450 s->name);
5451 else
5452 {
5453 s_end = (s->lma + s->size) & addr_mask;
5454 if (s_end != 0 && s_end < (s->lma & addr_mask))
5455 einfo (_("%X%P: section %s LMA wraps around address space\n"),
5456 s->name);
5457 }
5458 }
5459
5460 if (bfd_count_sections (link_info.output_bfd) <= 1)
5461 return;
5462
5463 count = bfd_count_sections (link_info.output_bfd);
5464 sections = XNEWVEC (struct check_sec, count);
5465
5466 /* Scan all sections in the output list. */
5467 count = 0;
5468 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5469 {
5470 if (IGNORE_SECTION (s)
5471 || s->size == 0)
5472 continue;
5473
5474 sections[count].sec = s;
5475 sections[count].warned = false;
5476 count++;
5477 }
5478
5479 if (count <= 1)
5480 {
5481 free (sections);
5482 return;
5483 }
5484
5485 qsort (sections, count, sizeof (*sections), sort_sections_by_lma);
5486
5487 /* First check section LMAs. There should be no overlap of LMAs on
5488 loadable sections, even with overlays. */
5489 for (p = NULL, i = 0; i < count; i++)
5490 {
5491 s = sections[i].sec;
5492 init_opb (s);
5493 if ((s->flags & SEC_LOAD) != 0)
5494 {
5495 s_start = s->lma;
5496 s_end = s_start + TO_ADDR (s->size) - 1;
5497
5498 /* Look for an overlap. We have sorted sections by lma, so
5499 we know that s_start >= p_start. Besides the obvious
5500 case of overlap when the current section starts before
5501 the previous one ends, we also must have overlap if the
5502 previous section wraps around the address space. */
5503 if (p != NULL
5504 && (s_start <= p_end
5505 || p_end < p_start))
5506 {
5507 einfo (_("%X%P: section %s LMA [%V,%V]"
5508 " overlaps section %s LMA [%V,%V]\n"),
5509 s->name, s_start, s_end, p->name, p_start, p_end);
5510 sections[i].warned = true;
5511 }
5512 p = s;
5513 p_start = s_start;
5514 p_end = s_end;
5515 }
5516 }
5517
5518 /* If any non-zero size allocated section (excluding tbss) starts at
5519 exactly the same VMA as another such section, then we have
5520 overlays. Overlays generated by the OVERLAY keyword will have
5521 this property. It is possible to intentionally generate overlays
5522 that fail this test, but it would be unusual. */
5523 qsort (sections, count, sizeof (*sections), sort_sections_by_vma);
5524 overlays = false;
5525 p_start = sections[0].sec->vma;
5526 for (i = 1; i < count; i++)
5527 {
5528 s_start = sections[i].sec->vma;
5529 if (p_start == s_start)
5530 {
5531 overlays = true;
5532 break;
5533 }
5534 p_start = s_start;
5535 }
5536
5537 /* Now check section VMAs if no overlays were detected. */
5538 if (!overlays)
5539 {
5540 for (p = NULL, i = 0; i < count; i++)
5541 {
5542 s = sections[i].sec;
5543 init_opb (s);
5544 s_start = s->vma;
5545 s_end = s_start + TO_ADDR (s->size) - 1;
5546
5547 if (p != NULL
5548 && !sections[i].warned
5549 && (s_start <= p_end
5550 || p_end < p_start))
5551 einfo (_("%X%P: section %s VMA [%V,%V]"
5552 " overlaps section %s VMA [%V,%V]\n"),
5553 s->name, s_start, s_end, p->name, p_start, p_end);
5554 p = s;
5555 p_start = s_start;
5556 p_end = s_end;
5557 }
5558 }
5559
5560 free (sections);
5561
5562 /* If any memory region has overflowed, report by how much.
5563 We do not issue this diagnostic for regions that had sections
5564 explicitly placed outside their bounds; os_region_check's
5565 diagnostics are adequate for that case.
5566
5567 FIXME: It is conceivable that m->current - (m->origin + m->length)
5568 might overflow a 32-bit integer. There is, alas, no way to print
5569 a bfd_vma quantity in decimal. */
5570 for (m = lang_memory_region_list; m; m = m->next)
5571 if (m->had_full_message)
5572 {
5573 unsigned long over = m->current - (m->origin + m->length);
5574 einfo (ngettext ("%X%P: region `%s' overflowed by %lu byte\n",
5575 "%X%P: region `%s' overflowed by %lu bytes\n",
5576 over),
5577 m->name_list.name, over);
5578 }
5579 }
5580
5581 /* Make sure the new address is within the region. We explicitly permit the
5582 current address to be at the exact end of the region when the address is
5583 non-zero, in case the region is at the end of addressable memory and the
5584 calculation wraps around. */
5585
5586 static void
5587 os_region_check (lang_output_section_statement_type *os,
5588 lang_memory_region_type *region,
5589 etree_type *tree,
5590 bfd_vma rbase)
5591 {
5592 if ((region->current < region->origin
5593 || (region->current - region->origin > region->length))
5594 && ((region->current != region->origin + region->length)
5595 || rbase == 0))
5596 {
5597 if (tree != NULL)
5598 {
5599 einfo (_("%X%P: address 0x%v of %pB section `%s'"
5600 " is not within region `%s'\n"),
5601 region->current,
5602 os->bfd_section->owner,
5603 os->bfd_section->name,
5604 region->name_list.name);
5605 }
5606 else if (!region->had_full_message)
5607 {
5608 region->had_full_message = true;
5609
5610 einfo (_("%X%P: %pB section `%s' will not fit in region `%s'\n"),
5611 os->bfd_section->owner,
5612 os->bfd_section->name,
5613 region->name_list.name);
5614 }
5615 }
5616 }
5617
5618 static void
5619 ldlang_check_relro_region (lang_statement_union_type *s)
5620 {
5621 seg_align_type *seg = &expld.dataseg;
5622
5623 if (seg->relro == exp_seg_relro_start)
5624 {
5625 if (!seg->relro_start_stat)
5626 seg->relro_start_stat = s;
5627 else
5628 {
5629 ASSERT (seg->relro_start_stat == s);
5630 }
5631 }
5632 else if (seg->relro == exp_seg_relro_end)
5633 {
5634 if (!seg->relro_end_stat)
5635 seg->relro_end_stat = s;
5636 else
5637 {
5638 ASSERT (seg->relro_end_stat == s);
5639 }
5640 }
5641 }
5642
5643 /* Set the sizes for all the output sections. */
5644
5645 static bfd_vma
5646 lang_size_sections_1
5647 (lang_statement_union_type **prev,
5648 lang_output_section_statement_type *output_section_statement,
5649 fill_type *fill,
5650 bfd_vma dot,
5651 bool *relax,
5652 bool check_regions)
5653 {
5654 lang_statement_union_type *s;
5655 lang_statement_union_type *prev_s = NULL;
5656 bool removed_prev_s = false;
5657
5658 /* Size up the sections from their constituent parts. */
5659 for (s = *prev; s != NULL; prev_s = s, s = s->header.next)
5660 {
5661 bool removed = false;
5662
5663 switch (s->header.type)
5664 {
5665 case lang_output_section_statement_enum:
5666 {
5667 bfd_vma newdot, after, dotdelta;
5668 lang_output_section_statement_type *os;
5669 lang_memory_region_type *r;
5670 int section_alignment = 0;
5671
5672 os = &s->output_section_statement;
5673 init_opb (os->bfd_section);
5674 if (os->constraint == -1)
5675 break;
5676
5677 /* FIXME: We shouldn't need to zero section vmas for ld -r
5678 here, in lang_insert_orphan, or in the default linker scripts.
5679 This is covering for coff backend linker bugs. See PR6945. */
5680 if (os->addr_tree == NULL
5681 && bfd_link_relocatable (&link_info)
5682 && (bfd_get_flavour (link_info.output_bfd)
5683 == bfd_target_coff_flavour))
5684 os->addr_tree = exp_intop (0);
5685 if (os->addr_tree != NULL)
5686 {
5687 exp_fold_tree (os->addr_tree, bfd_abs_section_ptr, &dot);
5688
5689 if (expld.result.valid_p)
5690 {
5691 dot = expld.result.value;
5692 if (expld.result.section != NULL)
5693 dot += expld.result.section->vma;
5694 }
5695 else if (expld.phase != lang_mark_phase_enum)
5696 einfo (_("%F%P:%pS: non constant or forward reference"
5697 " address expression for section %s\n"),
5698 os->addr_tree, os->name);
5699 }
5700
5701 if (os->bfd_section == NULL)
5702 /* This section was removed or never actually created. */
5703 break;
5704
5705 /* If this is a COFF shared library section, use the size and
5706 address from the input section. FIXME: This is COFF
5707 specific; it would be cleaner if there were some other way
5708 to do this, but nothing simple comes to mind. */
5709 if (((bfd_get_flavour (link_info.output_bfd)
5710 == bfd_target_ecoff_flavour)
5711 || (bfd_get_flavour (link_info.output_bfd)
5712 == bfd_target_coff_flavour))
5713 && (os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
5714 {
5715 asection *input;
5716
5717 if (os->children.head == NULL
5718 || os->children.head->header.next != NULL
5719 || (os->children.head->header.type
5720 != lang_input_section_enum))
5721 einfo (_("%X%P: internal error on COFF shared library"
5722 " section %s\n"), os->name);
5723
5724 input = os->children.head->input_section.section;
5725 bfd_set_section_vma (os->bfd_section,
5726 bfd_section_vma (input));
5727 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5728 os->bfd_section->size = input->size;
5729 break;
5730 }
5731
5732 newdot = dot;
5733 dotdelta = 0;
5734 if (bfd_is_abs_section (os->bfd_section))
5735 {
5736 /* No matter what happens, an abs section starts at zero. */
5737 ASSERT (os->bfd_section->vma == 0);
5738 }
5739 else
5740 {
5741 if (os->addr_tree == NULL)
5742 {
5743 /* No address specified for this section, get one
5744 from the region specification. */
5745 if (os->region == NULL
5746 || ((os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))
5747 && os->region->name_list.name[0] == '*'
5748 && strcmp (os->region->name_list.name,
5749 DEFAULT_MEMORY_REGION) == 0))
5750 {
5751 os->region = lang_memory_default (os->bfd_section);
5752 }
5753
5754 /* If a loadable section is using the default memory
5755 region, and some non default memory regions were
5756 defined, issue an error message. */
5757 if (!os->ignored
5758 && !IGNORE_SECTION (os->bfd_section)
5759 && !bfd_link_relocatable (&link_info)
5760 && check_regions
5761 && strcmp (os->region->name_list.name,
5762 DEFAULT_MEMORY_REGION) == 0
5763 && lang_memory_region_list != NULL
5764 && (strcmp (lang_memory_region_list->name_list.name,
5765 DEFAULT_MEMORY_REGION) != 0
5766 || lang_memory_region_list->next != NULL)
5767 && lang_sizing_iteration == 1)
5768 {
5769 /* By default this is an error rather than just a
5770 warning because if we allocate the section to the
5771 default memory region we can end up creating an
5772 excessively large binary, or even seg faulting when
5773 attempting to perform a negative seek. See
5774 sources.redhat.com/ml/binutils/2003-04/msg00423.html
5775 for an example of this. This behaviour can be
5776 overridden by the using the --no-check-sections
5777 switch. */
5778 if (command_line.check_section_addresses)
5779 einfo (_("%F%P: error: no memory region specified"
5780 " for loadable section `%s'\n"),
5781 bfd_section_name (os->bfd_section));
5782 else
5783 einfo (_("%P: warning: no memory region specified"
5784 " for loadable section `%s'\n"),
5785 bfd_section_name (os->bfd_section));
5786 }
5787
5788 newdot = os->region->current;
5789 section_alignment = os->bfd_section->alignment_power;
5790 }
5791 else
5792 section_alignment = exp_get_power (os->section_alignment,
5793 "section alignment");
5794
5795 /* Align to what the section needs. */
5796 if (section_alignment > 0)
5797 {
5798 bfd_vma savedot = newdot;
5799 bfd_vma diff = 0;
5800
5801 newdot = align_power (newdot, section_alignment);
5802 dotdelta = newdot - savedot;
5803
5804 if (lang_sizing_iteration == 1)
5805 diff = dotdelta;
5806 else if (lang_sizing_iteration > 1)
5807 {
5808 /* Only report adjustments that would change
5809 alignment from what we have already reported. */
5810 diff = newdot - os->bfd_section->vma;
5811 if (!(diff & (((bfd_vma) 1 << section_alignment) - 1)))
5812 diff = 0;
5813 }
5814 if (diff != 0
5815 && (config.warn_section_align
5816 || os->addr_tree != NULL))
5817 einfo (_("%P: warning: "
5818 "start of section %s changed by %ld\n"),
5819 os->name, (long) diff);
5820 }
5821
5822 bfd_set_section_vma (os->bfd_section, newdot);
5823
5824 os->bfd_section->output_offset = 0;
5825 }
5826
5827 lang_size_sections_1 (&os->children.head, os,
5828 os->fill, newdot, relax, check_regions);
5829
5830 os->processed_vma = true;
5831
5832 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
5833 /* Except for some special linker created sections,
5834 no output section should change from zero size
5835 after strip_excluded_output_sections. A non-zero
5836 size on an ignored section indicates that some
5837 input section was not sized early enough. */
5838 ASSERT (os->bfd_section->size == 0);
5839 else
5840 {
5841 dot = os->bfd_section->vma;
5842
5843 /* Put the section within the requested block size, or
5844 align at the block boundary. */
5845 after = ((dot
5846 + TO_ADDR (os->bfd_section->size)
5847 + os->block_value - 1)
5848 & - (bfd_vma) os->block_value);
5849
5850 if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5851 os->bfd_section->size = TO_SIZE (after
5852 - os->bfd_section->vma);
5853 }
5854
5855 /* Set section lma. */
5856 r = os->region;
5857 if (r == NULL)
5858 r = lang_memory_region_lookup (DEFAULT_MEMORY_REGION, false);
5859
5860 if (os->load_base)
5861 {
5862 bfd_vma lma = exp_get_abs_int (os->load_base, 0, "load base");
5863 os->bfd_section->lma = lma;
5864 }
5865 else if (os->lma_region != NULL)
5866 {
5867 bfd_vma lma = os->lma_region->current;
5868
5869 if (os->align_lma_with_input)
5870 lma += dotdelta;
5871 else
5872 {
5873 /* When LMA_REGION is the same as REGION, align the LMA
5874 as we did for the VMA, possibly including alignment
5875 from the bfd section. If a different region, then
5876 only align according to the value in the output
5877 statement. */
5878 if (os->lma_region != os->region)
5879 section_alignment = exp_get_power (os->section_alignment,
5880 "section alignment");
5881 if (section_alignment > 0)
5882 lma = align_power (lma, section_alignment);
5883 }
5884 os->bfd_section->lma = lma;
5885 }
5886 else if (r->last_os != NULL
5887 && (os->bfd_section->flags & SEC_ALLOC) != 0)
5888 {
5889 bfd_vma lma;
5890 asection *last;
5891
5892 last = r->last_os->output_section_statement.bfd_section;
5893
5894 /* A backwards move of dot should be accompanied by
5895 an explicit assignment to the section LMA (ie.
5896 os->load_base set) because backwards moves can
5897 create overlapping LMAs. */
5898 if (dot < last->vma
5899 && os->bfd_section->size != 0
5900 && dot + TO_ADDR (os->bfd_section->size) <= last->vma)
5901 {
5902 /* If dot moved backwards then leave lma equal to
5903 vma. This is the old default lma, which might
5904 just happen to work when the backwards move is
5905 sufficiently large. Nag if this changes anything,
5906 so people can fix their linker scripts. */
5907
5908 if (last->vma != last->lma)
5909 einfo (_("%P: warning: dot moved backwards "
5910 "before `%s'\n"), os->name);
5911 }
5912 else
5913 {
5914 /* If this is an overlay, set the current lma to that
5915 at the end of the previous section. */
5916 if (os->sectype == overlay_section)
5917 lma = last->lma + TO_ADDR (last->size);
5918
5919 /* Otherwise, keep the same lma to vma relationship
5920 as the previous section. */
5921 else
5922 lma = os->bfd_section->vma + last->lma - last->vma;
5923
5924 if (section_alignment > 0)
5925 lma = align_power (lma, section_alignment);
5926 os->bfd_section->lma = lma;
5927 }
5928 }
5929 os->processed_lma = true;
5930
5931 /* Keep track of normal sections using the default
5932 lma region. We use this to set the lma for
5933 following sections. Overlays or other linker
5934 script assignment to lma might mean that the
5935 default lma == vma is incorrect.
5936 To avoid warnings about dot moving backwards when using
5937 -Ttext, don't start tracking sections until we find one
5938 of non-zero size or with lma set differently to vma.
5939 Do this tracking before we short-cut the loop so that we
5940 track changes for the case where the section size is zero,
5941 but the lma is set differently to the vma. This is
5942 important, if an orphan section is placed after an
5943 otherwise empty output section that has an explicit lma
5944 set, we want that lma reflected in the orphans lma. */
5945 if (((!IGNORE_SECTION (os->bfd_section)
5946 && (os->bfd_section->size != 0
5947 || (r->last_os == NULL
5948 && os->bfd_section->vma != os->bfd_section->lma)
5949 || (r->last_os != NULL
5950 && dot >= (r->last_os->output_section_statement
5951 .bfd_section->vma))))
5952 || os->sectype == first_overlay_section)
5953 && os->lma_region == NULL
5954 && !bfd_link_relocatable (&link_info))
5955 r->last_os = s;
5956
5957 if (bfd_is_abs_section (os->bfd_section) || os->ignored)
5958 break;
5959
5960 /* .tbss sections effectively have zero size. */
5961 if (!IS_TBSS (os->bfd_section)
5962 || bfd_link_relocatable (&link_info))
5963 dotdelta = TO_ADDR (os->bfd_section->size);
5964 else
5965 dotdelta = 0;
5966 dot += dotdelta;
5967
5968 if (os->update_dot_tree != 0)
5969 exp_fold_tree (os->update_dot_tree, bfd_abs_section_ptr, &dot);
5970
5971 /* Update dot in the region ?
5972 We only do this if the section is going to be allocated,
5973 since unallocated sections do not contribute to the region's
5974 overall size in memory. */
5975 if (os->region != NULL
5976 && (os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD)))
5977 {
5978 os->region->current = dot;
5979
5980 if (check_regions)
5981 /* Make sure the new address is within the region. */
5982 os_region_check (os, os->region, os->addr_tree,
5983 os->bfd_section->vma);
5984
5985 if (os->lma_region != NULL && os->lma_region != os->region
5986 && ((os->bfd_section->flags & SEC_LOAD)
5987 || os->align_lma_with_input))
5988 {
5989 os->lma_region->current = os->bfd_section->lma + dotdelta;
5990
5991 if (check_regions)
5992 os_region_check (os, os->lma_region, NULL,
5993 os->bfd_section->lma);
5994 }
5995 }
5996 }
5997 break;
5998
5999 case lang_constructors_statement_enum:
6000 dot = lang_size_sections_1 (&constructor_list.head,
6001 output_section_statement,
6002 fill, dot, relax, check_regions);
6003 break;
6004
6005 case lang_data_statement_enum:
6006 {
6007 unsigned int size = 0;
6008
6009 s->data_statement.output_offset =
6010 dot - output_section_statement->bfd_section->vma;
6011 s->data_statement.output_section =
6012 output_section_statement->bfd_section;
6013
6014 /* We might refer to provided symbols in the expression, and
6015 need to mark them as needed. */
6016 exp_fold_tree (s->data_statement.exp, bfd_abs_section_ptr, &dot);
6017
6018 switch (s->data_statement.type)
6019 {
6020 default:
6021 abort ();
6022 case QUAD:
6023 case SQUAD:
6024 size = QUAD_SIZE;
6025 break;
6026 case LONG:
6027 size = LONG_SIZE;
6028 break;
6029 case SHORT:
6030 size = SHORT_SIZE;
6031 break;
6032 case BYTE:
6033 size = BYTE_SIZE;
6034 break;
6035 }
6036 if (size < TO_SIZE ((unsigned) 1))
6037 size = TO_SIZE ((unsigned) 1);
6038 dot += TO_ADDR (size);
6039 if (!(output_section_statement->bfd_section->flags
6040 & SEC_FIXED_SIZE))
6041 output_section_statement->bfd_section->size
6042 = TO_SIZE (dot - output_section_statement->bfd_section->vma);
6043
6044 }
6045 break;
6046
6047 case lang_reloc_statement_enum:
6048 {
6049 int size;
6050
6051 s->reloc_statement.output_offset =
6052 dot - output_section_statement->bfd_section->vma;
6053 s->reloc_statement.output_section =
6054 output_section_statement->bfd_section;
6055 size = bfd_get_reloc_size (s->reloc_statement.howto);
6056 dot += TO_ADDR (size);
6057 if (!(output_section_statement->bfd_section->flags
6058 & SEC_FIXED_SIZE))
6059 output_section_statement->bfd_section->size
6060 = TO_SIZE (dot - output_section_statement->bfd_section->vma);
6061 }
6062 break;
6063
6064 case lang_wild_statement_enum:
6065 dot = lang_size_sections_1 (&s->wild_statement.children.head,
6066 output_section_statement,
6067 fill, dot, relax, check_regions);
6068 break;
6069
6070 case lang_object_symbols_statement_enum:
6071 link_info.create_object_symbols_section
6072 = output_section_statement->bfd_section;
6073 output_section_statement->bfd_section->flags |= SEC_KEEP;
6074 break;
6075
6076 case lang_output_statement_enum:
6077 case lang_target_statement_enum:
6078 break;
6079
6080 case lang_input_section_enum:
6081 {
6082 asection *i;
6083
6084 i = s->input_section.section;
6085 if (relax)
6086 {
6087 bool again;
6088
6089 if (!bfd_relax_section (i->owner, i, &link_info, &again))
6090 einfo (_("%F%P: can't relax section: %E\n"));
6091 if (again)
6092 *relax = true;
6093 }
6094 dot = size_input_section (prev, output_section_statement,
6095 fill, &removed, dot);
6096 }
6097 break;
6098
6099 case lang_input_statement_enum:
6100 break;
6101
6102 case lang_fill_statement_enum:
6103 s->fill_statement.output_section =
6104 output_section_statement->bfd_section;
6105
6106 fill = s->fill_statement.fill;
6107 break;
6108
6109 case lang_assignment_statement_enum:
6110 {
6111 bfd_vma newdot = dot;
6112 etree_type *tree = s->assignment_statement.exp;
6113
6114 expld.dataseg.relro = exp_seg_relro_none;
6115
6116 exp_fold_tree (tree,
6117 output_section_statement->bfd_section,
6118 &newdot);
6119
6120 ldlang_check_relro_region (s);
6121
6122 expld.dataseg.relro = exp_seg_relro_none;
6123
6124 /* This symbol may be relative to this section. */
6125 if ((tree->type.node_class == etree_provided
6126 || tree->type.node_class == etree_assign)
6127 && (tree->assign.dst [0] != '.'
6128 || tree->assign.dst [1] != '\0'))
6129 output_section_statement->update_dot = 1;
6130
6131 if (!output_section_statement->ignored)
6132 {
6133 if (output_section_statement == abs_output_section)
6134 {
6135 /* If we don't have an output section, then just adjust
6136 the default memory address. */
6137 lang_memory_region_lookup (DEFAULT_MEMORY_REGION,
6138 false)->current = newdot;
6139 }
6140 else if (newdot != dot)
6141 {
6142 /* Insert a pad after this statement. We can't
6143 put the pad before when relaxing, in case the
6144 assignment references dot. */
6145 insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
6146 output_section_statement->bfd_section, dot);
6147
6148 /* Don't neuter the pad below when relaxing. */
6149 s = s->header.next;
6150
6151 /* If dot is advanced, this implies that the section
6152 should have space allocated to it, unless the
6153 user has explicitly stated that the section
6154 should not be allocated. */
6155 if (output_section_statement->sectype != noalloc_section
6156 && (output_section_statement->sectype != noload_section
6157 || (bfd_get_flavour (link_info.output_bfd)
6158 == bfd_target_elf_flavour)))
6159 output_section_statement->bfd_section->flags |= SEC_ALLOC;
6160 }
6161 dot = newdot;
6162 }
6163 }
6164 break;
6165
6166 case lang_padding_statement_enum:
6167 /* If this is the first time lang_size_sections is called,
6168 we won't have any padding statements. If this is the
6169 second or later passes when relaxing, we should allow
6170 padding to shrink. If padding is needed on this pass, it
6171 will be added back in. */
6172 s->padding_statement.size = 0;
6173
6174 /* Make sure output_offset is valid. If relaxation shrinks
6175 the section and this pad isn't needed, it's possible to
6176 have output_offset larger than the final size of the
6177 section. bfd_set_section_contents will complain even for
6178 a pad size of zero. */
6179 s->padding_statement.output_offset
6180 = dot - output_section_statement->bfd_section->vma;
6181 break;
6182
6183 case lang_group_statement_enum:
6184 dot = lang_size_sections_1 (&s->group_statement.children.head,
6185 output_section_statement,
6186 fill, dot, relax, check_regions);
6187 break;
6188
6189 case lang_insert_statement_enum:
6190 break;
6191
6192 /* We can only get here when relaxing is turned on. */
6193 case lang_address_statement_enum:
6194 break;
6195
6196 default:
6197 FAIL ();
6198 break;
6199 }
6200
6201 /* If an input section doesn't fit in the current output
6202 section, remove it from the list. Handle the case where we
6203 have to remove an input_section statement here: there is a
6204 special case to remove the first element of the list. */
6205 if (link_info.non_contiguous_regions && removed)
6206 {
6207 /* If we removed the first element during the previous
6208 iteration, override the loop assignment of prev_s. */
6209 if (removed_prev_s)
6210 prev_s = NULL;
6211
6212 if (prev_s)
6213 {
6214 /* If there was a real previous input section, just skip
6215 the current one. */
6216 prev_s->header.next=s->header.next;
6217 s = prev_s;
6218 removed_prev_s = false;
6219 }
6220 else
6221 {
6222 /* Remove the first input section of the list. */
6223 *prev = s->header.next;
6224 removed_prev_s = true;
6225 }
6226
6227 /* Move to next element, unless we removed the head of the
6228 list. */
6229 if (!removed_prev_s)
6230 prev = &s->header.next;
6231 }
6232 else
6233 {
6234 prev = &s->header.next;
6235 removed_prev_s = false;
6236 }
6237 }
6238 return dot;
6239 }
6240
6241 /* Callback routine that is used in _bfd_elf_map_sections_to_segments.
6242 The BFD library has set NEW_SEGMENT to TRUE iff it thinks that
6243 CURRENT_SECTION and PREVIOUS_SECTION ought to be placed into different
6244 segments. We are allowed an opportunity to override this decision. */
6245
6246 bool
6247 ldlang_override_segment_assignment (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6248 bfd *abfd ATTRIBUTE_UNUSED,
6249 asection *current_section,
6250 asection *previous_section,
6251 bool new_segment)
6252 {
6253 lang_output_section_statement_type *cur;
6254 lang_output_section_statement_type *prev;
6255
6256 /* The checks below are only necessary when the BFD library has decided
6257 that the two sections ought to be placed into the same segment. */
6258 if (new_segment)
6259 return true;
6260
6261 /* Paranoia checks. */
6262 if (current_section == NULL || previous_section == NULL)
6263 return new_segment;
6264
6265 /* If this flag is set, the target never wants code and non-code
6266 sections comingled in the same segment. */
6267 if (config.separate_code
6268 && ((current_section->flags ^ previous_section->flags) & SEC_CODE))
6269 return true;
6270
6271 /* Find the memory regions associated with the two sections.
6272 We call lang_output_section_find() here rather than scanning the list
6273 of output sections looking for a matching section pointer because if
6274 we have a large number of sections then a hash lookup is faster. */
6275 cur = lang_output_section_find (current_section->name);
6276 prev = lang_output_section_find (previous_section->name);
6277
6278 /* More paranoia. */
6279 if (cur == NULL || prev == NULL)
6280 return new_segment;
6281
6282 /* If the regions are different then force the sections to live in
6283 different segments. See the email thread starting at the following
6284 URL for the reasons why this is necessary:
6285 http://sourceware.org/ml/binutils/2007-02/msg00216.html */
6286 return cur->region != prev->region;
6287 }
6288
6289 void
6290 one_lang_size_sections_pass (bool *relax, bool check_regions)
6291 {
6292 lang_statement_iteration++;
6293 if (expld.phase != lang_mark_phase_enum)
6294 lang_sizing_iteration++;
6295 lang_size_sections_1 (&statement_list.head, abs_output_section,
6296 0, 0, relax, check_regions);
6297 }
6298
6299 static bool
6300 lang_size_segment (void)
6301 {
6302 /* If XXX_SEGMENT_ALIGN XXX_SEGMENT_END pair was seen, check whether
6303 a page could be saved in the data segment. */
6304 seg_align_type *seg = &expld.dataseg;
6305 bfd_vma first, last;
6306
6307 first = -seg->base & (seg->commonpagesize - 1);
6308 last = seg->end & (seg->commonpagesize - 1);
6309 if (first && last
6310 && ((seg->base & ~(seg->commonpagesize - 1))
6311 != (seg->end & ~(seg->commonpagesize - 1)))
6312 && first + last <= seg->commonpagesize)
6313 {
6314 seg->phase = exp_seg_adjust;
6315 return true;
6316 }
6317
6318 seg->phase = exp_seg_done;
6319 return false;
6320 }
6321
6322 static bfd_vma
6323 lang_size_relro_segment_1 (void)
6324 {
6325 seg_align_type *seg = &expld.dataseg;
6326 bfd_vma relro_end, desired_end;
6327 asection *sec;
6328
6329 /* Compute the expected PT_GNU_RELRO/PT_LOAD segment end. */
6330 relro_end = (seg->relro_end + seg->relropagesize - 1) & -seg->relropagesize;
6331
6332 /* Adjust by the offset arg of XXX_SEGMENT_RELRO_END. */
6333 desired_end = relro_end - seg->relro_offset;
6334
6335 /* For sections in the relro segment.. */
6336 for (sec = link_info.output_bfd->section_last; sec; sec = sec->prev)
6337 if ((sec->flags & SEC_ALLOC) != 0
6338 && sec->vma >= seg->base
6339 && sec->vma < seg->relro_end - seg->relro_offset)
6340 {
6341 /* Where do we want to put this section so that it ends as
6342 desired? */
6343 bfd_vma start, end, bump;
6344
6345 end = start = sec->vma;
6346 if (!IS_TBSS (sec))
6347 end += TO_ADDR (sec->size);
6348 bump = desired_end - end;
6349 /* We'd like to increase START by BUMP, but we must heed
6350 alignment so the increase might be less than optimum. */
6351 start += bump;
6352 start &= ~(((bfd_vma) 1 << sec->alignment_power) - 1);
6353 /* This is now the desired end for the previous section. */
6354 desired_end = start;
6355 }
6356
6357 seg->phase = exp_seg_relro_adjust;
6358 ASSERT (desired_end >= seg->base);
6359 seg->base = desired_end;
6360 return relro_end;
6361 }
6362
6363 static bool
6364 lang_size_relro_segment (bool *relax, bool check_regions)
6365 {
6366 bool do_reset = false;
6367
6368 if (link_info.relro && expld.dataseg.relro_end)
6369 {
6370 bfd_vma data_initial_base = expld.dataseg.base;
6371 bfd_vma data_relro_end = lang_size_relro_segment_1 ();
6372
6373 lang_reset_memory_regions ();
6374 one_lang_size_sections_pass (relax, check_regions);
6375
6376 /* Assignments to dot, or to output section address in a user
6377 script have increased padding over the original. Revert. */
6378 if (expld.dataseg.relro_end > data_relro_end)
6379 {
6380 expld.dataseg.base = data_initial_base;
6381 do_reset = true;
6382 }
6383 }
6384 else if (lang_size_segment ())
6385 do_reset = true;
6386
6387 return do_reset;
6388 }
6389
6390 void
6391 lang_size_sections (bool *relax, bool check_regions)
6392 {
6393 expld.phase = lang_allocating_phase_enum;
6394 expld.dataseg.phase = exp_seg_none;
6395
6396 one_lang_size_sections_pass (relax, check_regions);
6397
6398 if (expld.dataseg.phase != exp_seg_end_seen)
6399 expld.dataseg.phase = exp_seg_done;
6400
6401 if (expld.dataseg.phase == exp_seg_end_seen)
6402 {
6403 bool do_reset
6404 = lang_size_relro_segment (relax, check_regions);
6405
6406 if (do_reset)
6407 {
6408 lang_reset_memory_regions ();
6409 one_lang_size_sections_pass (relax, check_regions);
6410 }
6411
6412 if (link_info.relro && expld.dataseg.relro_end)
6413 {
6414 link_info.relro_start = expld.dataseg.base;
6415 link_info.relro_end = expld.dataseg.relro_end;
6416 }
6417 }
6418 }
6419
6420 static lang_output_section_statement_type *current_section;
6421 static lang_assignment_statement_type *current_assign;
6422 static bool prefer_next_section;
6423
6424 /* Worker function for lang_do_assignments. Recursiveness goes here. */
6425
6426 static bfd_vma
6427 lang_do_assignments_1 (lang_statement_union_type *s,
6428 lang_output_section_statement_type *current_os,
6429 fill_type *fill,
6430 bfd_vma dot,
6431 bool *found_end)
6432 {
6433 for (; s != NULL; s = s->header.next)
6434 {
6435 switch (s->header.type)
6436 {
6437 case lang_constructors_statement_enum:
6438 dot = lang_do_assignments_1 (constructor_list.head,
6439 current_os, fill, dot, found_end);
6440 break;
6441
6442 case lang_output_section_statement_enum:
6443 {
6444 lang_output_section_statement_type *os;
6445 bfd_vma newdot;
6446
6447 os = &(s->output_section_statement);
6448 os->after_end = *found_end;
6449 init_opb (os->bfd_section);
6450 newdot = dot;
6451 if (os->bfd_section != NULL)
6452 {
6453 if (!os->ignored && (os->bfd_section->flags & SEC_ALLOC) != 0)
6454 {
6455 current_section = os;
6456 prefer_next_section = false;
6457 }
6458 newdot = os->bfd_section->vma;
6459 }
6460 newdot = lang_do_assignments_1 (os->children.head,
6461 os, os->fill, newdot, found_end);
6462 if (!os->ignored)
6463 {
6464 if (os->bfd_section != NULL)
6465 {
6466 newdot = os->bfd_section->vma;
6467
6468 /* .tbss sections effectively have zero size. */
6469 if (!IS_TBSS (os->bfd_section)
6470 || bfd_link_relocatable (&link_info))
6471 newdot += TO_ADDR (os->bfd_section->size);
6472
6473 if (os->update_dot_tree != NULL)
6474 exp_fold_tree (os->update_dot_tree,
6475 bfd_abs_section_ptr, &newdot);
6476 }
6477 dot = newdot;
6478 }
6479 }
6480 break;
6481
6482 case lang_wild_statement_enum:
6483
6484 dot = lang_do_assignments_1 (s->wild_statement.children.head,
6485 current_os, fill, dot, found_end);
6486 break;
6487
6488 case lang_object_symbols_statement_enum:
6489 case lang_output_statement_enum:
6490 case lang_target_statement_enum:
6491 break;
6492
6493 case lang_data_statement_enum:
6494 exp_fold_tree (s->data_statement.exp, bfd_abs_section_ptr, &dot);
6495 if (expld.result.valid_p)
6496 {
6497 s->data_statement.value = expld.result.value;
6498 if (expld.result.section != NULL)
6499 s->data_statement.value += expld.result.section->vma;
6500 }
6501 else if (expld.phase == lang_final_phase_enum)
6502 einfo (_("%F%P: invalid data statement\n"));
6503 {
6504 unsigned int size;
6505 switch (s->data_statement.type)
6506 {
6507 default:
6508 abort ();
6509 case QUAD:
6510 case SQUAD:
6511 size = QUAD_SIZE;
6512 break;
6513 case LONG:
6514 size = LONG_SIZE;
6515 break;
6516 case SHORT:
6517 size = SHORT_SIZE;
6518 break;
6519 case BYTE:
6520 size = BYTE_SIZE;
6521 break;
6522 }
6523 if (size < TO_SIZE ((unsigned) 1))
6524 size = TO_SIZE ((unsigned) 1);
6525 dot += TO_ADDR (size);
6526 }
6527 break;
6528
6529 case lang_reloc_statement_enum:
6530 exp_fold_tree (s->reloc_statement.addend_exp,
6531 bfd_abs_section_ptr, &dot);
6532 if (expld.result.valid_p)
6533 s->reloc_statement.addend_value = expld.result.value;
6534 else if (expld.phase == lang_final_phase_enum)
6535 einfo (_("%F%P: invalid reloc statement\n"));
6536 dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
6537 break;
6538
6539 case lang_input_section_enum:
6540 {
6541 asection *in = s->input_section.section;
6542
6543 if ((in->flags & SEC_EXCLUDE) == 0)
6544 dot += TO_ADDR (in->size);
6545 }
6546 break;
6547
6548 case lang_input_statement_enum:
6549 break;
6550
6551 case lang_fill_statement_enum:
6552 fill = s->fill_statement.fill;
6553 break;
6554
6555 case lang_assignment_statement_enum:
6556 current_assign = &s->assignment_statement;
6557 if (current_assign->exp->type.node_class != etree_assert)
6558 {
6559 const char *p = current_assign->exp->assign.dst;
6560
6561 if (current_os == abs_output_section && p[0] == '.' && p[1] == 0)
6562 prefer_next_section = true;
6563
6564 while (*p == '_')
6565 ++p;
6566 if (strcmp (p, "end") == 0)
6567 *found_end = true;
6568 }
6569 exp_fold_tree (s->assignment_statement.exp,
6570 (current_os->bfd_section != NULL
6571 ? current_os->bfd_section : bfd_und_section_ptr),
6572 &dot);
6573 break;
6574
6575 case lang_padding_statement_enum:
6576 dot += TO_ADDR (s->padding_statement.size);
6577 break;
6578
6579 case lang_group_statement_enum:
6580 dot = lang_do_assignments_1 (s->group_statement.children.head,
6581 current_os, fill, dot, found_end);
6582 break;
6583
6584 case lang_insert_statement_enum:
6585 break;
6586
6587 case lang_address_statement_enum:
6588 break;
6589
6590 default:
6591 FAIL ();
6592 break;
6593 }
6594 }
6595 return dot;
6596 }
6597
6598 void
6599 lang_do_assignments (lang_phase_type phase)
6600 {
6601 bool found_end = false;
6602
6603 current_section = NULL;
6604 prefer_next_section = false;
6605 expld.phase = phase;
6606 lang_statement_iteration++;
6607 lang_do_assignments_1 (statement_list.head,
6608 abs_output_section, NULL, 0, &found_end);
6609 }
6610
6611 /* For an assignment statement outside of an output section statement,
6612 choose the best of neighbouring output sections to use for values
6613 of "dot". */
6614
6615 asection *
6616 section_for_dot (void)
6617 {
6618 asection *s;
6619
6620 /* Assignments belong to the previous output section, unless there
6621 has been an assignment to "dot", in which case following
6622 assignments belong to the next output section. (The assumption
6623 is that an assignment to "dot" is setting up the address for the
6624 next output section.) Except that past the assignment to "_end"
6625 we always associate with the previous section. This exception is
6626 for targets like SH that define an alloc .stack or other
6627 weirdness after non-alloc sections. */
6628 if (current_section == NULL || prefer_next_section)
6629 {
6630 lang_statement_union_type *stmt;
6631 lang_output_section_statement_type *os;
6632
6633 for (stmt = (lang_statement_union_type *) current_assign;
6634 stmt != NULL;
6635 stmt = stmt->header.next)
6636 if (stmt->header.type == lang_output_section_statement_enum)
6637 break;
6638
6639 os = stmt ? &stmt->output_section_statement : NULL;
6640 while (os != NULL
6641 && !os->after_end
6642 && (os->bfd_section == NULL
6643 || (os->bfd_section->flags & SEC_EXCLUDE) != 0
6644 || bfd_section_removed_from_list (link_info.output_bfd,
6645 os->bfd_section)))
6646 os = os->next;
6647
6648 if (current_section == NULL || os == NULL || !os->after_end)
6649 {
6650 if (os != NULL)
6651 s = os->bfd_section;
6652 else
6653 s = link_info.output_bfd->section_last;
6654 while (s != NULL
6655 && ((s->flags & SEC_ALLOC) == 0
6656 || (s->flags & SEC_THREAD_LOCAL) != 0))
6657 s = s->prev;
6658 if (s != NULL)
6659 return s;
6660
6661 return bfd_abs_section_ptr;
6662 }
6663 }
6664
6665 s = current_section->bfd_section;
6666
6667 /* The section may have been stripped. */
6668 while (s != NULL
6669 && ((s->flags & SEC_EXCLUDE) != 0
6670 || (s->flags & SEC_ALLOC) == 0
6671 || (s->flags & SEC_THREAD_LOCAL) != 0
6672 || bfd_section_removed_from_list (link_info.output_bfd, s)))
6673 s = s->prev;
6674 if (s == NULL)
6675 s = link_info.output_bfd->sections;
6676 while (s != NULL
6677 && ((s->flags & SEC_ALLOC) == 0
6678 || (s->flags & SEC_THREAD_LOCAL) != 0))
6679 s = s->next;
6680 if (s != NULL)
6681 return s;
6682
6683 return bfd_abs_section_ptr;
6684 }
6685
6686 /* Array of __start/__stop/.startof./.sizeof/ symbols. */
6687
6688 static struct bfd_link_hash_entry **start_stop_syms;
6689 static size_t start_stop_count = 0;
6690 static size_t start_stop_alloc = 0;
6691
6692 /* Give start/stop SYMBOL for SEC a preliminary definition, and add it
6693 to start_stop_syms. */
6694
6695 static void
6696 lang_define_start_stop (const char *symbol, asection *sec)
6697 {
6698 struct bfd_link_hash_entry *h;
6699
6700 h = bfd_define_start_stop (link_info.output_bfd, &link_info, symbol, sec);
6701 if (h != NULL)
6702 {
6703 if (start_stop_count == start_stop_alloc)
6704 {
6705 start_stop_alloc = 2 * start_stop_alloc + 10;
6706 start_stop_syms
6707 = xrealloc (start_stop_syms,
6708 start_stop_alloc * sizeof (*start_stop_syms));
6709 }
6710 start_stop_syms[start_stop_count++] = h;
6711 }
6712 }
6713
6714 /* Check for input sections whose names match references to
6715 __start_SECNAME or __stop_SECNAME symbols. Give the symbols
6716 preliminary definitions. */
6717
6718 static void
6719 lang_init_start_stop (void)
6720 {
6721 bfd *abfd;
6722 asection *s;
6723 char leading_char = bfd_get_symbol_leading_char (link_info.output_bfd);
6724
6725 for (abfd = link_info.input_bfds; abfd != NULL; abfd = abfd->link.next)
6726 for (s = abfd->sections; s != NULL; s = s->next)
6727 {
6728 const char *ps;
6729 const char *secname = s->name;
6730
6731 for (ps = secname; *ps != '\0'; ps++)
6732 if (!ISALNUM ((unsigned char) *ps) && *ps != '_')
6733 break;
6734 if (*ps == '\0')
6735 {
6736 char *symbol = (char *) xmalloc (10 + strlen (secname));
6737
6738 symbol[0] = leading_char;
6739 sprintf (symbol + (leading_char != 0), "__start_%s", secname);
6740 lang_define_start_stop (symbol, s);
6741
6742 symbol[1] = leading_char;
6743 memcpy (symbol + 1 + (leading_char != 0), "__stop", 6);
6744 lang_define_start_stop (symbol + 1, s);
6745
6746 free (symbol);
6747 }
6748 }
6749 }
6750
6751 /* Iterate over start_stop_syms. */
6752
6753 static void
6754 foreach_start_stop (void (*func) (struct bfd_link_hash_entry *))
6755 {
6756 size_t i;
6757
6758 for (i = 0; i < start_stop_count; ++i)
6759 func (start_stop_syms[i]);
6760 }
6761
6762 /* __start and __stop symbols are only supposed to be defined by the
6763 linker for orphan sections, but we now extend that to sections that
6764 map to an output section of the same name. The symbols were
6765 defined early for --gc-sections, before we mapped input to output
6766 sections, so undo those that don't satisfy this rule. */
6767
6768 static void
6769 undef_start_stop (struct bfd_link_hash_entry *h)
6770 {
6771 if (h->ldscript_def)
6772 return;
6773
6774 if (h->u.def.section->output_section == NULL
6775 || h->u.def.section->output_section->owner != link_info.output_bfd
6776 || strcmp (h->u.def.section->name,
6777 h->u.def.section->output_section->name) != 0)
6778 {
6779 asection *sec = bfd_get_section_by_name (link_info.output_bfd,
6780 h->u.def.section->name);
6781 if (sec != NULL)
6782 {
6783 /* When there are more than one input sections with the same
6784 section name, SECNAME, linker picks the first one to define
6785 __start_SECNAME and __stop_SECNAME symbols. When the first
6786 input section is removed by comdat group, we need to check
6787 if there is still an output section with section name
6788 SECNAME. */
6789 asection *i;
6790 for (i = sec->map_head.s; i != NULL; i = i->map_head.s)
6791 if (strcmp (h->u.def.section->name, i->name) == 0)
6792 {
6793 h->u.def.section = i;
6794 return;
6795 }
6796 }
6797 h->type = bfd_link_hash_undefined;
6798 h->u.undef.abfd = NULL;
6799 if (is_elf_hash_table (link_info.hash))
6800 {
6801 const struct elf_backend_data *bed;
6802 struct elf_link_hash_entry *eh = (struct elf_link_hash_entry *) h;
6803 unsigned int was_forced = eh->forced_local;
6804
6805 bed = get_elf_backend_data (link_info.output_bfd);
6806 (*bed->elf_backend_hide_symbol) (&link_info, eh, true);
6807 if (!eh->ref_regular_nonweak)
6808 h->type = bfd_link_hash_undefweak;
6809 eh->def_regular = 0;
6810 eh->forced_local = was_forced;
6811 }
6812 }
6813 }
6814
6815 static void
6816 lang_undef_start_stop (void)
6817 {
6818 foreach_start_stop (undef_start_stop);
6819 }
6820
6821 /* Check for output sections whose names match references to
6822 .startof.SECNAME or .sizeof.SECNAME symbols. Give the symbols
6823 preliminary definitions. */
6824
6825 static void
6826 lang_init_startof_sizeof (void)
6827 {
6828 asection *s;
6829
6830 for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
6831 {
6832 const char *secname = s->name;
6833 char *symbol = (char *) xmalloc (10 + strlen (secname));
6834
6835 sprintf (symbol, ".startof.%s", secname);
6836 lang_define_start_stop (symbol, s);
6837
6838 memcpy (symbol + 1, ".size", 5);
6839 lang_define_start_stop (symbol + 1, s);
6840 free (symbol);
6841 }
6842 }
6843
6844 /* Set .startof., .sizeof., __start and __stop symbols final values. */
6845
6846 static void
6847 set_start_stop (struct bfd_link_hash_entry *h)
6848 {
6849 if (h->ldscript_def
6850 || h->type != bfd_link_hash_defined)
6851 return;
6852
6853 if (h->root.string[0] == '.')
6854 {
6855 /* .startof. or .sizeof. symbol.
6856 .startof. already has final value. */
6857 if (h->root.string[2] == 'i')
6858 {
6859 /* .sizeof. */
6860 h->u.def.value = TO_ADDR (h->u.def.section->size);
6861 h->u.def.section = bfd_abs_section_ptr;
6862 }
6863 }
6864 else
6865 {
6866 /* __start or __stop symbol. */
6867 int has_lead = bfd_get_symbol_leading_char (link_info.output_bfd) != 0;
6868
6869 h->u.def.section = h->u.def.section->output_section;
6870 if (h->root.string[4 + has_lead] == 'o')
6871 {
6872 /* __stop_ */
6873 h->u.def.value = TO_ADDR (h->u.def.section->size);
6874 }
6875 }
6876 }
6877
6878 static void
6879 lang_finalize_start_stop (void)
6880 {
6881 foreach_start_stop (set_start_stop);
6882 }
6883
6884 static void
6885 lang_symbol_tweaks (void)
6886 {
6887 /* Give initial values for __start and __stop symbols, so that ELF
6888 gc_sections will keep sections referenced by these symbols. Must
6889 be done before lang_do_assignments. */
6890 if (config.build_constructors)
6891 lang_init_start_stop ();
6892
6893 /* Make __ehdr_start hidden, and set def_regular even though it is
6894 likely undefined at this stage. For lang_check_relocs. */
6895 if (is_elf_hash_table (link_info.hash)
6896 && !bfd_link_relocatable (&link_info))
6897 {
6898 struct elf_link_hash_entry *h = (struct elf_link_hash_entry *)
6899 bfd_link_hash_lookup (link_info.hash, "__ehdr_start",
6900 false, false, true);
6901
6902 /* Only adjust the export class if the symbol was referenced
6903 and not defined, otherwise leave it alone. */
6904 if (h != NULL
6905 && (h->root.type == bfd_link_hash_new
6906 || h->root.type == bfd_link_hash_undefined
6907 || h->root.type == bfd_link_hash_undefweak
6908 || h->root.type == bfd_link_hash_common))
6909 {
6910 const struct elf_backend_data *bed;
6911 bed = get_elf_backend_data (link_info.output_bfd);
6912 (*bed->elf_backend_hide_symbol) (&link_info, h, true);
6913 if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
6914 h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
6915 h->def_regular = 1;
6916 h->root.linker_def = 1;
6917 h->root.rel_from_abs = 1;
6918 }
6919 }
6920 }
6921
6922 static void
6923 lang_end (void)
6924 {
6925 struct bfd_link_hash_entry *h;
6926 bool warn;
6927
6928 if ((bfd_link_relocatable (&link_info) && !link_info.gc_sections)
6929 || bfd_link_dll (&link_info))
6930 warn = entry_from_cmdline;
6931 else
6932 warn = true;
6933
6934 /* Force the user to specify a root when generating a relocatable with
6935 --gc-sections, unless --gc-keep-exported was also given. */
6936 if (bfd_link_relocatable (&link_info)
6937 && link_info.gc_sections
6938 && !link_info.gc_keep_exported)
6939 {
6940 struct bfd_sym_chain *sym;
6941
6942 for (sym = link_info.gc_sym_list; sym != NULL; sym = sym->next)
6943 {
6944 h = bfd_link_hash_lookup (link_info.hash, sym->name,
6945 false, false, false);
6946 if (h != NULL
6947 && (h->type == bfd_link_hash_defined
6948 || h->type == bfd_link_hash_defweak)
6949 && !bfd_is_const_section (h->u.def.section))
6950 break;
6951 }
6952 if (!sym)
6953 einfo (_("%F%P: --gc-sections requires a defined symbol root "
6954 "specified by -e or -u\n"));
6955 }
6956
6957 if (entry_symbol.name == NULL)
6958 {
6959 /* No entry has been specified. Look for the default entry, but
6960 don't warn if we don't find it. */
6961 entry_symbol.name = entry_symbol_default;
6962 warn = false;
6963 }
6964
6965 h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
6966 false, false, true);
6967 if (h != NULL
6968 && (h->type == bfd_link_hash_defined
6969 || h->type == bfd_link_hash_defweak)
6970 && h->u.def.section->output_section != NULL)
6971 {
6972 bfd_vma val;
6973
6974 val = (h->u.def.value
6975 + bfd_section_vma (h->u.def.section->output_section)
6976 + h->u.def.section->output_offset);
6977 if (!bfd_set_start_address (link_info.output_bfd, val))
6978 einfo (_("%F%P: %s: can't set start address\n"), entry_symbol.name);
6979 }
6980 else
6981 {
6982 bfd_vma val;
6983 const char *send;
6984
6985 /* We couldn't find the entry symbol. Try parsing it as a
6986 number. */
6987 val = bfd_scan_vma (entry_symbol.name, &send, 0);
6988 if (*send == '\0')
6989 {
6990 if (!bfd_set_start_address (link_info.output_bfd, val))
6991 einfo (_("%F%P: can't set start address\n"));
6992 }
6993 /* BZ 2004952: Only use the start of the entry section for executables. */
6994 else if bfd_link_executable (&link_info)
6995 {
6996 asection *ts;
6997
6998 /* Can't find the entry symbol, and it's not a number. Use
6999 the first address in the text section. */
7000 ts = bfd_get_section_by_name (link_info.output_bfd, entry_section);
7001 if (ts != NULL)
7002 {
7003 if (warn)
7004 einfo (_("%P: warning: cannot find entry symbol %s;"
7005 " defaulting to %V\n"),
7006 entry_symbol.name,
7007 bfd_section_vma (ts));
7008 if (!bfd_set_start_address (link_info.output_bfd,
7009 bfd_section_vma (ts)))
7010 einfo (_("%F%P: can't set start address\n"));
7011 }
7012 else
7013 {
7014 if (warn)
7015 einfo (_("%P: warning: cannot find entry symbol %s;"
7016 " not setting start address\n"),
7017 entry_symbol.name);
7018 }
7019 }
7020 else
7021 {
7022 if (warn)
7023 einfo (_("%P: warning: cannot find entry symbol %s;"
7024 " not setting start address\n"),
7025 entry_symbol.name);
7026 }
7027 }
7028 }
7029
7030 /* This is a small function used when we want to ignore errors from
7031 BFD. */
7032
7033 static void
7034 ignore_bfd_errors (const char *fmt ATTRIBUTE_UNUSED,
7035 va_list ap ATTRIBUTE_UNUSED)
7036 {
7037 /* Don't do anything. */
7038 }
7039
7040 /* Check that the architecture of all the input files is compatible
7041 with the output file. Also call the backend to let it do any
7042 other checking that is needed. */
7043
7044 static void
7045 lang_check (void)
7046 {
7047 lang_input_statement_type *file;
7048 bfd *input_bfd;
7049 const bfd_arch_info_type *compatible;
7050
7051 for (file = (void *) file_chain.head;
7052 file != NULL;
7053 file = file->next)
7054 {
7055 #if BFD_SUPPORTS_PLUGINS
7056 /* Don't check format of files claimed by plugin. */
7057 if (file->flags.claimed)
7058 continue;
7059 #endif /* BFD_SUPPORTS_PLUGINS */
7060 input_bfd = file->the_bfd;
7061 compatible
7062 = bfd_arch_get_compatible (input_bfd, link_info.output_bfd,
7063 command_line.accept_unknown_input_arch);
7064
7065 /* In general it is not possible to perform a relocatable
7066 link between differing object formats when the input
7067 file has relocations, because the relocations in the
7068 input format may not have equivalent representations in
7069 the output format (and besides BFD does not translate
7070 relocs for other link purposes than a final link). */
7071 if (!file->flags.just_syms
7072 && (bfd_link_relocatable (&link_info)
7073 || link_info.emitrelocations)
7074 && (compatible == NULL
7075 || (bfd_get_flavour (input_bfd)
7076 != bfd_get_flavour (link_info.output_bfd)))
7077 && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
7078 {
7079 einfo (_("%F%P: relocatable linking with relocations from"
7080 " format %s (%pB) to format %s (%pB) is not supported\n"),
7081 bfd_get_target (input_bfd), input_bfd,
7082 bfd_get_target (link_info.output_bfd), link_info.output_bfd);
7083 /* einfo with %F exits. */
7084 }
7085
7086 if (compatible == NULL)
7087 {
7088 if (command_line.warn_mismatch)
7089 einfo (_("%X%P: %s architecture of input file `%pB'"
7090 " is incompatible with %s output\n"),
7091 bfd_printable_name (input_bfd), input_bfd,
7092 bfd_printable_name (link_info.output_bfd));
7093 }
7094
7095 /* If the input bfd has no contents, it shouldn't set the
7096 private data of the output bfd. */
7097 else if (!file->flags.just_syms
7098 && ((input_bfd->flags & DYNAMIC) != 0
7099 || bfd_count_sections (input_bfd) != 0))
7100 {
7101 bfd_error_handler_type pfn = NULL;
7102
7103 /* If we aren't supposed to warn about mismatched input
7104 files, temporarily set the BFD error handler to a
7105 function which will do nothing. We still want to call
7106 bfd_merge_private_bfd_data, since it may set up
7107 information which is needed in the output file. */
7108 if (!command_line.warn_mismatch)
7109 pfn = bfd_set_error_handler (ignore_bfd_errors);
7110 if (!bfd_merge_private_bfd_data (input_bfd, &link_info))
7111 {
7112 if (command_line.warn_mismatch)
7113 einfo (_("%X%P: failed to merge target specific data"
7114 " of file %pB\n"), input_bfd);
7115 }
7116 if (!command_line.warn_mismatch)
7117 bfd_set_error_handler (pfn);
7118 }
7119 }
7120 }
7121
7122 /* Look through all the global common symbols and attach them to the
7123 correct section. The -sort-common command line switch may be used
7124 to roughly sort the entries by alignment. */
7125
7126 static void
7127 lang_common (void)
7128 {
7129 if (link_info.inhibit_common_definition)
7130 return;
7131 if (bfd_link_relocatable (&link_info)
7132 && !command_line.force_common_definition)
7133 return;
7134
7135 if (!config.sort_common)
7136 bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
7137 else
7138 {
7139 unsigned int power;
7140
7141 if (config.sort_common == sort_descending)
7142 {
7143 for (power = 4; power > 0; power--)
7144 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7145
7146 power = 0;
7147 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7148 }
7149 else
7150 {
7151 for (power = 0; power <= 4; power++)
7152 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7153
7154 power = (unsigned int) -1;
7155 bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7156 }
7157 }
7158 }
7159
7160 /* Place one common symbol in the correct section. */
7161
7162 static bool
7163 lang_one_common (struct bfd_link_hash_entry *h, void *info)
7164 {
7165 unsigned int power_of_two;
7166 bfd_vma size;
7167 asection *section;
7168
7169 if (h->type != bfd_link_hash_common)
7170 return true;
7171
7172 size = h->u.c.size;
7173 power_of_two = h->u.c.p->alignment_power;
7174
7175 if (config.sort_common == sort_descending
7176 && power_of_two < *(unsigned int *) info)
7177 return true;
7178 else if (config.sort_common == sort_ascending
7179 && power_of_two > *(unsigned int *) info)
7180 return true;
7181
7182 section = h->u.c.p->section;
7183 if (!bfd_define_common_symbol (link_info.output_bfd, &link_info, h))
7184 einfo (_("%F%P: could not define common symbol `%pT': %E\n"),
7185 h->root.string);
7186
7187 if (config.map_file != NULL)
7188 {
7189 static bool header_printed;
7190 int len;
7191 char *name;
7192 char buf[32];
7193
7194 if (!header_printed)
7195 {
7196 minfo (_("\nAllocating common symbols\n"));
7197 minfo (_("Common symbol size file\n\n"));
7198 header_printed = true;
7199 }
7200
7201 name = bfd_demangle (link_info.output_bfd, h->root.string,
7202 DMGL_ANSI | DMGL_PARAMS);
7203 if (name == NULL)
7204 {
7205 minfo ("%s", h->root.string);
7206 len = strlen (h->root.string);
7207 }
7208 else
7209 {
7210 minfo ("%s", name);
7211 len = strlen (name);
7212 free (name);
7213 }
7214
7215 if (len >= 19)
7216 {
7217 print_nl ();
7218 len = 0;
7219 }
7220
7221 sprintf (buf, "%" PRIx64, (uint64_t) size);
7222 fprintf (config.map_file, "%*s0x%-16s", 20 - len, "", buf);
7223
7224 minfo ("%pB\n", section->owner);
7225 }
7226
7227 return true;
7228 }
7229
7230 /* Handle a single orphan section S, placing the orphan into an appropriate
7231 output section. The effects of the --orphan-handling command line
7232 option are handled here. */
7233
7234 static void
7235 ldlang_place_orphan (asection *s)
7236 {
7237 if (config.orphan_handling == orphan_handling_discard)
7238 {
7239 lang_output_section_statement_type *os;
7240 os = lang_output_section_statement_lookup (DISCARD_SECTION_NAME, 0, 1);
7241 if (os->addr_tree == NULL
7242 && (bfd_link_relocatable (&link_info)
7243 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7244 os->addr_tree = exp_intop (0);
7245 lang_add_section (&os->children, s, NULL, NULL, os);
7246 }
7247 else
7248 {
7249 lang_output_section_statement_type *os;
7250 const char *name = s->name;
7251 int constraint = 0;
7252
7253 if (config.orphan_handling == orphan_handling_error)
7254 einfo (_("%X%P: error: unplaced orphan section `%pA' from `%pB'\n"),
7255 s, s->owner);
7256
7257 if (config.unique_orphan_sections || unique_section_p (s, NULL))
7258 constraint = SPECIAL;
7259
7260 os = ldemul_place_orphan (s, name, constraint);
7261 if (os == NULL)
7262 {
7263 os = lang_output_section_statement_lookup (name, constraint, 1);
7264 if (os->addr_tree == NULL
7265 && (bfd_link_relocatable (&link_info)
7266 || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7267 os->addr_tree = exp_intop (0);
7268 lang_add_section (&os->children, s, NULL, NULL, os);
7269 }
7270
7271 if (config.orphan_handling == orphan_handling_warn)
7272 einfo (_("%P: warning: orphan section `%pA' from `%pB' being "
7273 "placed in section `%s'\n"),
7274 s, s->owner, os->name);
7275 }
7276 }
7277
7278 /* Run through the input files and ensure that every input section has
7279 somewhere to go. If one is found without a destination then create
7280 an input request and place it into the statement tree. */
7281
7282 static void
7283 lang_place_orphans (void)
7284 {
7285 LANG_FOR_EACH_INPUT_STATEMENT (file)
7286 {
7287 asection *s;
7288
7289 for (s = file->the_bfd->sections; s != NULL; s = s->next)
7290 {
7291 if (s->output_section == NULL)
7292 {
7293 /* This section of the file is not attached, root
7294 around for a sensible place for it to go. */
7295
7296 if (file->flags.just_syms)
7297 bfd_link_just_syms (file->the_bfd, s, &link_info);
7298 else if (lang_discard_section_p (s))
7299 s->output_section = bfd_abs_section_ptr;
7300 else if (strcmp (s->name, "COMMON") == 0)
7301 {
7302 /* This is a lonely common section which must have
7303 come from an archive. We attach to the section
7304 with the wildcard. */
7305 if (!bfd_link_relocatable (&link_info)
7306 || command_line.force_common_definition)
7307 {
7308 if (default_common_section == NULL)
7309 default_common_section
7310 = lang_output_section_statement_lookup (".bss", 0, 1);
7311 lang_add_section (&default_common_section->children, s,
7312 NULL, NULL, default_common_section);
7313 }
7314 }
7315 else
7316 ldlang_place_orphan (s);
7317 }
7318 }
7319 }
7320 }
7321
7322 void
7323 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
7324 {
7325 flagword *ptr_flags;
7326
7327 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7328
7329 while (*flags)
7330 {
7331 switch (*flags)
7332 {
7333 /* PR 17900: An exclamation mark in the attributes reverses
7334 the sense of any of the attributes that follow. */
7335 case '!':
7336 invert = !invert;
7337 ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7338 break;
7339
7340 case 'A': case 'a':
7341 *ptr_flags |= SEC_ALLOC;
7342 break;
7343
7344 case 'R': case 'r':
7345 *ptr_flags |= SEC_READONLY;
7346 break;
7347
7348 case 'W': case 'w':
7349 *ptr_flags |= SEC_DATA;
7350 break;
7351
7352 case 'X': case 'x':
7353 *ptr_flags |= SEC_CODE;
7354 break;
7355
7356 case 'L': case 'l':
7357 case 'I': case 'i':
7358 *ptr_flags |= SEC_LOAD;
7359 break;
7360
7361 default:
7362 einfo (_("%F%P: invalid character %c (%d) in flags\n"),
7363 *flags, *flags);
7364 break;
7365 }
7366 flags++;
7367 }
7368 }
7369
7370 /* Call a function on each real input file. This function will be
7371 called on an archive, but not on the elements. */
7372
7373 void
7374 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
7375 {
7376 lang_input_statement_type *f;
7377
7378 for (f = (void *) input_file_chain.head;
7379 f != NULL;
7380 f = f->next_real_file)
7381 if (f->flags.real)
7382 func (f);
7383 }
7384
7385 /* Call a function on each real file. The function will be called on
7386 all the elements of an archive which are included in the link, but
7387 will not be called on the archive file itself. */
7388
7389 void
7390 lang_for_each_file (void (*func) (lang_input_statement_type *))
7391 {
7392 LANG_FOR_EACH_INPUT_STATEMENT (f)
7393 {
7394 if (f->flags.real)
7395 func (f);
7396 }
7397 }
7398
7399 void
7400 ldlang_add_file (lang_input_statement_type *entry)
7401 {
7402 lang_statement_append (&file_chain, entry, &entry->next);
7403
7404 /* The BFD linker needs to have a list of all input BFDs involved in
7405 a link. */
7406 ASSERT (link_info.input_bfds_tail != &entry->the_bfd->link.next
7407 && entry->the_bfd->link.next == NULL);
7408 ASSERT (entry->the_bfd != link_info.output_bfd);
7409
7410 *link_info.input_bfds_tail = entry->the_bfd;
7411 link_info.input_bfds_tail = &entry->the_bfd->link.next;
7412 bfd_set_usrdata (entry->the_bfd, entry);
7413 bfd_set_gp_size (entry->the_bfd, g_switch_value);
7414
7415 /* Look through the sections and check for any which should not be
7416 included in the link. We need to do this now, so that we can
7417 notice when the backend linker tries to report multiple
7418 definition errors for symbols which are in sections we aren't
7419 going to link. FIXME: It might be better to entirely ignore
7420 symbols which are defined in sections which are going to be
7421 discarded. This would require modifying the backend linker for
7422 each backend which might set the SEC_LINK_ONCE flag. If we do
7423 this, we should probably handle SEC_EXCLUDE in the same way. */
7424
7425 bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
7426 }
7427
7428 void
7429 lang_add_output (const char *name, int from_script)
7430 {
7431 /* Make -o on command line override OUTPUT in script. */
7432 if (!had_output_filename || !from_script)
7433 {
7434 output_filename = name;
7435 had_output_filename = true;
7436 }
7437 }
7438
7439 lang_output_section_statement_type *
7440 lang_enter_output_section_statement (const char *output_section_statement_name,
7441 etree_type *address_exp,
7442 enum section_type sectype,
7443 etree_type *sectype_value,
7444 etree_type *align,
7445 etree_type *subalign,
7446 etree_type *ebase,
7447 int constraint,
7448 int align_with_input)
7449 {
7450 lang_output_section_statement_type *os;
7451
7452 os = lang_output_section_statement_lookup (output_section_statement_name,
7453 constraint, 2);
7454 current_section = os;
7455
7456 if (os->addr_tree == NULL)
7457 {
7458 os->addr_tree = address_exp;
7459 }
7460 os->sectype = sectype;
7461 if (sectype == type_section || sectype == typed_readonly_section)
7462 os->sectype_value = sectype_value;
7463 else if (sectype == noload_section)
7464 os->flags = SEC_NEVER_LOAD;
7465 else
7466 os->flags = SEC_NO_FLAGS;
7467 os->block_value = 1;
7468
7469 /* Make next things chain into subchain of this. */
7470 push_stat_ptr (&os->children);
7471
7472 os->align_lma_with_input = align_with_input == ALIGN_WITH_INPUT;
7473 if (os->align_lma_with_input && align != NULL)
7474 einfo (_("%F%P:%pS: error: align with input and explicit align specified\n"),
7475 NULL);
7476
7477 os->subsection_alignment = subalign;
7478 os->section_alignment = align;
7479
7480 os->load_base = ebase;
7481 return os;
7482 }
7483
7484 void
7485 lang_final (void)
7486 {
7487 lang_output_statement_type *new_stmt;
7488
7489 new_stmt = new_stat (lang_output_statement, stat_ptr);
7490 new_stmt->name = output_filename;
7491 }
7492
7493 /* Reset the current counters in the regions. */
7494
7495 void
7496 lang_reset_memory_regions (void)
7497 {
7498 lang_memory_region_type *p = lang_memory_region_list;
7499 asection *o;
7500 lang_output_section_statement_type *os;
7501
7502 for (p = lang_memory_region_list; p != NULL; p = p->next)
7503 {
7504 p->current = p->origin;
7505 p->last_os = NULL;
7506 }
7507
7508 for (os = (void *) lang_os_list.head;
7509 os != NULL;
7510 os = os->next)
7511 {
7512 os->processed_vma = false;
7513 os->processed_lma = false;
7514 }
7515
7516 for (o = link_info.output_bfd->sections; o != NULL; o = o->next)
7517 {
7518 /* Save the last size for possible use by bfd_relax_section. */
7519 o->rawsize = o->size;
7520 if (!(o->flags & SEC_FIXED_SIZE))
7521 o->size = 0;
7522 }
7523 }
7524
7525 /* Worker for lang_gc_sections_1. */
7526
7527 static void
7528 gc_section_callback (lang_wild_statement_type *ptr,
7529 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7530 asection *section,
7531 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7532 void *data ATTRIBUTE_UNUSED)
7533 {
7534 /* If the wild pattern was marked KEEP, the member sections
7535 should be as well. */
7536 if (ptr->keep_sections)
7537 section->flags |= SEC_KEEP;
7538 }
7539
7540 /* Iterate over sections marking them against GC. */
7541
7542 static void
7543 lang_gc_sections_1 (lang_statement_union_type *s)
7544 {
7545 for (; s != NULL; s = s->header.next)
7546 {
7547 switch (s->header.type)
7548 {
7549 case lang_wild_statement_enum:
7550 walk_wild (&s->wild_statement, gc_section_callback, NULL);
7551 break;
7552 case lang_constructors_statement_enum:
7553 lang_gc_sections_1 (constructor_list.head);
7554 break;
7555 case lang_output_section_statement_enum:
7556 lang_gc_sections_1 (s->output_section_statement.children.head);
7557 break;
7558 case lang_group_statement_enum:
7559 lang_gc_sections_1 (s->group_statement.children.head);
7560 break;
7561 default:
7562 break;
7563 }
7564 }
7565 }
7566
7567 static void
7568 lang_gc_sections (void)
7569 {
7570 /* Keep all sections so marked in the link script. */
7571 lang_gc_sections_1 (statement_list.head);
7572
7573 /* SEC_EXCLUDE is ignored when doing a relocatable link, except in
7574 the special case of .stabstr debug info. (See bfd/stabs.c)
7575 Twiddle the flag here, to simplify later linker code. */
7576 if (bfd_link_relocatable (&link_info))
7577 {
7578 LANG_FOR_EACH_INPUT_STATEMENT (f)
7579 {
7580 asection *sec;
7581 #if BFD_SUPPORTS_PLUGINS
7582 if (f->flags.claimed)
7583 continue;
7584 #endif
7585 for (sec = f->the_bfd->sections; sec != NULL; sec = sec->next)
7586 if ((sec->flags & SEC_DEBUGGING) == 0
7587 || strcmp (sec->name, ".stabstr") != 0)
7588 sec->flags &= ~SEC_EXCLUDE;
7589 }
7590 }
7591
7592 if (link_info.gc_sections)
7593 bfd_gc_sections (link_info.output_bfd, &link_info);
7594 }
7595
7596 /* Worker for lang_find_relro_sections_1. */
7597
7598 static void
7599 find_relro_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
7600 struct wildcard_list *sec ATTRIBUTE_UNUSED,
7601 asection *section,
7602 lang_input_statement_type *file ATTRIBUTE_UNUSED,
7603 void *data)
7604 {
7605 /* Discarded, excluded and ignored sections effectively have zero
7606 size. */
7607 if (section->output_section != NULL
7608 && section->output_section->owner == link_info.output_bfd
7609 && (section->output_section->flags & SEC_EXCLUDE) == 0
7610 && !IGNORE_SECTION (section)
7611 && section->size != 0)
7612 {
7613 bool *has_relro_section = (bool *) data;
7614 *has_relro_section = true;
7615 }
7616 }
7617
7618 /* Iterate over sections for relro sections. */
7619
7620 static void
7621 lang_find_relro_sections_1 (lang_statement_union_type *s,
7622 bool *has_relro_section)
7623 {
7624 if (*has_relro_section)
7625 return;
7626
7627 for (; s != NULL; s = s->header.next)
7628 {
7629 if (s == expld.dataseg.relro_end_stat)
7630 break;
7631
7632 switch (s->header.type)
7633 {
7634 case lang_wild_statement_enum:
7635 walk_wild (&s->wild_statement,
7636 find_relro_section_callback,
7637 has_relro_section);
7638 break;
7639 case lang_constructors_statement_enum:
7640 lang_find_relro_sections_1 (constructor_list.head,
7641 has_relro_section);
7642 break;
7643 case lang_output_section_statement_enum:
7644 lang_find_relro_sections_1 (s->output_section_statement.children.head,
7645 has_relro_section);
7646 break;
7647 case lang_group_statement_enum:
7648 lang_find_relro_sections_1 (s->group_statement.children.head,
7649 has_relro_section);
7650 break;
7651 default:
7652 break;
7653 }
7654 }
7655 }
7656
7657 static void
7658 lang_find_relro_sections (void)
7659 {
7660 bool has_relro_section = false;
7661
7662 /* Check all sections in the link script. */
7663
7664 lang_find_relro_sections_1 (expld.dataseg.relro_start_stat,
7665 &has_relro_section);
7666
7667 if (!has_relro_section)
7668 link_info.relro = false;
7669 }
7670
7671 /* Relax all sections until bfd_relax_section gives up. */
7672
7673 void
7674 lang_relax_sections (bool need_layout)
7675 {
7676 /* NB: Also enable relaxation to layout sections for DT_RELR. */
7677 if (RELAXATION_ENABLED || link_info.enable_dt_relr)
7678 {
7679 /* We may need more than one relaxation pass. */
7680 int i = link_info.relax_pass;
7681
7682 /* The backend can use it to determine the current pass. */
7683 link_info.relax_pass = 0;
7684
7685 while (i--)
7686 {
7687 /* Keep relaxing until bfd_relax_section gives up. */
7688 bool relax_again;
7689
7690 link_info.relax_trip = -1;
7691 do
7692 {
7693 link_info.relax_trip++;
7694
7695 /* Note: pe-dll.c does something like this also. If you find
7696 you need to change this code, you probably need to change
7697 pe-dll.c also. DJ */
7698
7699 /* Do all the assignments with our current guesses as to
7700 section sizes. */
7701 lang_do_assignments (lang_assigning_phase_enum);
7702
7703 /* We must do this after lang_do_assignments, because it uses
7704 size. */
7705 lang_reset_memory_regions ();
7706
7707 /* Perform another relax pass - this time we know where the
7708 globals are, so can make a better guess. */
7709 relax_again = false;
7710 lang_size_sections (&relax_again, false);
7711 }
7712 while (relax_again);
7713
7714 link_info.relax_pass++;
7715 }
7716 need_layout = true;
7717 }
7718
7719 if (need_layout)
7720 {
7721 /* Final extra sizing to report errors. */
7722 lang_do_assignments (lang_assigning_phase_enum);
7723 lang_reset_memory_regions ();
7724 lang_size_sections (NULL, true);
7725 }
7726 }
7727
7728 #if BFD_SUPPORTS_PLUGINS
7729 /* Find the insert point for the plugin's replacement files. We
7730 place them after the first claimed real object file, or if the
7731 first claimed object is an archive member, after the last real
7732 object file immediately preceding the archive. In the event
7733 no objects have been claimed at all, we return the first dummy
7734 object file on the list as the insert point; that works, but
7735 the callee must be careful when relinking the file_chain as it
7736 is not actually on that chain, only the statement_list and the
7737 input_file list; in that case, the replacement files must be
7738 inserted at the head of the file_chain. */
7739
7740 static lang_input_statement_type *
7741 find_replacements_insert_point (bool *before)
7742 {
7743 lang_input_statement_type *claim1, *lastobject;
7744 lastobject = (void *) input_file_chain.head;
7745 for (claim1 = (void *) file_chain.head;
7746 claim1 != NULL;
7747 claim1 = claim1->next)
7748 {
7749 if (claim1->flags.claimed)
7750 {
7751 *before = claim1->flags.claim_archive;
7752 return claim1->flags.claim_archive ? lastobject : claim1;
7753 }
7754 /* Update lastobject if this is a real object file. */
7755 if (claim1->the_bfd != NULL && claim1->the_bfd->my_archive == NULL)
7756 lastobject = claim1;
7757 }
7758 /* No files were claimed by the plugin. Choose the last object
7759 file found on the list (maybe the first, dummy entry) as the
7760 insert point. */
7761 *before = false;
7762 return lastobject;
7763 }
7764
7765 /* Find where to insert ADD, an archive element or shared library
7766 added during a rescan. */
7767
7768 static lang_input_statement_type **
7769 find_rescan_insertion (lang_input_statement_type *add)
7770 {
7771 bfd *add_bfd = add->the_bfd;
7772 lang_input_statement_type *f;
7773 lang_input_statement_type *last_loaded = NULL;
7774 lang_input_statement_type *before = NULL;
7775 lang_input_statement_type **iter = NULL;
7776
7777 if (add_bfd->my_archive != NULL)
7778 add_bfd = add_bfd->my_archive;
7779
7780 /* First look through the input file chain, to find an object file
7781 before the one we've rescanned. Normal object files always
7782 appear on both the input file chain and the file chain, so this
7783 lets us get quickly to somewhere near the correct place on the
7784 file chain if it is full of archive elements. Archives don't
7785 appear on the file chain, but if an element has been extracted
7786 then their input_statement->next points at it. */
7787 for (f = (void *) input_file_chain.head;
7788 f != NULL;
7789 f = f->next_real_file)
7790 {
7791 if (f->the_bfd == add_bfd)
7792 {
7793 before = last_loaded;
7794 if (f->next != NULL)
7795 return &f->next->next;
7796 }
7797 if (f->the_bfd != NULL && f->next != NULL)
7798 last_loaded = f;
7799 }
7800
7801 for (iter = before ? &before->next : &file_chain.head->input_statement.next;
7802 *iter != NULL;
7803 iter = &(*iter)->next)
7804 if (!(*iter)->flags.claim_archive
7805 && (*iter)->the_bfd->my_archive == NULL)
7806 break;
7807
7808 return iter;
7809 }
7810
7811 /* Insert SRCLIST into DESTLIST after given element by chaining
7812 on FIELD as the next-pointer. (Counterintuitively does not need
7813 a pointer to the actual after-node itself, just its chain field.) */
7814
7815 static void
7816 lang_list_insert_after (lang_statement_list_type *destlist,
7817 lang_statement_list_type *srclist,
7818 lang_statement_union_type **field)
7819 {
7820 *(srclist->tail) = *field;
7821 *field = srclist->head;
7822 if (destlist->tail == field)
7823 destlist->tail = srclist->tail;
7824 }
7825
7826 /* Detach new nodes added to DESTLIST since the time ORIGLIST
7827 was taken as a copy of it and leave them in ORIGLIST. */
7828
7829 static void
7830 lang_list_remove_tail (lang_statement_list_type *destlist,
7831 lang_statement_list_type *origlist)
7832 {
7833 union lang_statement_union **savetail;
7834 /* Check that ORIGLIST really is an earlier state of DESTLIST. */
7835 ASSERT (origlist->head == destlist->head);
7836 savetail = origlist->tail;
7837 origlist->head = *(savetail);
7838 origlist->tail = destlist->tail;
7839 destlist->tail = savetail;
7840 *savetail = NULL;
7841 }
7842
7843 static lang_statement_union_type **
7844 find_next_input_statement (lang_statement_union_type **s)
7845 {
7846 for ( ; *s; s = &(*s)->header.next)
7847 {
7848 lang_statement_union_type **t;
7849 switch ((*s)->header.type)
7850 {
7851 case lang_input_statement_enum:
7852 return s;
7853 case lang_wild_statement_enum:
7854 t = &(*s)->wild_statement.children.head;
7855 break;
7856 case lang_group_statement_enum:
7857 t = &(*s)->group_statement.children.head;
7858 break;
7859 case lang_output_section_statement_enum:
7860 t = &(*s)->output_section_statement.children.head;
7861 break;
7862 default:
7863 continue;
7864 }
7865 t = find_next_input_statement (t);
7866 if (*t)
7867 return t;
7868 }
7869 return s;
7870 }
7871 #endif /* BFD_SUPPORTS_PLUGINS */
7872
7873 /* Add NAME to the list of garbage collection entry points. */
7874
7875 void
7876 lang_add_gc_name (const char *name)
7877 {
7878 struct bfd_sym_chain *sym;
7879
7880 if (name == NULL)
7881 return;
7882
7883 sym = stat_alloc (sizeof (*sym));
7884
7885 sym->next = link_info.gc_sym_list;
7886 sym->name = name;
7887 link_info.gc_sym_list = sym;
7888 }
7889
7890 /* Check relocations. */
7891
7892 static void
7893 lang_check_relocs (void)
7894 {
7895 if (link_info.check_relocs_after_open_input)
7896 {
7897 bfd *abfd;
7898
7899 for (abfd = link_info.input_bfds;
7900 abfd != (bfd *) NULL; abfd = abfd->link.next)
7901 if (!bfd_link_check_relocs (abfd, &link_info))
7902 {
7903 /* No object output, fail return. */
7904 config.make_executable = false;
7905 /* Note: we do not abort the loop, but rather
7906 continue the scan in case there are other
7907 bad relocations to report. */
7908 }
7909 }
7910 }
7911
7912 /* Look through all output sections looking for places where we can
7913 propagate forward the lma region. */
7914
7915 static void
7916 lang_propagate_lma_regions (void)
7917 {
7918 lang_output_section_statement_type *os;
7919
7920 for (os = (void *) lang_os_list.head;
7921 os != NULL;
7922 os = os->next)
7923 {
7924 if (os->prev != NULL
7925 && os->lma_region == NULL
7926 && os->load_base == NULL
7927 && os->addr_tree == NULL
7928 && os->region == os->prev->region)
7929 os->lma_region = os->prev->lma_region;
7930 }
7931 }
7932
7933 static void
7934 warn_non_contiguous_discards (void)
7935 {
7936 LANG_FOR_EACH_INPUT_STATEMENT (file)
7937 {
7938 if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
7939 || file->flags.just_syms)
7940 continue;
7941
7942 for (asection *s = file->the_bfd->sections; s != NULL; s = s->next)
7943 if (s->output_section == NULL
7944 && (s->flags & SEC_LINKER_CREATED) == 0)
7945 einfo (_("%P: warning: --enable-non-contiguous-regions "
7946 "discards section `%pA' from `%pB'\n"),
7947 s, file->the_bfd);
7948 }
7949 }
7950
7951 static void
7952 reset_one_wild (lang_statement_union_type *statement)
7953 {
7954 if (statement->header.type == lang_wild_statement_enum)
7955 {
7956 lang_wild_statement_type *stmt = &statement->wild_statement;
7957 lang_list_init (&stmt->matching_sections);
7958 }
7959 }
7960
7961 static void
7962 reset_resolved_wilds (void)
7963 {
7964 lang_for_each_statement (reset_one_wild);
7965 }
7966
7967 void
7968 lang_process (void)
7969 {
7970 /* Finalize dynamic list. */
7971 if (link_info.dynamic_list)
7972 lang_finalize_version_expr_head (&link_info.dynamic_list->head);
7973
7974 current_target = default_target;
7975
7976 /* Open the output file. */
7977 lang_for_each_statement (ldlang_open_output);
7978 init_opb (NULL);
7979
7980 ldemul_create_output_section_statements ();
7981
7982 /* Add to the hash table all undefineds on the command line. */
7983 lang_place_undefineds ();
7984
7985 if (!bfd_section_already_linked_table_init ())
7986 einfo (_("%F%P: can not create hash table: %E\n"));
7987
7988 /* A first pass through the memory regions ensures that if any region
7989 references a symbol for its origin or length then this symbol will be
7990 added to the symbol table. Having these symbols in the symbol table
7991 means that when we call open_input_bfds PROVIDE statements will
7992 trigger to provide any needed symbols. The regions origins and
7993 lengths are not assigned as a result of this call. */
7994 lang_do_memory_regions (false);
7995
7996 /* Create a bfd for each input file. */
7997 current_target = default_target;
7998 lang_statement_iteration++;
7999 open_input_bfds (statement_list.head, OPEN_BFD_NORMAL);
8000
8001 /* Now that open_input_bfds has processed assignments and provide
8002 statements we can give values to symbolic origin/length now. */
8003 lang_do_memory_regions (true);
8004
8005 ldemul_before_plugin_all_symbols_read ();
8006
8007 #if BFD_SUPPORTS_PLUGINS
8008 if (link_info.lto_plugin_active)
8009 {
8010 lang_statement_list_type added;
8011 lang_statement_list_type files, inputfiles;
8012
8013 /* Now all files are read, let the plugin(s) decide if there
8014 are any more to be added to the link before we call the
8015 emulation's after_open hook. We create a private list of
8016 input statements for this purpose, which we will eventually
8017 insert into the global statement list after the first claimed
8018 file. */
8019 added = *stat_ptr;
8020 /* We need to manipulate all three chains in synchrony. */
8021 files = file_chain;
8022 inputfiles = input_file_chain;
8023 if (plugin_call_all_symbols_read ())
8024 einfo (_("%F%P: %s: plugin reported error after all symbols read\n"),
8025 plugin_error_plugin ());
8026 link_info.lto_all_symbols_read = true;
8027 /* Open any newly added files, updating the file chains. */
8028 plugin_undefs = link_info.hash->undefs_tail;
8029 open_input_bfds (*added.tail, OPEN_BFD_NORMAL);
8030 if (plugin_undefs == link_info.hash->undefs_tail)
8031 plugin_undefs = NULL;
8032 /* Restore the global list pointer now they have all been added. */
8033 lang_list_remove_tail (stat_ptr, &added);
8034 /* And detach the fresh ends of the file lists. */
8035 lang_list_remove_tail (&file_chain, &files);
8036 lang_list_remove_tail (&input_file_chain, &inputfiles);
8037 /* Were any new files added? */
8038 if (added.head != NULL)
8039 {
8040 /* If so, we will insert them into the statement list immediately
8041 after the first input file that was claimed by the plugin,
8042 unless that file was an archive in which case it is inserted
8043 immediately before. */
8044 bool before;
8045 lang_statement_union_type **prev;
8046 plugin_insert = find_replacements_insert_point (&before);
8047 /* If a plugin adds input files without having claimed any, we
8048 don't really have a good idea where to place them. Just putting
8049 them at the start or end of the list is liable to leave them
8050 outside the crtbegin...crtend range. */
8051 ASSERT (plugin_insert != NULL);
8052 /* Splice the new statement list into the old one. */
8053 prev = &plugin_insert->header.next;
8054 if (before)
8055 {
8056 prev = find_next_input_statement (prev);
8057 if (*prev != (void *) plugin_insert->next_real_file)
8058 {
8059 /* We didn't find the expected input statement.
8060 Fall back to adding after plugin_insert. */
8061 prev = &plugin_insert->header.next;
8062 }
8063 }
8064 lang_list_insert_after (stat_ptr, &added, prev);
8065 /* Likewise for the file chains. */
8066 lang_list_insert_after (&input_file_chain, &inputfiles,
8067 (void *) &plugin_insert->next_real_file);
8068 /* We must be careful when relinking file_chain; we may need to
8069 insert the new files at the head of the list if the insert
8070 point chosen is the dummy first input file. */
8071 if (plugin_insert->filename)
8072 lang_list_insert_after (&file_chain, &files,
8073 (void *) &plugin_insert->next);
8074 else
8075 lang_list_insert_after (&file_chain, &files, &file_chain.head);
8076
8077 /* Rescan archives in case new undefined symbols have appeared. */
8078 files = file_chain;
8079 lang_statement_iteration++;
8080 open_input_bfds (statement_list.head, OPEN_BFD_RESCAN);
8081 lang_list_remove_tail (&file_chain, &files);
8082 while (files.head != NULL)
8083 {
8084 lang_input_statement_type **insert;
8085 lang_input_statement_type **iter, *temp;
8086 bfd *my_arch;
8087
8088 insert = find_rescan_insertion (&files.head->input_statement);
8089 /* All elements from an archive can be added at once. */
8090 iter = &files.head->input_statement.next;
8091 my_arch = files.head->input_statement.the_bfd->my_archive;
8092 if (my_arch != NULL)
8093 for (; *iter != NULL; iter = &(*iter)->next)
8094 if ((*iter)->the_bfd->my_archive != my_arch)
8095 break;
8096 temp = *insert;
8097 *insert = &files.head->input_statement;
8098 files.head = (lang_statement_union_type *) *iter;
8099 *iter = temp;
8100 if (file_chain.tail == (lang_statement_union_type **) insert)
8101 file_chain.tail = (lang_statement_union_type **) iter;
8102 if (my_arch != NULL)
8103 {
8104 lang_input_statement_type *parent = bfd_usrdata (my_arch);
8105 if (parent != NULL)
8106 parent->next = (lang_input_statement_type *)
8107 ((char *) iter
8108 - offsetof (lang_input_statement_type, next));
8109 }
8110 }
8111 }
8112 }
8113 #endif /* BFD_SUPPORTS_PLUGINS */
8114
8115 struct bfd_sym_chain **sym = &link_info.gc_sym_list;
8116 while (*sym)
8117 sym = &(*sym)->next;
8118
8119 *sym = &entry_symbol;
8120
8121 if (entry_symbol.name == NULL)
8122 {
8123 *sym = ldlang_undef_chain_list_head;
8124
8125 /* entry_symbol is normally initialised by an ENTRY definition in the
8126 linker script or the -e command line option. But if neither of
8127 these have been used, the target specific backend may still have
8128 provided an entry symbol via a call to lang_default_entry().
8129 Unfortunately this value will not be processed until lang_end()
8130 is called, long after this function has finished. So detect this
8131 case here and add the target's entry symbol to the list of starting
8132 points for garbage collection resolution. */
8133 lang_add_gc_name (entry_symbol_default);
8134 }
8135
8136 lang_add_gc_name (link_info.init_function);
8137 lang_add_gc_name (link_info.fini_function);
8138
8139 ldemul_after_open ();
8140 if (config.map_file != NULL)
8141 lang_print_asneeded ();
8142
8143 ldlang_open_ctf ();
8144
8145 bfd_section_already_linked_table_free ();
8146
8147 /* Make sure that we're not mixing architectures. We call this
8148 after all the input files have been opened, but before we do any
8149 other processing, so that any operations merge_private_bfd_data
8150 does on the output file will be known during the rest of the
8151 link. */
8152 lang_check ();
8153
8154 /* Handle .exports instead of a version script if we're told to do so. */
8155 if (command_line.version_exports_section)
8156 lang_do_version_exports_section ();
8157
8158 /* Build all sets based on the information gathered from the input
8159 files. */
8160 ldctor_build_sets ();
8161
8162 lang_symbol_tweaks ();
8163
8164 /* PR 13683: We must rerun the assignments prior to running garbage
8165 collection in order to make sure that all symbol aliases are resolved. */
8166 lang_do_assignments (lang_mark_phase_enum);
8167 expld.phase = lang_first_phase_enum;
8168
8169 /* Size up the common data. */
8170 lang_common ();
8171
8172 if (0)
8173 debug_prefix_tree ();
8174
8175 resolve_wilds ();
8176
8177 /* Remove unreferenced sections if asked to. */
8178 lang_gc_sections ();
8179
8180 lang_mark_undefineds ();
8181
8182 /* Check relocations. */
8183 lang_check_relocs ();
8184
8185 ldemul_after_check_relocs ();
8186
8187 /* There might have been new sections created (e.g. as result of
8188 checking relocs to need a .got, or suchlike), so to properly order
8189 them into our lists of matching sections reset them here. */
8190 reset_resolved_wilds ();
8191 resolve_wilds ();
8192
8193 /* Update wild statements in case the user gave --sort-section.
8194 Note how the option might have come after the linker script and
8195 so couldn't have been set when the wild statements were created. */
8196 update_wild_statements (statement_list.head);
8197
8198 /* Run through the contours of the script and attach input sections
8199 to the correct output sections. */
8200 lang_statement_iteration++;
8201 map_input_to_output_sections (statement_list.head, NULL, NULL);
8202
8203 /* Start at the statement immediately after the special abs_section
8204 output statement, so that it isn't reordered. */
8205 process_insert_statements (&lang_os_list.head->header.next);
8206
8207 ldemul_before_place_orphans ();
8208
8209 /* Find any sections not attached explicitly and handle them. */
8210 lang_place_orphans ();
8211
8212 if (!bfd_link_relocatable (&link_info))
8213 {
8214 asection *found;
8215
8216 /* Merge SEC_MERGE sections. This has to be done after GC of
8217 sections, so that GCed sections are not merged, but before
8218 assigning dynamic symbols, since removing whole input sections
8219 is hard then. */
8220 bfd_merge_sections (link_info.output_bfd, &link_info);
8221
8222 /* Look for a text section and set the readonly attribute in it. */
8223 found = bfd_get_section_by_name (link_info.output_bfd, ".text");
8224
8225 if (found != NULL)
8226 {
8227 if (config.text_read_only)
8228 found->flags |= SEC_READONLY;
8229 else
8230 found->flags &= ~SEC_READONLY;
8231 }
8232 }
8233
8234 /* Merge together CTF sections. After this, only the symtab-dependent
8235 function and data object sections need adjustment. */
8236 lang_merge_ctf ();
8237
8238 /* Emit the CTF, iff the emulation doesn't need to do late emission after
8239 examining things laid out late, like the strtab. */
8240 lang_write_ctf (0);
8241
8242 /* Copy forward lma regions for output sections in same lma region. */
8243 lang_propagate_lma_regions ();
8244
8245 /* Defining __start/__stop symbols early for --gc-sections to work
8246 around a glibc build problem can result in these symbols being
8247 defined when they should not be. Fix them now. */
8248 if (config.build_constructors)
8249 lang_undef_start_stop ();
8250
8251 /* Define .startof./.sizeof. symbols with preliminary values before
8252 dynamic symbols are created. */
8253 if (!bfd_link_relocatable (&link_info))
8254 lang_init_startof_sizeof ();
8255
8256 /* Do anything special before sizing sections. This is where ELF
8257 and other back-ends size dynamic sections. */
8258 ldemul_before_allocation ();
8259
8260 /* We must record the program headers before we try to fix the
8261 section positions, since they will affect SIZEOF_HEADERS. */
8262 lang_record_phdrs ();
8263
8264 /* Check relro sections. */
8265 if (link_info.relro && !bfd_link_relocatable (&link_info))
8266 lang_find_relro_sections ();
8267
8268 /* Size up the sections. */
8269 lang_size_sections (NULL, !RELAXATION_ENABLED);
8270
8271 /* See if anything special should be done now we know how big
8272 everything is. This is where relaxation is done. */
8273 ldemul_after_allocation ();
8274
8275 /* Fix any __start, __stop, .startof. or .sizeof. symbols. */
8276 lang_finalize_start_stop ();
8277
8278 /* Do all the assignments again, to report errors. Assignment
8279 statements are processed multiple times, updating symbols; In
8280 open_input_bfds, lang_do_assignments, and lang_size_sections.
8281 Since lang_relax_sections calls lang_do_assignments, symbols are
8282 also updated in ldemul_after_allocation. */
8283 lang_do_assignments (lang_final_phase_enum);
8284
8285 ldemul_finish ();
8286
8287 /* Convert absolute symbols to section relative. */
8288 ldexp_finalize_syms ();
8289
8290 /* Make sure that the section addresses make sense. */
8291 if (command_line.check_section_addresses)
8292 lang_check_section_addresses ();
8293
8294 if (link_info.non_contiguous_regions
8295 && link_info.non_contiguous_regions_warnings)
8296 warn_non_contiguous_discards ();
8297
8298 /* Check any required symbols are known. */
8299 ldlang_check_require_defined_symbols ();
8300
8301 lang_end ();
8302 }
8303
8304 void
8305 lang_add_version_string (void)
8306 {
8307 if (! enable_linker_version)
8308 return;
8309
8310 const char * str = "GNU ld ";
8311 int len = strlen (str);
8312 int i;
8313
8314 for (i = 0 ; i < len ; i++)
8315 lang_add_data (BYTE, exp_intop (str[i]));
8316
8317 str = BFD_VERSION_STRING;
8318 len = strlen (str);
8319
8320 for (i = 0 ; i < len ; i++)
8321 lang_add_data (BYTE, exp_intop (str[i]));
8322
8323 lang_add_data (BYTE, exp_intop ('\0'));
8324 }
8325
8326 /* EXPORTED TO YACC */
8327
8328 void
8329 lang_add_wild (struct wildcard_spec *filespec,
8330 struct wildcard_list *section_list,
8331 bool keep_sections)
8332 {
8333 struct wildcard_list *curr, *next;
8334 lang_wild_statement_type *new_stmt;
8335 bool any_specs_sorted = false;
8336
8337 /* Reverse the list as the parser puts it back to front. */
8338 for (curr = section_list, section_list = NULL;
8339 curr != NULL;
8340 section_list = curr, curr = next)
8341 {
8342 if (curr->spec.sorted != none && curr->spec.sorted != by_none)
8343 any_specs_sorted = true;
8344 next = curr->next;
8345 curr->next = section_list;
8346 }
8347
8348 if (filespec != NULL && filespec->name != NULL)
8349 {
8350 if (strcmp (filespec->name, "*") == 0)
8351 filespec->name = NULL;
8352 else if (!wildcardp (filespec->name))
8353 lang_has_input_file = true;
8354 }
8355
8356 new_stmt = new_stat (lang_wild_statement, stat_ptr);
8357 new_stmt->filename = NULL;
8358 new_stmt->filenames_sorted = false;
8359 new_stmt->any_specs_sorted = any_specs_sorted;
8360 new_stmt->section_flag_list = NULL;
8361 new_stmt->exclude_name_list = NULL;
8362 if (filespec != NULL)
8363 {
8364 new_stmt->filename = filespec->name;
8365 new_stmt->filenames_sorted = filespec->sorted == by_name;
8366 new_stmt->section_flag_list = filespec->section_flag_list;
8367 new_stmt->exclude_name_list = filespec->exclude_name_list;
8368 }
8369 new_stmt->section_list = section_list;
8370 new_stmt->keep_sections = keep_sections;
8371 lang_list_init (&new_stmt->children);
8372 lang_list_init (&new_stmt->matching_sections);
8373 analyze_walk_wild_section_handler (new_stmt);
8374 if (0)
8375 {
8376 printf ("wild %s(", new_stmt->filename ? new_stmt->filename : "*");
8377 for (curr = new_stmt->section_list; curr; curr = curr->next)
8378 printf ("%s ", curr->spec.name ? curr->spec.name : "*");
8379 printf (")\n");
8380 }
8381 }
8382
8383 void
8384 lang_section_start (const char *name, etree_type *address,
8385 const segment_type *segment)
8386 {
8387 lang_address_statement_type *ad;
8388
8389 ad = new_stat (lang_address_statement, stat_ptr);
8390 ad->section_name = name;
8391 ad->address = address;
8392 ad->segment = segment;
8393 }
8394
8395 /* Set the start symbol to NAME. CMDLINE is nonzero if this is called
8396 because of a -e argument on the command line, or zero if this is
8397 called by ENTRY in a linker script. Command line arguments take
8398 precedence. */
8399
8400 void
8401 lang_add_entry (const char *name, bool cmdline)
8402 {
8403 if (entry_symbol.name == NULL
8404 || cmdline
8405 || !entry_from_cmdline)
8406 {
8407 entry_symbol.name = name;
8408 entry_from_cmdline = cmdline;
8409 }
8410 }
8411
8412 /* Set the default start symbol to NAME. .em files should use this,
8413 not lang_add_entry, to override the use of "start" if neither the
8414 linker script nor the command line specifies an entry point. NAME
8415 must be permanently allocated. */
8416 void
8417 lang_default_entry (const char *name)
8418 {
8419 entry_symbol_default = name;
8420 }
8421
8422 void
8423 lang_add_target (const char *name)
8424 {
8425 lang_target_statement_type *new_stmt;
8426
8427 new_stmt = new_stat (lang_target_statement, stat_ptr);
8428 new_stmt->target = name;
8429 }
8430
8431 void
8432 lang_add_map (const char *name)
8433 {
8434 while (*name)
8435 {
8436 switch (*name)
8437 {
8438 case 'F':
8439 map_option_f = true;
8440 break;
8441 }
8442 name++;
8443 }
8444 }
8445
8446 void
8447 lang_add_fill (fill_type *fill)
8448 {
8449 lang_fill_statement_type *new_stmt;
8450
8451 new_stmt = new_stat (lang_fill_statement, stat_ptr);
8452 new_stmt->fill = fill;
8453 }
8454
8455 void
8456 lang_add_data (int type, union etree_union *exp)
8457 {
8458 lang_data_statement_type *new_stmt;
8459
8460 new_stmt = new_stat (lang_data_statement, stat_ptr);
8461 new_stmt->exp = exp;
8462 new_stmt->type = type;
8463 }
8464
8465 void
8466 lang_add_string (const char *s)
8467 {
8468 bfd_vma len = strlen (s);
8469 bfd_vma i;
8470 bool escape = false;
8471
8472 /* Add byte expressions until end of string. */
8473 for (i = 0 ; i < len; i++)
8474 {
8475 char c = *s++;
8476
8477 if (escape)
8478 {
8479 switch (c)
8480 {
8481 default:
8482 /* Ignore the escape. */
8483 break;
8484
8485 case 'n': c = '\n'; break;
8486 case 'r': c = '\r'; break;
8487 case 't': c = '\t'; break;
8488
8489 case '0':
8490 case '1':
8491 case '2':
8492 case '3':
8493 case '4':
8494 case '5':
8495 case '6':
8496 case '7':
8497 /* We have an octal number. */
8498 {
8499 unsigned int value = c - '0';
8500
8501 c = *s;
8502 if ((c >= '0') && (c <= '7'))
8503 {
8504 value <<= 3;
8505 value += (c - '0');
8506 i++;
8507 s++;
8508
8509 c = *s;
8510 if ((c >= '0') && (c <= '7'))
8511 {
8512 value <<= 3;
8513 value += (c - '0');
8514 i++;
8515 s++;
8516 }
8517 }
8518
8519 if (value > 0xff)
8520 {
8521 /* octal: \777 is treated as '\077' + '7' */
8522 value >>= 3;
8523 i--;
8524 s--;
8525 }
8526
8527 c = value;
8528 }
8529 break;
8530 }
8531
8532 lang_add_data (BYTE, exp_intop (c));
8533 escape = false;
8534 }
8535 else
8536 {
8537 if (c == '\\')
8538 escape = true;
8539 else
8540 lang_add_data (BYTE, exp_intop (c));
8541 }
8542 }
8543
8544 /* Remeber to terminate the string. */
8545 lang_add_data (BYTE, exp_intop (0));
8546 }
8547
8548 /* Create a new reloc statement. RELOC is the BFD relocation type to
8549 generate. HOWTO is the corresponding howto structure (we could
8550 look this up, but the caller has already done so). SECTION is the
8551 section to generate a reloc against, or NAME is the name of the
8552 symbol to generate a reloc against. Exactly one of SECTION and
8553 NAME must be NULL. ADDEND is an expression for the addend. */
8554
8555 void
8556 lang_add_reloc (bfd_reloc_code_real_type reloc,
8557 reloc_howto_type *howto,
8558 asection *section,
8559 const char *name,
8560 union etree_union *addend)
8561 {
8562 lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
8563
8564 p->reloc = reloc;
8565 p->howto = howto;
8566 p->section = section;
8567 p->name = name;
8568 p->addend_exp = addend;
8569
8570 p->addend_value = 0;
8571 p->output_section = NULL;
8572 p->output_offset = 0;
8573 }
8574
8575 lang_assignment_statement_type *
8576 lang_add_assignment (etree_type *exp)
8577 {
8578 lang_assignment_statement_type *new_stmt;
8579
8580 new_stmt = new_stat (lang_assignment_statement, stat_ptr);
8581 new_stmt->exp = exp;
8582 return new_stmt;
8583 }
8584
8585 void
8586 lang_add_attribute (enum statement_enum attribute)
8587 {
8588 new_statement (attribute, sizeof (lang_statement_header_type), stat_ptr);
8589 }
8590
8591 void
8592 lang_startup (const char *name)
8593 {
8594 if (first_file->filename != NULL)
8595 {
8596 einfo (_("%F%P: multiple STARTUP files\n"));
8597 }
8598 first_file->filename = name;
8599 first_file->local_sym_name = name;
8600 first_file->flags.real = true;
8601 }
8602
8603 void
8604 lang_float (bool maybe)
8605 {
8606 lang_float_flag = maybe;
8607 }
8608
8609
8610 /* Work out the load- and run-time regions from a script statement, and
8611 store them in *LMA_REGION and *REGION respectively.
8612
8613 MEMSPEC is the name of the run-time region, or the value of
8614 DEFAULT_MEMORY_REGION if the statement didn't specify one.
8615 LMA_MEMSPEC is the name of the load-time region, or null if the
8616 statement didn't specify one.HAVE_LMA_P is TRUE if the statement
8617 had an explicit load address.
8618
8619 It is an error to specify both a load region and a load address. */
8620
8621 static void
8622 lang_get_regions (lang_memory_region_type **region,
8623 lang_memory_region_type **lma_region,
8624 const char *memspec,
8625 const char *lma_memspec,
8626 bool have_lma,
8627 bool have_vma)
8628 {
8629 *lma_region = lang_memory_region_lookup (lma_memspec, false);
8630
8631 /* If no runtime region or VMA has been specified, but the load region
8632 has been specified, then use the load region for the runtime region
8633 as well. */
8634 if (lma_memspec != NULL
8635 && !have_vma
8636 && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
8637 *region = *lma_region;
8638 else
8639 *region = lang_memory_region_lookup (memspec, false);
8640
8641 if (have_lma && lma_memspec != 0)
8642 einfo (_("%X%P:%pS: section has both a load address and a load region\n"),
8643 NULL);
8644 }
8645
8646 void
8647 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
8648 lang_output_section_phdr_list *phdrs,
8649 const char *lma_memspec)
8650 {
8651 lang_get_regions (&current_section->region,
8652 &current_section->lma_region,
8653 memspec, lma_memspec,
8654 current_section->load_base != NULL,
8655 current_section->addr_tree != NULL);
8656
8657 current_section->fill = fill;
8658 current_section->phdrs = phdrs;
8659 pop_stat_ptr ();
8660 }
8661
8662 /* Set the output format type. -oformat overrides scripts. */
8663
8664 void
8665 lang_add_output_format (const char *format,
8666 const char *big,
8667 const char *little,
8668 int from_script)
8669 {
8670 if (output_target == NULL || !from_script)
8671 {
8672 if (command_line.endian == ENDIAN_BIG
8673 && big != NULL)
8674 format = big;
8675 else if (command_line.endian == ENDIAN_LITTLE
8676 && little != NULL)
8677 format = little;
8678
8679 output_target = format;
8680 }
8681 }
8682
8683 void
8684 lang_add_insert (const char *where, int is_before)
8685 {
8686 lang_insert_statement_type *new_stmt;
8687
8688 new_stmt = new_stat (lang_insert_statement, stat_ptr);
8689 new_stmt->where = where;
8690 new_stmt->is_before = is_before;
8691 saved_script_handle = previous_script_handle;
8692 }
8693
8694 /* Enter a group. This creates a new lang_group_statement, and sets
8695 stat_ptr to build new statements within the group. */
8696
8697 void
8698 lang_enter_group (void)
8699 {
8700 lang_group_statement_type *g;
8701
8702 g = new_stat (lang_group_statement, stat_ptr);
8703 lang_list_init (&g->children);
8704 push_stat_ptr (&g->children);
8705 }
8706
8707 /* Leave a group. This just resets stat_ptr to start writing to the
8708 regular list of statements again. Note that this will not work if
8709 groups can occur inside anything else which can adjust stat_ptr,
8710 but currently they can't. */
8711
8712 void
8713 lang_leave_group (void)
8714 {
8715 pop_stat_ptr ();
8716 }
8717
8718 /* Add a new program header. This is called for each entry in a PHDRS
8719 command in a linker script. */
8720
8721 void
8722 lang_new_phdr (const char *name,
8723 etree_type *type,
8724 bool filehdr,
8725 bool phdrs,
8726 etree_type *at,
8727 etree_type *flags)
8728 {
8729 struct lang_phdr *n, **pp;
8730 bool hdrs;
8731
8732 n = stat_alloc (sizeof (struct lang_phdr));
8733 n->next = NULL;
8734 n->name = name;
8735 n->type = exp_get_vma (type, 0, "program header type");
8736 n->filehdr = filehdr;
8737 n->phdrs = phdrs;
8738 n->at = at;
8739 n->flags = flags;
8740
8741 hdrs = n->type == 1 && (phdrs || filehdr);
8742
8743 for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
8744 if (hdrs
8745 && (*pp)->type == 1
8746 && !((*pp)->filehdr || (*pp)->phdrs))
8747 {
8748 einfo (_("%X%P:%pS: PHDRS and FILEHDR are not supported"
8749 " when prior PT_LOAD headers lack them\n"), NULL);
8750 hdrs = false;
8751 }
8752
8753 *pp = n;
8754 }
8755
8756 /* Record the program header information in the output BFD. FIXME: We
8757 should not be calling an ELF specific function here. */
8758
8759 static void
8760 lang_record_phdrs (void)
8761 {
8762 unsigned int alc;
8763 asection **secs;
8764 lang_output_section_phdr_list *last;
8765 struct lang_phdr *l;
8766 lang_output_section_statement_type *os;
8767
8768 alc = 10;
8769 secs = (asection **) xmalloc (alc * sizeof (asection *));
8770 last = NULL;
8771
8772 for (l = lang_phdr_list; l != NULL; l = l->next)
8773 {
8774 unsigned int c;
8775 flagword flags;
8776 bfd_vma at;
8777
8778 c = 0;
8779 for (os = (void *) lang_os_list.head;
8780 os != NULL;
8781 os = os->next)
8782 {
8783 lang_output_section_phdr_list *pl;
8784
8785 if (os->constraint < 0)
8786 continue;
8787
8788 pl = os->phdrs;
8789 if (pl != NULL)
8790 last = pl;
8791 else
8792 {
8793 if (os->sectype == noload_section
8794 || os->bfd_section == NULL
8795 || (os->bfd_section->flags & SEC_ALLOC) == 0)
8796 continue;
8797
8798 /* Don't add orphans to PT_INTERP header. */
8799 if (l->type == 3)
8800 continue;
8801
8802 if (last == NULL)
8803 {
8804 lang_output_section_statement_type *tmp_os;
8805
8806 /* If we have not run across a section with a program
8807 header assigned to it yet, then scan forwards to find
8808 one. This prevents inconsistencies in the linker's
8809 behaviour when a script has specified just a single
8810 header and there are sections in that script which are
8811 not assigned to it, and which occur before the first
8812 use of that header. See here for more details:
8813 http://sourceware.org/ml/binutils/2007-02/msg00291.html */
8814 for (tmp_os = os; tmp_os; tmp_os = tmp_os->next)
8815 if (tmp_os->phdrs)
8816 {
8817 last = tmp_os->phdrs;
8818 break;
8819 }
8820 if (last == NULL)
8821 einfo (_("%F%P: no sections assigned to phdrs\n"));
8822 }
8823 pl = last;
8824 }
8825
8826 if (os->bfd_section == NULL)
8827 continue;
8828
8829 for (; pl != NULL; pl = pl->next)
8830 {
8831 if (strcmp (pl->name, l->name) == 0)
8832 {
8833 if (c >= alc)
8834 {
8835 alc *= 2;
8836 secs = (asection **) xrealloc (secs,
8837 alc * sizeof (asection *));
8838 }
8839 secs[c] = os->bfd_section;
8840 ++c;
8841 pl->used = true;
8842 }
8843 }
8844 }
8845
8846 if (l->flags == NULL)
8847 flags = 0;
8848 else
8849 flags = exp_get_vma (l->flags, 0, "phdr flags");
8850
8851 if (l->at == NULL)
8852 at = 0;
8853 else
8854 at = exp_get_vma (l->at, 0, "phdr load address");
8855
8856 if (!bfd_record_phdr (link_info.output_bfd, l->type,
8857 l->flags != NULL, flags, l->at != NULL,
8858 at, l->filehdr, l->phdrs, c, secs))
8859 einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
8860 }
8861
8862 free (secs);
8863
8864 /* Make sure all the phdr assignments succeeded. */
8865 for (os = (void *) lang_os_list.head;
8866 os != NULL;
8867 os = os->next)
8868 {
8869 lang_output_section_phdr_list *pl;
8870
8871 if (os->constraint < 0
8872 || os->bfd_section == NULL)
8873 continue;
8874
8875 for (pl = os->phdrs;
8876 pl != NULL;
8877 pl = pl->next)
8878 if (!pl->used && strcmp (pl->name, "NONE") != 0)
8879 einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
8880 os->name, pl->name);
8881 }
8882 }
8883
8884 /* Record a list of sections which may not be cross referenced. */
8885
8886 void
8887 lang_add_nocrossref (lang_nocrossref_type *l)
8888 {
8889 struct lang_nocrossrefs *n;
8890
8891 n = (struct lang_nocrossrefs *) xmalloc (sizeof *n);
8892 n->next = nocrossref_list;
8893 n->list = l;
8894 n->onlyfirst = false;
8895 nocrossref_list = n;
8896
8897 /* Set notice_all so that we get informed about all symbols. */
8898 link_info.notice_all = true;
8899 }
8900
8901 /* Record a section that cannot be referenced from a list of sections. */
8902
8903 void
8904 lang_add_nocrossref_to (lang_nocrossref_type *l)
8905 {
8906 lang_add_nocrossref (l);
8907 nocrossref_list->onlyfirst = true;
8908 }
8909 \f
8910 /* Overlay handling. We handle overlays with some static variables. */
8911
8912 /* The overlay virtual address. */
8913 static etree_type *overlay_vma;
8914 /* And subsection alignment. */
8915 static etree_type *overlay_subalign;
8916
8917 /* An expression for the maximum section size seen so far. */
8918 static etree_type *overlay_max;
8919
8920 /* A list of all the sections in this overlay. */
8921
8922 struct overlay_list {
8923 struct overlay_list *next;
8924 lang_output_section_statement_type *os;
8925 };
8926
8927 static struct overlay_list *overlay_list;
8928
8929 /* Start handling an overlay. */
8930
8931 void
8932 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
8933 {
8934 /* The grammar should prevent nested overlays from occurring. */
8935 ASSERT (overlay_vma == NULL
8936 && overlay_subalign == NULL
8937 && overlay_max == NULL);
8938
8939 overlay_vma = vma_expr;
8940 overlay_subalign = subalign;
8941 }
8942
8943 /* Start a section in an overlay. We handle this by calling
8944 lang_enter_output_section_statement with the correct VMA.
8945 lang_leave_overlay sets up the LMA and memory regions. */
8946
8947 void
8948 lang_enter_overlay_section (const char *name)
8949 {
8950 struct overlay_list *n;
8951 etree_type *size;
8952
8953 lang_enter_output_section_statement (name, overlay_vma, overlay_section,
8954 0, 0, overlay_subalign, 0, 0, 0);
8955
8956 /* If this is the first section, then base the VMA of future
8957 sections on this one. This will work correctly even if `.' is
8958 used in the addresses. */
8959 if (overlay_list == NULL)
8960 overlay_vma = exp_nameop (ADDR, name);
8961
8962 /* Remember the section. */
8963 n = (struct overlay_list *) xmalloc (sizeof *n);
8964 n->os = current_section;
8965 n->next = overlay_list;
8966 overlay_list = n;
8967
8968 size = exp_nameop (SIZEOF, name);
8969
8970 /* Arrange to work out the maximum section end address. */
8971 if (overlay_max == NULL)
8972 overlay_max = size;
8973 else
8974 overlay_max = exp_binop (MAX_K, overlay_max, size);
8975 }
8976
8977 /* Finish a section in an overlay. There isn't any special to do
8978 here. */
8979
8980 void
8981 lang_leave_overlay_section (fill_type *fill,
8982 lang_output_section_phdr_list *phdrs)
8983 {
8984 const char *name;
8985 char *clean, *s2;
8986 const char *s1;
8987 char *buf;
8988
8989 name = current_section->name;
8990
8991 /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
8992 region and that no load-time region has been specified. It doesn't
8993 really matter what we say here, since lang_leave_overlay will
8994 override it. */
8995 lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
8996
8997 /* Define the magic symbols. */
8998
8999 clean = (char *) xmalloc (strlen (name) + 1);
9000 s2 = clean;
9001 for (s1 = name; *s1 != '\0'; s1++)
9002 if (ISALNUM (*s1) || *s1 == '_')
9003 *s2++ = *s1;
9004 *s2 = '\0';
9005
9006 buf = (char *) xmalloc (strlen (clean) + sizeof "__load_start_");
9007 sprintf (buf, "__load_start_%s", clean);
9008 lang_add_assignment (exp_provide (buf,
9009 exp_nameop (LOADADDR, name),
9010 false));
9011
9012 buf = (char *) xmalloc (strlen (clean) + sizeof "__load_stop_");
9013 sprintf (buf, "__load_stop_%s", clean);
9014 lang_add_assignment (exp_provide (buf,
9015 exp_binop ('+',
9016 exp_nameop (LOADADDR, name),
9017 exp_nameop (SIZEOF, name)),
9018 false));
9019
9020 free (clean);
9021 }
9022
9023 /* Finish an overlay. If there are any overlay wide settings, this
9024 looks through all the sections in the overlay and sets them. */
9025
9026 void
9027 lang_leave_overlay (etree_type *lma_expr,
9028 int nocrossrefs,
9029 fill_type *fill,
9030 const char *memspec,
9031 lang_output_section_phdr_list *phdrs,
9032 const char *lma_memspec)
9033 {
9034 lang_memory_region_type *region;
9035 lang_memory_region_type *lma_region;
9036 struct overlay_list *l;
9037 lang_nocrossref_type *nocrossref;
9038
9039 lang_get_regions (&region, &lma_region,
9040 memspec, lma_memspec,
9041 lma_expr != NULL, false);
9042
9043 nocrossref = NULL;
9044
9045 /* After setting the size of the last section, set '.' to end of the
9046 overlay region. */
9047 if (overlay_list != NULL)
9048 {
9049 overlay_list->os->update_dot = 1;
9050 overlay_list->os->update_dot_tree
9051 = exp_assign (".", exp_binop ('+', overlay_vma, overlay_max), false);
9052 }
9053
9054 l = overlay_list;
9055 while (l != NULL)
9056 {
9057 struct overlay_list *next;
9058
9059 if (fill != NULL && l->os->fill == NULL)
9060 l->os->fill = fill;
9061
9062 l->os->region = region;
9063 l->os->lma_region = lma_region;
9064
9065 /* The first section has the load address specified in the
9066 OVERLAY statement. The rest are worked out from that.
9067 The base address is not needed (and should be null) if
9068 an LMA region was specified. */
9069 if (l->next == 0)
9070 {
9071 l->os->load_base = lma_expr;
9072 l->os->sectype = first_overlay_section;
9073 }
9074 if (phdrs != NULL && l->os->phdrs == NULL)
9075 l->os->phdrs = phdrs;
9076
9077 if (nocrossrefs)
9078 {
9079 lang_nocrossref_type *nc;
9080
9081 nc = (lang_nocrossref_type *) xmalloc (sizeof *nc);
9082 nc->name = l->os->name;
9083 nc->next = nocrossref;
9084 nocrossref = nc;
9085 }
9086
9087 next = l->next;
9088 free (l);
9089 l = next;
9090 }
9091
9092 if (nocrossref != NULL)
9093 lang_add_nocrossref (nocrossref);
9094
9095 overlay_vma = NULL;
9096 overlay_list = NULL;
9097 overlay_max = NULL;
9098 overlay_subalign = NULL;
9099 }
9100 \f
9101 /* Version handling. This is only useful for ELF. */
9102
9103 /* If PREV is NULL, return first version pattern matching particular symbol.
9104 If PREV is non-NULL, return first version pattern matching particular
9105 symbol after PREV (previously returned by lang_vers_match). */
9106
9107 static struct bfd_elf_version_expr *
9108 lang_vers_match (struct bfd_elf_version_expr_head *head,
9109 struct bfd_elf_version_expr *prev,
9110 const char *sym)
9111 {
9112 const char *c_sym;
9113 const char *cxx_sym = sym;
9114 const char *java_sym = sym;
9115 struct bfd_elf_version_expr *expr = NULL;
9116 enum demangling_styles curr_style;
9117
9118 curr_style = CURRENT_DEMANGLING_STYLE;
9119 cplus_demangle_set_style (no_demangling);
9120 c_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_NO_OPTS);
9121 if (!c_sym)
9122 c_sym = sym;
9123 cplus_demangle_set_style (curr_style);
9124
9125 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9126 {
9127 cxx_sym = bfd_demangle (link_info.output_bfd, sym,
9128 DMGL_PARAMS | DMGL_ANSI);
9129 if (!cxx_sym)
9130 cxx_sym = sym;
9131 }
9132 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9133 {
9134 java_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_JAVA);
9135 if (!java_sym)
9136 java_sym = sym;
9137 }
9138
9139 if (head->htab && (prev == NULL || prev->literal))
9140 {
9141 struct bfd_elf_version_expr e;
9142
9143 switch (prev ? prev->mask : 0)
9144 {
9145 case 0:
9146 if (head->mask & BFD_ELF_VERSION_C_TYPE)
9147 {
9148 e.pattern = c_sym;
9149 expr = (struct bfd_elf_version_expr *)
9150 htab_find ((htab_t) head->htab, &e);
9151 while (expr && strcmp (expr->pattern, c_sym) == 0)
9152 if (expr->mask == BFD_ELF_VERSION_C_TYPE)
9153 goto out_ret;
9154 else
9155 expr = expr->next;
9156 }
9157 /* Fallthrough */
9158 case BFD_ELF_VERSION_C_TYPE:
9159 if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
9160 {
9161 e.pattern = cxx_sym;
9162 expr = (struct bfd_elf_version_expr *)
9163 htab_find ((htab_t) head->htab, &e);
9164 while (expr && strcmp (expr->pattern, cxx_sym) == 0)
9165 if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9166 goto out_ret;
9167 else
9168 expr = expr->next;
9169 }
9170 /* Fallthrough */
9171 case BFD_ELF_VERSION_CXX_TYPE:
9172 if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
9173 {
9174 e.pattern = java_sym;
9175 expr = (struct bfd_elf_version_expr *)
9176 htab_find ((htab_t) head->htab, &e);
9177 while (expr && strcmp (expr->pattern, java_sym) == 0)
9178 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9179 goto out_ret;
9180 else
9181 expr = expr->next;
9182 }
9183 /* Fallthrough */
9184 default:
9185 break;
9186 }
9187 }
9188
9189 /* Finally, try the wildcards. */
9190 if (prev == NULL || prev->literal)
9191 expr = head->remaining;
9192 else
9193 expr = prev->next;
9194 for (; expr; expr = expr->next)
9195 {
9196 const char *s;
9197
9198 if (!expr->pattern)
9199 continue;
9200
9201 if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
9202 break;
9203
9204 if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
9205 s = java_sym;
9206 else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
9207 s = cxx_sym;
9208 else
9209 s = c_sym;
9210 if (fnmatch (expr->pattern, s, 0) == 0)
9211 break;
9212 }
9213
9214 out_ret:
9215 if (c_sym != sym)
9216 free ((char *) c_sym);
9217 if (cxx_sym != sym)
9218 free ((char *) cxx_sym);
9219 if (java_sym != sym)
9220 free ((char *) java_sym);
9221 return expr;
9222 }
9223
9224 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
9225 return a pointer to the symbol name with any backslash quotes removed. */
9226
9227 static const char *
9228 realsymbol (const char *pattern)
9229 {
9230 const char *p;
9231 bool changed = false, backslash = false;
9232 char *s, *symbol = (char *) xmalloc (strlen (pattern) + 1);
9233
9234 for (p = pattern, s = symbol; *p != '\0'; ++p)
9235 {
9236 /* It is a glob pattern only if there is no preceding
9237 backslash. */
9238 if (backslash)
9239 {
9240 /* Remove the preceding backslash. */
9241 *(s - 1) = *p;
9242 backslash = false;
9243 changed = true;
9244 }
9245 else
9246 {
9247 if (*p == '?' || *p == '*' || *p == '[')
9248 {
9249 free (symbol);
9250 return NULL;
9251 }
9252
9253 *s++ = *p;
9254 backslash = *p == '\\';
9255 }
9256 }
9257
9258 if (changed)
9259 {
9260 *s = '\0';
9261 return symbol;
9262 }
9263 else
9264 {
9265 free (symbol);
9266 return pattern;
9267 }
9268 }
9269
9270 /* This is called for each variable name or match expression. NEW_NAME is
9271 the name of the symbol to match, or, if LITERAL_P is FALSE, a glob
9272 pattern to be matched against symbol names. */
9273
9274 struct bfd_elf_version_expr *
9275 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
9276 const char *new_name,
9277 const char *lang,
9278 bool literal_p)
9279 {
9280 struct bfd_elf_version_expr *ret;
9281
9282 ret = (struct bfd_elf_version_expr *) xmalloc (sizeof *ret);
9283 ret->next = orig;
9284 ret->symver = 0;
9285 ret->script = 0;
9286 ret->literal = true;
9287 ret->pattern = literal_p ? new_name : realsymbol (new_name);
9288 if (ret->pattern == NULL)
9289 {
9290 ret->pattern = new_name;
9291 ret->literal = false;
9292 }
9293
9294 if (lang == NULL || strcasecmp (lang, "C") == 0)
9295 ret->mask = BFD_ELF_VERSION_C_TYPE;
9296 else if (strcasecmp (lang, "C++") == 0)
9297 ret->mask = BFD_ELF_VERSION_CXX_TYPE;
9298 else if (strcasecmp (lang, "Java") == 0)
9299 ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
9300 else
9301 {
9302 einfo (_("%X%P: unknown language `%s' in version information\n"),
9303 lang);
9304 ret->mask = BFD_ELF_VERSION_C_TYPE;
9305 }
9306
9307 return ldemul_new_vers_pattern (ret);
9308 }
9309
9310 /* This is called for each set of variable names and match
9311 expressions. */
9312
9313 struct bfd_elf_version_tree *
9314 lang_new_vers_node (struct bfd_elf_version_expr *globals,
9315 struct bfd_elf_version_expr *locals)
9316 {
9317 struct bfd_elf_version_tree *ret;
9318
9319 ret = (struct bfd_elf_version_tree *) xcalloc (1, sizeof *ret);
9320 ret->globals.list = globals;
9321 ret->locals.list = locals;
9322 ret->match = lang_vers_match;
9323 ret->name_indx = (unsigned int) -1;
9324 return ret;
9325 }
9326
9327 /* This static variable keeps track of version indices. */
9328
9329 static int version_index;
9330
9331 static hashval_t
9332 version_expr_head_hash (const void *p)
9333 {
9334 const struct bfd_elf_version_expr *e =
9335 (const struct bfd_elf_version_expr *) p;
9336
9337 return htab_hash_string (e->pattern);
9338 }
9339
9340 static int
9341 version_expr_head_eq (const void *p1, const void *p2)
9342 {
9343 const struct bfd_elf_version_expr *e1 =
9344 (const struct bfd_elf_version_expr *) p1;
9345 const struct bfd_elf_version_expr *e2 =
9346 (const struct bfd_elf_version_expr *) p2;
9347
9348 return strcmp (e1->pattern, e2->pattern) == 0;
9349 }
9350
9351 static void
9352 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
9353 {
9354 size_t count = 0;
9355 struct bfd_elf_version_expr *e, *next;
9356 struct bfd_elf_version_expr **list_loc, **remaining_loc;
9357
9358 for (e = head->list; e; e = e->next)
9359 {
9360 if (e->literal)
9361 count++;
9362 head->mask |= e->mask;
9363 }
9364
9365 if (count)
9366 {
9367 head->htab = htab_create (count * 2, version_expr_head_hash,
9368 version_expr_head_eq, NULL);
9369 list_loc = &head->list;
9370 remaining_loc = &head->remaining;
9371 for (e = head->list; e; e = next)
9372 {
9373 next = e->next;
9374 if (!e->literal)
9375 {
9376 *remaining_loc = e;
9377 remaining_loc = &e->next;
9378 }
9379 else
9380 {
9381 void **loc = htab_find_slot ((htab_t) head->htab, e, INSERT);
9382
9383 if (*loc)
9384 {
9385 struct bfd_elf_version_expr *e1, *last;
9386
9387 e1 = (struct bfd_elf_version_expr *) *loc;
9388 last = NULL;
9389 do
9390 {
9391 if (e1->mask == e->mask)
9392 {
9393 last = NULL;
9394 break;
9395 }
9396 last = e1;
9397 e1 = e1->next;
9398 }
9399 while (e1 && strcmp (e1->pattern, e->pattern) == 0);
9400
9401 if (last == NULL)
9402 {
9403 /* This is a duplicate. */
9404 /* FIXME: Memory leak. Sometimes pattern is not
9405 xmalloced alone, but in larger chunk of memory. */
9406 /* free (e->pattern); */
9407 free (e);
9408 }
9409 else
9410 {
9411 e->next = last->next;
9412 last->next = e;
9413 }
9414 }
9415 else
9416 {
9417 *loc = e;
9418 *list_loc = e;
9419 list_loc = &e->next;
9420 }
9421 }
9422 }
9423 *remaining_loc = NULL;
9424 *list_loc = head->remaining;
9425 }
9426 else
9427 head->remaining = head->list;
9428 }
9429
9430 /* This is called when we know the name and dependencies of the
9431 version. */
9432
9433 void
9434 lang_register_vers_node (const char *name,
9435 struct bfd_elf_version_tree *version,
9436 struct bfd_elf_version_deps *deps)
9437 {
9438 struct bfd_elf_version_tree *t, **pp;
9439 struct bfd_elf_version_expr *e1;
9440
9441 if (name == NULL)
9442 name = "";
9443
9444 if (link_info.version_info != NULL
9445 && (name[0] == '\0' || link_info.version_info->name[0] == '\0'))
9446 {
9447 einfo (_("%X%P: anonymous version tag cannot be combined"
9448 " with other version tags\n"));
9449 free (version);
9450 return;
9451 }
9452
9453 /* Make sure this node has a unique name. */
9454 for (t = link_info.version_info; t != NULL; t = t->next)
9455 if (strcmp (t->name, name) == 0)
9456 einfo (_("%X%P: duplicate version tag `%s'\n"), name);
9457
9458 lang_finalize_version_expr_head (&version->globals);
9459 lang_finalize_version_expr_head (&version->locals);
9460
9461 /* Check the global and local match names, and make sure there
9462 aren't any duplicates. */
9463
9464 for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
9465 {
9466 for (t = link_info.version_info; t != NULL; t = t->next)
9467 {
9468 struct bfd_elf_version_expr *e2;
9469
9470 if (t->locals.htab && e1->literal)
9471 {
9472 e2 = (struct bfd_elf_version_expr *)
9473 htab_find ((htab_t) t->locals.htab, e1);
9474 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9475 {
9476 if (e1->mask == e2->mask)
9477 einfo (_("%X%P: duplicate expression `%s'"
9478 " in version information\n"), e1->pattern);
9479 e2 = e2->next;
9480 }
9481 }
9482 else if (!e1->literal)
9483 for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
9484 if (strcmp (e1->pattern, e2->pattern) == 0
9485 && e1->mask == e2->mask)
9486 einfo (_("%X%P: duplicate expression `%s'"
9487 " in version information\n"), e1->pattern);
9488 }
9489 }
9490
9491 for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
9492 {
9493 for (t = link_info.version_info; t != NULL; t = t->next)
9494 {
9495 struct bfd_elf_version_expr *e2;
9496
9497 if (t->globals.htab && e1->literal)
9498 {
9499 e2 = (struct bfd_elf_version_expr *)
9500 htab_find ((htab_t) t->globals.htab, e1);
9501 while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9502 {
9503 if (e1->mask == e2->mask)
9504 einfo (_("%X%P: duplicate expression `%s'"
9505 " in version information\n"),
9506 e1->pattern);
9507 e2 = e2->next;
9508 }
9509 }
9510 else if (!e1->literal)
9511 for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
9512 if (strcmp (e1->pattern, e2->pattern) == 0
9513 && e1->mask == e2->mask)
9514 einfo (_("%X%P: duplicate expression `%s'"
9515 " in version information\n"), e1->pattern);
9516 }
9517 }
9518
9519 version->deps = deps;
9520 version->name = name;
9521 if (name[0] != '\0')
9522 {
9523 ++version_index;
9524 version->vernum = version_index;
9525 }
9526 else
9527 version->vernum = 0;
9528
9529 for (pp = &link_info.version_info; *pp != NULL; pp = &(*pp)->next)
9530 ;
9531 *pp = version;
9532 }
9533
9534 /* This is called when we see a version dependency. */
9535
9536 struct bfd_elf_version_deps *
9537 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
9538 {
9539 struct bfd_elf_version_deps *ret;
9540 struct bfd_elf_version_tree *t;
9541
9542 ret = (struct bfd_elf_version_deps *) xmalloc (sizeof *ret);
9543 ret->next = list;
9544
9545 for (t = link_info.version_info; t != NULL; t = t->next)
9546 {
9547 if (strcmp (t->name, name) == 0)
9548 {
9549 ret->version_needed = t;
9550 return ret;
9551 }
9552 }
9553
9554 einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
9555
9556 ret->version_needed = NULL;
9557 return ret;
9558 }
9559
9560 static void
9561 lang_do_version_exports_section (void)
9562 {
9563 struct bfd_elf_version_expr *greg = NULL, *lreg;
9564
9565 LANG_FOR_EACH_INPUT_STATEMENT (is)
9566 {
9567 asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
9568 char *contents, *p;
9569 bfd_size_type len;
9570
9571 if (sec == NULL)
9572 continue;
9573
9574 len = sec->size;
9575 contents = (char *) xmalloc (len);
9576 if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
9577 einfo (_("%X%P: unable to read .exports section contents\n"), sec);
9578
9579 p = contents;
9580 while (p < contents + len)
9581 {
9582 greg = lang_new_vers_pattern (greg, p, NULL, false);
9583 p = strchr (p, '\0') + 1;
9584 }
9585
9586 /* Do not free the contents, as we used them creating the regex. */
9587
9588 /* Do not include this section in the link. */
9589 sec->flags |= SEC_EXCLUDE | SEC_KEEP;
9590 }
9591
9592 lreg = lang_new_vers_pattern (NULL, "*", NULL, false);
9593 lang_register_vers_node (command_line.version_exports_section,
9594 lang_new_vers_node (greg, lreg), NULL);
9595 }
9596
9597 /* Evaluate LENGTH and ORIGIN parts of MEMORY spec. This is initially
9598 called with UPDATE_REGIONS_P set to FALSE, in this case no errors are
9599 thrown, however, references to symbols in the origin and length fields
9600 will be pushed into the symbol table, this allows PROVIDE statements to
9601 then provide these symbols. This function is called a second time with
9602 UPDATE_REGIONS_P set to TRUE, this time the we update the actual region
9603 data structures, and throw errors if missing symbols are encountered. */
9604
9605 static void
9606 lang_do_memory_regions (bool update_regions_p)
9607 {
9608 lang_memory_region_type *r = lang_memory_region_list;
9609
9610 for (; r != NULL; r = r->next)
9611 {
9612 if (r->origin_exp)
9613 {
9614 exp_fold_tree_no_dot (r->origin_exp);
9615 if (update_regions_p)
9616 {
9617 if (expld.result.valid_p)
9618 {
9619 r->origin = expld.result.value;
9620 r->current = r->origin;
9621 }
9622 else
9623 einfo (_("%P: invalid origin for memory region %s\n"),
9624 r->name_list.name);
9625 }
9626 }
9627 if (r->length_exp)
9628 {
9629 exp_fold_tree_no_dot (r->length_exp);
9630 if (update_regions_p)
9631 {
9632 if (expld.result.valid_p)
9633 r->length = expld.result.value;
9634 else
9635 einfo (_("%P: invalid length for memory region %s\n"),
9636 r->name_list.name);
9637 }
9638 }
9639 }
9640 }
9641
9642 void
9643 lang_add_unique (const char *name)
9644 {
9645 struct unique_sections *ent;
9646
9647 for (ent = unique_section_list; ent; ent = ent->next)
9648 if (strcmp (ent->name, name) == 0)
9649 return;
9650
9651 ent = (struct unique_sections *) xmalloc (sizeof *ent);
9652 ent->name = xstrdup (name);
9653 ent->next = unique_section_list;
9654 unique_section_list = ent;
9655 }
9656
9657 /* Append the list of dynamic symbols to the existing one. */
9658
9659 void
9660 lang_append_dynamic_list (struct bfd_elf_dynamic_list **list_p,
9661 struct bfd_elf_version_expr *dynamic)
9662 {
9663 if (*list_p)
9664 {
9665 struct bfd_elf_version_expr *tail;
9666 for (tail = dynamic; tail->next != NULL; tail = tail->next)
9667 ;
9668 tail->next = (*list_p)->head.list;
9669 (*list_p)->head.list = dynamic;
9670 }
9671 else
9672 {
9673 struct bfd_elf_dynamic_list *d;
9674
9675 d = (struct bfd_elf_dynamic_list *) xcalloc (1, sizeof *d);
9676 d->head.list = dynamic;
9677 d->match = lang_vers_match;
9678 *list_p = d;
9679 }
9680 }
9681
9682 /* Append the list of C++ typeinfo dynamic symbols to the existing
9683 one. */
9684
9685 void
9686 lang_append_dynamic_list_cpp_typeinfo (void)
9687 {
9688 const char *symbols[] =
9689 {
9690 "typeinfo name for*",
9691 "typeinfo for*"
9692 };
9693 struct bfd_elf_version_expr *dynamic = NULL;
9694 unsigned int i;
9695
9696 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9697 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9698 false);
9699
9700 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9701 }
9702
9703 /* Append the list of C++ operator new and delete dynamic symbols to the
9704 existing one. */
9705
9706 void
9707 lang_append_dynamic_list_cpp_new (void)
9708 {
9709 const char *symbols[] =
9710 {
9711 "operator new*",
9712 "operator delete*"
9713 };
9714 struct bfd_elf_version_expr *dynamic = NULL;
9715 unsigned int i;
9716
9717 for (i = 0; i < ARRAY_SIZE (symbols); i++)
9718 dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9719 false);
9720
9721 lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9722 }
9723
9724 /* Scan a space and/or comma separated string of features. */
9725
9726 void
9727 lang_ld_feature (char *str)
9728 {
9729 char *p, *q;
9730
9731 p = str;
9732 while (*p)
9733 {
9734 char sep;
9735 while (*p == ',' || ISSPACE (*p))
9736 ++p;
9737 if (!*p)
9738 break;
9739 q = p + 1;
9740 while (*q && *q != ',' && !ISSPACE (*q))
9741 ++q;
9742 sep = *q;
9743 *q = 0;
9744 if (strcasecmp (p, "SANE_EXPR") == 0)
9745 config.sane_expr = true;
9746 else
9747 einfo (_("%X%P: unknown feature `%s'\n"), p);
9748 *q = sep;
9749 p = q;
9750 }
9751 }
9752
9753 /* Pretty print memory amount. */
9754
9755 static void
9756 lang_print_memory_size (uint64_t sz)
9757 {
9758 if ((sz & 0x3fffffff) == 0)
9759 printf ("%10" PRIu64 " GB", sz >> 30);
9760 else if ((sz & 0xfffff) == 0)
9761 printf ("%10" PRIu64 " MB", sz >> 20);
9762 else if ((sz & 0x3ff) == 0)
9763 printf ("%10" PRIu64 " KB", sz >> 10);
9764 else
9765 printf (" %10" PRIu64 " B", sz);
9766 }
9767
9768 /* Implement --print-memory-usage: disply per region memory usage. */
9769
9770 void
9771 lang_print_memory_usage (void)
9772 {
9773 lang_memory_region_type *r;
9774
9775 printf ("Memory region Used Size Region Size %%age Used\n");
9776 for (r = lang_memory_region_list; r->next != NULL; r = r->next)
9777 {
9778 bfd_vma used_length = r->current - r->origin;
9779
9780 printf ("%16s: ",r->name_list.name);
9781 lang_print_memory_size (used_length);
9782 lang_print_memory_size (r->length);
9783
9784 if (r->length != 0)
9785 {
9786 double percent = used_length * 100.0 / r->length;
9787 printf (" %6.2f%%", percent);
9788 }
9789 printf ("\n");
9790 }
9791 }