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