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