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