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