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