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