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