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