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