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