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