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