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