* ldgram.y (statement_anywhere): Add assert rule.
[external/binutils.git] / ld / ldlang.c
1 /* Linker command language support.
2    Copyright 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004
4    Free Software Foundation, Inc.
5
6    This file is part of GLD, the Gnu Linker.
7
8    GLD is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    GLD is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GLD; see the file COPYING.  If not, write to the Free
20    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21    02111-1307, USA.  */
22
23 #include "bfd.h"
24 #include "sysdep.h"
25 #include "libiberty.h"
26 #include "safe-ctype.h"
27 #include "obstack.h"
28 #include "bfdlink.h"
29
30 #include "ld.h"
31 #include "ldmain.h"
32 #include "ldexp.h"
33 #include "ldlang.h"
34 #include <ldgram.h>
35 #include "ldlex.h"
36 #include "ldmisc.h"
37 #include "ldctor.h"
38 #include "ldfile.h"
39 #include "ldemul.h"
40 #include "fnmatch.h"
41 #include "demangle.h"
42 #include "hashtab.h"
43
44 #ifndef offsetof
45 #define offsetof(TYPE, MEMBER) ((size_t) & (((TYPE*) 0)->MEMBER))
46 #endif
47
48 /* Locals variables.  */
49 static struct obstack stat_obstack;
50
51 #define obstack_chunk_alloc xmalloc
52 #define obstack_chunk_free free
53 static const char *startup_file;
54 static lang_statement_list_type input_file_chain;
55 static bfd_boolean placed_commons = FALSE;
56 static lang_output_section_statement_type *default_common_section;
57 static bfd_boolean map_option_f;
58 static bfd_vma print_dot;
59 static lang_input_statement_type *first_file;
60 static const char *current_target;
61 static const char *output_target;
62 static lang_statement_list_type statement_list;
63 static struct lang_phdr *lang_phdr_list;
64 static struct bfd_hash_table lang_definedness_table;
65
66 /* Forward declarations.  */
67 static void exp_init_os (etree_type *);
68 static bfd_boolean wildcardp (const char *);
69 static lang_input_statement_type *lookup_name (const char *);
70 static bfd_boolean load_symbols (lang_input_statement_type *,
71                                  lang_statement_list_type *);
72 static struct bfd_hash_entry *lang_definedness_newfunc
73  (struct bfd_hash_entry *, struct bfd_hash_table *, const char *);
74 static void insert_undefined (const char *);
75 static void print_statement (lang_statement_union_type *,
76                              lang_output_section_statement_type *);
77 static void print_statement_list (lang_statement_union_type *,
78                                   lang_output_section_statement_type *);
79 static void print_statements (void);
80 static bfd_boolean lang_one_common (struct bfd_link_hash_entry *, void *);
81 static void lang_record_phdrs (void);
82 static void lang_do_version_exports_section (void);
83
84 typedef void (*callback_t) (lang_wild_statement_type *, struct wildcard_list *,
85                             asection *, lang_input_statement_type *, void *);
86
87 /* Exported variables.  */
88 lang_output_section_statement_type *abs_output_section;
89 lang_statement_list_type lang_output_section_statement;
90 lang_statement_list_type *stat_ptr = &statement_list;
91 lang_statement_list_type file_chain = { NULL, NULL };
92 struct bfd_sym_chain entry_symbol = { NULL, NULL };
93 const char *entry_section = ".text";
94 bfd_boolean entry_from_cmdline;
95 bfd_boolean lang_has_input_file = FALSE;
96 bfd_boolean had_output_filename = FALSE;
97 bfd_boolean lang_float_flag = FALSE;
98 bfd_boolean delete_output_file_on_failure = FALSE;
99 struct lang_nocrossrefs *nocrossref_list;
100 struct unique_sections *unique_section_list;
101 static bfd_boolean ldlang_sysrooted_script = FALSE;
102 int lang_statement_iteration = 0;
103
104 etree_type *base; /* Relocation base - or null */
105
106 #define new_stat(x, y) \
107   (x##_type *) new_statement (x##_enum, sizeof (x##_type), y)
108
109 #define outside_section_address(q) \
110   ((q)->output_offset + (q)->output_section->vma)
111
112 #define outside_symbol_address(q) \
113   ((q)->value + outside_section_address (q->section))
114
115 #define SECTION_NAME_MAP_LENGTH (16)
116
117 void *
118 stat_alloc (size_t size)
119 {
120   return obstack_alloc (&stat_obstack, size);
121 }
122
123 bfd_boolean
124 unique_section_p (const char *secnam)
125 {
126   struct unique_sections *unam;
127
128   for (unam = unique_section_list; unam; unam = unam->next)
129     if (wildcardp (unam->name)
130         ? fnmatch (unam->name, secnam, 0) == 0
131         : strcmp (unam->name, secnam) == 0)
132       {
133         return TRUE;
134       }
135
136   return FALSE;
137 }
138
139 /* Generic traversal routines for finding matching sections.  */
140
141 static void
142 walk_wild_section (lang_wild_statement_type *ptr,
143                    lang_input_statement_type *file,
144                    callback_t callback,
145                    void *data)
146 {
147   asection *s;
148
149   if (file->just_syms_flag)
150     return;
151
152   for (s = file->the_bfd->sections; s != NULL; s = s->next)
153     {
154       struct wildcard_list *sec;
155
156       sec = ptr->section_list;
157       if (sec == NULL)
158         (*callback) (ptr, sec, s, file, data);
159
160       while (sec != NULL)
161         {
162           bfd_boolean skip = FALSE;
163           struct name_list *list_tmp;
164
165           /* Don't process sections from files which were
166              excluded.  */
167           for (list_tmp = sec->spec.exclude_name_list;
168                list_tmp;
169                list_tmp = list_tmp->next)
170             {
171               if (wildcardp (list_tmp->name))
172                 skip = fnmatch (list_tmp->name, file->filename, 0) == 0;
173               else
174                 skip = strcmp (list_tmp->name, file->filename) == 0;
175
176               /* If this file is part of an archive, and the archive is
177                  excluded, exclude this file.  */
178               if (! skip && file->the_bfd != NULL
179                   && file->the_bfd->my_archive != NULL
180                   && file->the_bfd->my_archive->filename != NULL)
181                 {
182                   if (wildcardp (list_tmp->name))
183                     skip = fnmatch (list_tmp->name,
184                                     file->the_bfd->my_archive->filename,
185                                     0) == 0;
186                   else
187                     skip = strcmp (list_tmp->name,
188                                    file->the_bfd->my_archive->filename) == 0;
189                 }
190
191               if (skip)
192                 break;
193             }
194
195           if (!skip && sec->spec.name != NULL)
196             {
197               const char *sname = bfd_get_section_name (file->the_bfd, s);
198
199               if (wildcardp (sec->spec.name))
200                 skip = fnmatch (sec->spec.name, sname, 0) != 0;
201               else
202                 skip = strcmp (sec->spec.name, sname) != 0;
203             }
204
205           if (!skip)
206             (*callback) (ptr, sec, s, file, data);
207
208           sec = sec->next;
209         }
210     }
211 }
212
213 /* Handle a wild statement for a single file F.  */
214
215 static void
216 walk_wild_file (lang_wild_statement_type *s,
217                 lang_input_statement_type *f,
218                 callback_t callback,
219                 void *data)
220 {
221   if (f->the_bfd == NULL
222       || ! bfd_check_format (f->the_bfd, bfd_archive))
223     walk_wild_section (s, f, callback, data);
224   else
225     {
226       bfd *member;
227
228       /* This is an archive file.  We must map each member of the
229          archive separately.  */
230       member = bfd_openr_next_archived_file (f->the_bfd, NULL);
231       while (member != NULL)
232         {
233           /* When lookup_name is called, it will call the add_symbols
234              entry point for the archive.  For each element of the
235              archive which is included, BFD will call ldlang_add_file,
236              which will set the usrdata field of the member to the
237              lang_input_statement.  */
238           if (member->usrdata != NULL)
239             {
240               walk_wild_section (s, member->usrdata, callback, data);
241             }
242
243           member = bfd_openr_next_archived_file (f->the_bfd, member);
244         }
245     }
246 }
247
248 static void
249 walk_wild (lang_wild_statement_type *s, callback_t callback, void *data)
250 {
251   const char *file_spec = s->filename;
252
253   if (file_spec == NULL)
254     {
255       /* Perform the iteration over all files in the list.  */
256       LANG_FOR_EACH_INPUT_STATEMENT (f)
257         {
258           walk_wild_file (s, f, callback, data);
259         }
260     }
261   else if (wildcardp (file_spec))
262     {
263       LANG_FOR_EACH_INPUT_STATEMENT (f)
264         {
265           if (fnmatch (file_spec, f->filename, FNM_FILE_NAME) == 0)
266             walk_wild_file (s, f, callback, data);
267         }
268     }
269   else
270     {
271       lang_input_statement_type *f;
272
273       /* Perform the iteration over a single file.  */
274       f = lookup_name (file_spec);
275       if (f)
276         walk_wild_file (s, f, callback, data);
277     }
278 }
279
280 /* lang_for_each_statement walks the parse tree and calls the provided
281    function for each node.  */
282
283 static void
284 lang_for_each_statement_worker (void (*func) (lang_statement_union_type *),
285                                 lang_statement_union_type *s)
286 {
287   for (; s != NULL; s = s->header.next)
288     {
289       func (s);
290
291       switch (s->header.type)
292         {
293         case lang_constructors_statement_enum:
294           lang_for_each_statement_worker (func, constructor_list.head);
295           break;
296         case lang_output_section_statement_enum:
297           lang_for_each_statement_worker
298             (func,
299              s->output_section_statement.children.head);
300           break;
301         case lang_wild_statement_enum:
302           lang_for_each_statement_worker
303             (func,
304              s->wild_statement.children.head);
305           break;
306         case lang_group_statement_enum:
307           lang_for_each_statement_worker (func,
308                                           s->group_statement.children.head);
309           break;
310         case lang_data_statement_enum:
311         case lang_reloc_statement_enum:
312         case lang_object_symbols_statement_enum:
313         case lang_output_statement_enum:
314         case lang_target_statement_enum:
315         case lang_input_section_enum:
316         case lang_input_statement_enum:
317         case lang_assignment_statement_enum:
318         case lang_padding_statement_enum:
319         case lang_address_statement_enum:
320         case lang_fill_statement_enum:
321           break;
322         default:
323           FAIL ();
324           break;
325         }
326     }
327 }
328
329 void
330 lang_for_each_statement (void (*func) (lang_statement_union_type *))
331 {
332   lang_for_each_statement_worker (func, statement_list.head);
333 }
334
335 /*----------------------------------------------------------------------*/
336
337 void
338 lang_list_init (lang_statement_list_type *list)
339 {
340   list->head = NULL;
341   list->tail = &list->head;
342 }
343
344 /* Build a new statement node for the parse tree.  */
345
346 static lang_statement_union_type *
347 new_statement (enum statement_enum type,
348                size_t size,
349                lang_statement_list_type *list)
350 {
351   lang_statement_union_type *new;
352
353   new = stat_alloc (size);
354   new->header.type = type;
355   new->header.next = NULL;
356   lang_statement_append (list, new, &new->header.next);
357   return new;
358 }
359
360 /* Build a new input file node for the language.  There are several
361    ways in which we treat an input file, eg, we only look at symbols,
362    or prefix it with a -l etc.
363
364    We can be supplied with requests for input files more than once;
365    they may, for example be split over several lines like foo.o(.text)
366    foo.o(.data) etc, so when asked for a file we check that we haven't
367    got it already so we don't duplicate the bfd.  */
368
369 static lang_input_statement_type *
370 new_afile (const char *name,
371            lang_input_file_enum_type file_type,
372            const char *target,
373            bfd_boolean add_to_list)
374 {
375   lang_input_statement_type *p;
376
377   if (add_to_list)
378     p = new_stat (lang_input_statement, stat_ptr);
379   else
380     {
381       p = stat_alloc (sizeof (lang_input_statement_type));
382       p->header.next = NULL;
383     }
384
385   lang_has_input_file = TRUE;
386   p->target = target;
387   p->sysrooted = FALSE;
388   switch (file_type)
389     {
390     case lang_input_file_is_symbols_only_enum:
391       p->filename = name;
392       p->is_archive = FALSE;
393       p->real = TRUE;
394       p->local_sym_name = name;
395       p->just_syms_flag = TRUE;
396       p->search_dirs_flag = FALSE;
397       break;
398     case lang_input_file_is_fake_enum:
399       p->filename = name;
400       p->is_archive = FALSE;
401       p->real = FALSE;
402       p->local_sym_name = name;
403       p->just_syms_flag = FALSE;
404       p->search_dirs_flag = FALSE;
405       break;
406     case lang_input_file_is_l_enum:
407       p->is_archive = TRUE;
408       p->filename = name;
409       p->real = TRUE;
410       p->local_sym_name = concat ("-l", name, NULL);
411       p->just_syms_flag = FALSE;
412       p->search_dirs_flag = TRUE;
413       break;
414     case lang_input_file_is_marker_enum:
415       p->filename = name;
416       p->is_archive = FALSE;
417       p->real = FALSE;
418       p->local_sym_name = name;
419       p->just_syms_flag = FALSE;
420       p->search_dirs_flag = TRUE;
421       break;
422     case lang_input_file_is_search_file_enum:
423       p->sysrooted = ldlang_sysrooted_script;
424       p->filename = name;
425       p->is_archive = FALSE;
426       p->real = TRUE;
427       p->local_sym_name = name;
428       p->just_syms_flag = FALSE;
429       p->search_dirs_flag = TRUE;
430       break;
431     case lang_input_file_is_file_enum:
432       p->filename = name;
433       p->is_archive = FALSE;
434       p->real = TRUE;
435       p->local_sym_name = name;
436       p->just_syms_flag = FALSE;
437       p->search_dirs_flag = FALSE;
438       break;
439     default:
440       FAIL ();
441     }
442   p->the_bfd = NULL;
443   p->asymbols = NULL;
444   p->next_real_file = NULL;
445   p->next = NULL;
446   p->symbol_count = 0;
447   p->dynamic = config.dynamic_link;
448   p->whole_archive = whole_archive;
449   p->loaded = FALSE;
450   lang_statement_append (&input_file_chain,
451                          (lang_statement_union_type *) p,
452                          &p->next_real_file);
453   return p;
454 }
455
456 lang_input_statement_type *
457 lang_add_input_file (const char *name,
458                      lang_input_file_enum_type file_type,
459                      const char *target)
460 {
461   lang_has_input_file = TRUE;
462   return new_afile (name, file_type, target, TRUE);
463 }
464
465 /* Build enough state so that the parser can build its tree.  */
466
467 void
468 lang_init (void)
469 {
470   obstack_begin (&stat_obstack, 1000);
471
472   stat_ptr = &statement_list;
473
474   lang_list_init (stat_ptr);
475
476   lang_list_init (&input_file_chain);
477   lang_list_init (&lang_output_section_statement);
478   lang_list_init (&file_chain);
479   first_file = lang_add_input_file (NULL, lang_input_file_is_marker_enum,
480                                     NULL);
481   abs_output_section =
482     lang_output_section_statement_lookup (BFD_ABS_SECTION_NAME);
483
484   abs_output_section->bfd_section = bfd_abs_section_ptr;
485
486   /* The value "3" is ad-hoc, somewhat related to the expected number of
487      DEFINED expressions in a linker script.  For most default linker
488      scripts, there are none.  Why a hash table then?  Well, it's somewhat
489      simpler to re-use working machinery than using a linked list in terms
490      of code-complexity here in ld, besides the initialization which just
491      looks like other code here.  */
492   if (bfd_hash_table_init_n (&lang_definedness_table,
493                              lang_definedness_newfunc, 3) != TRUE)
494     einfo (_("%P%F: out of memory during initialization"));
495
496   /* Callers of exp_fold_tree need to increment this.  */
497   lang_statement_iteration = 0;
498 }
499
500 /*----------------------------------------------------------------------
501   A region is an area of memory declared with the
502   MEMORY {  name:org=exp, len=exp ... }
503   syntax.
504
505   We maintain a list of all the regions here.
506
507   If no regions are specified in the script, then the default is used
508   which is created when looked up to be the entire data space.
509
510   If create is true we are creating a region inside a MEMORY block.
511   In this case it is probably an error to create a region that has
512   already been created.  If we are not inside a MEMORY block it is
513   dubious to use an undeclared region name (except DEFAULT_MEMORY_REGION)
514   and so we issue a warning.  */
515
516 static lang_memory_region_type *lang_memory_region_list;
517 static lang_memory_region_type **lang_memory_region_list_tail = &lang_memory_region_list;
518
519 lang_memory_region_type *
520 lang_memory_region_lookup (const char *const name, bfd_boolean create)
521 {
522   lang_memory_region_type *p;
523   lang_memory_region_type *new;
524
525   /* NAME is NULL for LMA memspecs if no region was specified.  */
526   if (name == NULL)
527     return NULL;
528
529   for (p = lang_memory_region_list; p != NULL; p = p->next)
530     if (strcmp (p->name, name) == 0)
531       {
532         if (create)
533           einfo (_("%P:%S: warning: redeclaration of memory region '%s'\n"), name);
534         return p;
535       }
536
537 #if 0
538   /* This code used to always use the first region in the list as the
539      default region.  I changed it to instead use a region
540      encompassing all of memory as the default region.  This permits
541      NOLOAD sections to work reasonably without requiring a region.
542      People should specify what region they mean, if they really want
543      a region.  */
544   if (strcmp (name, DEFAULT_MEMORY_REGION) == 0)
545     {
546       if (lang_memory_region_list != NULL)
547         return lang_memory_region_list;
548     }
549 #endif
550
551   if (!create && strcmp (name, DEFAULT_MEMORY_REGION))
552     einfo (_("%P:%S: warning: memory region %s not declared\n"), name);
553
554   new = stat_alloc (sizeof (lang_memory_region_type));
555
556   new->name = xstrdup (name);
557   new->next = NULL;
558
559   *lang_memory_region_list_tail = new;
560   lang_memory_region_list_tail = &new->next;
561   new->origin = 0;
562   new->flags = 0;
563   new->not_flags = 0;
564   new->length = ~(bfd_size_type) 0;
565   new->current = 0;
566   new->had_full_message = FALSE;
567
568   return new;
569 }
570
571 static lang_memory_region_type *
572 lang_memory_default (asection *section)
573 {
574   lang_memory_region_type *p;
575
576   flagword sec_flags = section->flags;
577
578   /* Override SEC_DATA to mean a writable section.  */
579   if ((sec_flags & (SEC_ALLOC | SEC_READONLY | SEC_CODE)) == SEC_ALLOC)
580     sec_flags |= SEC_DATA;
581
582   for (p = lang_memory_region_list; p != NULL; p = p->next)
583     {
584       if ((p->flags & sec_flags) != 0
585           && (p->not_flags & sec_flags) == 0)
586         {
587           return p;
588         }
589     }
590   return lang_memory_region_lookup (DEFAULT_MEMORY_REGION, FALSE);
591 }
592
593 lang_output_section_statement_type *
594 lang_output_section_find (const char *const name)
595 {
596   lang_statement_union_type *u;
597   lang_output_section_statement_type *lookup;
598
599   for (u = lang_output_section_statement.head; u != NULL; u = lookup->next)
600     {
601       lookup = &u->output_section_statement;
602       if (strcmp (name, lookup->name) == 0)
603         return lookup;
604     }
605   return NULL;
606 }
607
608 lang_output_section_statement_type *
609 lang_output_section_statement_lookup (const char *const name)
610 {
611   lang_output_section_statement_type *lookup;
612
613   lookup = lang_output_section_find (name);
614   if (lookup == NULL)
615     {
616       lookup = new_stat (lang_output_section_statement, stat_ptr);
617       lookup->region = NULL;
618       lookup->lma_region = NULL;
619       lookup->fill = 0;
620       lookup->block_value = 1;
621       lookup->name = name;
622
623       lookup->next = NULL;
624       lookup->bfd_section = NULL;
625       lookup->processed = FALSE;
626       lookup->sectype = normal_section;
627       lookup->addr_tree = NULL;
628       lang_list_init (&lookup->children);
629
630       lookup->memspec = NULL;
631       lookup->flags = 0;
632       lookup->subsection_alignment = -1;
633       lookup->section_alignment = -1;
634       lookup->load_base = NULL;
635       lookup->update_dot_tree = NULL;
636       lookup->phdrs = NULL;
637
638       lang_statement_append (&lang_output_section_statement,
639                              (lang_statement_union_type *) lookup,
640                              &lookup->next);
641     }
642   return lookup;
643 }
644
645 static void
646 lang_map_flags (flagword flag)
647 {
648   if (flag & SEC_ALLOC)
649     minfo ("a");
650
651   if (flag & SEC_CODE)
652     minfo ("x");
653
654   if (flag & SEC_READONLY)
655     minfo ("r");
656
657   if (flag & SEC_DATA)
658     minfo ("w");
659
660   if (flag & SEC_LOAD)
661     minfo ("l");
662 }
663
664 void
665 lang_map (void)
666 {
667   lang_memory_region_type *m;
668
669   minfo (_("\nMemory Configuration\n\n"));
670   fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
671            _("Name"), _("Origin"), _("Length"), _("Attributes"));
672
673   for (m = lang_memory_region_list; m != NULL; m = m->next)
674     {
675       char buf[100];
676       int len;
677
678       fprintf (config.map_file, "%-16s ", m->name);
679
680       sprintf_vma (buf, m->origin);
681       minfo ("0x%s ", buf);
682       len = strlen (buf);
683       while (len < 16)
684         {
685           print_space ();
686           ++len;
687         }
688
689       minfo ("0x%V", m->length);
690       if (m->flags || m->not_flags)
691         {
692 #ifndef BFD64
693           minfo ("        ");
694 #endif
695           if (m->flags)
696             {
697               print_space ();
698               lang_map_flags (m->flags);
699             }
700
701           if (m->not_flags)
702             {
703               minfo (" !");
704               lang_map_flags (m->not_flags);
705             }
706         }
707
708       print_nl ();
709     }
710
711   fprintf (config.map_file, _("\nLinker script and memory map\n\n"));
712
713   print_statements ();
714 }
715
716 /* Initialize an output section.  */
717
718 static void
719 init_os (lang_output_section_statement_type *s)
720 {
721   section_userdata_type *new;
722
723   if (s->bfd_section != NULL)
724     return;
725
726   if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
727     einfo (_("%P%F: Illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
728
729   new = stat_alloc (sizeof (section_userdata_type));
730
731   s->bfd_section = bfd_get_section_by_name (output_bfd, s->name);
732   if (s->bfd_section == NULL)
733     s->bfd_section = bfd_make_section (output_bfd, s->name);
734   if (s->bfd_section == NULL)
735     {
736       einfo (_("%P%F: output format %s cannot represent section called %s\n"),
737              output_bfd->xvec->name, s->name);
738     }
739   s->bfd_section->output_section = s->bfd_section;
740
741   /* We initialize an output sections output offset to minus its own
742      vma to allow us to output a section through itself.  */
743   s->bfd_section->output_offset = 0;
744   get_userdata (s->bfd_section) = new;
745
746   /* If there is a base address, make sure that any sections it might
747      mention are initialized.  */
748   if (s->addr_tree != NULL)
749     exp_init_os (s->addr_tree);
750
751   if (s->load_base != NULL)
752     exp_init_os (s->load_base);
753 }
754
755 /* Make sure that all output sections mentioned in an expression are
756    initialized.  */
757
758 static void
759 exp_init_os (etree_type *exp)
760 {
761   switch (exp->type.node_class)
762     {
763     case etree_assign:
764       exp_init_os (exp->assign.src);
765       break;
766
767     case etree_binary:
768       exp_init_os (exp->binary.lhs);
769       exp_init_os (exp->binary.rhs);
770       break;
771
772     case etree_trinary:
773       exp_init_os (exp->trinary.cond);
774       exp_init_os (exp->trinary.lhs);
775       exp_init_os (exp->trinary.rhs);
776       break;
777
778     case etree_assert:
779       exp_init_os (exp->assert_s.child);
780       break;
781       
782     case etree_unary:
783       exp_init_os (exp->unary.child);
784       break;
785
786     case etree_name:
787       switch (exp->type.node_code)
788         {
789         case ADDR:
790         case LOADADDR:
791         case SIZEOF:
792           {
793             lang_output_section_statement_type *os;
794
795             os = lang_output_section_find (exp->name.name);
796             if (os != NULL && os->bfd_section == NULL)
797               init_os (os);
798           }
799         }
800       break;
801
802     default:
803       break;
804     }
805 }
806 \f
807 /* Sections marked with the SEC_LINK_ONCE flag should only be linked
808    once into the output.  This routine checks each section, and
809    arrange to discard it if a section of the same name has already
810    been linked.  If the section has COMDAT information, then it uses
811    that to decide whether the section should be included.  This code
812    assumes that all relevant sections have the SEC_LINK_ONCE flag set;
813    that is, it does not depend solely upon the section name.
814    section_already_linked is called via bfd_map_over_sections.  */
815
816 /* This is the shape of the elements inside the already_linked hash
817    table. It maps a name onto a list of already_linked elements with
818    the same name.  It's possible to get more than one element in a
819    list if the COMDAT sections have different names.  */
820
821 struct already_linked_hash_entry
822 {
823   struct bfd_hash_entry root;
824   struct already_linked *entry;
825 };
826
827 struct already_linked
828 {
829   struct already_linked *next;
830   asection *sec;
831 };
832
833 /* The hash table.  */
834
835 static struct bfd_hash_table already_linked_table;
836
837 static void
838 section_already_linked (bfd *abfd, asection *sec, void *data)
839 {
840   lang_input_statement_type *entry = data;
841   flagword flags;
842   const char *name;
843   struct already_linked *l;
844   struct already_linked_hash_entry *already_linked_list;
845
846   /* If we are only reading symbols from this object, then we want to
847      discard all sections.  */
848   if (entry->just_syms_flag)
849     {
850       bfd_link_just_syms (sec, &link_info);
851       return;
852     }
853
854   flags = bfd_get_section_flags (abfd, sec);
855
856   if ((flags & SEC_LINK_ONCE) == 0)
857     return;
858
859   /* FIXME: When doing a relocatable link, we may have trouble
860      copying relocations in other sections that refer to local symbols
861      in the section being discarded.  Those relocations will have to
862      be converted somehow; as of this writing I'm not sure that any of
863      the backends handle that correctly.
864
865      It is tempting to instead not discard link once sections when
866      doing a relocatable link (technically, they should be discarded
867      whenever we are building constructors).  However, that fails,
868      because the linker winds up combining all the link once sections
869      into a single large link once section, which defeats the purpose
870      of having link once sections in the first place.
871
872      Also, not merging link once sections in a relocatable link
873      causes trouble for MIPS ELF, which relies on link once semantics
874      to handle the .reginfo section correctly.  */
875
876   name = bfd_get_section_name (abfd, sec);
877
878   already_linked_list =
879     ((struct already_linked_hash_entry *)
880      bfd_hash_lookup (&already_linked_table, name, TRUE, FALSE));
881
882   for (l = already_linked_list->entry; l != NULL; l = l->next)
883     {
884       if (sec->comdat == NULL
885           || l->sec->comdat == NULL
886           || strcmp (sec->comdat->name, l->sec->comdat->name) == 0)
887         {
888           /* The section has already been linked.  See if we should
889              issue a warning.  */
890           switch (flags & SEC_LINK_DUPLICATES)
891             {
892             default:
893               abort ();
894
895             case SEC_LINK_DUPLICATES_DISCARD:
896               break;
897
898             case SEC_LINK_DUPLICATES_ONE_ONLY:
899               if (sec->comdat == NULL)
900                 einfo (_("%P: %B: warning: ignoring duplicate section `%s'\n"),
901                        abfd, name);
902               else
903                 einfo (_("%P: %B: warning: ignoring duplicate `%s' section symbol `%s'\n"),
904                        abfd, name, sec->comdat->name);
905               break;
906
907             case SEC_LINK_DUPLICATES_SAME_CONTENTS:
908               /* FIXME: We should really dig out the contents of both
909                  sections and memcmp them.  The COFF/PE spec says that
910                  the Microsoft linker does not implement this
911                  correctly, so I'm not going to bother doing it
912                  either.  */
913               /* Fall through.  */
914             case SEC_LINK_DUPLICATES_SAME_SIZE:
915               if (bfd_section_size (abfd, sec)
916                   != bfd_section_size (l->sec->owner, l->sec))
917                 einfo (_("%P: %B: warning: duplicate section `%s' has different size\n"),
918                        abfd, name);
919               break;
920             }
921
922           /* Set the output_section field so that lang_add_section
923              does not create a lang_input_section structure for this
924              section.  Since there might be a symbol in the section
925              being discarded, we must retain a pointer to the section
926              which we are really going to use.  */
927           sec->output_section = bfd_abs_section_ptr;
928           sec->kept_section = l->sec;
929
930           if (flags & SEC_GROUP)
931             bfd_discard_group (abfd, sec);
932
933           return;
934         }
935     }
936
937   /* This is the first section with this name.  Record it.  Allocate
938      the memory from the same obstack as the hash table is kept in.  */
939
940   l = bfd_hash_allocate (&already_linked_table, sizeof *l);
941
942   l->sec = sec;
943   l->next = already_linked_list->entry;
944   already_linked_list->entry = l;
945 }
946
947 /* Support routines for the hash table used by section_already_linked,
948    initialize the table, fill in an entry and remove the table.  */
949
950 static struct bfd_hash_entry *
951 already_linked_newfunc (struct bfd_hash_entry *entry ATTRIBUTE_UNUSED,
952                         struct bfd_hash_table *table,
953                         const char *string ATTRIBUTE_UNUSED)
954 {
955   struct already_linked_hash_entry *ret =
956     bfd_hash_allocate (table, sizeof (struct already_linked_hash_entry));
957
958   ret->entry = NULL;
959
960   return &ret->root;
961 }
962
963 static void
964 already_linked_table_init (void)
965 {
966   if (! bfd_hash_table_init_n (&already_linked_table,
967                                already_linked_newfunc,
968                                42))
969     einfo (_("%P%F: Failed to create hash table\n"));
970 }
971
972 static void
973 already_linked_table_free (void)
974 {
975   bfd_hash_table_free (&already_linked_table);
976 }
977 \f
978 /* The wild routines.
979
980    These expand statements like *(.text) and foo.o to a list of
981    explicit actions, like foo.o(.text), bar.o(.text) and
982    foo.o(.text, .data).  */
983
984 /* Return TRUE if the PATTERN argument is a wildcard pattern.
985    Although backslashes are treated specially if a pattern contains
986    wildcards, we do not consider the mere presence of a backslash to
987    be enough to cause the pattern to be treated as a wildcard.
988    That lets us handle DOS filenames more naturally.  */
989
990 static bfd_boolean
991 wildcardp (const char *pattern)
992 {
993   const char *s;
994
995   for (s = pattern; *s != '\0'; ++s)
996     if (*s == '?'
997         || *s == '*'
998         || *s == '[')
999       return TRUE;
1000   return FALSE;
1001 }
1002
1003 /* Add SECTION to the output section OUTPUT.  Do this by creating a
1004    lang_input_section statement which is placed at PTR.  FILE is the
1005    input file which holds SECTION.  */
1006
1007 void
1008 lang_add_section (lang_statement_list_type *ptr,
1009                   asection *section,
1010                   lang_output_section_statement_type *output,
1011                   lang_input_statement_type *file)
1012 {
1013   flagword flags;
1014   bfd_boolean discard;
1015
1016   flags = bfd_get_section_flags (section->owner, section);
1017
1018   discard = FALSE;
1019
1020   /* Discard sections marked with SEC_EXCLUDE if we are doing a final
1021      link.  Discard debugging sections marked with SEC_EXCLUDE on a
1022      relocatable link too.  */
1023   if ((flags & SEC_EXCLUDE) != 0
1024       && ((flags & SEC_DEBUGGING) != 0 || !link_info.relocatable))
1025     discard = TRUE;
1026
1027   /* Discard input sections which are assigned to a section named
1028      DISCARD_SECTION_NAME.  */
1029   if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
1030     discard = TRUE;
1031
1032   /* Discard debugging sections if we are stripping debugging
1033      information.  */
1034   if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
1035       && (flags & SEC_DEBUGGING) != 0)
1036     discard = TRUE;
1037
1038   if (discard)
1039     {
1040       if (section->output_section == NULL)
1041         {
1042           /* This prevents future calls from assigning this section.  */
1043           section->output_section = bfd_abs_section_ptr;
1044         }
1045       return;
1046     }
1047
1048   if (section->output_section == NULL)
1049     {
1050       bfd_boolean first;
1051       lang_input_section_type *new;
1052       flagword flags;
1053
1054       if (output->bfd_section == NULL)
1055         init_os (output);
1056
1057       first = ! output->bfd_section->linker_has_input;
1058       output->bfd_section->linker_has_input = 1;
1059
1060       /* Add a section reference to the list.  */
1061       new = new_stat (lang_input_section, ptr);
1062
1063       new->section = section;
1064       new->ifile = file;
1065       section->output_section = output->bfd_section;
1066
1067       flags = section->flags;
1068
1069       /* We don't copy the SEC_NEVER_LOAD flag from an input section
1070          to an output section, because we want to be able to include a
1071          SEC_NEVER_LOAD section in the middle of an otherwise loaded
1072          section (I don't know why we want to do this, but we do).
1073          build_link_order in ldwrite.c handles this case by turning
1074          the embedded SEC_NEVER_LOAD section into a fill.  */
1075
1076       flags &= ~ SEC_NEVER_LOAD;
1077
1078       /* If final link, don't copy the SEC_LINK_ONCE flags, they've
1079          already been processed.  One reason to do this is that on pe
1080          format targets, .text$foo sections go into .text and it's odd
1081          to see .text with SEC_LINK_ONCE set.  */
1082
1083       if (! link_info.relocatable)
1084         flags &= ~ (SEC_LINK_ONCE | SEC_LINK_DUPLICATES);
1085
1086       /* If this is not the first input section, and the SEC_READONLY
1087          flag is not currently set, then don't set it just because the
1088          input section has it set.  */
1089
1090       if (! first && (section->output_section->flags & SEC_READONLY) == 0)
1091         flags &= ~ SEC_READONLY;
1092
1093       /* Keep SEC_MERGE and SEC_STRINGS only if they are the same.  */
1094       if (! first
1095           && ((section->output_section->flags & (SEC_MERGE | SEC_STRINGS))
1096               != (flags & (SEC_MERGE | SEC_STRINGS))
1097               || ((flags & SEC_MERGE)
1098                   && section->output_section->entsize != section->entsize)))
1099         {
1100           section->output_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
1101           flags &= ~ (SEC_MERGE | SEC_STRINGS);
1102         }
1103
1104       /* For now make .tbss normal section.  */
1105       if ((flags & SEC_THREAD_LOCAL) && ! link_info.relocatable)
1106         flags |= SEC_LOAD;
1107
1108       section->output_section->flags |= flags;
1109
1110       if (flags & SEC_MERGE)
1111         section->output_section->entsize = section->entsize;
1112
1113       /* If SEC_READONLY is not set in the input section, then clear
1114          it from the output section.  */
1115       if ((section->flags & SEC_READONLY) == 0)
1116         section->output_section->flags &= ~SEC_READONLY;
1117
1118       switch (output->sectype)
1119         {
1120         case normal_section:
1121           break;
1122         case dsect_section:
1123         case copy_section:
1124         case info_section:
1125         case overlay_section:
1126           output->bfd_section->flags &= ~SEC_ALLOC;
1127           break;
1128         case noload_section:
1129           output->bfd_section->flags &= ~SEC_LOAD;
1130           output->bfd_section->flags |= SEC_NEVER_LOAD;
1131           break;
1132         }
1133
1134       /* Copy over SEC_SMALL_DATA.  */
1135       if (section->flags & SEC_SMALL_DATA)
1136         section->output_section->flags |= SEC_SMALL_DATA;
1137
1138       if (section->alignment_power > output->bfd_section->alignment_power)
1139         output->bfd_section->alignment_power = section->alignment_power;
1140
1141       /* If supplied an alignment, then force it.  */
1142       if (output->section_alignment != -1)
1143         output->bfd_section->alignment_power = output->section_alignment;
1144
1145       if (section->flags & SEC_BLOCK)
1146         {
1147           section->output_section->flags |= SEC_BLOCK;
1148           /* FIXME: This value should really be obtained from the bfd...  */
1149           output->block_value = 128;
1150         }
1151     }
1152 }
1153
1154 /* Handle wildcard sorting.  This returns the lang_input_section which
1155    should follow the one we are going to create for SECTION and FILE,
1156    based on the sorting requirements of WILD.  It returns NULL if the
1157    new section should just go at the end of the current list.  */
1158
1159 static lang_statement_union_type *
1160 wild_sort (lang_wild_statement_type *wild,
1161            struct wildcard_list *sec,
1162            lang_input_statement_type *file,
1163            asection *section)
1164 {
1165   const char *section_name;
1166   lang_statement_union_type *l;
1167
1168   if (!wild->filenames_sorted && (sec == NULL || !sec->spec.sorted))
1169     return NULL;
1170
1171   section_name = bfd_get_section_name (file->the_bfd, section);
1172   for (l = wild->children.head; l != NULL; l = l->header.next)
1173     {
1174       lang_input_section_type *ls;
1175
1176       if (l->header.type != lang_input_section_enum)
1177         continue;
1178       ls = &l->input_section;
1179
1180       /* Sorting by filename takes precedence over sorting by section
1181          name.  */
1182
1183       if (wild->filenames_sorted)
1184         {
1185           const char *fn, *ln;
1186           bfd_boolean fa, la;
1187           int i;
1188
1189           /* The PE support for the .idata section as generated by
1190              dlltool assumes that files will be sorted by the name of
1191              the archive and then the name of the file within the
1192              archive.  */
1193
1194           if (file->the_bfd != NULL
1195               && bfd_my_archive (file->the_bfd) != NULL)
1196             {
1197               fn = bfd_get_filename (bfd_my_archive (file->the_bfd));
1198               fa = TRUE;
1199             }
1200           else
1201             {
1202               fn = file->filename;
1203               fa = FALSE;
1204             }
1205
1206           if (ls->ifile->the_bfd != NULL
1207               && bfd_my_archive (ls->ifile->the_bfd) != NULL)
1208             {
1209               ln = bfd_get_filename (bfd_my_archive (ls->ifile->the_bfd));
1210               la = TRUE;
1211             }
1212           else
1213             {
1214               ln = ls->ifile->filename;
1215               la = FALSE;
1216             }
1217
1218           i = strcmp (fn, ln);
1219           if (i > 0)
1220             continue;
1221           else if (i < 0)
1222             break;
1223
1224           if (fa || la)
1225             {
1226               if (fa)
1227                 fn = file->filename;
1228               if (la)
1229                 ln = ls->ifile->filename;
1230
1231               i = strcmp (fn, ln);
1232               if (i > 0)
1233                 continue;
1234               else if (i < 0)
1235                 break;
1236             }
1237         }
1238
1239       /* Here either the files are not sorted by name, or we are
1240          looking at the sections for this file.  */
1241
1242       if (sec != NULL && sec->spec.sorted)
1243         {
1244           if (strcmp (section_name,
1245                       bfd_get_section_name (ls->ifile->the_bfd,
1246                                             ls->section))
1247               < 0)
1248             break;
1249         }
1250     }
1251
1252   return l;
1253 }
1254
1255 /* Expand a wild statement for a particular FILE.  SECTION may be
1256    NULL, in which case it is a wild card.  */
1257
1258 static void
1259 output_section_callback (lang_wild_statement_type *ptr,
1260                          struct wildcard_list *sec,
1261                          asection *section,
1262                          lang_input_statement_type *file,
1263                          void *output)
1264 {
1265   lang_statement_union_type *before;
1266
1267   /* Exclude sections that match UNIQUE_SECTION_LIST.  */
1268   if (unique_section_p (bfd_get_section_name (file->the_bfd, section)))
1269     return;
1270
1271   /* If the wild pattern was marked KEEP, the member sections
1272      should be as well.  */
1273   if (ptr->keep_sections)
1274     section->flags |= SEC_KEEP;
1275
1276   before = wild_sort (ptr, sec, file, section);
1277
1278   /* Here BEFORE points to the lang_input_section which
1279      should follow the one we are about to add.  If BEFORE
1280      is NULL, then the section should just go at the end
1281      of the current list.  */
1282
1283   if (before == NULL)
1284     lang_add_section (&ptr->children, section,
1285                       (lang_output_section_statement_type *) output,
1286                       file);
1287   else
1288     {
1289       lang_statement_list_type list;
1290       lang_statement_union_type **pp;
1291
1292       lang_list_init (&list);
1293       lang_add_section (&list, section,
1294                         (lang_output_section_statement_type *) output,
1295                         file);
1296
1297       /* If we are discarding the section, LIST.HEAD will
1298          be NULL.  */
1299       if (list.head != NULL)
1300         {
1301           ASSERT (list.head->header.next == NULL);
1302
1303           for (pp = &ptr->children.head;
1304                *pp != before;
1305                pp = &(*pp)->header.next)
1306             ASSERT (*pp != NULL);
1307
1308           list.head->header.next = *pp;
1309           *pp = list.head;
1310         }
1311     }
1312 }
1313
1314 /* This is passed a file name which must have been seen already and
1315    added to the statement tree.  We will see if it has been opened
1316    already and had its symbols read.  If not then we'll read it.  */
1317
1318 static lang_input_statement_type *
1319 lookup_name (const char *name)
1320 {
1321   lang_input_statement_type *search;
1322
1323   for (search = (lang_input_statement_type *) input_file_chain.head;
1324        search != NULL;
1325        search = (lang_input_statement_type *) search->next_real_file)
1326     {
1327       /* Use the local_sym_name as the name of the file that has
1328          already been loaded as filename might have been transformed
1329          via the search directory lookup mechanism.  */
1330       const char * filename = search->local_sym_name;
1331
1332       if (filename == NULL && name == NULL)
1333         return search;
1334       if (filename != NULL
1335           && name != NULL
1336           && strcmp (filename, name) == 0)
1337         break;
1338     }
1339
1340   if (search == NULL)
1341     search = new_afile (name, lang_input_file_is_search_file_enum, default_target,
1342                         FALSE);
1343
1344   /* If we have already added this file, or this file is not real
1345      (FIXME: can that ever actually happen?) or the name is NULL
1346      (FIXME: can that ever actually happen?) don't add this file.  */
1347   if (search->loaded
1348       || ! search->real
1349       || search->filename == NULL)
1350     return search;
1351
1352   if (! load_symbols (search, NULL))
1353     return NULL;
1354
1355   return search;
1356 }
1357
1358 /* Get the symbols for an input file.  */
1359
1360 static bfd_boolean
1361 load_symbols (lang_input_statement_type *entry,
1362               lang_statement_list_type *place)
1363 {
1364   char **matching;
1365
1366   if (entry->loaded)
1367     return TRUE;
1368
1369   ldfile_open_file (entry);
1370
1371   if (! bfd_check_format (entry->the_bfd, bfd_archive)
1372       && ! bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
1373     {
1374       bfd_error_type err;
1375       lang_statement_list_type *hold;
1376       bfd_boolean bad_load = TRUE;
1377       bfd_boolean save_ldlang_sysrooted_script;
1378
1379       err = bfd_get_error ();
1380
1381       /* See if the emulation has some special knowledge.  */
1382       if (ldemul_unrecognized_file (entry))
1383         return TRUE;
1384
1385       if (err == bfd_error_file_ambiguously_recognized)
1386         {
1387           char **p;
1388
1389           einfo (_("%B: file not recognized: %E\n"), entry->the_bfd);
1390           einfo (_("%B: matching formats:"), entry->the_bfd);
1391           for (p = matching; *p != NULL; p++)
1392             einfo (" %s", *p);
1393           einfo ("%F\n");
1394         }
1395       else if (err != bfd_error_file_not_recognized
1396                || place == NULL)
1397           einfo (_("%F%B: file not recognized: %E\n"), entry->the_bfd);
1398       else
1399         bad_load = FALSE;
1400
1401       bfd_close (entry->the_bfd);
1402       entry->the_bfd = NULL;
1403
1404       /* Try to interpret the file as a linker script.  */
1405       ldfile_open_command_file (entry->filename);
1406
1407       hold = stat_ptr;
1408       stat_ptr = place;
1409       save_ldlang_sysrooted_script = ldlang_sysrooted_script;
1410       ldlang_sysrooted_script = entry->sysrooted;
1411
1412       ldfile_assumed_script = TRUE;
1413       parser_input = input_script;
1414       yyparse ();
1415       ldfile_assumed_script = FALSE;
1416
1417       ldlang_sysrooted_script = save_ldlang_sysrooted_script;
1418       stat_ptr = hold;
1419
1420       return ! bad_load;
1421     }
1422
1423   if (ldemul_recognized_file (entry))
1424     return TRUE;
1425
1426   /* We don't call ldlang_add_file for an archive.  Instead, the
1427      add_symbols entry point will call ldlang_add_file, via the
1428      add_archive_element callback, for each element of the archive
1429      which is used.  */
1430   switch (bfd_get_format (entry->the_bfd))
1431     {
1432     default:
1433       break;
1434
1435     case bfd_object:
1436       ldlang_add_file (entry);
1437       if (trace_files || trace_file_tries)
1438         info_msg ("%I\n", entry);
1439       break;
1440
1441     case bfd_archive:
1442       if (entry->whole_archive)
1443         {
1444           bfd *member = NULL;
1445           bfd_boolean loaded = TRUE;
1446
1447           for (;;)
1448             {
1449               member = bfd_openr_next_archived_file (entry->the_bfd, member);
1450
1451               if (member == NULL)
1452                 break;
1453
1454               if (! bfd_check_format (member, bfd_object))
1455                 {
1456                   einfo (_("%F%B: member %B in archive is not an object\n"),
1457                          entry->the_bfd, member);
1458                   loaded = FALSE;
1459                 }
1460
1461               if (! ((*link_info.callbacks->add_archive_element)
1462                      (&link_info, member, "--whole-archive")))
1463                 abort ();
1464
1465               if (! bfd_link_add_symbols (member, &link_info))
1466                 {
1467                   einfo (_("%F%B: could not read symbols: %E\n"), member);
1468                   loaded = FALSE;
1469                 }
1470             }
1471
1472           entry->loaded = loaded;
1473           return loaded;
1474         }
1475       break;
1476     }
1477
1478   if (bfd_link_add_symbols (entry->the_bfd, &link_info))
1479     entry->loaded = TRUE;
1480   else
1481     einfo (_("%F%B: could not read symbols: %E\n"), entry->the_bfd);
1482
1483   return entry->loaded;
1484 }
1485
1486 /* Handle a wild statement.  S->FILENAME or S->SECTION_LIST or both
1487    may be NULL, indicating that it is a wildcard.  Separate
1488    lang_input_section statements are created for each part of the
1489    expansion; they are added after the wild statement S.  OUTPUT is
1490    the output section.  */
1491
1492 static void
1493 wild (lang_wild_statement_type *s,
1494       const char *target ATTRIBUTE_UNUSED,
1495       lang_output_section_statement_type *output)
1496 {
1497   struct wildcard_list *sec;
1498
1499   walk_wild (s, output_section_callback, output);
1500
1501   for (sec = s->section_list; sec != NULL; sec = sec->next)
1502     {
1503       if (default_common_section != NULL)
1504         break;
1505       if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
1506         {
1507           /* Remember the section that common is going to in case we
1508              later get something which doesn't know where to put it.  */
1509           default_common_section = output;
1510         }
1511     }
1512 }
1513
1514 /* Return TRUE iff target is the sought target.  */
1515
1516 static int
1517 get_target (const bfd_target *target, void *data)
1518 {
1519   const char *sought = data;
1520
1521   return strcmp (target->name, sought) == 0;
1522 }
1523
1524 /* Like strcpy() but convert to lower case as well.  */
1525
1526 static void
1527 stricpy (char *dest, char *src)
1528 {
1529   char c;
1530
1531   while ((c = *src++) != 0)
1532     *dest++ = TOLOWER (c);
1533
1534   *dest = 0;
1535 }
1536
1537 /* Remove the first occurrence of needle (if any) in haystack
1538    from haystack.  */
1539
1540 static void
1541 strcut (char *haystack, char *needle)
1542 {
1543   haystack = strstr (haystack, needle);
1544
1545   if (haystack)
1546     {
1547       char *src;
1548
1549       for (src = haystack + strlen (needle); *src;)
1550         *haystack++ = *src++;
1551
1552       *haystack = 0;
1553     }
1554 }
1555
1556 /* Compare two target format name strings.
1557    Return a value indicating how "similar" they are.  */
1558
1559 static int
1560 name_compare (char *first, char *second)
1561 {
1562   char *copy1;
1563   char *copy2;
1564   int result;
1565
1566   copy1 = xmalloc (strlen (first) + 1);
1567   copy2 = xmalloc (strlen (second) + 1);
1568
1569   /* Convert the names to lower case.  */
1570   stricpy (copy1, first);
1571   stricpy (copy2, second);
1572
1573   /* Remove size and endian strings from the name.  */
1574   strcut (copy1, "big");
1575   strcut (copy1, "little");
1576   strcut (copy2, "big");
1577   strcut (copy2, "little");
1578
1579   /* Return a value based on how many characters match,
1580      starting from the beginning.   If both strings are
1581      the same then return 10 * their length.  */
1582   for (result = 0; copy1[result] == copy2[result]; result++)
1583     if (copy1[result] == 0)
1584       {
1585         result *= 10;
1586         break;
1587       }
1588
1589   free (copy1);
1590   free (copy2);
1591
1592   return result;
1593 }
1594
1595 /* Set by closest_target_match() below.  */
1596 static const bfd_target *winner;
1597
1598 /* Scan all the valid bfd targets looking for one that has the endianness
1599    requirement that was specified on the command line, and is the nearest
1600    match to the original output target.  */
1601
1602 static int
1603 closest_target_match (const bfd_target *target, void *data)
1604 {
1605   const bfd_target *original = data;
1606
1607   if (command_line.endian == ENDIAN_BIG
1608       && target->byteorder != BFD_ENDIAN_BIG)
1609     return 0;
1610
1611   if (command_line.endian == ENDIAN_LITTLE
1612       && target->byteorder != BFD_ENDIAN_LITTLE)
1613     return 0;
1614
1615   /* Must be the same flavour.  */
1616   if (target->flavour != original->flavour)
1617     return 0;
1618
1619   /* If we have not found a potential winner yet, then record this one.  */
1620   if (winner == NULL)
1621     {
1622       winner = target;
1623       return 0;
1624     }
1625
1626   /* Oh dear, we now have two potential candidates for a successful match.
1627      Compare their names and choose the better one.  */
1628   if (name_compare (target->name, original->name)
1629       > name_compare (winner->name, original->name))
1630     winner = target;
1631
1632   /* Keep on searching until wqe have checked them all.  */
1633   return 0;
1634 }
1635
1636 /* Return the BFD target format of the first input file.  */
1637
1638 static char *
1639 get_first_input_target (void)
1640 {
1641   char *target = NULL;
1642
1643   LANG_FOR_EACH_INPUT_STATEMENT (s)
1644     {
1645       if (s->header.type == lang_input_statement_enum
1646           && s->real)
1647         {
1648           ldfile_open_file (s);
1649
1650           if (s->the_bfd != NULL
1651               && bfd_check_format (s->the_bfd, bfd_object))
1652             {
1653               target = bfd_get_target (s->the_bfd);
1654
1655               if (target != NULL)
1656                 break;
1657             }
1658         }
1659     }
1660
1661   return target;
1662 }
1663
1664 const char *
1665 lang_get_output_target (void)
1666 {
1667   const char *target;
1668
1669   /* Has the user told us which output format to use?  */
1670   if (output_target != NULL)
1671     return output_target;
1672
1673   /* No - has the current target been set to something other than
1674      the default?  */
1675   if (current_target != default_target)
1676     return current_target;
1677
1678   /* No - can we determine the format of the first input file?  */
1679   target = get_first_input_target ();
1680   if (target != NULL)
1681     return target;
1682
1683   /* Failed - use the default output target.  */
1684   return default_target;
1685 }
1686
1687 /* Open the output file.  */
1688
1689 static bfd *
1690 open_output (const char *name)
1691 {
1692   bfd *output;
1693
1694   output_target = lang_get_output_target ();
1695
1696   /* Has the user requested a particular endianness on the command
1697      line?  */
1698   if (command_line.endian != ENDIAN_UNSET)
1699     {
1700       const bfd_target *target;
1701       enum bfd_endian desired_endian;
1702
1703       /* Get the chosen target.  */
1704       target = bfd_search_for_target (get_target, (void *) output_target);
1705
1706       /* If the target is not supported, we cannot do anything.  */
1707       if (target != NULL)
1708         {
1709           if (command_line.endian == ENDIAN_BIG)
1710             desired_endian = BFD_ENDIAN_BIG;
1711           else
1712             desired_endian = BFD_ENDIAN_LITTLE;
1713
1714           /* See if the target has the wrong endianness.  This should
1715              not happen if the linker script has provided big and
1716              little endian alternatives, but some scrips don't do
1717              this.  */
1718           if (target->byteorder != desired_endian)
1719             {
1720               /* If it does, then see if the target provides
1721                  an alternative with the correct endianness.  */
1722               if (target->alternative_target != NULL
1723                   && (target->alternative_target->byteorder == desired_endian))
1724                 output_target = target->alternative_target->name;
1725               else
1726                 {
1727                   /* Try to find a target as similar as possible to
1728                      the default target, but which has the desired
1729                      endian characteristic.  */
1730                   bfd_search_for_target (closest_target_match,
1731                                          (void *) target);
1732
1733                   /* Oh dear - we could not find any targets that
1734                      satisfy our requirements.  */
1735                   if (winner == NULL)
1736                     einfo (_("%P: warning: could not find any targets that match endianness requirement\n"));
1737                   else
1738                     output_target = winner->name;
1739                 }
1740             }
1741         }
1742     }
1743
1744   output = bfd_openw (name, output_target);
1745
1746   if (output == NULL)
1747     {
1748       if (bfd_get_error () == bfd_error_invalid_target)
1749         einfo (_("%P%F: target %s not found\n"), output_target);
1750
1751       einfo (_("%P%F: cannot open output file %s: %E\n"), name);
1752     }
1753
1754   delete_output_file_on_failure = TRUE;
1755
1756 #if 0
1757   output->flags |= D_PAGED;
1758 #endif
1759
1760   if (! bfd_set_format (output, bfd_object))
1761     einfo (_("%P%F:%s: can not make object file: %E\n"), name);
1762   if (! bfd_set_arch_mach (output,
1763                            ldfile_output_architecture,
1764                            ldfile_output_machine))
1765     einfo (_("%P%F:%s: can not set architecture: %E\n"), name);
1766
1767   link_info.hash = bfd_link_hash_table_create (output);
1768   if (link_info.hash == NULL)
1769     einfo (_("%P%F: can not create link hash table: %E\n"));
1770
1771   bfd_set_gp_size (output, g_switch_value);
1772   return output;
1773 }
1774
1775 static void
1776 ldlang_open_output (lang_statement_union_type *statement)
1777 {
1778   switch (statement->header.type)
1779     {
1780     case lang_output_statement_enum:
1781       ASSERT (output_bfd == NULL);
1782       output_bfd = open_output (statement->output_statement.name);
1783       ldemul_set_output_arch ();
1784       if (config.magic_demand_paged && !link_info.relocatable)
1785         output_bfd->flags |= D_PAGED;
1786       else
1787         output_bfd->flags &= ~D_PAGED;
1788       if (config.text_read_only)
1789         output_bfd->flags |= WP_TEXT;
1790       else
1791         output_bfd->flags &= ~WP_TEXT;
1792       if (link_info.traditional_format)
1793         output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
1794       else
1795         output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
1796       break;
1797
1798     case lang_target_statement_enum:
1799       current_target = statement->target_statement.target;
1800       break;
1801     default:
1802       break;
1803     }
1804 }
1805
1806 /* Convert between addresses in bytes and sizes in octets.
1807    For currently supported targets, octets_per_byte is always a power
1808    of two, so we can use shifts.  */
1809 #define TO_ADDR(X) ((X) >> opb_shift)
1810 #define TO_SIZE(X) ((X) << opb_shift)
1811
1812 /* Support the above.  */
1813 static unsigned int opb_shift = 0;
1814
1815 static void
1816 init_opb (void)
1817 {
1818   unsigned x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
1819                                               ldfile_output_machine);
1820   opb_shift = 0;
1821   if (x > 1)
1822     while ((x & 1) == 0)
1823       {
1824         x >>= 1;
1825         ++opb_shift;
1826       }
1827   ASSERT (x == 1);
1828 }
1829
1830 /* Open all the input files.  */
1831
1832 static void
1833 open_input_bfds (lang_statement_union_type *s, bfd_boolean force)
1834 {
1835   for (; s != NULL; s = s->header.next)
1836     {
1837       switch (s->header.type)
1838         {
1839         case lang_constructors_statement_enum:
1840           open_input_bfds (constructor_list.head, force);
1841           break;
1842         case lang_output_section_statement_enum:
1843           open_input_bfds (s->output_section_statement.children.head, force);
1844           break;
1845         case lang_wild_statement_enum:
1846           /* Maybe we should load the file's symbols.  */
1847           if (s->wild_statement.filename
1848               && ! wildcardp (s->wild_statement.filename))
1849             (void) lookup_name (s->wild_statement.filename);
1850           open_input_bfds (s->wild_statement.children.head, force);
1851           break;
1852         case lang_group_statement_enum:
1853           {
1854             struct bfd_link_hash_entry *undefs;
1855
1856             /* We must continually search the entries in the group
1857                until no new symbols are added to the list of undefined
1858                symbols.  */
1859
1860             do
1861               {
1862                 undefs = link_info.hash->undefs_tail;
1863                 open_input_bfds (s->group_statement.children.head, TRUE);
1864               }
1865             while (undefs != link_info.hash->undefs_tail);
1866           }
1867           break;
1868         case lang_target_statement_enum:
1869           current_target = s->target_statement.target;
1870           break;
1871         case lang_input_statement_enum:
1872           if (s->input_statement.real)
1873             {
1874               lang_statement_list_type add;
1875
1876               s->input_statement.target = current_target;
1877
1878               /* If we are being called from within a group, and this
1879                  is an archive which has already been searched, then
1880                  force it to be researched unless the whole archive
1881                  has been loaded already.  */
1882               if (force
1883                   && !s->input_statement.whole_archive
1884                   && s->input_statement.loaded
1885                   && bfd_check_format (s->input_statement.the_bfd,
1886                                        bfd_archive))
1887                 s->input_statement.loaded = FALSE;
1888
1889               lang_list_init (&add);
1890
1891               if (! load_symbols (&s->input_statement, &add))
1892                 config.make_executable = FALSE;
1893
1894               if (add.head != NULL)
1895                 {
1896                   *add.tail = s->header.next;
1897                   s->header.next = add.head;
1898                 }
1899             }
1900           break;
1901         default:
1902           break;
1903         }
1904     }
1905 }
1906
1907 /* If there are [COMMONS] statements, put a wild one into the bss
1908    section.  */
1909
1910 static void
1911 lang_reasonable_defaults (void)
1912 {
1913 #if 0
1914   lang_output_section_statement_lookup (".text");
1915   lang_output_section_statement_lookup (".data");
1916
1917   default_common_section = lang_output_section_statement_lookup (".bss");
1918
1919   if (!placed_commons)
1920     {
1921       lang_wild_statement_type *new =
1922       new_stat (lang_wild_statement,
1923                 &default_common_section->children);
1924
1925       new->section_name = "COMMON";
1926       new->filename = NULL;
1927       lang_list_init (&new->children);
1928     }
1929 #endif
1930 }
1931
1932 /* Add a symbol to a hash of symbols used in DEFINED (NAME) expressions.  */
1933
1934 void
1935 lang_track_definedness (const char *name)
1936 {
1937   if (bfd_hash_lookup (&lang_definedness_table, name, TRUE, FALSE) == NULL)
1938     einfo (_("%P%F: bfd_hash_lookup failed creating symbol %s\n"), name);
1939 }
1940
1941 /* New-function for the definedness hash table.  */
1942
1943 static struct bfd_hash_entry *
1944 lang_definedness_newfunc (struct bfd_hash_entry *entry,
1945                           struct bfd_hash_table *table ATTRIBUTE_UNUSED,
1946                           const char *name ATTRIBUTE_UNUSED)
1947 {
1948   struct lang_definedness_hash_entry *ret
1949     = (struct lang_definedness_hash_entry *) entry;
1950
1951   if (ret == NULL)
1952     ret = (struct lang_definedness_hash_entry *)
1953       bfd_hash_allocate (table, sizeof (struct lang_definedness_hash_entry));
1954
1955   if (ret == NULL)
1956     einfo (_("%P%F: bfd_hash_allocate failed creating symbol %s\n"), name);
1957
1958   ret->iteration = -1;
1959   return &ret->root;
1960 }
1961
1962 /* Return the iteration when the definition of NAME was last updated.  A
1963    value of -1 means that the symbol is not defined in the linker script
1964    or the command line, but may be defined in the linker symbol table.  */
1965
1966 int
1967 lang_symbol_definition_iteration (const char *name)
1968 {
1969   struct lang_definedness_hash_entry *defentry
1970     = (struct lang_definedness_hash_entry *)
1971     bfd_hash_lookup (&lang_definedness_table, name, FALSE, FALSE);
1972
1973   /* We've already created this one on the presence of DEFINED in the
1974      script, so it can't be NULL unless something is borked elsewhere in
1975      the code.  */
1976   if (defentry == NULL)
1977     FAIL ();
1978
1979   return defentry->iteration;
1980 }
1981
1982 /* Update the definedness state of NAME.  */
1983
1984 void
1985 lang_update_definedness (const char *name, struct bfd_link_hash_entry *h)
1986 {
1987   struct lang_definedness_hash_entry *defentry
1988     = (struct lang_definedness_hash_entry *)
1989     bfd_hash_lookup (&lang_definedness_table, name, FALSE, FALSE);
1990
1991   /* We don't keep track of symbols not tested with DEFINED.  */
1992   if (defentry == NULL)
1993     return;
1994
1995   /* If the symbol was already defined, and not from an earlier statement
1996      iteration, don't update the definedness iteration, because that'd
1997      make the symbol seem defined in the linker script at this point, and
1998      it wasn't; it was defined in some object.  If we do anyway, DEFINED
1999      would start to yield false before this point and the construct "sym =
2000      DEFINED (sym) ? sym : X;" would change sym to X despite being defined
2001      in an object.  */
2002   if (h->type != bfd_link_hash_undefined
2003       && h->type != bfd_link_hash_common
2004       && h->type != bfd_link_hash_new
2005       && defentry->iteration == -1)
2006     return;
2007
2008   defentry->iteration = lang_statement_iteration;
2009 }
2010
2011 /* Add the supplied name to the symbol table as an undefined reference.
2012    This is a two step process as the symbol table doesn't even exist at
2013    the time the ld command line is processed.  First we put the name
2014    on a list, then, once the output file has been opened, transfer the
2015    name to the symbol table.  */
2016
2017 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
2018
2019 #define ldlang_undef_chain_list_head entry_symbol.next
2020
2021 void
2022 ldlang_add_undef (const char *const name)
2023 {
2024   ldlang_undef_chain_list_type *new =
2025     stat_alloc (sizeof (ldlang_undef_chain_list_type));
2026
2027   new->next = ldlang_undef_chain_list_head;
2028   ldlang_undef_chain_list_head = new;
2029
2030   new->name = xstrdup (name);
2031
2032   if (output_bfd != NULL)
2033     insert_undefined (new->name);
2034 }
2035
2036 /* Insert NAME as undefined in the symbol table.  */
2037
2038 static void
2039 insert_undefined (const char *name)
2040 {
2041   struct bfd_link_hash_entry *h;
2042
2043   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, FALSE, TRUE);
2044   if (h == NULL)
2045     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
2046   if (h->type == bfd_link_hash_new)
2047     {
2048       h->type = bfd_link_hash_undefined;
2049       h->u.undef.abfd = NULL;
2050       bfd_link_add_undef (link_info.hash, h);
2051     }
2052 }
2053
2054 /* Run through the list of undefineds created above and place them
2055    into the linker hash table as undefined symbols belonging to the
2056    script file.  */
2057
2058 static void
2059 lang_place_undefineds (void)
2060 {
2061   ldlang_undef_chain_list_type *ptr;
2062
2063   for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
2064     insert_undefined (ptr->name);
2065 }
2066
2067 /* Open input files and attach to output sections.  */
2068
2069 static void
2070 map_input_to_output_sections
2071   (lang_statement_union_type *s, const char *target,
2072    lang_output_section_statement_type *output_section_statement)
2073 {
2074   for (; s != NULL; s = s->header.next)
2075     {
2076       switch (s->header.type)
2077         {
2078         case lang_wild_statement_enum:
2079           wild (&s->wild_statement, target, output_section_statement);
2080           break;
2081         case lang_constructors_statement_enum:
2082           map_input_to_output_sections (constructor_list.head,
2083                                         target,
2084                                         output_section_statement);
2085           break;
2086         case lang_output_section_statement_enum:
2087           map_input_to_output_sections (s->output_section_statement.children.head,
2088                                         target,
2089                                         &s->output_section_statement);
2090           break;
2091         case lang_output_statement_enum:
2092           break;
2093         case lang_target_statement_enum:
2094           target = s->target_statement.target;
2095           break;
2096         case lang_group_statement_enum:
2097           map_input_to_output_sections (s->group_statement.children.head,
2098                                         target,
2099                                         output_section_statement);
2100           break;
2101         case lang_fill_statement_enum:
2102         case lang_input_section_enum:
2103         case lang_object_symbols_statement_enum:
2104         case lang_data_statement_enum:
2105         case lang_reloc_statement_enum:
2106         case lang_padding_statement_enum:
2107         case lang_input_statement_enum:
2108           if (output_section_statement != NULL
2109               && output_section_statement->bfd_section == NULL)
2110             init_os (output_section_statement);
2111           break;
2112         case lang_assignment_statement_enum:
2113           if (output_section_statement != NULL
2114               && output_section_statement->bfd_section == NULL)
2115             init_os (output_section_statement);
2116
2117           /* Make sure that any sections mentioned in the assignment
2118              are initialized.  */
2119           exp_init_os (s->assignment_statement.exp);
2120           break;
2121         case lang_afile_asection_pair_statement_enum:
2122           FAIL ();
2123           break;
2124         case lang_address_statement_enum:
2125           /* Mark the specified section with the supplied address.  */
2126           {
2127             lang_output_section_statement_type *os =
2128               lang_output_section_statement_lookup
2129                 (s->address_statement.section_name);
2130
2131             if (os->bfd_section == NULL)
2132               init_os (os);
2133             os->addr_tree = s->address_statement.address;
2134           }
2135           break;
2136         }
2137     }
2138 }
2139
2140 /* An output section might have been removed after its statement was
2141    added.  For example, ldemul_before_allocation can remove dynamic
2142    sections if they turn out to be not needed.  Clean them up here.  */
2143
2144 static void
2145 strip_excluded_output_sections (void)
2146 {
2147   lang_statement_union_type *u;
2148
2149   for (u = lang_output_section_statement.head;
2150        u != NULL;
2151        u = u->output_section_statement.next)
2152     {
2153       lang_output_section_statement_type *os;
2154       asection *s;
2155
2156       os = &u->output_section_statement;
2157       s = os->bfd_section;
2158       if (s != NULL && (s->flags & SEC_EXCLUDE) != 0)
2159         {
2160           asection **p;
2161
2162           os->bfd_section = NULL;
2163
2164           for (p = &output_bfd->sections; *p; p = &(*p)->next)
2165             if (*p == s)
2166               {
2167                 bfd_section_list_remove (output_bfd, p);
2168                 output_bfd->section_count--;
2169                 break;
2170               }
2171         }
2172     }
2173 }
2174
2175 static void
2176 print_output_section_statement
2177   (lang_output_section_statement_type *output_section_statement)
2178 {
2179   asection *section = output_section_statement->bfd_section;
2180   int len;
2181
2182   if (output_section_statement != abs_output_section)
2183     {
2184       minfo ("\n%s", output_section_statement->name);
2185
2186       if (section != NULL)
2187         {
2188           print_dot = section->vma;
2189
2190           len = strlen (output_section_statement->name);
2191           if (len >= SECTION_NAME_MAP_LENGTH - 1)
2192             {
2193               print_nl ();
2194               len = 0;
2195             }
2196           while (len < SECTION_NAME_MAP_LENGTH)
2197             {
2198               print_space ();
2199               ++len;
2200             }
2201
2202           minfo ("0x%V %W", section->vma, section->_raw_size);
2203
2204           if (output_section_statement->load_base != NULL)
2205             {
2206               bfd_vma addr;
2207
2208               addr = exp_get_abs_int (output_section_statement->load_base, 0,
2209                                       "load base", lang_final_phase_enum);
2210               minfo (_(" load address 0x%V"), addr);
2211             }
2212         }
2213
2214       print_nl ();
2215     }
2216
2217   print_statement_list (output_section_statement->children.head,
2218                         output_section_statement);
2219 }
2220
2221 static void
2222 print_assignment (lang_assignment_statement_type *assignment,
2223                   lang_output_section_statement_type *output_section)
2224 {
2225   int i;
2226   etree_value_type result;
2227
2228   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
2229     print_space ();
2230
2231   result = exp_fold_tree (assignment->exp->assign.src, output_section,
2232                           lang_final_phase_enum, print_dot, &print_dot);
2233   if (result.valid_p)
2234     {
2235       const char *dst;
2236       bfd_vma value;
2237
2238       value = result.value + result.section->bfd_section->vma;
2239       dst = assignment->exp->assign.dst;
2240
2241       minfo ("0x%V", value);
2242       if (dst[0] == '.' && dst[1] == 0)
2243         print_dot = value;
2244     }
2245   else
2246     {
2247       minfo ("*undef*   ");
2248 #ifdef BFD64
2249       minfo ("        ");
2250 #endif
2251     }
2252
2253   minfo ("                ");
2254
2255   exp_print_tree (assignment->exp);
2256
2257   print_nl ();
2258 }
2259
2260 static void
2261 print_input_statement (lang_input_statement_type *statm)
2262 {
2263   if (statm->filename != NULL)
2264     {
2265       fprintf (config.map_file, "LOAD %s\n", statm->filename);
2266     }
2267 }
2268
2269 /* Print all symbols defined in a particular section.  This is called
2270    via bfd_link_hash_traverse.  */
2271
2272 static bfd_boolean
2273 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
2274 {
2275   asection *sec = ptr;
2276
2277   if ((hash_entry->type == bfd_link_hash_defined
2278        || hash_entry->type == bfd_link_hash_defweak)
2279       && sec == hash_entry->u.def.section)
2280     {
2281       int i;
2282
2283       for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
2284         print_space ();
2285       minfo ("0x%V   ",
2286              (hash_entry->u.def.value
2287               + hash_entry->u.def.section->output_offset
2288               + hash_entry->u.def.section->output_section->vma));
2289
2290       minfo ("             %T\n", hash_entry->root.string);
2291     }
2292
2293   return TRUE;
2294 }
2295
2296 /* Print information about an input section to the map file.  */
2297
2298 static void
2299 print_input_section (lang_input_section_type *in)
2300 {
2301   asection *i = in->section;
2302   bfd_size_type size = i->_cooked_size != 0 ? i->_cooked_size : i->_raw_size;
2303
2304   init_opb ();
2305   if (size != 0)
2306     {
2307       print_space ();
2308
2309       minfo ("%s", i->name);
2310
2311       if (i->output_section != NULL)
2312         {
2313           int len;
2314
2315           len = 1 + strlen (i->name);
2316           if (len >= SECTION_NAME_MAP_LENGTH - 1)
2317             {
2318               print_nl ();
2319               len = 0;
2320             }
2321           while (len < SECTION_NAME_MAP_LENGTH)
2322             {
2323               print_space ();
2324               ++len;
2325             }
2326
2327           minfo ("0x%V %W %B\n",
2328                  i->output_section->vma + i->output_offset, TO_ADDR (size),
2329                  i->owner);
2330
2331           if (i->_cooked_size != 0 && i->_cooked_size != i->_raw_size)
2332             {
2333               len = SECTION_NAME_MAP_LENGTH + 3;
2334 #ifdef BFD64
2335               len += 16;
2336 #else
2337               len += 8;
2338 #endif
2339               while (len > 0)
2340                 {
2341                   print_space ();
2342                   --len;
2343                 }
2344
2345               minfo (_("%W (size before relaxing)\n"), i->_raw_size);
2346             }
2347
2348           bfd_link_hash_traverse (link_info.hash, print_one_symbol, i);
2349
2350           print_dot = (i->output_section->vma + i->output_offset
2351                        + TO_ADDR (size));
2352         }
2353     }
2354 }
2355
2356 static void
2357 print_fill_statement (lang_fill_statement_type *fill)
2358 {
2359   size_t size;
2360   unsigned char *p;
2361   fputs (" FILL mask 0x", config.map_file);
2362   for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
2363     fprintf (config.map_file, "%02x", *p);
2364   fputs ("\n", config.map_file);
2365 }
2366
2367 static void
2368 print_data_statement (lang_data_statement_type *data)
2369 {
2370   int i;
2371   bfd_vma addr;
2372   bfd_size_type size;
2373   const char *name;
2374
2375   init_opb ();
2376   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
2377     print_space ();
2378
2379   addr = data->output_vma;
2380   if (data->output_section != NULL)
2381     addr += data->output_section->vma;
2382
2383   switch (data->type)
2384     {
2385     default:
2386       abort ();
2387     case BYTE:
2388       size = BYTE_SIZE;
2389       name = "BYTE";
2390       break;
2391     case SHORT:
2392       size = SHORT_SIZE;
2393       name = "SHORT";
2394       break;
2395     case LONG:
2396       size = LONG_SIZE;
2397       name = "LONG";
2398       break;
2399     case QUAD:
2400       size = QUAD_SIZE;
2401       name = "QUAD";
2402       break;
2403     case SQUAD:
2404       size = QUAD_SIZE;
2405       name = "SQUAD";
2406       break;
2407     }
2408
2409   minfo ("0x%V %W %s 0x%v", addr, size, name, data->value);
2410
2411   if (data->exp->type.node_class != etree_value)
2412     {
2413       print_space ();
2414       exp_print_tree (data->exp);
2415     }
2416
2417   print_nl ();
2418
2419   print_dot = addr + TO_ADDR (size);
2420 }
2421
2422 /* Print an address statement.  These are generated by options like
2423    -Ttext.  */
2424
2425 static void
2426 print_address_statement (lang_address_statement_type *address)
2427 {
2428   minfo (_("Address of section %s set to "), address->section_name);
2429   exp_print_tree (address->address);
2430   print_nl ();
2431 }
2432
2433 /* Print a reloc statement.  */
2434
2435 static void
2436 print_reloc_statement (lang_reloc_statement_type *reloc)
2437 {
2438   int i;
2439   bfd_vma addr;
2440   bfd_size_type size;
2441
2442   init_opb ();
2443   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
2444     print_space ();
2445
2446   addr = reloc->output_vma;
2447   if (reloc->output_section != NULL)
2448     addr += reloc->output_section->vma;
2449
2450   size = bfd_get_reloc_size (reloc->howto);
2451
2452   minfo ("0x%V %W RELOC %s ", addr, size, reloc->howto->name);
2453
2454   if (reloc->name != NULL)
2455     minfo ("%s+", reloc->name);
2456   else
2457     minfo ("%s+", reloc->section->name);
2458
2459   exp_print_tree (reloc->addend_exp);
2460
2461   print_nl ();
2462
2463   print_dot = addr + TO_ADDR (size);
2464 }
2465
2466 static void
2467 print_padding_statement (lang_padding_statement_type *s)
2468 {
2469   int len;
2470   bfd_vma addr;
2471
2472   init_opb ();
2473   minfo (" *fill*");
2474
2475   len = sizeof " *fill*" - 1;
2476   while (len < SECTION_NAME_MAP_LENGTH)
2477     {
2478       print_space ();
2479       ++len;
2480     }
2481
2482   addr = s->output_offset;
2483   if (s->output_section != NULL)
2484     addr += s->output_section->vma;
2485   minfo ("0x%V %W ", addr, s->size);
2486
2487   if (s->fill->size != 0)
2488     {
2489       size_t size;
2490       unsigned char *p;
2491       for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
2492         fprintf (config.map_file, "%02x", *p);
2493     }
2494
2495   print_nl ();
2496
2497   print_dot = addr + TO_ADDR (s->size);
2498 }
2499
2500 static void
2501 print_wild_statement (lang_wild_statement_type *w,
2502                       lang_output_section_statement_type *os)
2503 {
2504   struct wildcard_list *sec;
2505
2506   print_space ();
2507
2508   if (w->filenames_sorted)
2509     minfo ("SORT(");
2510   if (w->filename != NULL)
2511     minfo ("%s", w->filename);
2512   else
2513     minfo ("*");
2514   if (w->filenames_sorted)
2515     minfo (")");
2516
2517   minfo ("(");
2518   for (sec = w->section_list; sec; sec = sec->next)
2519     {
2520       if (sec->spec.sorted)
2521         minfo ("SORT(");
2522       if (sec->spec.exclude_name_list != NULL)
2523         {
2524           name_list *tmp;
2525           minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
2526           for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
2527             minfo (" %s", tmp->name);
2528           minfo (") ");
2529         }
2530       if (sec->spec.name != NULL)
2531         minfo ("%s", sec->spec.name);
2532       else
2533         minfo ("*");
2534       if (sec->spec.sorted)
2535         minfo (")");
2536       if (sec->next)
2537         minfo (" ");
2538     }
2539   minfo (")");
2540
2541   print_nl ();
2542
2543   print_statement_list (w->children.head, os);
2544 }
2545
2546 /* Print a group statement.  */
2547
2548 static void
2549 print_group (lang_group_statement_type *s,
2550              lang_output_section_statement_type *os)
2551 {
2552   fprintf (config.map_file, "START GROUP\n");
2553   print_statement_list (s->children.head, os);
2554   fprintf (config.map_file, "END GROUP\n");
2555 }
2556
2557 /* Print the list of statements in S.
2558    This can be called for any statement type.  */
2559
2560 static void
2561 print_statement_list (lang_statement_union_type *s,
2562                       lang_output_section_statement_type *os)
2563 {
2564   while (s != NULL)
2565     {
2566       print_statement (s, os);
2567       s = s->header.next;
2568     }
2569 }
2570
2571 /* Print the first statement in statement list S.
2572    This can be called for any statement type.  */
2573
2574 static void
2575 print_statement (lang_statement_union_type *s,
2576                  lang_output_section_statement_type *os)
2577 {
2578   switch (s->header.type)
2579     {
2580     default:
2581       fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
2582       FAIL ();
2583       break;
2584     case lang_constructors_statement_enum:
2585       if (constructor_list.head != NULL)
2586         {
2587           if (constructors_sorted)
2588             minfo (" SORT (CONSTRUCTORS)\n");
2589           else
2590             minfo (" CONSTRUCTORS\n");
2591           print_statement_list (constructor_list.head, os);
2592         }
2593       break;
2594     case lang_wild_statement_enum:
2595       print_wild_statement (&s->wild_statement, os);
2596       break;
2597     case lang_address_statement_enum:
2598       print_address_statement (&s->address_statement);
2599       break;
2600     case lang_object_symbols_statement_enum:
2601       minfo (" CREATE_OBJECT_SYMBOLS\n");
2602       break;
2603     case lang_fill_statement_enum:
2604       print_fill_statement (&s->fill_statement);
2605       break;
2606     case lang_data_statement_enum:
2607       print_data_statement (&s->data_statement);
2608       break;
2609     case lang_reloc_statement_enum:
2610       print_reloc_statement (&s->reloc_statement);
2611       break;
2612     case lang_input_section_enum:
2613       print_input_section (&s->input_section);
2614       break;
2615     case lang_padding_statement_enum:
2616       print_padding_statement (&s->padding_statement);
2617       break;
2618     case lang_output_section_statement_enum:
2619       print_output_section_statement (&s->output_section_statement);
2620       break;
2621     case lang_assignment_statement_enum:
2622       print_assignment (&s->assignment_statement, os);
2623       break;
2624     case lang_target_statement_enum:
2625       fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
2626       break;
2627     case lang_output_statement_enum:
2628       minfo ("OUTPUT(%s", s->output_statement.name);
2629       if (output_target != NULL)
2630         minfo (" %s", output_target);
2631       minfo (")\n");
2632       break;
2633     case lang_input_statement_enum:
2634       print_input_statement (&s->input_statement);
2635       break;
2636     case lang_group_statement_enum:
2637       print_group (&s->group_statement, os);
2638       break;
2639     case lang_afile_asection_pair_statement_enum:
2640       FAIL ();
2641       break;
2642     }
2643 }
2644
2645 static void
2646 print_statements (void)
2647 {
2648   print_statement_list (statement_list.head, abs_output_section);
2649 }
2650
2651 /* Print the first N statements in statement list S to STDERR.
2652    If N == 0, nothing is printed.
2653    If N < 0, the entire list is printed.
2654    Intended to be called from GDB.  */
2655
2656 void
2657 dprint_statement (lang_statement_union_type *s, int n)
2658 {
2659   FILE *map_save = config.map_file;
2660
2661   config.map_file = stderr;
2662
2663   if (n < 0)
2664     print_statement_list (s, abs_output_section);
2665   else
2666     {
2667       while (s && --n >= 0)
2668         {
2669           print_statement (s, abs_output_section);
2670           s = s->header.next;
2671         }
2672     }
2673
2674   config.map_file = map_save;
2675 }
2676
2677 static void
2678 insert_pad (lang_statement_union_type **ptr,
2679             fill_type *fill,
2680             unsigned int alignment_needed,
2681             asection *output_section,
2682             bfd_vma dot)
2683 {
2684   static fill_type zero_fill = { 1, { 0 } };
2685   lang_statement_union_type *pad;
2686
2687   pad = ((lang_statement_union_type *)
2688          ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
2689   if (ptr != &statement_list.head
2690       && pad->header.type == lang_padding_statement_enum
2691       && pad->padding_statement.output_section == output_section)
2692     {
2693       /* Use the existing pad statement.  The above test on output
2694          section is probably redundant, but it doesn't hurt to check.  */
2695     }
2696   else
2697     {
2698       /* Make a new padding statement, linked into existing chain.  */
2699       pad = stat_alloc (sizeof (lang_padding_statement_type));
2700       pad->header.next = *ptr;
2701       *ptr = pad;
2702       pad->header.type = lang_padding_statement_enum;
2703       pad->padding_statement.output_section = output_section;
2704       if (fill == NULL)
2705         fill = &zero_fill;
2706       pad->padding_statement.fill = fill;
2707     }
2708   pad->padding_statement.output_offset = dot - output_section->vma;
2709   pad->padding_statement.size = alignment_needed;
2710   output_section->_raw_size += alignment_needed;
2711 }
2712
2713 /* Work out how much this section will move the dot point.  */
2714
2715 static bfd_vma
2716 size_input_section (lang_statement_union_type **this_ptr,
2717                     lang_output_section_statement_type *output_section_statement,
2718                     fill_type *fill,
2719                     bfd_vma dot)
2720 {
2721   lang_input_section_type *is = &((*this_ptr)->input_section);
2722   asection *i = is->section;
2723
2724   if (!is->ifile->just_syms_flag)
2725     {
2726       unsigned int alignment_needed;
2727       asection *o;
2728
2729       /* Align this section first to the input sections requirement,
2730          then to the output section's requirement.  If this alignment
2731          is greater than any seen before, then record it too.  Perform
2732          the alignment by inserting a magic 'padding' statement.  */
2733
2734       if (output_section_statement->subsection_alignment != -1)
2735         i->alignment_power = output_section_statement->subsection_alignment;
2736
2737       o = output_section_statement->bfd_section;
2738       if (o->alignment_power < i->alignment_power)
2739         o->alignment_power = i->alignment_power;
2740
2741       alignment_needed = align_power (dot, i->alignment_power) - dot;
2742
2743       if (alignment_needed != 0)
2744         {
2745           insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
2746           dot += alignment_needed;
2747         }
2748
2749       /* Remember where in the output section this input section goes.  */
2750
2751       i->output_offset = dot - o->vma;
2752
2753       /* Mark how big the output section must be to contain this now.  */
2754       if (i->_cooked_size != 0)
2755         dot += TO_ADDR (i->_cooked_size);
2756       else
2757         dot += TO_ADDR (i->_raw_size);
2758       o->_raw_size = TO_SIZE (dot - o->vma);
2759     }
2760   else
2761     {
2762       i->output_offset = i->vma - output_section_statement->bfd_section->vma;
2763     }
2764
2765   return dot;
2766 }
2767
2768 #define IGNORE_SECTION(bfd, s) \
2769   (((bfd_get_section_flags (bfd, s) & (SEC_ALLOC | SEC_NEVER_LOAD))     \
2770     != SEC_ALLOC)                                                       \
2771    || bfd_section_size (bfd, s) == 0)
2772
2773 /* Check to see if any allocated sections overlap with other allocated
2774    sections.  This can happen when the linker script specifically specifies
2775    the output section addresses of the two sections.  */
2776
2777 static void
2778 lang_check_section_addresses (void)
2779 {
2780   asection *s;
2781
2782   /* Scan all sections in the output list.  */
2783   for (s = output_bfd->sections; s != NULL; s = s->next)
2784     {
2785       asection *os;
2786
2787       /* Ignore sections which are not loaded or which have no contents.  */
2788       if (IGNORE_SECTION (output_bfd, s))
2789         continue;
2790
2791       /* Once we reach section 's' stop our seach.  This prevents two
2792          warning messages from being produced, one for 'section A overlaps
2793          section B' and one for 'section B overlaps section A'.  */
2794       for (os = output_bfd->sections; os != s; os = os->next)
2795         {
2796           bfd_vma s_start;
2797           bfd_vma s_end;
2798           bfd_vma os_start;
2799           bfd_vma os_end;
2800
2801           /* Only consider loadable sections with real contents.  */
2802           if (IGNORE_SECTION (output_bfd, os))
2803             continue;
2804
2805           /* We must check the sections' LMA addresses not their
2806              VMA addresses because overlay sections can have
2807              overlapping VMAs but they must have distinct LMAs.  */
2808           s_start = bfd_section_lma (output_bfd, s);
2809           os_start = bfd_section_lma (output_bfd, os);
2810           s_end = s_start + TO_ADDR (bfd_section_size (output_bfd, s)) - 1;
2811           os_end = os_start + TO_ADDR (bfd_section_size (output_bfd, os)) - 1;
2812
2813           /* Look for an overlap.  */
2814           if ((s_end < os_start) || (s_start > os_end))
2815             continue;
2816
2817           einfo (
2818 _("%X%P: section %s [%V -> %V] overlaps section %s [%V -> %V]\n"),
2819                  s->name, s_start, s_end, os->name, os_start, os_end);
2820
2821           /* Once we have found one overlap for this section,
2822              stop looking for others.  */
2823           break;
2824         }
2825     }
2826 }
2827
2828 /* Make sure the new address is within the region.  We explicitly permit the
2829    current address to be at the exact end of the region when the address is
2830    non-zero, in case the region is at the end of addressable memory and the
2831    calculation wraps around.  */
2832
2833 static void
2834 os_region_check (lang_output_section_statement_type *os,
2835                  lang_memory_region_type *region,
2836                  etree_type *tree,
2837                  bfd_vma base)
2838 {
2839   if ((region->current < region->origin
2840        || (region->current - region->origin > region->length))
2841       && ((region->current != region->origin + region->length)
2842           || base == 0))
2843     {
2844       if (tree != NULL)
2845         {
2846           einfo (_("%X%P: address 0x%v of %B section %s is not within region %s\n"),
2847                  region->current,
2848                  os->bfd_section->owner,
2849                  os->bfd_section->name,
2850                  region->name);
2851         }
2852       else
2853         {
2854           einfo (_("%X%P: region %s is full (%B section %s)\n"),
2855                  region->name,
2856                  os->bfd_section->owner,
2857                  os->bfd_section->name);
2858         }
2859       /* Reset the region pointer.  */
2860       region->current = region->origin;
2861     }
2862 }
2863
2864 /* Set the sizes for all the output sections.  */
2865
2866 static bfd_vma
2867 lang_size_sections_1
2868   (lang_statement_union_type *s,
2869    lang_output_section_statement_type *output_section_statement,
2870    lang_statement_union_type **prev,
2871    fill_type *fill,
2872    bfd_vma dot,
2873    bfd_boolean *relax,
2874    bfd_boolean check_regions)
2875 {
2876   /* Size up the sections from their constituent parts.  */
2877   for (; s != NULL; s = s->header.next)
2878     {
2879       switch (s->header.type)
2880         {
2881         case lang_output_section_statement_enum:
2882           {
2883             bfd_vma after;
2884             lang_output_section_statement_type *os;
2885
2886             os = &s->output_section_statement;
2887             if (os->bfd_section == NULL)
2888               /* This section was never actually created.  */
2889               break;
2890
2891             /* If this is a COFF shared library section, use the size and
2892                address from the input section.  FIXME: This is COFF
2893                specific; it would be cleaner if there were some other way
2894                to do this, but nothing simple comes to mind.  */
2895             if ((os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
2896               {
2897                 asection *input;
2898
2899                 if (os->children.head == NULL
2900                     || os->children.head->header.next != NULL
2901                     || os->children.head->header.type != lang_input_section_enum)
2902                   einfo (_("%P%X: Internal error on COFF shared library section %s\n"),
2903                          os->name);
2904
2905                 input = os->children.head->input_section.section;
2906                 bfd_set_section_vma (os->bfd_section->owner,
2907                                      os->bfd_section,
2908                                      bfd_section_vma (input->owner, input));
2909                 os->bfd_section->_raw_size = input->_raw_size;
2910                 break;
2911               }
2912
2913             if (bfd_is_abs_section (os->bfd_section))
2914               {
2915                 /* No matter what happens, an abs section starts at zero.  */
2916                 ASSERT (os->bfd_section->vma == 0);
2917               }
2918             else
2919               {
2920                 if (os->addr_tree == NULL)
2921                   {
2922                     /* No address specified for this section, get one
2923                        from the region specification.  */
2924                     if (os->region == NULL
2925                         || (((bfd_get_section_flags (output_bfd, os->bfd_section)
2926                               & (SEC_ALLOC | SEC_LOAD)) != 0)
2927                             && os->region->name[0] == '*'
2928                             && strcmp (os->region->name, DEFAULT_MEMORY_REGION) == 0))
2929                       {
2930                         os->region = lang_memory_default (os->bfd_section);
2931                       }
2932
2933                     /* If a loadable section is using the default memory
2934                        region, and some non default memory regions were
2935                        defined, issue an error message.  */
2936                     if (!IGNORE_SECTION (output_bfd, os->bfd_section)
2937                         && ! link_info.relocatable
2938                         && check_regions
2939                         && strcmp (os->region->name, DEFAULT_MEMORY_REGION) == 0
2940                         && lang_memory_region_list != NULL
2941                         && (strcmp (lang_memory_region_list->name,
2942                                     DEFAULT_MEMORY_REGION) != 0
2943                             || lang_memory_region_list->next != NULL))
2944                       {
2945                         /* By default this is an error rather than just a
2946                            warning because if we allocate the section to the
2947                            default memory region we can end up creating an
2948                            excessively large binary, or even seg faulting when
2949                            attempting to perform a negative seek.  See
2950                              http://sources.redhat.com/ml/binutils/2003-04/msg00423.html
2951                            for an example of this.  This behaviour can be
2952                            overridden by the using the --no-check-sections
2953                            switch.  */
2954                         if (command_line.check_section_addresses)
2955                           einfo (_("%P%F: error: no memory region specified for loadable section `%s'\n"),
2956                                  bfd_get_section_name (output_bfd,
2957                                                        os->bfd_section));
2958                         else
2959                           einfo (_("%P: warning: no memory region specified for loadable section `%s'\n"),
2960                                  bfd_get_section_name (output_bfd,
2961                                                        os->bfd_section));
2962                       }
2963
2964                     dot = os->region->current;
2965
2966                     if (os->section_alignment == -1)
2967                       {
2968                         bfd_vma olddot;
2969
2970                         olddot = dot;
2971                         dot = align_power (dot,
2972                                            os->bfd_section->alignment_power);
2973
2974                         if (dot != olddot && config.warn_section_align)
2975                           einfo (_("%P: warning: changing start of section %s by %u bytes\n"),
2976                                  os->name, (unsigned int) (dot - olddot));
2977                       }
2978                   }
2979                 else
2980                   {
2981                     etree_value_type r;
2982
2983                     r = exp_fold_tree (os->addr_tree,
2984                                        abs_output_section,
2985                                        lang_allocating_phase_enum,
2986                                        dot, &dot);
2987                     if (!r.valid_p)
2988                       einfo (_("%F%S: non constant address expression for section %s\n"),
2989                              os->name);
2990
2991                     dot = r.value + r.section->bfd_section->vma;
2992                   }
2993
2994                 /* The section starts here.
2995                    First, align to what the section needs.  */
2996
2997                 if (os->section_alignment != -1)
2998                   dot = align_power (dot, os->section_alignment);
2999
3000                 bfd_set_section_vma (0, os->bfd_section, dot);
3001
3002                 os->bfd_section->output_offset = 0;
3003               }
3004
3005             lang_size_sections_1 (os->children.head, os, &os->children.head,
3006                                   os->fill, dot, relax, check_regions);
3007
3008             /* Put the section within the requested block size, or
3009                align at the block boundary.  */
3010             after = ((os->bfd_section->vma
3011                       + TO_ADDR (os->bfd_section->_raw_size)
3012                       + os->block_value - 1)
3013                      & - (bfd_vma) os->block_value);
3014
3015             if (bfd_is_abs_section (os->bfd_section))
3016               ASSERT (after == os->bfd_section->vma);
3017             else if ((os->bfd_section->flags & SEC_HAS_CONTENTS) == 0
3018                      && (os->bfd_section->flags & SEC_THREAD_LOCAL)
3019                      && ! link_info.relocatable)
3020               os->bfd_section->_raw_size = 0;
3021             else
3022               os->bfd_section->_raw_size
3023                 = TO_SIZE (after - os->bfd_section->vma);
3024
3025             dot = os->bfd_section->vma + TO_ADDR (os->bfd_section->_raw_size);
3026             os->processed = TRUE;
3027
3028             if (os->update_dot_tree != 0)
3029               exp_fold_tree (os->update_dot_tree, abs_output_section,
3030                              lang_allocating_phase_enum, dot, &dot);
3031
3032             /* Update dot in the region ?
3033                We only do this if the section is going to be allocated,
3034                since unallocated sections do not contribute to the region's
3035                overall size in memory.
3036
3037                If the SEC_NEVER_LOAD bit is not set, it will affect the
3038                addresses of sections after it. We have to update
3039                dot.  */
3040             if (os->region != NULL
3041                 && ((bfd_get_section_flags (output_bfd, os->bfd_section)
3042                      & SEC_NEVER_LOAD) == 0
3043                     || (bfd_get_section_flags (output_bfd, os->bfd_section)
3044                         & (SEC_ALLOC | SEC_LOAD))))
3045               {
3046                 os->region->current = dot;
3047
3048                 if (check_regions)
3049                   /* Make sure the new address is within the region.  */
3050                   os_region_check (os, os->region, os->addr_tree,
3051                                    os->bfd_section->vma);
3052
3053                 /* If there's no load address specified, use the run
3054                    region as the load region.  */
3055                 if (os->lma_region == NULL && os->load_base == NULL)
3056                   os->lma_region = os->region;
3057
3058                 if (os->lma_region != NULL && os->lma_region != os->region)
3059                   {
3060                     /* Set load_base, which will be handled later.  */
3061                     os->load_base = exp_intop (os->lma_region->current);
3062                     os->lma_region->current +=
3063                       TO_ADDR (os->bfd_section->_raw_size);
3064                     if (check_regions)
3065                       os_region_check (os, os->lma_region, NULL,
3066                                        os->bfd_section->lma);
3067                   }
3068               }
3069           }
3070           break;
3071
3072         case lang_constructors_statement_enum:
3073           dot = lang_size_sections_1 (constructor_list.head,
3074                                       output_section_statement,
3075                                       &s->wild_statement.children.head,
3076                                       fill, dot, relax, check_regions);
3077           break;
3078
3079         case lang_data_statement_enum:
3080           {
3081             unsigned int size = 0;
3082
3083             s->data_statement.output_vma =
3084               dot - output_section_statement->bfd_section->vma;
3085             s->data_statement.output_section =
3086               output_section_statement->bfd_section;
3087
3088             switch (s->data_statement.type)
3089               {
3090               default:
3091                 abort ();
3092               case QUAD:
3093               case SQUAD:
3094                 size = QUAD_SIZE;
3095                 break;
3096               case LONG:
3097                 size = LONG_SIZE;
3098                 break;
3099               case SHORT:
3100                 size = SHORT_SIZE;
3101                 break;
3102               case BYTE:
3103                 size = BYTE_SIZE;
3104                 break;
3105               }
3106             if (size < TO_SIZE ((unsigned) 1))
3107               size = TO_SIZE ((unsigned) 1);
3108             dot += TO_ADDR (size);
3109             output_section_statement->bfd_section->_raw_size += size;
3110             /* The output section gets contents, and then we inspect for
3111                any flags set in the input script which override any ALLOC.  */
3112             output_section_statement->bfd_section->flags |= SEC_HAS_CONTENTS;
3113             if (!(output_section_statement->flags & SEC_NEVER_LOAD))
3114               {
3115                 output_section_statement->bfd_section->flags |=
3116                   SEC_ALLOC | SEC_LOAD;
3117               }
3118           }
3119           break;
3120
3121         case lang_reloc_statement_enum:
3122           {
3123             int size;
3124
3125             s->reloc_statement.output_vma =
3126               dot - output_section_statement->bfd_section->vma;
3127             s->reloc_statement.output_section =
3128               output_section_statement->bfd_section;
3129             size = bfd_get_reloc_size (s->reloc_statement.howto);
3130             dot += TO_ADDR (size);
3131             output_section_statement->bfd_section->_raw_size += size;
3132           }
3133           break;
3134
3135         case lang_wild_statement_enum:
3136
3137           dot = lang_size_sections_1 (s->wild_statement.children.head,
3138                                       output_section_statement,
3139                                       &s->wild_statement.children.head,
3140                                       fill, dot, relax, check_regions);
3141
3142           break;
3143
3144         case lang_object_symbols_statement_enum:
3145           link_info.create_object_symbols_section =
3146             output_section_statement->bfd_section;
3147           break;
3148         case lang_output_statement_enum:
3149         case lang_target_statement_enum:
3150           break;
3151         case lang_input_section_enum:
3152           {
3153             asection *i;
3154
3155             i = (*prev)->input_section.section;
3156             if (! relax)
3157               {
3158                 if (i->_cooked_size == 0)
3159                   i->_cooked_size = i->_raw_size;
3160               }
3161             else
3162               {
3163                 bfd_boolean again;
3164
3165                 if (! bfd_relax_section (i->owner, i, &link_info, &again))
3166                   einfo (_("%P%F: can't relax section: %E\n"));
3167                 if (again)
3168                   *relax = TRUE;
3169               }
3170             dot = size_input_section (prev, output_section_statement,
3171                                       output_section_statement->fill, dot);
3172           }
3173           break;
3174         case lang_input_statement_enum:
3175           break;
3176         case lang_fill_statement_enum:
3177           s->fill_statement.output_section =
3178             output_section_statement->bfd_section;
3179
3180           fill = s->fill_statement.fill;
3181           break;
3182         case lang_assignment_statement_enum:
3183           {
3184             bfd_vma newdot = dot;
3185
3186             exp_fold_tree (s->assignment_statement.exp,
3187                            output_section_statement,
3188                            lang_allocating_phase_enum,
3189                            dot,
3190                            &newdot);
3191
3192             if (newdot != dot)
3193               {
3194                 if (output_section_statement == abs_output_section)
3195                   {
3196                     /* If we don't have an output section, then just adjust
3197                        the default memory address.  */
3198                     lang_memory_region_lookup (DEFAULT_MEMORY_REGION, FALSE)->current = newdot;
3199                   }
3200                 else
3201                   {
3202                     /* Insert a pad after this statement.  We can't
3203                        put the pad before when relaxing, in case the
3204                        assignment references dot.  */
3205                     insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
3206                                 output_section_statement->bfd_section, dot);
3207
3208                     /* Don't neuter the pad below when relaxing.  */
3209                     s = s->header.next;
3210                   }
3211
3212                 /* If dot is advanced, this implies that the section should
3213                    have space allocated to it, unless the user has explicitly
3214                    stated that the section should never be loaded.  */
3215                 if (!(output_section_statement->flags & (SEC_NEVER_LOAD | SEC_ALLOC)))
3216                   output_section_statement->bfd_section->flags |= SEC_ALLOC;
3217
3218                 dot = newdot;
3219               }
3220           }
3221           break;
3222
3223         case lang_padding_statement_enum:
3224           /* If this is the first time lang_size_sections is called,
3225              we won't have any padding statements.  If this is the
3226              second or later passes when relaxing, we should allow
3227              padding to shrink.  If padding is needed on this pass, it
3228              will be added back in.  */
3229           s->padding_statement.size = 0;
3230
3231           /* Make sure output_offset is valid.  If relaxation shrinks
3232              the section and this pad isn't needed, it's possible to
3233              have output_offset larger than the final size of the
3234              section.  bfd_set_section_contents will complain even for
3235              a pad size of zero.  */
3236           s->padding_statement.output_offset
3237             = dot - output_section_statement->bfd_section->vma;
3238           break;
3239
3240         case lang_group_statement_enum:
3241           dot = lang_size_sections_1 (s->group_statement.children.head,
3242                                       output_section_statement,
3243                                       &s->group_statement.children.head,
3244                                       fill, dot, relax, check_regions);
3245           break;
3246
3247         default:
3248           FAIL ();
3249           break;
3250
3251           /* We can only get here when relaxing is turned on.  */
3252         case lang_address_statement_enum:
3253           break;
3254         }
3255       prev = &s->header.next;
3256     }
3257   return dot;
3258 }
3259
3260 bfd_vma
3261 lang_size_sections
3262   (lang_statement_union_type *s,
3263    lang_output_section_statement_type *output_section_statement,
3264    lang_statement_union_type **prev,
3265    fill_type *fill,
3266    bfd_vma dot,
3267    bfd_boolean *relax,
3268    bfd_boolean check_regions)
3269 {
3270   bfd_vma result;
3271   asection *o;
3272
3273   /* Callers of exp_fold_tree need to increment this.  */
3274   lang_statement_iteration++;
3275
3276   exp_data_seg.phase = exp_dataseg_none;
3277   result = lang_size_sections_1 (s, output_section_statement, prev, fill,
3278                                  dot, relax, check_regions);
3279   if (exp_data_seg.phase == exp_dataseg_end_seen)
3280     {
3281       /* If DATA_SEGMENT_ALIGN DATA_SEGMENT_END pair was seen, check whether
3282          a page could be saved in the data segment.  */
3283       bfd_vma first, last;
3284
3285       first = -exp_data_seg.base & (exp_data_seg.pagesize - 1);
3286       last = exp_data_seg.end & (exp_data_seg.pagesize - 1);
3287       if (first && last
3288           && ((exp_data_seg.base & ~(exp_data_seg.pagesize - 1))
3289               != (exp_data_seg.end & ~(exp_data_seg.pagesize - 1)))
3290           && first + last <= exp_data_seg.pagesize)
3291         {
3292           exp_data_seg.phase = exp_dataseg_adjust;
3293           result = lang_size_sections_1 (s, output_section_statement, prev,
3294                                          fill, dot, relax, check_regions);
3295         }
3296     }
3297
3298   /* Some backend relaxers want to refer to the output section size.  Give
3299      them a section size that does not change on the next call while they
3300      relax.  We can't set this at top because lang_reset_memory_regions
3301      which is called before we get here, sets _raw_size to 0 on relaxing
3302      rounds.  */
3303   for (o = output_bfd->sections; o != NULL; o = o->next)
3304     o->_cooked_size = o->_raw_size;
3305
3306   return result;
3307 }
3308
3309 /* Worker function for lang_do_assignments.  Recursiveness goes here.  */
3310
3311 static bfd_vma
3312 lang_do_assignments_1
3313   (lang_statement_union_type *s,
3314    lang_output_section_statement_type *output_section_statement,
3315    fill_type *fill,
3316    bfd_vma dot)
3317 {
3318   for (; s != NULL; s = s->header.next)
3319     {
3320       switch (s->header.type)
3321         {
3322         case lang_constructors_statement_enum:
3323           dot = lang_do_assignments_1 (constructor_list.head,
3324                                        output_section_statement,
3325                                        fill,
3326                                        dot);
3327           break;
3328
3329         case lang_output_section_statement_enum:
3330           {
3331             lang_output_section_statement_type *os;
3332
3333             os = &(s->output_section_statement);
3334             if (os->bfd_section != NULL)
3335               {
3336                 dot = os->bfd_section->vma;
3337                 (void) lang_do_assignments_1 (os->children.head, os,
3338                                               os->fill, dot);
3339                 dot = (os->bfd_section->vma
3340                        + TO_ADDR (os->bfd_section->_raw_size));
3341
3342               }
3343             if (os->load_base)
3344               {
3345                 /* If nothing has been placed into the output section then
3346                    it won't have a bfd_section.  */
3347                 if (os->bfd_section)
3348                   {
3349                     os->bfd_section->lma
3350                       = exp_get_abs_int (os->load_base, 0, "load base",
3351                                          lang_final_phase_enum);
3352                   }
3353               }
3354           }
3355           break;
3356         case lang_wild_statement_enum:
3357
3358           dot = lang_do_assignments_1 (s->wild_statement.children.head,
3359                                        output_section_statement,
3360                                        fill, dot);
3361
3362           break;
3363
3364         case lang_object_symbols_statement_enum:
3365         case lang_output_statement_enum:
3366         case lang_target_statement_enum:
3367 #if 0
3368         case lang_common_statement_enum:
3369 #endif
3370           break;
3371         case lang_data_statement_enum:
3372           {
3373             etree_value_type value;
3374
3375             value = exp_fold_tree (s->data_statement.exp,
3376                                    abs_output_section,
3377                                    lang_final_phase_enum, dot, &dot);
3378             s->data_statement.value = value.value;
3379             if (!value.valid_p)
3380               einfo (_("%F%P: invalid data statement\n"));
3381           }
3382           {
3383             unsigned int size;
3384             switch (s->data_statement.type)
3385               {
3386               default:
3387                 abort ();
3388               case QUAD:
3389               case SQUAD:
3390                 size = QUAD_SIZE;
3391                 break;
3392               case LONG:
3393                 size = LONG_SIZE;
3394                 break;
3395               case SHORT:
3396                 size = SHORT_SIZE;
3397                 break;
3398               case BYTE:
3399                 size = BYTE_SIZE;
3400                 break;
3401               }
3402             if (size < TO_SIZE ((unsigned) 1))
3403               size = TO_SIZE ((unsigned) 1);
3404             dot += TO_ADDR (size);
3405           }
3406           break;
3407
3408         case lang_reloc_statement_enum:
3409           {
3410             etree_value_type value;
3411
3412             value = exp_fold_tree (s->reloc_statement.addend_exp,
3413                                    abs_output_section,
3414                                    lang_final_phase_enum, dot, &dot);
3415             s->reloc_statement.addend_value = value.value;
3416             if (!value.valid_p)
3417               einfo (_("%F%P: invalid reloc statement\n"));
3418           }
3419           dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
3420           break;
3421
3422         case lang_input_section_enum:
3423           {
3424             asection *in = s->input_section.section;
3425
3426             if (in->_cooked_size != 0)
3427               dot += TO_ADDR (in->_cooked_size);
3428             else
3429               dot += TO_ADDR (in->_raw_size);
3430           }
3431           break;
3432
3433         case lang_input_statement_enum:
3434           break;
3435         case lang_fill_statement_enum:
3436           fill = s->fill_statement.fill;
3437           break;
3438         case lang_assignment_statement_enum:
3439           {
3440             exp_fold_tree (s->assignment_statement.exp,
3441                            output_section_statement,
3442                            lang_final_phase_enum,
3443                            dot,
3444                            &dot);
3445           }
3446
3447           break;
3448         case lang_padding_statement_enum:
3449           dot += TO_ADDR (s->padding_statement.size);
3450           break;
3451
3452         case lang_group_statement_enum:
3453           dot = lang_do_assignments_1 (s->group_statement.children.head,
3454                                        output_section_statement,
3455                                        fill, dot);
3456
3457           break;
3458
3459         default:
3460           FAIL ();
3461           break;
3462         case lang_address_statement_enum:
3463           break;
3464         }
3465
3466     }
3467   return dot;
3468 }
3469
3470 void
3471 lang_do_assignments (lang_statement_union_type *s,
3472                      lang_output_section_statement_type *output_section_statement,
3473                      fill_type *fill,
3474                      bfd_vma dot)
3475 {
3476   /* Callers of exp_fold_tree need to increment this.  */
3477   lang_statement_iteration++;
3478   lang_do_assignments_1 (s, output_section_statement, fill, dot);
3479 }
3480
3481 /* Fix any .startof. or .sizeof. symbols.  When the assemblers see the
3482    operator .startof. (section_name), it produces an undefined symbol
3483    .startof.section_name.  Similarly, when it sees
3484    .sizeof. (section_name), it produces an undefined symbol
3485    .sizeof.section_name.  For all the output sections, we look for
3486    such symbols, and set them to the correct value.  */
3487
3488 static void
3489 lang_set_startof (void)
3490 {
3491   asection *s;
3492
3493   if (link_info.relocatable)
3494     return;
3495
3496   for (s = output_bfd->sections; s != NULL; s = s->next)
3497     {
3498       const char *secname;
3499       char *buf;
3500       struct bfd_link_hash_entry *h;
3501
3502       secname = bfd_get_section_name (output_bfd, s);
3503       buf = xmalloc (10 + strlen (secname));
3504
3505       sprintf (buf, ".startof.%s", secname);
3506       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
3507       if (h != NULL && h->type == bfd_link_hash_undefined)
3508         {
3509           h->type = bfd_link_hash_defined;
3510           h->u.def.value = bfd_get_section_vma (output_bfd, s);
3511           h->u.def.section = bfd_abs_section_ptr;
3512         }
3513
3514       sprintf (buf, ".sizeof.%s", secname);
3515       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
3516       if (h != NULL && h->type == bfd_link_hash_undefined)
3517         {
3518           h->type = bfd_link_hash_defined;
3519           if (s->_cooked_size != 0)
3520             h->u.def.value = TO_ADDR (s->_cooked_size);
3521           else
3522             h->u.def.value = TO_ADDR (s->_raw_size);
3523           h->u.def.section = bfd_abs_section_ptr;
3524         }
3525
3526       free (buf);
3527     }
3528 }
3529
3530 static void
3531 lang_finish (void)
3532 {
3533   struct bfd_link_hash_entry *h;
3534   bfd_boolean warn;
3535
3536   if (link_info.relocatable || link_info.shared)
3537     warn = FALSE;
3538   else
3539     warn = TRUE;
3540
3541   if (entry_symbol.name == NULL)
3542     {
3543       /* No entry has been specified.  Look for start, but don't warn
3544          if we don't find it.  */
3545       entry_symbol.name = "start";
3546       warn = FALSE;
3547     }
3548
3549   h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
3550                             FALSE, FALSE, TRUE);
3551   if (h != NULL
3552       && (h->type == bfd_link_hash_defined
3553           || h->type == bfd_link_hash_defweak)
3554       && h->u.def.section->output_section != NULL)
3555     {
3556       bfd_vma val;
3557
3558       val = (h->u.def.value
3559              + bfd_get_section_vma (output_bfd,
3560                                     h->u.def.section->output_section)
3561              + h->u.def.section->output_offset);
3562       if (! bfd_set_start_address (output_bfd, val))
3563         einfo (_("%P%F:%s: can't set start address\n"), entry_symbol.name);
3564     }
3565   else
3566     {
3567       bfd_vma val;
3568       const char *send;
3569
3570       /* We couldn't find the entry symbol.  Try parsing it as a
3571          number.  */
3572       val = bfd_scan_vma (entry_symbol.name, &send, 0);
3573       if (*send == '\0')
3574         {
3575           if (! bfd_set_start_address (output_bfd, val))
3576             einfo (_("%P%F: can't set start address\n"));
3577         }
3578       else
3579         {
3580           asection *ts;
3581
3582           /* Can't find the entry symbol, and it's not a number.  Use
3583              the first address in the text section.  */
3584           ts = bfd_get_section_by_name (output_bfd, entry_section);
3585           if (ts != NULL)
3586             {
3587               if (warn)
3588                 einfo (_("%P: warning: cannot find entry symbol %s; defaulting to %V\n"),
3589                        entry_symbol.name,
3590                        bfd_get_section_vma (output_bfd, ts));
3591               if (! bfd_set_start_address (output_bfd,
3592                                            bfd_get_section_vma (output_bfd,
3593                                                                 ts)))
3594                 einfo (_("%P%F: can't set start address\n"));
3595             }
3596           else
3597             {
3598               if (warn)
3599                 einfo (_("%P: warning: cannot find entry symbol %s; not setting start address\n"),
3600                        entry_symbol.name);
3601             }
3602         }
3603     }
3604
3605   bfd_hash_table_free (&lang_definedness_table);
3606 }
3607
3608 /* This is a small function used when we want to ignore errors from
3609    BFD.  */
3610
3611 static void
3612 ignore_bfd_errors (const char *s ATTRIBUTE_UNUSED, ...)
3613 {
3614   /* Don't do anything.  */
3615 }
3616
3617 /* Check that the architecture of all the input files is compatible
3618    with the output file.  Also call the backend to let it do any
3619    other checking that is needed.  */
3620
3621 static void
3622 lang_check (void)
3623 {
3624   lang_statement_union_type *file;
3625   bfd *input_bfd;
3626   const bfd_arch_info_type *compatible;
3627
3628   for (file = file_chain.head; file != NULL; file = file->input_statement.next)
3629     {
3630       input_bfd = file->input_statement.the_bfd;
3631       compatible = bfd_arch_get_compatible (input_bfd, output_bfd,
3632                                             command_line.accept_unknown_input_arch);
3633
3634       /* In general it is not possible to perform a relocatable
3635          link between differing object formats when the input
3636          file has relocations, because the relocations in the
3637          input format may not have equivalent representations in
3638          the output format (and besides BFD does not translate
3639          relocs for other link purposes than a final link).  */
3640       if ((link_info.relocatable || link_info.emitrelocations)
3641           && (compatible == NULL
3642               || bfd_get_flavour (input_bfd) != bfd_get_flavour (output_bfd))
3643           && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
3644         {
3645           einfo (_("%P%F: Relocatable linking with relocations from format %s (%B) to format %s (%B) is not supported\n"),
3646                  bfd_get_target (input_bfd), input_bfd,
3647                  bfd_get_target (output_bfd), output_bfd);
3648           /* einfo with %F exits.  */
3649         }
3650
3651       if (compatible == NULL)
3652         {
3653           if (command_line.warn_mismatch)
3654             einfo (_("%P: warning: %s architecture of input file `%B' is incompatible with %s output\n"),
3655                    bfd_printable_name (input_bfd), input_bfd,
3656                    bfd_printable_name (output_bfd));
3657         }
3658       else if (bfd_count_sections (input_bfd))
3659         {
3660           /* If the input bfd has no contents, it shouldn't set the
3661              private data of the output bfd.  */
3662
3663           bfd_error_handler_type pfn = NULL;
3664
3665           /* If we aren't supposed to warn about mismatched input
3666              files, temporarily set the BFD error handler to a
3667              function which will do nothing.  We still want to call
3668              bfd_merge_private_bfd_data, since it may set up
3669              information which is needed in the output file.  */
3670           if (! command_line.warn_mismatch)
3671             pfn = bfd_set_error_handler (ignore_bfd_errors);
3672           if (! bfd_merge_private_bfd_data (input_bfd, output_bfd))
3673             {
3674               if (command_line.warn_mismatch)
3675                 einfo (_("%E%X: failed to merge target specific data of file %B\n"),
3676                        input_bfd);
3677             }
3678           if (! command_line.warn_mismatch)
3679             bfd_set_error_handler (pfn);
3680         }
3681     }
3682 }
3683
3684 /* Look through all the global common symbols and attach them to the
3685    correct section.  The -sort-common command line switch may be used
3686    to roughly sort the entries by size.  */
3687
3688 static void
3689 lang_common (void)
3690 {
3691   if (command_line.inhibit_common_definition)
3692     return;
3693   if (link_info.relocatable
3694       && ! command_line.force_common_definition)
3695     return;
3696
3697   if (! config.sort_common)
3698     bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
3699   else
3700     {
3701       int power;
3702
3703       for (power = 4; power >= 0; power--)
3704         bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
3705     }
3706 }
3707
3708 /* Place one common symbol in the correct section.  */
3709
3710 static bfd_boolean
3711 lang_one_common (struct bfd_link_hash_entry *h, void *info)
3712 {
3713   unsigned int power_of_two;
3714   bfd_vma size;
3715   asection *section;
3716
3717   if (h->type != bfd_link_hash_common)
3718     return TRUE;
3719
3720   size = h->u.c.size;
3721   power_of_two = h->u.c.p->alignment_power;
3722
3723   if (config.sort_common
3724       && power_of_two < (unsigned int) *(int *) info)
3725     return TRUE;
3726
3727   section = h->u.c.p->section;
3728
3729   /* Increase the size of the section to align the common sym.  */
3730   section->_cooked_size += ((bfd_vma) 1 << (power_of_two + opb_shift)) - 1;
3731   section->_cooked_size &= (- (bfd_vma) 1 << (power_of_two + opb_shift));
3732
3733   /* Adjust the alignment if necessary.  */
3734   if (power_of_two > section->alignment_power)
3735     section->alignment_power = power_of_two;
3736
3737   /* Change the symbol from common to defined.  */
3738   h->type = bfd_link_hash_defined;
3739   h->u.def.section = section;
3740   h->u.def.value = section->_cooked_size;
3741
3742   /* Increase the size of the section.  */
3743   section->_cooked_size += size;
3744
3745   /* Make sure the section is allocated in memory, and make sure that
3746      it is no longer a common section.  */
3747   section->flags |= SEC_ALLOC;
3748   section->flags &= ~SEC_IS_COMMON;
3749
3750   if (config.map_file != NULL)
3751     {
3752       static bfd_boolean header_printed;
3753       int len;
3754       char *name;
3755       char buf[50];
3756
3757       if (! header_printed)
3758         {
3759           minfo (_("\nAllocating common symbols\n"));
3760           minfo (_("Common symbol       size              file\n\n"));
3761           header_printed = TRUE;
3762         }
3763
3764       name = demangle (h->root.string);
3765       minfo ("%s", name);
3766       len = strlen (name);
3767       free (name);
3768
3769       if (len >= 19)
3770         {
3771           print_nl ();
3772           len = 0;
3773         }
3774       while (len < 20)
3775         {
3776           print_space ();
3777           ++len;
3778         }
3779
3780       minfo ("0x");
3781       if (size <= 0xffffffff)
3782         sprintf (buf, "%lx", (unsigned long) size);
3783       else
3784         sprintf_vma (buf, size);
3785       minfo ("%s", buf);
3786       len = strlen (buf);
3787
3788       while (len < 16)
3789         {
3790           print_space ();
3791           ++len;
3792         }
3793
3794       minfo ("%B\n", section->owner);
3795     }
3796
3797   return TRUE;
3798 }
3799
3800 /* Run through the input files and ensure that every input section has
3801    somewhere to go.  If one is found without a destination then create
3802    an input request and place it into the statement tree.  */
3803
3804 static void
3805 lang_place_orphans (void)
3806 {
3807   LANG_FOR_EACH_INPUT_STATEMENT (file)
3808     {
3809       asection *s;
3810
3811       for (s = file->the_bfd->sections; s != NULL; s = s->next)
3812         {
3813           if (s->output_section == NULL)
3814             {
3815               /* This section of the file is not attached, root
3816                  around for a sensible place for it to go.  */
3817
3818               if (file->just_syms_flag)
3819                 {
3820                   abort ();
3821                 }
3822               else if (strcmp (s->name, "COMMON") == 0)
3823                 {
3824                   /* This is a lonely common section which must have
3825                      come from an archive.  We attach to the section
3826                      with the wildcard.  */
3827                   if (! link_info.relocatable
3828                       || command_line.force_common_definition)
3829                     {
3830                       if (default_common_section == NULL)
3831                         {
3832 #if 0
3833                           /* This message happens when using the
3834                              svr3.ifile linker script, so I have
3835                              disabled it.  */
3836                           info_msg (_("%P: no [COMMON] command, defaulting to .bss\n"));
3837 #endif
3838                           default_common_section =
3839                             lang_output_section_statement_lookup (".bss");
3840
3841                         }
3842                       lang_add_section (&default_common_section->children, s,
3843                                         default_common_section, file);
3844                     }
3845                 }
3846               else if (ldemul_place_orphan (file, s))
3847                 ;
3848               else
3849                 {
3850                   lang_output_section_statement_type *os;
3851
3852                   os = lang_output_section_statement_lookup (s->name);
3853                   lang_add_section (&os->children, s, os, file);
3854                 }
3855             }
3856         }
3857     }
3858 }
3859
3860 void
3861 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
3862 {
3863   flagword *ptr_flags;
3864
3865   ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
3866   while (*flags)
3867     {
3868       switch (*flags)
3869         {
3870         case 'A': case 'a':
3871           *ptr_flags |= SEC_ALLOC;
3872           break;
3873
3874         case 'R': case 'r':
3875           *ptr_flags |= SEC_READONLY;
3876           break;
3877
3878         case 'W': case 'w':
3879           *ptr_flags |= SEC_DATA;
3880           break;
3881
3882         case 'X': case 'x':
3883           *ptr_flags |= SEC_CODE;
3884           break;
3885
3886         case 'L': case 'l':
3887         case 'I': case 'i':
3888           *ptr_flags |= SEC_LOAD;
3889           break;
3890
3891         default:
3892           einfo (_("%P%F: invalid syntax in flags\n"));
3893           break;
3894         }
3895       flags++;
3896     }
3897 }
3898
3899 /* Call a function on each input file.  This function will be called
3900    on an archive, but not on the elements.  */
3901
3902 void
3903 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
3904 {
3905   lang_input_statement_type *f;
3906
3907   for (f = (lang_input_statement_type *) input_file_chain.head;
3908        f != NULL;
3909        f = (lang_input_statement_type *) f->next_real_file)
3910     func (f);
3911 }
3912
3913 /* Call a function on each file.  The function will be called on all
3914    the elements of an archive which are included in the link, but will
3915    not be called on the archive file itself.  */
3916
3917 void
3918 lang_for_each_file (void (*func) (lang_input_statement_type *))
3919 {
3920   LANG_FOR_EACH_INPUT_STATEMENT (f)
3921     {
3922       func (f);
3923     }
3924 }
3925
3926 #if 0
3927
3928 /* Not used.  */
3929
3930 void
3931 lang_for_each_input_section (void (*func) (bfd *ab, asection *as))
3932 {
3933   LANG_FOR_EACH_INPUT_STATEMENT (f)
3934     {
3935       asection *s;
3936
3937       for (s = f->the_bfd->sections; s != NULL; s = s->next)
3938         func (f->the_bfd, s);
3939     }
3940 }
3941
3942 #endif
3943
3944 void
3945 ldlang_add_file (lang_input_statement_type *entry)
3946 {
3947   bfd **pp;
3948
3949   lang_statement_append (&file_chain,
3950                          (lang_statement_union_type *) entry,
3951                          &entry->next);
3952
3953   /* The BFD linker needs to have a list of all input BFDs involved in
3954      a link.  */
3955   ASSERT (entry->the_bfd->link_next == NULL);
3956   ASSERT (entry->the_bfd != output_bfd);
3957   for (pp = &link_info.input_bfds; *pp != NULL; pp = &(*pp)->link_next)
3958     ;
3959   *pp = entry->the_bfd;
3960   entry->the_bfd->usrdata = entry;
3961   bfd_set_gp_size (entry->the_bfd, g_switch_value);
3962
3963   /* Look through the sections and check for any which should not be
3964      included in the link.  We need to do this now, so that we can
3965      notice when the backend linker tries to report multiple
3966      definition errors for symbols which are in sections we aren't
3967      going to link.  FIXME: It might be better to entirely ignore
3968      symbols which are defined in sections which are going to be
3969      discarded.  This would require modifying the backend linker for
3970      each backend which might set the SEC_LINK_ONCE flag.  If we do
3971      this, we should probably handle SEC_EXCLUDE in the same way.  */
3972
3973   bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
3974 }
3975
3976 void
3977 lang_add_output (const char *name, int from_script)
3978 {
3979   /* Make -o on command line override OUTPUT in script.  */
3980   if (!had_output_filename || !from_script)
3981     {
3982       output_filename = name;
3983       had_output_filename = TRUE;
3984     }
3985 }
3986
3987 static lang_output_section_statement_type *current_section;
3988
3989 static int
3990 topower (int x)
3991 {
3992   unsigned int i = 1;
3993   int l;
3994
3995   if (x < 0)
3996     return -1;
3997
3998   for (l = 0; l < 32; l++)
3999     {
4000       if (i >= (unsigned int) x)
4001         return l;
4002       i <<= 1;
4003     }
4004
4005   return 0;
4006 }
4007
4008 lang_output_section_statement_type *
4009 lang_enter_output_section_statement (const char *output_section_statement_name,
4010                                      etree_type *address_exp,
4011                                      enum section_type sectype,
4012                                      etree_type *align,
4013                                      etree_type *subalign,
4014                                      etree_type *ebase)
4015 {
4016   lang_output_section_statement_type *os;
4017
4018   current_section =
4019    os =
4020     lang_output_section_statement_lookup (output_section_statement_name);
4021
4022   /* Add this statement to tree.  */
4023 #if 0
4024   add_statement (lang_output_section_statement_enum,
4025                  output_section_statement);
4026 #endif
4027   /* Make next things chain into subchain of this.  */
4028
4029   if (os->addr_tree == NULL)
4030     {
4031       os->addr_tree = address_exp;
4032     }
4033   os->sectype = sectype;
4034   if (sectype != noload_section)
4035     os->flags = SEC_NO_FLAGS;
4036   else
4037     os->flags = SEC_NEVER_LOAD;
4038   os->block_value = 1;
4039   stat_ptr = &os->children;
4040
4041   os->subsection_alignment =
4042     topower (exp_get_value_int (subalign, -1, "subsection alignment", 0));
4043   os->section_alignment =
4044     topower (exp_get_value_int (align, -1, "section alignment", 0));
4045
4046   os->load_base = ebase;
4047   return os;
4048 }
4049
4050 void
4051 lang_final (void)
4052 {
4053   lang_output_statement_type *new =
4054     new_stat (lang_output_statement, stat_ptr);
4055
4056   new->name = output_filename;
4057 }
4058
4059 /* Reset the current counters in the regions.  */
4060
4061 void
4062 lang_reset_memory_regions (void)
4063 {
4064   lang_memory_region_type *p = lang_memory_region_list;
4065   asection *o;
4066
4067   for (p = lang_memory_region_list; p != NULL; p = p->next)
4068     {
4069       p->old_length = (bfd_size_type) (p->current - p->origin);
4070       p->current = p->origin;
4071     }
4072
4073   for (o = output_bfd->sections; o != NULL; o = o->next)
4074     o->_raw_size = 0;
4075 }
4076
4077 /* If the wild pattern was marked KEEP, the member sections
4078    should be as well.  */
4079
4080 static void
4081 gc_section_callback (lang_wild_statement_type *ptr,
4082                      struct wildcard_list *sec ATTRIBUTE_UNUSED,
4083                      asection *section,
4084                      lang_input_statement_type *file ATTRIBUTE_UNUSED,
4085                      void *data ATTRIBUTE_UNUSED)
4086 {
4087   if (ptr->keep_sections)
4088     section->flags |= SEC_KEEP;
4089 }
4090
4091 /* Handle a wild statement, marking it against GC.  */
4092
4093 static void
4094 lang_gc_wild (lang_wild_statement_type *s)
4095 {
4096   walk_wild (s, gc_section_callback, NULL);
4097 }
4098
4099 /* Iterate over sections marking them against GC.  */
4100
4101 static void
4102 lang_gc_sections_1 (lang_statement_union_type *s)
4103 {
4104   for (; s != NULL; s = s->header.next)
4105     {
4106       switch (s->header.type)
4107         {
4108         case lang_wild_statement_enum:
4109           lang_gc_wild (&s->wild_statement);
4110           break;
4111         case lang_constructors_statement_enum:
4112           lang_gc_sections_1 (constructor_list.head);
4113           break;
4114         case lang_output_section_statement_enum:
4115           lang_gc_sections_1 (s->output_section_statement.children.head);
4116           break;
4117         case lang_group_statement_enum:
4118           lang_gc_sections_1 (s->group_statement.children.head);
4119           break;
4120         default:
4121           break;
4122         }
4123     }
4124 }
4125
4126 static void
4127 lang_gc_sections (void)
4128 {
4129   struct bfd_link_hash_entry *h;
4130   ldlang_undef_chain_list_type *ulist;
4131
4132   /* Keep all sections so marked in the link script.  */
4133
4134   lang_gc_sections_1 (statement_list.head);
4135
4136   /* Keep all sections containing symbols undefined on the command-line,
4137      and the section containing the entry symbol.  */
4138
4139   for (ulist = link_info.gc_sym_list; ulist; ulist = ulist->next)
4140     {
4141       h = bfd_link_hash_lookup (link_info.hash, ulist->name,
4142                                 FALSE, FALSE, FALSE);
4143
4144       if (h != NULL
4145           && (h->type == bfd_link_hash_defined
4146               || h->type == bfd_link_hash_defweak)
4147           && ! bfd_is_abs_section (h->u.def.section))
4148         {
4149           h->u.def.section->flags |= SEC_KEEP;
4150         }
4151     }
4152
4153   bfd_gc_sections (output_bfd, &link_info);
4154 }
4155
4156 void
4157 lang_process (void)
4158 {
4159   lang_reasonable_defaults ();
4160   current_target = default_target;
4161
4162   /* Open the output file.  */
4163   lang_for_each_statement (ldlang_open_output);
4164   init_opb ();
4165
4166   ldemul_create_output_section_statements ();
4167
4168   /* Add to the hash table all undefineds on the command line.  */
4169   lang_place_undefineds ();
4170
4171   already_linked_table_init ();
4172
4173   /* Create a bfd for each input file.  */
4174   current_target = default_target;
4175   open_input_bfds (statement_list.head, FALSE);
4176
4177   link_info.gc_sym_list = &entry_symbol;
4178   if (entry_symbol.name == NULL)
4179     link_info.gc_sym_list = ldlang_undef_chain_list_head;
4180
4181   ldemul_after_open ();
4182
4183   already_linked_table_free ();
4184
4185   /* Make sure that we're not mixing architectures.  We call this
4186      after all the input files have been opened, but before we do any
4187      other processing, so that any operations merge_private_bfd_data
4188      does on the output file will be known during the rest of the
4189      link.  */
4190   lang_check ();
4191
4192   /* Handle .exports instead of a version script if we're told to do so.  */
4193   if (command_line.version_exports_section)
4194     lang_do_version_exports_section ();
4195
4196   /* Build all sets based on the information gathered from the input
4197      files.  */
4198   ldctor_build_sets ();
4199
4200   /* Remove unreferenced sections if asked to.  */
4201   if (command_line.gc_sections)
4202     lang_gc_sections ();
4203
4204   /* If there were any SEC_MERGE sections, finish their merging, so that
4205      section sizes can be computed.  This has to be done after GC of sections,
4206      so that GCed sections are not merged, but before assigning output
4207      sections, since removing whole input sections is hard then.  */
4208   bfd_merge_sections (output_bfd, &link_info);
4209
4210   /* Size up the common data.  */
4211   lang_common ();
4212
4213   /* Run through the contours of the script and attach input sections
4214      to the correct output sections.  */
4215   map_input_to_output_sections (statement_list.head, NULL, NULL);
4216
4217   /* Find any sections not attached explicitly and handle them.  */
4218   lang_place_orphans ();
4219
4220   if (! link_info.relocatable)
4221     {
4222       /* Look for a text section and set the readonly attribute in it.  */
4223       asection *found = bfd_get_section_by_name (output_bfd, ".text");
4224
4225       if (found != NULL)
4226         {
4227           if (config.text_read_only)
4228             found->flags |= SEC_READONLY;
4229           else
4230             found->flags &= ~SEC_READONLY;
4231         }
4232     }
4233
4234   /* Do anything special before sizing sections.  This is where ELF
4235      and other back-ends size dynamic sections.  */
4236   ldemul_before_allocation ();
4237
4238   if (!link_info.relocatable)
4239     strip_excluded_output_sections ();
4240
4241   /* We must record the program headers before we try to fix the
4242      section positions, since they will affect SIZEOF_HEADERS.  */
4243   lang_record_phdrs ();
4244
4245   /* Size up the sections.  */
4246   lang_size_sections (statement_list.head, abs_output_section,
4247                       &statement_list.head, 0, 0, NULL,
4248                       command_line.relax ? FALSE : TRUE);
4249
4250   /* Now run around and relax if we can.  */
4251   if (command_line.relax)
4252     {
4253       /* Keep relaxing until bfd_relax_section gives up.  */
4254       bfd_boolean relax_again;
4255
4256       do
4257         {
4258           relax_again = FALSE;
4259
4260           /* Note: pe-dll.c does something like this also.  If you find
4261              you need to change this code, you probably need to change
4262              pe-dll.c also.  DJ  */
4263
4264           /* Do all the assignments with our current guesses as to
4265              section sizes.  */
4266           lang_do_assignments (statement_list.head, abs_output_section,
4267                                NULL, 0);
4268
4269           /* We must do this after lang_do_assignments, because it uses
4270              _raw_size.  */
4271           lang_reset_memory_regions ();
4272
4273           /* Perform another relax pass - this time we know where the
4274              globals are, so can make a better guess.  */
4275           lang_size_sections (statement_list.head, abs_output_section,
4276                               &statement_list.head, 0, 0, &relax_again, FALSE);
4277
4278           /* If the normal relax is done and the relax finalize pass
4279              is not performed yet, we perform another relax pass.  */
4280           if (!relax_again && link_info.need_relax_finalize)
4281             {
4282               link_info.need_relax_finalize = FALSE;
4283               relax_again = TRUE;
4284             }
4285         }
4286       while (relax_again);
4287
4288       /* Final extra sizing to report errors.  */
4289       lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
4290       lang_reset_memory_regions ();
4291       lang_size_sections (statement_list.head, abs_output_section,
4292                           &statement_list.head, 0, 0, NULL, TRUE);
4293     }
4294
4295   /* See if anything special should be done now we know how big
4296      everything is.  */
4297   ldemul_after_allocation ();
4298
4299   /* Fix any .startof. or .sizeof. symbols.  */
4300   lang_set_startof ();
4301
4302   /* Do all the assignments, now that we know the final resting places
4303      of all the symbols.  */
4304
4305   lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
4306
4307   /* Make sure that the section addresses make sense.  */
4308   if (! link_info.relocatable
4309       && command_line.check_section_addresses)
4310     lang_check_section_addresses ();
4311
4312   /* Final stuffs.  */
4313
4314   ldemul_finish ();
4315   lang_finish ();
4316 }
4317
4318 /* EXPORTED TO YACC */
4319
4320 void
4321 lang_add_wild (struct wildcard_spec *filespec,
4322                struct wildcard_list *section_list,
4323                bfd_boolean keep_sections)
4324 {
4325   struct wildcard_list *curr, *next;
4326   lang_wild_statement_type *new;
4327
4328   /* Reverse the list as the parser puts it back to front.  */
4329   for (curr = section_list, section_list = NULL;
4330        curr != NULL;
4331        section_list = curr, curr = next)
4332     {
4333       if (curr->spec.name != NULL && strcmp (curr->spec.name, "COMMON") == 0)
4334         placed_commons = TRUE;
4335
4336       next = curr->next;
4337       curr->next = section_list;
4338     }
4339
4340   if (filespec != NULL && filespec->name != NULL)
4341     {
4342       if (strcmp (filespec->name, "*") == 0)
4343         filespec->name = NULL;
4344       else if (! wildcardp (filespec->name))
4345         lang_has_input_file = TRUE;
4346     }
4347
4348   new = new_stat (lang_wild_statement, stat_ptr);
4349   new->filename = NULL;
4350   new->filenames_sorted = FALSE;
4351   if (filespec != NULL)
4352     {
4353       new->filename = filespec->name;
4354       new->filenames_sorted = filespec->sorted;
4355     }
4356   new->section_list = section_list;
4357   new->keep_sections = keep_sections;
4358   lang_list_init (&new->children);
4359 }
4360
4361 void
4362 lang_section_start (const char *name, etree_type *address)
4363 {
4364   lang_address_statement_type *ad;
4365
4366   ad = new_stat (lang_address_statement, stat_ptr);
4367   ad->section_name = name;
4368   ad->address = address;
4369 }
4370
4371 /* Set the start symbol to NAME.  CMDLINE is nonzero if this is called
4372    because of a -e argument on the command line, or zero if this is
4373    called by ENTRY in a linker script.  Command line arguments take
4374    precedence.  */
4375
4376 void
4377 lang_add_entry (const char *name, bfd_boolean cmdline)
4378 {
4379   if (entry_symbol.name == NULL
4380       || cmdline
4381       || ! entry_from_cmdline)
4382     {
4383       entry_symbol.name = name;
4384       entry_from_cmdline = cmdline;
4385     }
4386 }
4387
4388 void
4389 lang_add_target (const char *name)
4390 {
4391   lang_target_statement_type *new = new_stat (lang_target_statement,
4392                                               stat_ptr);
4393
4394   new->target = name;
4395
4396 }
4397
4398 void
4399 lang_add_map (const char *name)
4400 {
4401   while (*name)
4402     {
4403       switch (*name)
4404         {
4405         case 'F':
4406           map_option_f = TRUE;
4407           break;
4408         }
4409       name++;
4410     }
4411 }
4412
4413 void
4414 lang_add_fill (fill_type *fill)
4415 {
4416   lang_fill_statement_type *new = new_stat (lang_fill_statement,
4417                                             stat_ptr);
4418
4419   new->fill = fill;
4420 }
4421
4422 void
4423 lang_add_data (int type, union etree_union *exp)
4424 {
4425
4426   lang_data_statement_type *new = new_stat (lang_data_statement,
4427                                             stat_ptr);
4428
4429   new->exp = exp;
4430   new->type = type;
4431
4432 }
4433
4434 /* Create a new reloc statement.  RELOC is the BFD relocation type to
4435    generate.  HOWTO is the corresponding howto structure (we could
4436    look this up, but the caller has already done so).  SECTION is the
4437    section to generate a reloc against, or NAME is the name of the
4438    symbol to generate a reloc against.  Exactly one of SECTION and
4439    NAME must be NULL.  ADDEND is an expression for the addend.  */
4440
4441 void
4442 lang_add_reloc (bfd_reloc_code_real_type reloc,
4443                 reloc_howto_type *howto,
4444                 asection *section,
4445                 const char *name,
4446                 union etree_union *addend)
4447 {
4448   lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
4449
4450   p->reloc = reloc;
4451   p->howto = howto;
4452   p->section = section;
4453   p->name = name;
4454   p->addend_exp = addend;
4455
4456   p->addend_value = 0;
4457   p->output_section = NULL;
4458   p->output_vma = 0;
4459 }
4460
4461 lang_assignment_statement_type *
4462 lang_add_assignment (etree_type *exp)
4463 {
4464   lang_assignment_statement_type *new = new_stat (lang_assignment_statement,
4465                                                   stat_ptr);
4466
4467   new->exp = exp;
4468   return new;
4469 }
4470
4471 void
4472 lang_add_attribute (enum statement_enum attribute)
4473 {
4474   new_statement (attribute, sizeof (lang_statement_union_type), stat_ptr);
4475 }
4476
4477 void
4478 lang_startup (const char *name)
4479 {
4480   if (startup_file != NULL)
4481     {
4482       einfo (_("%P%Fmultiple STARTUP files\n"));
4483     }
4484   first_file->filename = name;
4485   first_file->local_sym_name = name;
4486   first_file->real = TRUE;
4487
4488   startup_file = name;
4489 }
4490
4491 void
4492 lang_float (bfd_boolean maybe)
4493 {
4494   lang_float_flag = maybe;
4495 }
4496
4497
4498 /* Work out the load- and run-time regions from a script statement, and
4499    store them in *LMA_REGION and *REGION respectively.
4500
4501    MEMSPEC is the name of the run-time region, or the value of
4502    DEFAULT_MEMORY_REGION if the statement didn't specify one.
4503    LMA_MEMSPEC is the name of the load-time region, or null if the
4504    statement didn't specify one.HAVE_LMA_P is TRUE if the statement
4505    had an explicit load address.
4506
4507    It is an error to specify both a load region and a load address.  */
4508
4509 static void
4510 lang_get_regions (lang_memory_region_type **region,
4511                   lang_memory_region_type **lma_region,
4512                   const char *memspec,
4513                   const char *lma_memspec,
4514                   bfd_boolean have_lma,
4515                   bfd_boolean have_vma)
4516 {
4517   *lma_region = lang_memory_region_lookup (lma_memspec, FALSE);
4518
4519   /* If no runtime region or VMA has been specified, but the load region has
4520      been specified, then use the load region for the runtime region as well.  */
4521   if (lma_memspec != NULL
4522       && ! have_vma
4523       && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
4524     *region = *lma_region;
4525   else
4526     *region = lang_memory_region_lookup (memspec, FALSE);
4527
4528   if (have_lma && lma_memspec != 0)
4529     einfo (_("%X%P:%S: section has both a load address and a load region\n"));
4530 }
4531
4532 void
4533 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
4534                                      lang_output_section_phdr_list *phdrs,
4535                                      const char *lma_memspec)
4536 {
4537   lang_get_regions (&current_section->region,
4538                     &current_section->lma_region,
4539                     memspec, lma_memspec,
4540                     current_section->load_base != NULL,
4541                     current_section->addr_tree != NULL);
4542   current_section->fill = fill;
4543   current_section->phdrs = phdrs;
4544   stat_ptr = &statement_list;
4545 }
4546
4547 /* Create an absolute symbol with the given name with the value of the
4548    address of first byte of the section named.
4549
4550    If the symbol already exists, then do nothing.  */
4551
4552 void
4553 lang_abs_symbol_at_beginning_of (const char *secname, const char *name)
4554 {
4555   struct bfd_link_hash_entry *h;
4556
4557   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
4558   if (h == NULL)
4559     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
4560
4561   if (h->type == bfd_link_hash_new
4562       || h->type == bfd_link_hash_undefined)
4563     {
4564       asection *sec;
4565
4566       h->type = bfd_link_hash_defined;
4567
4568       sec = bfd_get_section_by_name (output_bfd, secname);
4569       if (sec == NULL)
4570         h->u.def.value = 0;
4571       else
4572         h->u.def.value = bfd_get_section_vma (output_bfd, sec);
4573
4574       h->u.def.section = bfd_abs_section_ptr;
4575     }
4576 }
4577
4578 /* Create an absolute symbol with the given name with the value of the
4579    address of the first byte after the end of the section named.
4580
4581    If the symbol already exists, then do nothing.  */
4582
4583 void
4584 lang_abs_symbol_at_end_of (const char *secname, const char *name)
4585 {
4586   struct bfd_link_hash_entry *h;
4587
4588   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
4589   if (h == NULL)
4590     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
4591
4592   if (h->type == bfd_link_hash_new
4593       || h->type == bfd_link_hash_undefined)
4594     {
4595       asection *sec;
4596
4597       h->type = bfd_link_hash_defined;
4598
4599       sec = bfd_get_section_by_name (output_bfd, secname);
4600       if (sec == NULL)
4601         h->u.def.value = 0;
4602       else
4603         h->u.def.value = (bfd_get_section_vma (output_bfd, sec)
4604                           + TO_ADDR (bfd_section_size (output_bfd, sec)));
4605
4606       h->u.def.section = bfd_abs_section_ptr;
4607     }
4608 }
4609
4610 void
4611 lang_statement_append (lang_statement_list_type *list,
4612                        lang_statement_union_type *element,
4613                        lang_statement_union_type **field)
4614 {
4615   *(list->tail) = element;
4616   list->tail = field;
4617 }
4618
4619 /* Set the output format type.  -oformat overrides scripts.  */
4620
4621 void
4622 lang_add_output_format (const char *format,
4623                         const char *big,
4624                         const char *little,
4625                         int from_script)
4626 {
4627   if (output_target == NULL || !from_script)
4628     {
4629       if (command_line.endian == ENDIAN_BIG
4630           && big != NULL)
4631         format = big;
4632       else if (command_line.endian == ENDIAN_LITTLE
4633                && little != NULL)
4634         format = little;
4635
4636       output_target = format;
4637     }
4638 }
4639
4640 /* Enter a group.  This creates a new lang_group_statement, and sets
4641    stat_ptr to build new statements within the group.  */
4642
4643 void
4644 lang_enter_group (void)
4645 {
4646   lang_group_statement_type *g;
4647
4648   g = new_stat (lang_group_statement, stat_ptr);
4649   lang_list_init (&g->children);
4650   stat_ptr = &g->children;
4651 }
4652
4653 /* Leave a group.  This just resets stat_ptr to start writing to the
4654    regular list of statements again.  Note that this will not work if
4655    groups can occur inside anything else which can adjust stat_ptr,
4656    but currently they can't.  */
4657
4658 void
4659 lang_leave_group (void)
4660 {
4661   stat_ptr = &statement_list;
4662 }
4663
4664 /* Add a new program header.  This is called for each entry in a PHDRS
4665    command in a linker script.  */
4666
4667 void
4668 lang_new_phdr (const char *name,
4669                etree_type *type,
4670                bfd_boolean filehdr,
4671                bfd_boolean phdrs,
4672                etree_type *at,
4673                etree_type *flags)
4674 {
4675   struct lang_phdr *n, **pp;
4676
4677   n = stat_alloc (sizeof (struct lang_phdr));
4678   n->next = NULL;
4679   n->name = name;
4680   n->type = exp_get_value_int (type, 0, "program header type",
4681                                lang_final_phase_enum);
4682   n->filehdr = filehdr;
4683   n->phdrs = phdrs;
4684   n->at = at;
4685   n->flags = flags;
4686
4687   for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
4688     ;
4689   *pp = n;
4690 }
4691
4692 /* Record the program header information in the output BFD.  FIXME: We
4693    should not be calling an ELF specific function here.  */
4694
4695 static void
4696 lang_record_phdrs (void)
4697 {
4698   unsigned int alc;
4699   asection **secs;
4700   lang_output_section_phdr_list *last;
4701   struct lang_phdr *l;
4702   lang_statement_union_type *u;
4703
4704   alc = 10;
4705   secs = xmalloc (alc * sizeof (asection *));
4706   last = NULL;
4707   for (l = lang_phdr_list; l != NULL; l = l->next)
4708     {
4709       unsigned int c;
4710       flagword flags;
4711       bfd_vma at;
4712
4713       c = 0;
4714       for (u = lang_output_section_statement.head;
4715            u != NULL;
4716            u = u->output_section_statement.next)
4717         {
4718           lang_output_section_statement_type *os;
4719           lang_output_section_phdr_list *pl;
4720
4721           os = &u->output_section_statement;
4722
4723           pl = os->phdrs;
4724           if (pl != NULL)
4725             last = pl;
4726           else
4727             {
4728               if (os->sectype == noload_section
4729                   || os->bfd_section == NULL
4730                   || (os->bfd_section->flags & SEC_ALLOC) == 0)
4731                 continue;
4732               pl = last;
4733             }
4734
4735           if (os->bfd_section == NULL)
4736             continue;
4737
4738           for (; pl != NULL; pl = pl->next)
4739             {
4740               if (strcmp (pl->name, l->name) == 0)
4741                 {
4742                   if (c >= alc)
4743                     {
4744                       alc *= 2;
4745                       secs = xrealloc (secs, alc * sizeof (asection *));
4746                     }
4747                   secs[c] = os->bfd_section;
4748                   ++c;
4749                   pl->used = TRUE;
4750                 }
4751             }
4752         }
4753
4754       if (l->flags == NULL)
4755         flags = 0;
4756       else
4757         flags = exp_get_vma (l->flags, 0, "phdr flags",
4758                              lang_final_phase_enum);
4759
4760       if (l->at == NULL)
4761         at = 0;
4762       else
4763         at = exp_get_vma (l->at, 0, "phdr load address",
4764                           lang_final_phase_enum);
4765
4766       if (! bfd_record_phdr (output_bfd, l->type,
4767                              l->flags != NULL, flags, l->at != NULL,
4768                              at, l->filehdr, l->phdrs, c, secs))
4769         einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
4770     }
4771
4772   free (secs);
4773
4774   /* Make sure all the phdr assignments succeeded.  */
4775   for (u = lang_output_section_statement.head;
4776        u != NULL;
4777        u = u->output_section_statement.next)
4778     {
4779       lang_output_section_phdr_list *pl;
4780
4781       if (u->output_section_statement.bfd_section == NULL)
4782         continue;
4783
4784       for (pl = u->output_section_statement.phdrs;
4785            pl != NULL;
4786            pl = pl->next)
4787         if (! pl->used && strcmp (pl->name, "NONE") != 0)
4788           einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
4789                  u->output_section_statement.name, pl->name);
4790     }
4791 }
4792
4793 /* Record a list of sections which may not be cross referenced.  */
4794
4795 void
4796 lang_add_nocrossref (lang_nocrossref_type *l)
4797 {
4798   struct lang_nocrossrefs *n;
4799
4800   n = xmalloc (sizeof *n);
4801   n->next = nocrossref_list;
4802   n->list = l;
4803   nocrossref_list = n;
4804
4805   /* Set notice_all so that we get informed about all symbols.  */
4806   link_info.notice_all = TRUE;
4807 }
4808 \f
4809 /* Overlay handling.  We handle overlays with some static variables.  */
4810
4811 /* The overlay virtual address.  */
4812 static etree_type *overlay_vma;
4813 /* And subsection alignment.  */
4814 static etree_type *overlay_subalign;
4815
4816 /* An expression for the maximum section size seen so far.  */
4817 static etree_type *overlay_max;
4818
4819 /* A list of all the sections in this overlay.  */
4820
4821 struct overlay_list {
4822   struct overlay_list *next;
4823   lang_output_section_statement_type *os;
4824 };
4825
4826 static struct overlay_list *overlay_list;
4827
4828 /* Start handling an overlay.  */
4829
4830 void
4831 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
4832 {
4833   /* The grammar should prevent nested overlays from occurring.  */
4834   ASSERT (overlay_vma == NULL
4835           && overlay_subalign == NULL
4836           && overlay_max == NULL);
4837
4838   overlay_vma = vma_expr;
4839   overlay_subalign = subalign;
4840 }
4841
4842 /* Start a section in an overlay.  We handle this by calling
4843    lang_enter_output_section_statement with the correct VMA.
4844    lang_leave_overlay sets up the LMA and memory regions.  */
4845
4846 void
4847 lang_enter_overlay_section (const char *name)
4848 {
4849   struct overlay_list *n;
4850   etree_type *size;
4851
4852   lang_enter_output_section_statement (name, overlay_vma, normal_section,
4853                                        0, overlay_subalign, 0);
4854
4855   /* If this is the first section, then base the VMA of future
4856      sections on this one.  This will work correctly even if `.' is
4857      used in the addresses.  */
4858   if (overlay_list == NULL)
4859     overlay_vma = exp_nameop (ADDR, name);
4860
4861   /* Remember the section.  */
4862   n = xmalloc (sizeof *n);
4863   n->os = current_section;
4864   n->next = overlay_list;
4865   overlay_list = n;
4866
4867   size = exp_nameop (SIZEOF, name);
4868
4869   /* Arrange to work out the maximum section end address.  */
4870   if (overlay_max == NULL)
4871     overlay_max = size;
4872   else
4873     overlay_max = exp_binop (MAX_K, overlay_max, size);
4874 }
4875
4876 /* Finish a section in an overlay.  There isn't any special to do
4877    here.  */
4878
4879 void
4880 lang_leave_overlay_section (fill_type *fill,
4881                             lang_output_section_phdr_list *phdrs)
4882 {
4883   const char *name;
4884   char *clean, *s2;
4885   const char *s1;
4886   char *buf;
4887
4888   name = current_section->name;
4889
4890   /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
4891      region and that no load-time region has been specified.  It doesn't
4892      really matter what we say here, since lang_leave_overlay will
4893      override it.  */
4894   lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
4895
4896   /* Define the magic symbols.  */
4897
4898   clean = xmalloc (strlen (name) + 1);
4899   s2 = clean;
4900   for (s1 = name; *s1 != '\0'; s1++)
4901     if (ISALNUM (*s1) || *s1 == '_')
4902       *s2++ = *s1;
4903   *s2 = '\0';
4904
4905   buf = xmalloc (strlen (clean) + sizeof "__load_start_");
4906   sprintf (buf, "__load_start_%s", clean);
4907   lang_add_assignment (exp_assop ('=', buf,
4908                                   exp_nameop (LOADADDR, name)));
4909
4910   buf = xmalloc (strlen (clean) + sizeof "__load_stop_");
4911   sprintf (buf, "__load_stop_%s", clean);
4912   lang_add_assignment (exp_assop ('=', buf,
4913                                   exp_binop ('+',
4914                                              exp_nameop (LOADADDR, name),
4915                                              exp_nameop (SIZEOF, name))));
4916
4917   free (clean);
4918 }
4919
4920 /* Finish an overlay.  If there are any overlay wide settings, this
4921    looks through all the sections in the overlay and sets them.  */
4922
4923 void
4924 lang_leave_overlay (etree_type *lma_expr,
4925                     int nocrossrefs,
4926                     fill_type *fill,
4927                     const char *memspec,
4928                     lang_output_section_phdr_list *phdrs,
4929                     const char *lma_memspec)
4930 {
4931   lang_memory_region_type *region;
4932   lang_memory_region_type *lma_region;
4933   struct overlay_list *l;
4934   lang_nocrossref_type *nocrossref;
4935
4936   lang_get_regions (&region, &lma_region,
4937                     memspec, lma_memspec,
4938                     lma_expr != NULL, FALSE);
4939
4940   nocrossref = NULL;
4941
4942   /* After setting the size of the last section, set '.' to end of the
4943      overlay region.  */
4944   if (overlay_list != NULL)
4945     overlay_list->os->update_dot_tree
4946       = exp_assop ('=', ".", exp_binop ('+', overlay_vma, overlay_max));
4947
4948   l = overlay_list;
4949   while (l != NULL)
4950     {
4951       struct overlay_list *next;
4952
4953       if (fill != NULL && l->os->fill == NULL)
4954         l->os->fill = fill;
4955
4956       l->os->region = region;
4957       l->os->lma_region = lma_region;
4958
4959       /* The first section has the load address specified in the
4960          OVERLAY statement.  The rest are worked out from that.
4961          The base address is not needed (and should be null) if
4962          an LMA region was specified.  */
4963       if (l->next == 0)
4964         l->os->load_base = lma_expr;
4965       else if (lma_region == 0)
4966         l->os->load_base = exp_binop ('+',
4967                                       exp_nameop (LOADADDR, l->next->os->name),
4968                                       exp_nameop (SIZEOF, l->next->os->name));
4969
4970       if (phdrs != NULL && l->os->phdrs == NULL)
4971         l->os->phdrs = phdrs;
4972
4973       if (nocrossrefs)
4974         {
4975           lang_nocrossref_type *nc;
4976
4977           nc = xmalloc (sizeof *nc);
4978           nc->name = l->os->name;
4979           nc->next = nocrossref;
4980           nocrossref = nc;
4981         }
4982
4983       next = l->next;
4984       free (l);
4985       l = next;
4986     }
4987
4988   if (nocrossref != NULL)
4989     lang_add_nocrossref (nocrossref);
4990
4991   overlay_vma = NULL;
4992   overlay_list = NULL;
4993   overlay_max = NULL;
4994 }
4995 \f
4996 /* Version handling.  This is only useful for ELF.  */
4997
4998 /* This global variable holds the version tree that we build.  */
4999
5000 struct bfd_elf_version_tree *lang_elf_version_info;
5001
5002 /* If PREV is NULL, return first version pattern matching particular symbol.
5003    If PREV is non-NULL, return first version pattern matching particular
5004    symbol after PREV (previously returned by lang_vers_match).  */
5005
5006 static struct bfd_elf_version_expr *
5007 lang_vers_match (struct bfd_elf_version_expr_head *head,
5008                  struct bfd_elf_version_expr *prev,
5009                  const char *sym)
5010 {
5011   const char *cxx_sym = sym;
5012   const char *java_sym = sym;
5013   struct bfd_elf_version_expr *expr = NULL;
5014
5015   if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
5016     {
5017       cxx_sym = cplus_demangle (sym, DMGL_PARAMS | DMGL_ANSI);
5018       if (!cxx_sym)
5019         cxx_sym = sym;
5020     }
5021   if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
5022     {
5023       java_sym = cplus_demangle (sym, DMGL_JAVA);
5024       if (!java_sym)
5025         java_sym = sym;
5026     }
5027
5028   if (head->htab && (prev == NULL || prev->symbol))
5029     {
5030       struct bfd_elf_version_expr e;
5031
5032       switch (prev ? prev->mask : 0)
5033         {
5034           case 0:
5035             if (head->mask & BFD_ELF_VERSION_C_TYPE)
5036               {
5037                 e.symbol = sym;
5038                 expr = htab_find (head->htab, &e);
5039                 while (expr && strcmp (expr->symbol, sym) == 0)
5040                   if (expr->mask == BFD_ELF_VERSION_C_TYPE)
5041                     goto out_ret;
5042                 else
5043                   expr = expr->next;
5044               }
5045             /* Fallthrough */
5046           case BFD_ELF_VERSION_C_TYPE:
5047             if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
5048               {
5049                 e.symbol = cxx_sym;
5050                 expr = htab_find (head->htab, &e);
5051                 while (expr && strcmp (expr->symbol, cxx_sym) == 0)
5052                   if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
5053                     goto out_ret;
5054                 else
5055                   expr = expr->next;
5056               }
5057             /* Fallthrough */
5058           case BFD_ELF_VERSION_CXX_TYPE:
5059             if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
5060               {
5061                 e.symbol = java_sym;
5062                 expr = htab_find (head->htab, &e);
5063                 while (expr && strcmp (expr->symbol, java_sym) == 0)
5064                   if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
5065                     goto out_ret;
5066                 else
5067                   expr = expr->next;
5068               }
5069             /* Fallthrough */
5070           default:
5071             break;
5072         }
5073     }
5074
5075   /* Finally, try the wildcards.  */
5076   if (prev == NULL || prev->symbol)
5077     expr = head->remaining;
5078   else
5079     expr = prev->next;
5080   while (expr)
5081     {
5082       const char *s;
5083
5084       if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
5085         break;
5086
5087       if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
5088         s = java_sym;
5089       else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
5090         s = cxx_sym;
5091       else
5092         s = sym;
5093       if (fnmatch (expr->pattern, s, 0) == 0)
5094         break;
5095       expr = expr->next;
5096     }
5097
5098 out_ret:
5099   if (cxx_sym != sym)
5100     free ((char *) cxx_sym);
5101   if (java_sym != sym)
5102     free ((char *) java_sym);
5103   return expr;
5104 }
5105
5106 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
5107    return a string pointing to the symbol name.  */
5108
5109 static const char *
5110 realsymbol (const char *pattern)
5111 {
5112   const char *p;
5113   bfd_boolean changed = FALSE, backslash = FALSE;
5114   char *s, *symbol = xmalloc (strlen (pattern) + 1);
5115
5116   for (p = pattern, s = symbol; *p != '\0'; ++p)
5117     {
5118       /* It is a glob pattern only if there is no preceding
5119          backslash.  */
5120       if (! backslash && (*p == '?' || *p == '*' || *p == '['))
5121         {
5122           free (symbol);
5123           return NULL;
5124         }
5125
5126       if (backslash)
5127         {
5128           /* Remove the preceding backslash.  */
5129           *(s - 1) = *p;
5130           changed = TRUE;
5131         }
5132       else
5133         *s++ = *p;
5134
5135       backslash = *p == '\\';
5136     }
5137
5138   if (changed)
5139     {
5140       *s = '\0';
5141       return symbol;
5142     }
5143   else
5144     {
5145       free (symbol);
5146       return pattern;
5147     }
5148 }
5149
5150 /* This is called for each variable name or match expression.  */
5151
5152 struct bfd_elf_version_expr *
5153 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
5154                        const char *new,
5155                        const char *lang)
5156 {
5157   struct bfd_elf_version_expr *ret;
5158
5159   ret = xmalloc (sizeof *ret);
5160   ret->next = orig;
5161   ret->pattern = new;
5162   ret->symver = 0;
5163   ret->script = 0;
5164   ret->symbol = realsymbol (new);
5165
5166   if (lang == NULL || strcasecmp (lang, "C") == 0)
5167     ret->mask = BFD_ELF_VERSION_C_TYPE;
5168   else if (strcasecmp (lang, "C++") == 0)
5169     ret->mask = BFD_ELF_VERSION_CXX_TYPE;
5170   else if (strcasecmp (lang, "Java") == 0)
5171     ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
5172   else
5173     {
5174       einfo (_("%X%P: unknown language `%s' in version information\n"),
5175              lang);
5176       ret->mask = BFD_ELF_VERSION_C_TYPE;
5177     }
5178
5179   return ldemul_new_vers_pattern (ret);
5180 }
5181
5182 /* This is called for each set of variable names and match
5183    expressions.  */
5184
5185 struct bfd_elf_version_tree *
5186 lang_new_vers_node (struct bfd_elf_version_expr *globals,
5187                     struct bfd_elf_version_expr *locals)
5188 {
5189   struct bfd_elf_version_tree *ret;
5190
5191   ret = xcalloc (1, sizeof *ret);
5192   ret->globals.list = globals;
5193   ret->locals.list = locals;
5194   ret->match = lang_vers_match;
5195   ret->name_indx = (unsigned int) -1;
5196   return ret;
5197 }
5198
5199 /* This static variable keeps track of version indices.  */
5200
5201 static int version_index;
5202
5203 static hashval_t
5204 version_expr_head_hash (const void *p)
5205 {
5206   const struct bfd_elf_version_expr *e = p;
5207
5208   return htab_hash_string (e->symbol);
5209 }
5210
5211 static int
5212 version_expr_head_eq (const void *p1, const void *p2)
5213 {
5214   const struct bfd_elf_version_expr *e1 = p1;
5215   const struct bfd_elf_version_expr *e2 = p2;
5216
5217   return strcmp (e1->symbol, e2->symbol) == 0;
5218 }
5219
5220 static void
5221 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
5222 {
5223   size_t count = 0;
5224   struct bfd_elf_version_expr *e, *next;
5225   struct bfd_elf_version_expr **list_loc, **remaining_loc;
5226
5227   for (e = head->list; e; e = e->next)
5228     {
5229       if (e->symbol)
5230         count++;
5231       head->mask |= e->mask;
5232     }
5233
5234   if (count)
5235     {
5236       head->htab = htab_create (count * 2, version_expr_head_hash,
5237                                 version_expr_head_eq, NULL);
5238       list_loc = &head->list;
5239       remaining_loc = &head->remaining;
5240       for (e = head->list; e; e = next)
5241         {
5242           next = e->next;
5243           if (!e->symbol)
5244             {
5245               *remaining_loc = e;
5246               remaining_loc = &e->next;
5247             }
5248           else
5249             {
5250               void **loc = htab_find_slot (head->htab, e, INSERT);
5251
5252               if (*loc)
5253                 {
5254                   struct bfd_elf_version_expr *e1, *last;
5255
5256                   e1 = *loc;
5257                   last = NULL;
5258                   do
5259                     {
5260                       if (e1->mask == e->mask)
5261                         {
5262                           last = NULL;
5263                           break;
5264                         }
5265                       last = e1;
5266                       e1 = e1->next;
5267                     }
5268                   while (e1 && strcmp (e1->symbol, e->symbol) == 0);
5269
5270                   if (last == NULL)
5271                     {
5272                       /* This is a duplicate.  */
5273                       /* FIXME: Memory leak.  Sometimes pattern is not
5274                          xmalloced alone, but in larger chunk of memory.  */
5275                       /* free (e->symbol); */
5276                       free (e);
5277                     }
5278                   else
5279                     {
5280                       e->next = last->next;
5281                       last->next = e;
5282                     }
5283                 }
5284               else
5285                 {
5286                   *loc = e;
5287                   *list_loc = e;
5288                   list_loc = &e->next;
5289                 }
5290             }
5291         }
5292       *remaining_loc = NULL;
5293       *list_loc = head->remaining;
5294     }
5295   else
5296     head->remaining = head->list;
5297 }
5298
5299 /* This is called when we know the name and dependencies of the
5300    version.  */
5301
5302 void
5303 lang_register_vers_node (const char *name,
5304                          struct bfd_elf_version_tree *version,
5305                          struct bfd_elf_version_deps *deps)
5306 {
5307   struct bfd_elf_version_tree *t, **pp;
5308   struct bfd_elf_version_expr *e1;
5309
5310   if (name == NULL)
5311     name = "";
5312
5313   if ((name[0] == '\0' && lang_elf_version_info != NULL)
5314       || (lang_elf_version_info && lang_elf_version_info->name[0] == '\0'))
5315     {
5316       einfo (_("%X%P: anonymous version tag cannot be combined with other version tags\n"));
5317       free (version);
5318       return;
5319     }
5320
5321   /* Make sure this node has a unique name.  */
5322   for (t = lang_elf_version_info; t != NULL; t = t->next)
5323     if (strcmp (t->name, name) == 0)
5324       einfo (_("%X%P: duplicate version tag `%s'\n"), name);
5325
5326   lang_finalize_version_expr_head (&version->globals);
5327   lang_finalize_version_expr_head (&version->locals);
5328
5329   /* Check the global and local match names, and make sure there
5330      aren't any duplicates.  */
5331
5332   for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
5333     {
5334       for (t = lang_elf_version_info; t != NULL; t = t->next)
5335         {
5336           struct bfd_elf_version_expr *e2;
5337
5338           if (t->locals.htab && e1->symbol)
5339             {
5340               e2 = htab_find (t->locals.htab, e1);
5341               while (e2 && strcmp (e1->symbol, e2->symbol) == 0)
5342                 {
5343                   if (e1->mask == e2->mask)
5344                     einfo (_("%X%P: duplicate expression `%s' in version information\n"),
5345                            e1->symbol);
5346                   e2 = e2->next;
5347                 }
5348             }
5349           else if (!e1->symbol)
5350             for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
5351               if (strcmp (e1->pattern, e2->pattern) == 0 && e1->mask == e2->mask)
5352                 einfo (_("%X%P: duplicate expression `%s' in version information\n"),
5353                        e1->pattern);
5354         }
5355     }
5356
5357   for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
5358     {
5359       for (t = lang_elf_version_info; t != NULL; t = t->next)
5360         {
5361           struct bfd_elf_version_expr *e2;
5362
5363           if (t->globals.htab && e1->symbol)
5364             {
5365               e2 = htab_find (t->globals.htab, e1);
5366               while (e2 && strcmp (e1->symbol, e2->symbol) == 0)
5367                 {
5368                   if (e1->mask == e2->mask)
5369                     einfo (_("%X%P: duplicate expression `%s' in version information\n"),
5370                            e1->symbol);
5371                   e2 = e2->next;
5372                 }
5373             }
5374           else if (!e1->symbol)
5375             for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
5376               if (strcmp (e1->pattern, e2->pattern) == 0 && e1->mask == e2->mask)
5377                 einfo (_("%X%P: duplicate expression `%s' in version information\n"),
5378                        e1->pattern);
5379         }
5380     }
5381
5382   version->deps = deps;
5383   version->name = name;
5384   if (name[0] != '\0')
5385     {
5386       ++version_index;
5387       version->vernum = version_index;
5388     }
5389   else
5390     version->vernum = 0;
5391
5392   for (pp = &lang_elf_version_info; *pp != NULL; pp = &(*pp)->next)
5393     ;
5394   *pp = version;
5395 }
5396
5397 /* This is called when we see a version dependency.  */
5398
5399 struct bfd_elf_version_deps *
5400 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
5401 {
5402   struct bfd_elf_version_deps *ret;
5403   struct bfd_elf_version_tree *t;
5404
5405   ret = xmalloc (sizeof *ret);
5406   ret->next = list;
5407
5408   for (t = lang_elf_version_info; t != NULL; t = t->next)
5409     {
5410       if (strcmp (t->name, name) == 0)
5411         {
5412           ret->version_needed = t;
5413           return ret;
5414         }
5415     }
5416
5417   einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
5418
5419   return ret;
5420 }
5421
5422 static void
5423 lang_do_version_exports_section (void)
5424 {
5425   struct bfd_elf_version_expr *greg = NULL, *lreg;
5426
5427   LANG_FOR_EACH_INPUT_STATEMENT (is)
5428     {
5429       asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
5430       char *contents, *p;
5431       bfd_size_type len;
5432
5433       if (sec == NULL)
5434         continue;
5435
5436       len = bfd_section_size (is->the_bfd, sec);
5437       contents = xmalloc (len);
5438       if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
5439         einfo (_("%X%P: unable to read .exports section contents\n"), sec);
5440
5441       p = contents;
5442       while (p < contents + len)
5443         {
5444           greg = lang_new_vers_pattern (greg, p, NULL);
5445           p = strchr (p, '\0') + 1;
5446         }
5447
5448       /* Do not free the contents, as we used them creating the regex.  */
5449
5450       /* Do not include this section in the link.  */
5451       bfd_set_section_flags (is->the_bfd, sec,
5452         bfd_get_section_flags (is->the_bfd, sec) | SEC_EXCLUDE);
5453     }
5454
5455   lreg = lang_new_vers_pattern (NULL, "*", NULL);
5456   lang_register_vers_node (command_line.version_exports_section,
5457                            lang_new_vers_node (greg, lreg), NULL);
5458 }
5459
5460 void
5461 lang_add_unique (const char *name)
5462 {
5463   struct unique_sections *ent;
5464
5465   for (ent = unique_section_list; ent; ent = ent->next)
5466     if (strcmp (ent->name, name) == 0)
5467       return;
5468
5469   ent = xmalloc (sizeof *ent);
5470   ent->name = xstrdup (name);
5471   ent->next = unique_section_list;
5472   unique_section_list = ent;
5473 }