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