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