OSDN Git Service

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