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