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