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