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