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