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