* ldlang.c (lang_size_sections_1): Use IGNORE_SECTION to tell
[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 (!IGNORE_SECTION (output_bfd, os->bfd_section)
2805                         && (bfd_get_section_flags (output_bfd, os->bfd_section)
2806                             & SEC_NEVER_LOAD) == 0
2807                         && ! link_info.relocatable
2808                         && check_regions
2809                         && strcmp (os->region->name, "*default*") == 0
2810                         && lang_memory_region_list != NULL
2811                         && (strcmp (lang_memory_region_list->name,
2812                                     "*default*") != 0
2813                             || lang_memory_region_list->next != NULL))
2814                       {
2815                         /* By default this is an error rather than just a
2816                            warning because if we allocate the section to the
2817                            default memory region we can end up creating an
2818                            excessivly large binary, or even seg faulting when
2819                            attmepting to perform a negative seek.  See
2820                              http://sources.redhat.com/ml/binutils/2003-04/msg00423.html
2821                            for an example of this.  This behaviour can be
2822                            overridden by the using the --no-check-sections
2823                            switch.  */
2824                         if (command_line.check_section_addresses)
2825                           einfo (_("%P%F: error: no memory region specified for loadable section `%s'\n"),
2826                                  bfd_get_section_name (output_bfd,
2827                                                        os->bfd_section));
2828                         else
2829                           einfo (_("%P: warning: no memory region specified for loadable section `%s'\n"),
2830                                  bfd_get_section_name (output_bfd,
2831                                                        os->bfd_section));
2832                       }
2833
2834                     dot = os->region->current;
2835
2836                     if (os->section_alignment == -1)
2837                       {
2838                         bfd_vma olddot;
2839
2840                         olddot = dot;
2841                         dot = align_power (dot,
2842                                            os->bfd_section->alignment_power);
2843
2844                         if (dot != olddot && config.warn_section_align)
2845                           einfo (_("%P: warning: changing start of section %s by %u bytes\n"),
2846                                  os->name, (unsigned int) (dot - olddot));
2847                       }
2848                   }
2849                 else
2850                   {
2851                     etree_value_type r;
2852
2853                     r = exp_fold_tree (os->addr_tree,
2854                                        abs_output_section,
2855                                        lang_allocating_phase_enum,
2856                                        dot, &dot);
2857                     if (!r.valid_p)
2858                       einfo (_("%F%S: non constant address expression for section %s\n"),
2859                              os->name);
2860
2861                     dot = r.value + r.section->bfd_section->vma;
2862                   }
2863
2864                 /* The section starts here.
2865                    First, align to what the section needs.  */
2866
2867                 if (os->section_alignment != -1)
2868                   dot = align_power (dot, os->section_alignment);
2869
2870                 bfd_set_section_vma (0, os->bfd_section, dot);
2871
2872                 os->bfd_section->output_offset = 0;
2873               }
2874
2875             lang_size_sections_1 (os->children.head, os, &os->children.head,
2876                                   os->fill, dot, relax, check_regions);
2877
2878             /* Put the section within the requested block size, or
2879                align at the block boundary.  */
2880             after = align_n (os->bfd_section->vma
2881                              + os->bfd_section->_raw_size / opb,
2882                              (bfd_vma) os->block_value);
2883
2884             if (bfd_is_abs_section (os->bfd_section))
2885               ASSERT (after == os->bfd_section->vma);
2886             else if ((os->bfd_section->flags & SEC_HAS_CONTENTS) == 0
2887                      && (os->bfd_section->flags & SEC_THREAD_LOCAL)
2888                      && ! link_info.relocatable)
2889               os->bfd_section->_raw_size = 0;
2890             else
2891               os->bfd_section->_raw_size =
2892                 (after - os->bfd_section->vma) * opb;
2893
2894             dot = os->bfd_section->vma + os->bfd_section->_raw_size / opb;
2895             os->processed = TRUE;
2896
2897             if (os->update_dot_tree != 0)
2898               exp_fold_tree (os->update_dot_tree, abs_output_section,
2899                              lang_allocating_phase_enum, dot, &dot);
2900
2901             /* Update dot in the region ?
2902                We only do this if the section is going to be allocated,
2903                since unallocated sections do not contribute to the region's
2904                overall size in memory.
2905
2906                If the SEC_NEVER_LOAD bit is not set, it will affect the
2907                addresses of sections after it. We have to update
2908                dot.  */
2909             if (os->region != NULL
2910                 && ((bfd_get_section_flags (output_bfd, os->bfd_section)
2911                      & SEC_NEVER_LOAD) == 0
2912                     || (bfd_get_section_flags (output_bfd, os->bfd_section)
2913                         & (SEC_ALLOC | SEC_LOAD))))
2914               {
2915                 os->region->current = dot;
2916
2917                 if (check_regions)
2918                   /* Make sure the new address is within the region.  */
2919                   os_region_check (os, os->region, os->addr_tree,
2920                                    os->bfd_section->vma);
2921
2922                 /* If there's no load address specified, use the run
2923                    region as the load region.  */
2924                 if (os->lma_region == NULL && os->load_base == NULL)
2925                   os->lma_region = os->region;
2926
2927                 if (os->lma_region != NULL && os->lma_region != os->region)
2928                   {
2929                     /* Set load_base, which will be handled later.  */
2930                     os->load_base = exp_intop (os->lma_region->current);
2931                     os->lma_region->current +=
2932                       os->bfd_section->_raw_size / opb;
2933                     if (check_regions)
2934                       os_region_check (os, os->lma_region, NULL,
2935                                        os->bfd_section->lma);
2936                   }
2937               }
2938           }
2939           break;
2940
2941         case lang_constructors_statement_enum:
2942           dot = lang_size_sections_1 (constructor_list.head,
2943                                       output_section_statement,
2944                                       &s->wild_statement.children.head,
2945                                       fill, dot, relax, check_regions);
2946           break;
2947
2948         case lang_data_statement_enum:
2949           {
2950             unsigned int size = 0;
2951
2952             s->data_statement.output_vma =
2953               dot - output_section_statement->bfd_section->vma;
2954             s->data_statement.output_section =
2955               output_section_statement->bfd_section;
2956
2957             switch (s->data_statement.type)
2958               {
2959               default:
2960                 abort ();
2961               case QUAD:
2962               case SQUAD:
2963                 size = QUAD_SIZE;
2964                 break;
2965               case LONG:
2966                 size = LONG_SIZE;
2967                 break;
2968               case SHORT:
2969                 size = SHORT_SIZE;
2970                 break;
2971               case BYTE:
2972                 size = BYTE_SIZE;
2973                 break;
2974               }
2975             if (size < opb)
2976               size = opb;
2977             dot += size / opb;
2978             output_section_statement->bfd_section->_raw_size += size;
2979             /* The output section gets contents, and then we inspect for
2980                any flags set in the input script which override any ALLOC.  */
2981             output_section_statement->bfd_section->flags |= SEC_HAS_CONTENTS;
2982             if (!(output_section_statement->flags & SEC_NEVER_LOAD))
2983               {
2984                 output_section_statement->bfd_section->flags |=
2985                   SEC_ALLOC | SEC_LOAD;
2986               }
2987           }
2988           break;
2989
2990         case lang_reloc_statement_enum:
2991           {
2992             int size;
2993
2994             s->reloc_statement.output_vma =
2995               dot - output_section_statement->bfd_section->vma;
2996             s->reloc_statement.output_section =
2997               output_section_statement->bfd_section;
2998             size = bfd_get_reloc_size (s->reloc_statement.howto);
2999             dot += size / opb;
3000             output_section_statement->bfd_section->_raw_size += size;
3001           }
3002           break;
3003
3004         case lang_wild_statement_enum:
3005
3006           dot = lang_size_sections_1 (s->wild_statement.children.head,
3007                                       output_section_statement,
3008                                       &s->wild_statement.children.head,
3009                                       fill, dot, relax, check_regions);
3010
3011           break;
3012
3013         case lang_object_symbols_statement_enum:
3014           link_info.create_object_symbols_section =
3015             output_section_statement->bfd_section;
3016           break;
3017         case lang_output_statement_enum:
3018         case lang_target_statement_enum:
3019           break;
3020         case lang_input_section_enum:
3021           {
3022             asection *i;
3023
3024             i = (*prev)->input_section.section;
3025             if (! relax)
3026               {
3027                 if (i->_cooked_size == 0)
3028                   i->_cooked_size = i->_raw_size;
3029               }
3030             else
3031               {
3032                 bfd_boolean again;
3033
3034                 if (! bfd_relax_section (i->owner, i, &link_info, &again))
3035                   einfo (_("%P%F: can't relax section: %E\n"));
3036                 if (again)
3037                   *relax = TRUE;
3038               }
3039             dot = size_input_section (prev, output_section_statement,
3040                                       output_section_statement->fill, dot);
3041           }
3042           break;
3043         case lang_input_statement_enum:
3044           break;
3045         case lang_fill_statement_enum:
3046           s->fill_statement.output_section =
3047             output_section_statement->bfd_section;
3048
3049           fill = s->fill_statement.fill;
3050           break;
3051         case lang_assignment_statement_enum:
3052           {
3053             bfd_vma newdot = dot;
3054
3055             exp_fold_tree (s->assignment_statement.exp,
3056                            output_section_statement,
3057                            lang_allocating_phase_enum,
3058                            dot,
3059                            &newdot);
3060
3061             if (newdot != dot)
3062               {
3063                 if (output_section_statement == abs_output_section)
3064                   {
3065                     /* If we don't have an output section, then just adjust
3066                        the default memory address.  */
3067                     lang_memory_region_lookup ("*default*")->current = newdot;
3068                   }
3069                 else
3070                   {
3071                     /* Insert a pad after this statement.  We can't
3072                        put the pad before when relaxing, in case the
3073                        assignment references dot.  */
3074                     insert_pad (&s->header.next, fill, (newdot - dot) * opb,
3075                                 output_section_statement->bfd_section, dot);
3076
3077                     /* Don't neuter the pad below when relaxing.  */
3078                     s = s->header.next;
3079                   }
3080
3081                 dot = newdot;
3082               }
3083           }
3084           break;
3085
3086         case lang_padding_statement_enum:
3087           /* If this is the first time lang_size_sections is called,
3088              we won't have any padding statements.  If this is the
3089              second or later passes when relaxing, we should allow
3090              padding to shrink.  If padding is needed on this pass, it
3091              will be added back in.  */
3092           s->padding_statement.size = 0;
3093
3094           /* Make sure output_offset is valid.  If relaxation shrinks
3095              the section and this pad isn't needed, it's possible to
3096              have output_offset larger than the final size of the
3097              section.  bfd_set_section_contents will complain even for
3098              a pad size of zero.  */
3099           s->padding_statement.output_offset
3100             = dot - output_section_statement->bfd_section->vma;
3101           break;
3102
3103         case lang_group_statement_enum:
3104           dot = lang_size_sections_1 (s->group_statement.children.head,
3105                                       output_section_statement,
3106                                       &s->group_statement.children.head,
3107                                       fill, dot, relax, check_regions);
3108           break;
3109
3110         default:
3111           FAIL ();
3112           break;
3113
3114           /* We can only get here when relaxing is turned on.  */
3115         case lang_address_statement_enum:
3116           break;
3117         }
3118       prev = &s->header.next;
3119     }
3120   return dot;
3121 }
3122
3123 bfd_vma
3124 lang_size_sections
3125   (lang_statement_union_type *s,
3126    lang_output_section_statement_type *output_section_statement,
3127    lang_statement_union_type **prev,
3128    fill_type *fill,
3129    bfd_vma dot,
3130    bfd_boolean *relax,
3131    bfd_boolean check_regions)
3132 {
3133   bfd_vma result;
3134
3135   exp_data_seg.phase = exp_dataseg_none;
3136   result = lang_size_sections_1 (s, output_section_statement, prev, fill,
3137                                  dot, relax, check_regions);
3138   if (exp_data_seg.phase == exp_dataseg_end_seen)
3139     {
3140       /* If DATA_SEGMENT_ALIGN DATA_SEGMENT_END pair was seen, check whether
3141          a page could be saved in the data segment.  */
3142       bfd_vma first, last;
3143
3144       first = -exp_data_seg.base & (exp_data_seg.pagesize - 1);
3145       last = exp_data_seg.end & (exp_data_seg.pagesize - 1);
3146       if (first && last
3147           && ((exp_data_seg.base & ~(exp_data_seg.pagesize - 1))
3148               != (exp_data_seg.end & ~(exp_data_seg.pagesize - 1)))
3149           && first + last <= exp_data_seg.pagesize)
3150         {
3151           exp_data_seg.phase = exp_dataseg_adjust;
3152           result = lang_size_sections_1 (s, output_section_statement, prev,
3153                                          fill, dot, relax, check_regions);
3154         }
3155     }
3156
3157   return result;
3158 }
3159
3160 bfd_vma
3161 lang_do_assignments
3162   (lang_statement_union_type *s,
3163    lang_output_section_statement_type *output_section_statement,
3164    fill_type *fill,
3165    bfd_vma dot)
3166 {
3167   unsigned opb = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3168                                                 ldfile_output_machine);
3169
3170   for (; s != NULL; s = s->header.next)
3171     {
3172       switch (s->header.type)
3173         {
3174         case lang_constructors_statement_enum:
3175           dot = lang_do_assignments (constructor_list.head,
3176                                      output_section_statement,
3177                                      fill,
3178                                      dot);
3179           break;
3180
3181         case lang_output_section_statement_enum:
3182           {
3183             lang_output_section_statement_type *os;
3184
3185             os = &(s->output_section_statement);
3186             if (os->bfd_section != NULL)
3187               {
3188                 dot = os->bfd_section->vma;
3189                 (void) lang_do_assignments (os->children.head, os,
3190                                             os->fill, dot);
3191                 dot = os->bfd_section->vma + os->bfd_section->_raw_size / opb;
3192
3193               }
3194             if (os->load_base)
3195               {
3196                 /* If nothing has been placed into the output section then
3197                    it won't have a bfd_section.  */
3198                 if (os->bfd_section)
3199                   {
3200                     os->bfd_section->lma
3201                       = exp_get_abs_int (os->load_base, 0, "load base",
3202                                          lang_final_phase_enum);
3203                   }
3204               }
3205           }
3206           break;
3207         case lang_wild_statement_enum:
3208
3209           dot = lang_do_assignments (s->wild_statement.children.head,
3210                                      output_section_statement,
3211                                      fill, dot);
3212
3213           break;
3214
3215         case lang_object_symbols_statement_enum:
3216         case lang_output_statement_enum:
3217         case lang_target_statement_enum:
3218 #if 0
3219         case lang_common_statement_enum:
3220 #endif
3221           break;
3222         case lang_data_statement_enum:
3223           {
3224             etree_value_type value;
3225
3226             value = exp_fold_tree (s->data_statement.exp,
3227                                    abs_output_section,
3228                                    lang_final_phase_enum, dot, &dot);
3229             s->data_statement.value = value.value;
3230             if (!value.valid_p)
3231               einfo (_("%F%P: invalid data statement\n"));
3232           }
3233           {
3234             unsigned int size;
3235             switch (s->data_statement.type)
3236               {
3237               default:
3238                 abort ();
3239               case QUAD:
3240               case SQUAD:
3241                 size = QUAD_SIZE;
3242                 break;
3243               case LONG:
3244                 size = LONG_SIZE;
3245                 break;
3246               case SHORT:
3247                 size = SHORT_SIZE;
3248                 break;
3249               case BYTE:
3250                 size = BYTE_SIZE;
3251                 break;
3252               }
3253             if (size < opb)
3254               size = opb;
3255             dot += size / opb;
3256           }
3257           break;
3258
3259         case lang_reloc_statement_enum:
3260           {
3261             etree_value_type value;
3262
3263             value = exp_fold_tree (s->reloc_statement.addend_exp,
3264                                    abs_output_section,
3265                                    lang_final_phase_enum, dot, &dot);
3266             s->reloc_statement.addend_value = value.value;
3267             if (!value.valid_p)
3268               einfo (_("%F%P: invalid reloc statement\n"));
3269           }
3270           dot += bfd_get_reloc_size (s->reloc_statement.howto) / opb;
3271           break;
3272
3273         case lang_input_section_enum:
3274           {
3275             asection *in = s->input_section.section;
3276
3277             if (in->_cooked_size != 0)
3278               dot += in->_cooked_size / opb;
3279             else
3280               dot += in->_raw_size / opb;
3281           }
3282           break;
3283
3284         case lang_input_statement_enum:
3285           break;
3286         case lang_fill_statement_enum:
3287           fill = s->fill_statement.fill;
3288           break;
3289         case lang_assignment_statement_enum:
3290           {
3291             exp_fold_tree (s->assignment_statement.exp,
3292                            output_section_statement,
3293                            lang_final_phase_enum,
3294                            dot,
3295                            &dot);
3296           }
3297
3298           break;
3299         case lang_padding_statement_enum:
3300           dot += s->padding_statement.size / opb;
3301           break;
3302
3303         case lang_group_statement_enum:
3304           dot = lang_do_assignments (s->group_statement.children.head,
3305                                      output_section_statement,
3306                                      fill, dot);
3307
3308           break;
3309
3310         default:
3311           FAIL ();
3312           break;
3313         case lang_address_statement_enum:
3314           break;
3315         }
3316
3317     }
3318   return dot;
3319 }
3320
3321 /* Fix any .startof. or .sizeof. symbols.  When the assemblers see the
3322    operator .startof. (section_name), it produces an undefined symbol
3323    .startof.section_name.  Similarly, when it sees
3324    .sizeof. (section_name), it produces an undefined symbol
3325    .sizeof.section_name.  For all the output sections, we look for
3326    such symbols, and set them to the correct value.  */
3327
3328 static void
3329 lang_set_startof (void)
3330 {
3331   asection *s;
3332
3333   if (link_info.relocatable)
3334     return;
3335
3336   for (s = output_bfd->sections; s != NULL; s = s->next)
3337     {
3338       const char *secname;
3339       char *buf;
3340       struct bfd_link_hash_entry *h;
3341
3342       secname = bfd_get_section_name (output_bfd, s);
3343       buf = xmalloc (10 + strlen (secname));
3344
3345       sprintf (buf, ".startof.%s", secname);
3346       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
3347       if (h != NULL && h->type == bfd_link_hash_undefined)
3348         {
3349           h->type = bfd_link_hash_defined;
3350           h->u.def.value = bfd_get_section_vma (output_bfd, s);
3351           h->u.def.section = bfd_abs_section_ptr;
3352         }
3353
3354       sprintf (buf, ".sizeof.%s", secname);
3355       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
3356       if (h != NULL && h->type == bfd_link_hash_undefined)
3357         {
3358           unsigned opb;
3359
3360           opb = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3361                                                ldfile_output_machine);
3362           h->type = bfd_link_hash_defined;
3363           if (s->_cooked_size != 0)
3364             h->u.def.value = s->_cooked_size / opb;
3365           else
3366             h->u.def.value = s->_raw_size / opb;
3367           h->u.def.section = bfd_abs_section_ptr;
3368         }
3369
3370       free (buf);
3371     }
3372 }
3373
3374 static void
3375 lang_finish (void)
3376 {
3377   struct bfd_link_hash_entry *h;
3378   bfd_boolean warn;
3379
3380   if (link_info.relocatable || link_info.shared)
3381     warn = FALSE;
3382   else
3383     warn = TRUE;
3384
3385   if (entry_symbol.name == NULL)
3386     {
3387       /* No entry has been specified.  Look for start, but don't warn
3388          if we don't find it.  */
3389       entry_symbol.name = "start";
3390       warn = FALSE;
3391     }
3392
3393   h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
3394                             FALSE, FALSE, TRUE);
3395   if (h != NULL
3396       && (h->type == bfd_link_hash_defined
3397           || h->type == bfd_link_hash_defweak)
3398       && h->u.def.section->output_section != NULL)
3399     {
3400       bfd_vma val;
3401
3402       val = (h->u.def.value
3403              + bfd_get_section_vma (output_bfd,
3404                                     h->u.def.section->output_section)
3405              + h->u.def.section->output_offset);
3406       if (! bfd_set_start_address (output_bfd, val))
3407         einfo (_("%P%F:%s: can't set start address\n"), entry_symbol.name);
3408     }
3409   else
3410     {
3411       bfd_vma val;
3412       const char *send;
3413
3414       /* We couldn't find the entry symbol.  Try parsing it as a
3415          number.  */
3416       val = bfd_scan_vma (entry_symbol.name, &send, 0);
3417       if (*send == '\0')
3418         {
3419           if (! bfd_set_start_address (output_bfd, val))
3420             einfo (_("%P%F: can't set start address\n"));
3421         }
3422       else
3423         {
3424           asection *ts;
3425
3426           /* Can't find the entry symbol, and it's not a number.  Use
3427              the first address in the text section.  */
3428           ts = bfd_get_section_by_name (output_bfd, entry_section);
3429           if (ts != NULL)
3430             {
3431               if (warn)
3432                 einfo (_("%P: warning: cannot find entry symbol %s; defaulting to %V\n"),
3433                        entry_symbol.name,
3434                        bfd_get_section_vma (output_bfd, ts));
3435               if (! bfd_set_start_address (output_bfd,
3436                                            bfd_get_section_vma (output_bfd,
3437                                                                 ts)))
3438                 einfo (_("%P%F: can't set start address\n"));
3439             }
3440           else
3441             {
3442               if (warn)
3443                 einfo (_("%P: warning: cannot find entry symbol %s; not setting start address\n"),
3444                        entry_symbol.name);
3445             }
3446         }
3447     }
3448 }
3449
3450 /* This is a small function used when we want to ignore errors from
3451    BFD.  */
3452
3453 static void
3454 ignore_bfd_errors (const char *s ATTRIBUTE_UNUSED, ...)
3455 {
3456   /* Don't do anything.  */
3457 }
3458
3459 /* Check that the architecture of all the input files is compatible
3460    with the output file.  Also call the backend to let it do any
3461    other checking that is needed.  */
3462
3463 static void
3464 lang_check (void)
3465 {
3466   lang_statement_union_type *file;
3467   bfd *input_bfd;
3468   const bfd_arch_info_type *compatible;
3469
3470   for (file = file_chain.head; file != NULL; file = file->input_statement.next)
3471     {
3472       input_bfd = file->input_statement.the_bfd;
3473       compatible = bfd_arch_get_compatible (input_bfd, output_bfd,
3474                                             command_line.accept_unknown_input_arch);
3475
3476       /* In general it is not possible to perform a relocatable
3477          link between differing object formats when the input
3478          file has relocations, because the relocations in the
3479          input format may not have equivalent representations in
3480          the output format (and besides BFD does not translate
3481          relocs for other link purposes than a final link).  */
3482       if ((link_info.relocatable || link_info.emitrelocations)
3483           && (compatible == NULL
3484               || bfd_get_flavour (input_bfd) != bfd_get_flavour (output_bfd))
3485           && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
3486         {
3487           einfo (_("%P%F: Relocatable linking with relocations from format %s (%B) to format %s (%B) is not supported\n"),
3488                  bfd_get_target (input_bfd), input_bfd,
3489                  bfd_get_target (output_bfd), output_bfd);
3490           /* einfo with %F exits.  */
3491         }
3492
3493       if (compatible == NULL)
3494         {
3495           if (command_line.warn_mismatch)
3496             einfo (_("%P: warning: %s architecture of input file `%B' is incompatible with %s output\n"),
3497                    bfd_printable_name (input_bfd), input_bfd,
3498                    bfd_printable_name (output_bfd));
3499         }
3500       else if (bfd_count_sections (input_bfd))
3501         {
3502           /* If the input bfd has no contents, it shouldn't set the
3503              private data of the output bfd.  */
3504
3505           bfd_error_handler_type pfn = NULL;
3506
3507           /* If we aren't supposed to warn about mismatched input
3508              files, temporarily set the BFD error handler to a
3509              function which will do nothing.  We still want to call
3510              bfd_merge_private_bfd_data, since it may set up
3511              information which is needed in the output file.  */
3512           if (! command_line.warn_mismatch)
3513             pfn = bfd_set_error_handler (ignore_bfd_errors);
3514           if (! bfd_merge_private_bfd_data (input_bfd, output_bfd))
3515             {
3516               if (command_line.warn_mismatch)
3517                 einfo (_("%E%X: failed to merge target specific data of file %B\n"),
3518                        input_bfd);
3519             }
3520           if (! command_line.warn_mismatch)
3521             bfd_set_error_handler (pfn);
3522         }
3523     }
3524 }
3525
3526 /* Look through all the global common symbols and attach them to the
3527    correct section.  The -sort-common command line switch may be used
3528    to roughly sort the entries by size.  */
3529
3530 static void
3531 lang_common (void)
3532 {
3533   if (command_line.inhibit_common_definition)
3534     return;
3535   if (link_info.relocatable
3536       && ! command_line.force_common_definition)
3537     return;
3538
3539   if (! config.sort_common)
3540     bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
3541   else
3542     {
3543       int power;
3544
3545       for (power = 4; power >= 0; power--)
3546         bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
3547     }
3548 }
3549
3550 /* Place one common symbol in the correct section.  */
3551
3552 static bfd_boolean
3553 lang_one_common (struct bfd_link_hash_entry *h, void *info)
3554 {
3555   unsigned int power_of_two;
3556   bfd_vma size;
3557   asection *section;
3558   unsigned opb = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3559                                                 ldfile_output_machine);
3560
3561   if (h->type != bfd_link_hash_common)
3562     return TRUE;
3563
3564   size = h->u.c.size;
3565   power_of_two = h->u.c.p->alignment_power;
3566
3567   if (config.sort_common
3568       && power_of_two < (unsigned int) *(int *) info)
3569     return TRUE;
3570
3571   section = h->u.c.p->section;
3572
3573   /* Increase the size of the section.  */
3574   section->_cooked_size = align_n ((section->_cooked_size + opb - 1) / opb,
3575                                    (bfd_vma) 1 << power_of_two) * opb;
3576
3577   /* Adjust the alignment if necessary.  */
3578   if (power_of_two > section->alignment_power)
3579     section->alignment_power = power_of_two;
3580
3581   /* Change the symbol from common to defined.  */
3582   h->type = bfd_link_hash_defined;
3583   h->u.def.section = section;
3584   h->u.def.value = section->_cooked_size;
3585
3586   /* Increase the size of the section.  */
3587   section->_cooked_size += size;
3588
3589   /* Make sure the section is allocated in memory, and make sure that
3590      it is no longer a common section.  */
3591   section->flags |= SEC_ALLOC;
3592   section->flags &= ~SEC_IS_COMMON;
3593
3594   if (config.map_file != NULL)
3595     {
3596       static bfd_boolean header_printed;
3597       int len;
3598       char *name;
3599       char buf[50];
3600
3601       if (! header_printed)
3602         {
3603           minfo (_("\nAllocating common symbols\n"));
3604           minfo (_("Common symbol       size              file\n\n"));
3605           header_printed = TRUE;
3606         }
3607
3608       name = demangle (h->root.string);
3609       minfo ("%s", name);
3610       len = strlen (name);
3611       free (name);
3612
3613       if (len >= 19)
3614         {
3615           print_nl ();
3616           len = 0;
3617         }
3618       while (len < 20)
3619         {
3620           print_space ();
3621           ++len;
3622         }
3623
3624       minfo ("0x");
3625       if (size <= 0xffffffff)
3626         sprintf (buf, "%lx", (unsigned long) size);
3627       else
3628         sprintf_vma (buf, size);
3629       minfo ("%s", buf);
3630       len = strlen (buf);
3631
3632       while (len < 16)
3633         {
3634           print_space ();
3635           ++len;
3636         }
3637
3638       minfo ("%B\n", section->owner);
3639     }
3640
3641   return TRUE;
3642 }
3643
3644 /* Run through the input files and ensure that every input section has
3645    somewhere to go.  If one is found without a destination then create
3646    an input request and place it into the statement tree.  */
3647
3648 static void
3649 lang_place_orphans (void)
3650 {
3651   LANG_FOR_EACH_INPUT_STATEMENT (file)
3652     {
3653       asection *s;
3654
3655       for (s = file->the_bfd->sections; s != NULL; s = s->next)
3656         {
3657           if (s->output_section == NULL)
3658             {
3659               /* This section of the file is not attached, root
3660                  around for a sensible place for it to go.  */
3661
3662               if (file->just_syms_flag)
3663                 {
3664                   abort ();
3665                 }
3666               else if (strcmp (s->name, "COMMON") == 0)
3667                 {
3668                   /* This is a lonely common section which must have
3669                      come from an archive.  We attach to the section
3670                      with the wildcard.  */
3671                   if (! link_info.relocatable
3672                       || command_line.force_common_definition)
3673                     {
3674                       if (default_common_section == NULL)
3675                         {
3676 #if 0
3677                           /* This message happens when using the
3678                              svr3.ifile linker script, so I have
3679                              disabled it.  */
3680                           info_msg (_("%P: no [COMMON] command, defaulting to .bss\n"));
3681 #endif
3682                           default_common_section =
3683                             lang_output_section_statement_lookup (".bss");
3684
3685                         }
3686                       lang_add_section (&default_common_section->children, s,
3687                                         default_common_section, file);
3688                     }
3689                 }
3690               else if (ldemul_place_orphan (file, s))
3691                 ;
3692               else
3693                 {
3694                   lang_output_section_statement_type *os;
3695
3696                   os = lang_output_section_statement_lookup (s->name);
3697                   lang_add_section (&os->children, s, os, file);
3698                 }
3699             }
3700         }
3701     }
3702 }
3703
3704 void
3705 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
3706 {
3707   flagword *ptr_flags;
3708
3709   ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
3710   while (*flags)
3711     {
3712       switch (*flags)
3713         {
3714         case 'A': case 'a':
3715           *ptr_flags |= SEC_ALLOC;
3716           break;
3717
3718         case 'R': case 'r':
3719           *ptr_flags |= SEC_READONLY;
3720           break;
3721
3722         case 'W': case 'w':
3723           *ptr_flags |= SEC_DATA;
3724           break;
3725
3726         case 'X': case 'x':
3727           *ptr_flags |= SEC_CODE;
3728           break;
3729
3730         case 'L': case 'l':
3731         case 'I': case 'i':
3732           *ptr_flags |= SEC_LOAD;
3733           break;
3734
3735         default:
3736           einfo (_("%P%F: invalid syntax in flags\n"));
3737           break;
3738         }
3739       flags++;
3740     }
3741 }
3742
3743 /* Call a function on each input file.  This function will be called
3744    on an archive, but not on the elements.  */
3745
3746 void
3747 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
3748 {
3749   lang_input_statement_type *f;
3750
3751   for (f = (lang_input_statement_type *) input_file_chain.head;
3752        f != NULL;
3753        f = (lang_input_statement_type *) f->next_real_file)
3754     func (f);
3755 }
3756
3757 /* Call a function on each file.  The function will be called on all
3758    the elements of an archive which are included in the link, but will
3759    not be called on the archive file itself.  */
3760
3761 void
3762 lang_for_each_file (void (*func) (lang_input_statement_type *))
3763 {
3764   LANG_FOR_EACH_INPUT_STATEMENT (f)
3765     {
3766       func (f);
3767     }
3768 }
3769
3770 #if 0
3771
3772 /* Not used.  */
3773
3774 void
3775 lang_for_each_input_section (void (*func) (bfd *ab, asection *as))
3776 {
3777   LANG_FOR_EACH_INPUT_STATEMENT (f)
3778     {
3779       asection *s;
3780
3781       for (s = f->the_bfd->sections; s != NULL; s = s->next)
3782         func (f->the_bfd, s);
3783     }
3784 }
3785
3786 #endif
3787
3788 void
3789 ldlang_add_file (lang_input_statement_type *entry)
3790 {
3791   bfd **pp;
3792
3793   lang_statement_append (&file_chain,
3794                          (lang_statement_union_type *) entry,
3795                          &entry->next);
3796
3797   /* The BFD linker needs to have a list of all input BFDs involved in
3798      a link.  */
3799   ASSERT (entry->the_bfd->link_next == NULL);
3800   ASSERT (entry->the_bfd != output_bfd);
3801   for (pp = &link_info.input_bfds; *pp != NULL; pp = &(*pp)->link_next)
3802     ;
3803   *pp = entry->the_bfd;
3804   entry->the_bfd->usrdata = entry;
3805   bfd_set_gp_size (entry->the_bfd, g_switch_value);
3806
3807   /* Look through the sections and check for any which should not be
3808      included in the link.  We need to do this now, so that we can
3809      notice when the backend linker tries to report multiple
3810      definition errors for symbols which are in sections we aren't
3811      going to link.  FIXME: It might be better to entirely ignore
3812      symbols which are defined in sections which are going to be
3813      discarded.  This would require modifying the backend linker for
3814      each backend which might set the SEC_LINK_ONCE flag.  If we do
3815      this, we should probably handle SEC_EXCLUDE in the same way.  */
3816
3817   bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
3818 }
3819
3820 void
3821 lang_add_output (const char *name, int from_script)
3822 {
3823   /* Make -o on command line override OUTPUT in script.  */
3824   if (!had_output_filename || !from_script)
3825     {
3826       output_filename = name;
3827       had_output_filename = TRUE;
3828     }
3829 }
3830
3831 static lang_output_section_statement_type *current_section;
3832
3833 static int
3834 topower (int x)
3835 {
3836   unsigned int i = 1;
3837   int l;
3838
3839   if (x < 0)
3840     return -1;
3841
3842   for (l = 0; l < 32; l++)
3843     {
3844       if (i >= (unsigned int) x)
3845         return l;
3846       i <<= 1;
3847     }
3848
3849   return 0;
3850 }
3851
3852 lang_output_section_statement_type *
3853 lang_enter_output_section_statement (const char *output_section_statement_name,
3854                                      etree_type *address_exp,
3855                                      enum section_type sectype,
3856                                      bfd_vma block_value,
3857                                      etree_type *align,
3858                                      etree_type *subalign,
3859                                      etree_type *ebase)
3860 {
3861   lang_output_section_statement_type *os;
3862
3863   current_section =
3864    os =
3865     lang_output_section_statement_lookup (output_section_statement_name);
3866
3867   /* Add this statement to tree.  */
3868 #if 0
3869   add_statement (lang_output_section_statement_enum,
3870                  output_section_statement);
3871 #endif
3872   /* Make next things chain into subchain of this.  */
3873
3874   if (os->addr_tree == NULL)
3875     {
3876       os->addr_tree = address_exp;
3877     }
3878   os->sectype = sectype;
3879   if (sectype != noload_section)
3880     os->flags = SEC_NO_FLAGS;
3881   else
3882     os->flags = SEC_NEVER_LOAD;
3883   os->block_value = block_value ? block_value : 1;
3884   stat_ptr = &os->children;
3885
3886   os->subsection_alignment =
3887     topower (exp_get_value_int (subalign, -1, "subsection alignment", 0));
3888   os->section_alignment =
3889     topower (exp_get_value_int (align, -1, "section alignment", 0));
3890
3891   os->load_base = ebase;
3892   return os;
3893 }
3894
3895 void
3896 lang_final (void)
3897 {
3898   lang_output_statement_type *new =
3899     new_stat (lang_output_statement, stat_ptr);
3900
3901   new->name = output_filename;
3902 }
3903
3904 /* Reset the current counters in the regions.  */
3905
3906 void
3907 lang_reset_memory_regions (void)
3908 {
3909   lang_memory_region_type *p = lang_memory_region_list;
3910   asection *o;
3911
3912   for (p = lang_memory_region_list; p != NULL; p = p->next)
3913     {
3914       p->old_length = (bfd_size_type) (p->current - p->origin);
3915       p->current = p->origin;
3916     }
3917
3918   for (o = output_bfd->sections; o != NULL; o = o->next)
3919     o->_raw_size = 0;
3920 }
3921
3922 /* If the wild pattern was marked KEEP, the member sections
3923    should be as well.  */
3924
3925 static void
3926 gc_section_callback (lang_wild_statement_type *ptr,
3927                      struct wildcard_list *sec ATTRIBUTE_UNUSED,
3928                      asection *section,
3929                      lang_input_statement_type *file ATTRIBUTE_UNUSED,
3930                      void *data ATTRIBUTE_UNUSED)
3931 {
3932   if (ptr->keep_sections)
3933     section->flags |= SEC_KEEP;
3934 }
3935
3936 /* Handle a wild statement, marking it against GC.  */
3937
3938 static void
3939 lang_gc_wild (lang_wild_statement_type *s)
3940 {
3941   walk_wild (s, gc_section_callback, NULL);
3942 }
3943
3944 /* Iterate over sections marking them against GC.  */
3945
3946 static void
3947 lang_gc_sections_1 (lang_statement_union_type *s)
3948 {
3949   for (; s != NULL; s = s->header.next)
3950     {
3951       switch (s->header.type)
3952         {
3953         case lang_wild_statement_enum:
3954           lang_gc_wild (&s->wild_statement);
3955           break;
3956         case lang_constructors_statement_enum:
3957           lang_gc_sections_1 (constructor_list.head);
3958           break;
3959         case lang_output_section_statement_enum:
3960           lang_gc_sections_1 (s->output_section_statement.children.head);
3961           break;
3962         case lang_group_statement_enum:
3963           lang_gc_sections_1 (s->group_statement.children.head);
3964           break;
3965         default:
3966           break;
3967         }
3968     }
3969 }
3970
3971 static void
3972 lang_gc_sections (void)
3973 {
3974   struct bfd_link_hash_entry *h;
3975   ldlang_undef_chain_list_type *ulist;
3976
3977   /* Keep all sections so marked in the link script.  */
3978
3979   lang_gc_sections_1 (statement_list.head);
3980
3981   /* Keep all sections containing symbols undefined on the command-line,
3982      and the section containing the entry symbol.  */
3983
3984   for (ulist = link_info.gc_sym_list; ulist; ulist = ulist->next)
3985     {
3986       h = bfd_link_hash_lookup (link_info.hash, ulist->name,
3987                                 FALSE, FALSE, FALSE);
3988
3989       if (h != NULL
3990           && (h->type == bfd_link_hash_defined
3991               || h->type == bfd_link_hash_defweak)
3992           && ! bfd_is_abs_section (h->u.def.section))
3993         {
3994           h->u.def.section->flags |= SEC_KEEP;
3995         }
3996     }
3997
3998   bfd_gc_sections (output_bfd, &link_info);
3999 }
4000
4001 void
4002 lang_process (void)
4003 {
4004   lang_reasonable_defaults ();
4005   current_target = default_target;
4006
4007   /* Open the output file.  */
4008   lang_for_each_statement (ldlang_open_output);
4009
4010   ldemul_create_output_section_statements ();
4011
4012   /* Add to the hash table all undefineds on the command line.  */
4013   lang_place_undefineds ();
4014
4015   already_linked_table_init ();
4016
4017   /* Create a bfd for each input file.  */
4018   current_target = default_target;
4019   open_input_bfds (statement_list.head, FALSE);
4020
4021   link_info.gc_sym_list = &entry_symbol;
4022   if (entry_symbol.name == NULL)
4023     link_info.gc_sym_list = ldlang_undef_chain_list_head;
4024
4025   ldemul_after_open ();
4026
4027   already_linked_table_free ();
4028
4029   /* Make sure that we're not mixing architectures.  We call this
4030      after all the input files have been opened, but before we do any
4031      other processing, so that any operations merge_private_bfd_data
4032      does on the output file will be known during the rest of the
4033      link.  */
4034   lang_check ();
4035
4036   /* Handle .exports instead of a version script if we're told to do so.  */
4037   if (command_line.version_exports_section)
4038     lang_do_version_exports_section ();
4039
4040   /* Build all sets based on the information gathered from the input
4041      files.  */
4042   ldctor_build_sets ();
4043
4044   /* Remove unreferenced sections if asked to.  */
4045   if (command_line.gc_sections)
4046     lang_gc_sections ();
4047
4048   /* If there were any SEC_MERGE sections, finish their merging, so that
4049      section sizes can be computed.  This has to be done after GC of sections,
4050      so that GCed sections are not merged, but before assigning output
4051      sections, since removing whole input sections is hard then.  */
4052   bfd_merge_sections (output_bfd, &link_info);
4053
4054   /* Size up the common data.  */
4055   lang_common ();
4056
4057   /* Run through the contours of the script and attach input sections
4058      to the correct output sections.  */
4059   map_input_to_output_sections (statement_list.head, NULL, NULL);
4060
4061   /* Find any sections not attached explicitly and handle them.  */
4062   lang_place_orphans ();
4063
4064   if (! link_info.relocatable)
4065     {
4066       /* Look for a text section and set the readonly attribute in it.  */
4067       asection *found = bfd_get_section_by_name (output_bfd, ".text");
4068
4069       if (found != NULL)
4070         {
4071           if (config.text_read_only)
4072             found->flags |= SEC_READONLY;
4073           else
4074             found->flags &= ~SEC_READONLY;
4075         }
4076     }
4077
4078   /* Do anything special before sizing sections.  This is where ELF
4079      and other back-ends size dynamic sections.  */
4080   ldemul_before_allocation ();
4081
4082   if (!link_info.relocatable)
4083     strip_excluded_output_sections ();
4084
4085   /* We must record the program headers before we try to fix the
4086      section positions, since they will affect SIZEOF_HEADERS.  */
4087   lang_record_phdrs ();
4088
4089   /* Size up the sections.  */
4090   lang_size_sections (statement_list.head, abs_output_section,
4091                       &statement_list.head, 0, 0, NULL,
4092                       command_line.relax ? FALSE : TRUE);
4093
4094   /* Now run around and relax if we can.  */
4095   if (command_line.relax)
4096     {
4097       /* Keep relaxing until bfd_relax_section gives up.  */
4098       bfd_boolean relax_again;
4099
4100       do
4101         {
4102           lang_reset_memory_regions ();
4103
4104           relax_again = FALSE;
4105
4106           /* Note: pe-dll.c does something like this also.  If you find
4107              you need to change this code, you probably need to change
4108              pe-dll.c also.  DJ  */
4109
4110           /* Do all the assignments with our current guesses as to
4111              section sizes.  */
4112           lang_do_assignments (statement_list.head, abs_output_section,
4113                                NULL, 0);
4114
4115           /* Perform another relax pass - this time we know where the
4116              globals are, so can make a better guess.  */
4117           lang_size_sections (statement_list.head, abs_output_section,
4118                               &statement_list.head, 0, 0, &relax_again, FALSE);
4119
4120           /* If the normal relax is done and the relax finalize pass
4121              is not performed yet, we perform another relax pass.  */
4122           if (!relax_again && !link_info.relax_finalizing)
4123             {
4124               link_info.relax_finalizing = TRUE;
4125               relax_again = TRUE;
4126             }
4127         }
4128       while (relax_again);
4129
4130       /* Final extra sizing to report errors.  */
4131       lang_reset_memory_regions ();
4132       lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
4133       lang_size_sections (statement_list.head, abs_output_section,
4134                           &statement_list.head, 0, 0, NULL, TRUE);
4135     }
4136
4137   /* See if anything special should be done now we know how big
4138      everything is.  */
4139   ldemul_after_allocation ();
4140
4141   /* Fix any .startof. or .sizeof. symbols.  */
4142   lang_set_startof ();
4143
4144   /* Do all the assignments, now that we know the final resting places
4145      of all the symbols.  */
4146
4147   lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
4148
4149   /* Make sure that the section addresses make sense.  */
4150   if (! link_info.relocatable
4151       && command_line.check_section_addresses)
4152     lang_check_section_addresses ();
4153
4154   /* Final stuffs.  */
4155
4156   ldemul_finish ();
4157   lang_finish ();
4158 }
4159
4160 /* EXPORTED TO YACC */
4161
4162 void
4163 lang_add_wild (struct wildcard_spec *filespec,
4164                struct wildcard_list *section_list,
4165                bfd_boolean keep_sections)
4166 {
4167   struct wildcard_list *curr, *next;
4168   lang_wild_statement_type *new;
4169
4170   /* Reverse the list as the parser puts it back to front.  */
4171   for (curr = section_list, section_list = NULL;
4172        curr != NULL;
4173        section_list = curr, curr = next)
4174     {
4175       if (curr->spec.name != NULL && strcmp (curr->spec.name, "COMMON") == 0)
4176         placed_commons = TRUE;
4177
4178       next = curr->next;
4179       curr->next = section_list;
4180     }
4181
4182   if (filespec != NULL && filespec->name != NULL)
4183     {
4184       if (strcmp (filespec->name, "*") == 0)
4185         filespec->name = NULL;
4186       else if (! wildcardp (filespec->name))
4187         lang_has_input_file = TRUE;
4188     }
4189
4190   new = new_stat (lang_wild_statement, stat_ptr);
4191   new->filename = NULL;
4192   new->filenames_sorted = FALSE;
4193   if (filespec != NULL)
4194     {
4195       new->filename = filespec->name;
4196       new->filenames_sorted = filespec->sorted;
4197     }
4198   new->section_list = section_list;
4199   new->keep_sections = keep_sections;
4200   lang_list_init (&new->children);
4201 }
4202
4203 void
4204 lang_section_start (const char *name, etree_type *address)
4205 {
4206   lang_address_statement_type *ad;
4207
4208   ad = new_stat (lang_address_statement, stat_ptr);
4209   ad->section_name = name;
4210   ad->address = address;
4211 }
4212
4213 /* Set the start symbol to NAME.  CMDLINE is nonzero if this is called
4214    because of a -e argument on the command line, or zero if this is
4215    called by ENTRY in a linker script.  Command line arguments take
4216    precedence.  */
4217
4218 void
4219 lang_add_entry (const char *name, bfd_boolean cmdline)
4220 {
4221   if (entry_symbol.name == NULL
4222       || cmdline
4223       || ! entry_from_cmdline)
4224     {
4225       entry_symbol.name = name;
4226       entry_from_cmdline = cmdline;
4227     }
4228 }
4229
4230 void
4231 lang_add_target (const char *name)
4232 {
4233   lang_target_statement_type *new = new_stat (lang_target_statement,
4234                                               stat_ptr);
4235
4236   new->target = name;
4237
4238 }
4239
4240 void
4241 lang_add_map (const char *name)
4242 {
4243   while (*name)
4244     {
4245       switch (*name)
4246         {
4247         case 'F':
4248           map_option_f = TRUE;
4249           break;
4250         }
4251       name++;
4252     }
4253 }
4254
4255 void
4256 lang_add_fill (fill_type *fill)
4257 {
4258   lang_fill_statement_type *new = new_stat (lang_fill_statement,
4259                                             stat_ptr);
4260
4261   new->fill = fill;
4262 }
4263
4264 void
4265 lang_add_data (int type, union etree_union *exp)
4266 {
4267
4268   lang_data_statement_type *new = new_stat (lang_data_statement,
4269                                             stat_ptr);
4270
4271   new->exp = exp;
4272   new->type = type;
4273
4274 }
4275
4276 /* Create a new reloc statement.  RELOC is the BFD relocation type to
4277    generate.  HOWTO is the corresponding howto structure (we could
4278    look this up, but the caller has already done so).  SECTION is the
4279    section to generate a reloc against, or NAME is the name of the
4280    symbol to generate a reloc against.  Exactly one of SECTION and
4281    NAME must be NULL.  ADDEND is an expression for the addend.  */
4282
4283 void
4284 lang_add_reloc (bfd_reloc_code_real_type reloc,
4285                 reloc_howto_type *howto,
4286                 asection *section,
4287                 const char *name,
4288                 union etree_union *addend)
4289 {
4290   lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
4291
4292   p->reloc = reloc;
4293   p->howto = howto;
4294   p->section = section;
4295   p->name = name;
4296   p->addend_exp = addend;
4297
4298   p->addend_value = 0;
4299   p->output_section = NULL;
4300   p->output_vma = 0;
4301 }
4302
4303 lang_assignment_statement_type *
4304 lang_add_assignment (etree_type *exp)
4305 {
4306   lang_assignment_statement_type *new = new_stat (lang_assignment_statement,
4307                                                   stat_ptr);
4308
4309   new->exp = exp;
4310   return new;
4311 }
4312
4313 void
4314 lang_add_attribute (enum statement_enum attribute)
4315 {
4316   new_statement (attribute, sizeof (lang_statement_union_type), stat_ptr);
4317 }
4318
4319 void
4320 lang_startup (const char *name)
4321 {
4322   if (startup_file != NULL)
4323     {
4324       einfo (_("%P%Fmultiple STARTUP files\n"));
4325     }
4326   first_file->filename = name;
4327   first_file->local_sym_name = name;
4328   first_file->real = TRUE;
4329
4330   startup_file = name;
4331 }
4332
4333 void
4334 lang_float (bfd_boolean maybe)
4335 {
4336   lang_float_flag = maybe;
4337 }
4338
4339
4340 /* Work out the load- and run-time regions from a script statement, and
4341    store them in *LMA_REGION and *REGION respectively.
4342
4343    MEMSPEC is the name of the run-time region, or "*default*" if the
4344    statement didn't specify one.  LMA_MEMSPEC is the name of the
4345    load-time region, or null if the statement didn't specify one.
4346    HAVE_LMA_P is TRUE if the statement had an explicit load address.
4347
4348    It is an error to specify both a load region and a load address.  */
4349
4350 static void
4351 lang_get_regions (struct memory_region_struct **region,
4352                   struct memory_region_struct **lma_region,
4353                   const char *memspec,
4354                   const char *lma_memspec,
4355                   int have_lma_p)
4356 {
4357   *lma_region = lang_memory_region_lookup (lma_memspec);
4358
4359   /* If no runtime region has been given, but the load region has
4360      been, use the load region.  */
4361   if (lma_memspec != 0 && strcmp (memspec, "*default*") == 0)
4362     *region = *lma_region;
4363   else
4364     *region = lang_memory_region_lookup (memspec);
4365
4366   if (have_lma_p && lma_memspec != 0)
4367     einfo (_("%X%P:%S: section has both a load address and a load region\n"));
4368 }
4369
4370 void
4371 lang_leave_output_section_statement
4372   (fill_type *fill, const char *memspec,
4373    struct lang_output_section_phdr_list *phdrs, const char *lma_memspec)
4374 {
4375   lang_get_regions (&current_section->region,
4376                     &current_section->lma_region,
4377                     memspec, lma_memspec,
4378                     current_section->load_base != 0);
4379   current_section->fill = fill;
4380   current_section->phdrs = phdrs;
4381   stat_ptr = &statement_list;
4382 }
4383
4384 /* Create an absolute symbol with the given name with the value of the
4385    address of first byte of the section named.
4386
4387    If the symbol already exists, then do nothing.  */
4388
4389 void
4390 lang_abs_symbol_at_beginning_of (const char *secname, const char *name)
4391 {
4392   struct bfd_link_hash_entry *h;
4393
4394   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
4395   if (h == NULL)
4396     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
4397
4398   if (h->type == bfd_link_hash_new
4399       || h->type == bfd_link_hash_undefined)
4400     {
4401       asection *sec;
4402
4403       h->type = bfd_link_hash_defined;
4404
4405       sec = bfd_get_section_by_name (output_bfd, secname);
4406       if (sec == NULL)
4407         h->u.def.value = 0;
4408       else
4409         h->u.def.value = bfd_get_section_vma (output_bfd, sec);
4410
4411       h->u.def.section = bfd_abs_section_ptr;
4412     }
4413 }
4414
4415 /* Create an absolute symbol with the given name with the value of the
4416    address of the first byte after the end of the section named.
4417
4418    If the symbol already exists, then do nothing.  */
4419
4420 void
4421 lang_abs_symbol_at_end_of (const char *secname, const char *name)
4422 {
4423   struct bfd_link_hash_entry *h;
4424
4425   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
4426   if (h == NULL)
4427     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
4428
4429   if (h->type == bfd_link_hash_new
4430       || h->type == bfd_link_hash_undefined)
4431     {
4432       asection *sec;
4433
4434       h->type = bfd_link_hash_defined;
4435
4436       sec = bfd_get_section_by_name (output_bfd, secname);
4437       if (sec == NULL)
4438         h->u.def.value = 0;
4439       else
4440         h->u.def.value = (bfd_get_section_vma (output_bfd, sec)
4441                           + bfd_section_size (output_bfd, sec) /
4442                           bfd_octets_per_byte (output_bfd));
4443
4444       h->u.def.section = bfd_abs_section_ptr;
4445     }
4446 }
4447
4448 void
4449 lang_statement_append (lang_statement_list_type *list,
4450                        lang_statement_union_type *element,
4451                        lang_statement_union_type **field)
4452 {
4453   *(list->tail) = element;
4454   list->tail = field;
4455 }
4456
4457 /* Set the output format type.  -oformat overrides scripts.  */
4458
4459 void
4460 lang_add_output_format (const char *format,
4461                         const char *big,
4462                         const char *little,
4463                         int from_script)
4464 {
4465   if (output_target == NULL || !from_script)
4466     {
4467       if (command_line.endian == ENDIAN_BIG
4468           && big != NULL)
4469         format = big;
4470       else if (command_line.endian == ENDIAN_LITTLE
4471                && little != NULL)
4472         format = little;
4473
4474       output_target = format;
4475     }
4476 }
4477
4478 /* Enter a group.  This creates a new lang_group_statement, and sets
4479    stat_ptr to build new statements within the group.  */
4480
4481 void
4482 lang_enter_group (void)
4483 {
4484   lang_group_statement_type *g;
4485
4486   g = new_stat (lang_group_statement, stat_ptr);
4487   lang_list_init (&g->children);
4488   stat_ptr = &g->children;
4489 }
4490
4491 /* Leave a group.  This just resets stat_ptr to start writing to the
4492    regular list of statements again.  Note that this will not work if
4493    groups can occur inside anything else which can adjust stat_ptr,
4494    but currently they can't.  */
4495
4496 void
4497 lang_leave_group (void)
4498 {
4499   stat_ptr = &statement_list;
4500 }
4501
4502 /* Add a new program header.  This is called for each entry in a PHDRS
4503    command in a linker script.  */
4504
4505 void
4506 lang_new_phdr (const char *name,
4507                etree_type *type,
4508                bfd_boolean filehdr,
4509                bfd_boolean phdrs,
4510                etree_type *at,
4511                etree_type *flags)
4512 {
4513   struct lang_phdr *n, **pp;
4514
4515   n = stat_alloc (sizeof (struct lang_phdr));
4516   n->next = NULL;
4517   n->name = name;
4518   n->type = exp_get_value_int (type, 0, "program header type",
4519                                lang_final_phase_enum);
4520   n->filehdr = filehdr;
4521   n->phdrs = phdrs;
4522   n->at = at;
4523   n->flags = flags;
4524
4525   for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
4526     ;
4527   *pp = n;
4528 }
4529
4530 /* Record the program header information in the output BFD.  FIXME: We
4531    should not be calling an ELF specific function here.  */
4532
4533 static void
4534 lang_record_phdrs (void)
4535 {
4536   unsigned int alc;
4537   asection **secs;
4538   struct lang_output_section_phdr_list *last;
4539   struct lang_phdr *l;
4540   lang_statement_union_type *u;
4541
4542   alc = 10;
4543   secs = xmalloc (alc * sizeof (asection *));
4544   last = NULL;
4545   for (l = lang_phdr_list; l != NULL; l = l->next)
4546     {
4547       unsigned int c;
4548       flagword flags;
4549       bfd_vma at;
4550
4551       c = 0;
4552       for (u = lang_output_section_statement.head;
4553            u != NULL;
4554            u = u->output_section_statement.next)
4555         {
4556           lang_output_section_statement_type *os;
4557           struct lang_output_section_phdr_list *pl;
4558
4559           os = &u->output_section_statement;
4560
4561           pl = os->phdrs;
4562           if (pl != NULL)
4563             last = pl;
4564           else
4565             {
4566               if (os->sectype == noload_section
4567                   || os->bfd_section == NULL
4568                   || (os->bfd_section->flags & SEC_ALLOC) == 0)
4569                 continue;
4570               pl = last;
4571             }
4572
4573           if (os->bfd_section == NULL)
4574             continue;
4575
4576           for (; pl != NULL; pl = pl->next)
4577             {
4578               if (strcmp (pl->name, l->name) == 0)
4579                 {
4580                   if (c >= alc)
4581                     {
4582                       alc *= 2;
4583                       secs = xrealloc (secs, alc * sizeof (asection *));
4584                     }
4585                   secs[c] = os->bfd_section;
4586                   ++c;
4587                   pl->used = TRUE;
4588                 }
4589             }
4590         }
4591
4592       if (l->flags == NULL)
4593         flags = 0;
4594       else
4595         flags = exp_get_vma (l->flags, 0, "phdr flags",
4596                              lang_final_phase_enum);
4597
4598       if (l->at == NULL)
4599         at = 0;
4600       else
4601         at = exp_get_vma (l->at, 0, "phdr load address",
4602                           lang_final_phase_enum);
4603
4604       if (! bfd_record_phdr (output_bfd, l->type,
4605                              l->flags != NULL, flags, l->at != NULL,
4606                              at, l->filehdr, l->phdrs, c, secs))
4607         einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
4608     }
4609
4610   free (secs);
4611
4612   /* Make sure all the phdr assignments succeeded.  */
4613   for (u = lang_output_section_statement.head;
4614        u != NULL;
4615        u = u->output_section_statement.next)
4616     {
4617       struct lang_output_section_phdr_list *pl;
4618
4619       if (u->output_section_statement.bfd_section == NULL)
4620         continue;
4621
4622       for (pl = u->output_section_statement.phdrs;
4623            pl != NULL;
4624            pl = pl->next)
4625         if (! pl->used && strcmp (pl->name, "NONE") != 0)
4626           einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
4627                  u->output_section_statement.name, pl->name);
4628     }
4629 }
4630
4631 /* Record a list of sections which may not be cross referenced.  */
4632
4633 void
4634 lang_add_nocrossref (struct lang_nocrossref *l)
4635 {
4636   struct lang_nocrossrefs *n;
4637
4638   n = xmalloc (sizeof *n);
4639   n->next = nocrossref_list;
4640   n->list = l;
4641   nocrossref_list = n;
4642
4643   /* Set notice_all so that we get informed about all symbols.  */
4644   link_info.notice_all = TRUE;
4645 }
4646 \f
4647 /* Overlay handling.  We handle overlays with some static variables.  */
4648
4649 /* The overlay virtual address.  */
4650 static etree_type *overlay_vma;
4651 /* And subsection alignment.  */
4652 static etree_type *overlay_subalign;
4653
4654 /* An expression for the maximum section size seen so far.  */
4655 static etree_type *overlay_max;
4656
4657 /* A list of all the sections in this overlay.  */
4658
4659 struct overlay_list {
4660   struct overlay_list *next;
4661   lang_output_section_statement_type *os;
4662 };
4663
4664 static struct overlay_list *overlay_list;
4665
4666 /* Start handling an overlay.  */
4667
4668 void
4669 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
4670 {
4671   /* The grammar should prevent nested overlays from occurring.  */
4672   ASSERT (overlay_vma == NULL
4673           && overlay_subalign == NULL
4674           && overlay_max == NULL);
4675
4676   overlay_vma = vma_expr;
4677   overlay_subalign = subalign;
4678 }
4679
4680 /* Start a section in an overlay.  We handle this by calling
4681    lang_enter_output_section_statement with the correct VMA.
4682    lang_leave_overlay sets up the LMA and memory regions.  */
4683
4684 void
4685 lang_enter_overlay_section (const char *name)
4686 {
4687   struct overlay_list *n;
4688   etree_type *size;
4689
4690   lang_enter_output_section_statement (name, overlay_vma, normal_section,
4691                                        0, 0, overlay_subalign, 0);
4692
4693   /* If this is the first section, then base the VMA of future
4694      sections on this one.  This will work correctly even if `.' is
4695      used in the addresses.  */
4696   if (overlay_list == NULL)
4697     overlay_vma = exp_nameop (ADDR, name);
4698
4699   /* Remember the section.  */
4700   n = xmalloc (sizeof *n);
4701   n->os = current_section;
4702   n->next = overlay_list;
4703   overlay_list = n;
4704
4705   size = exp_nameop (SIZEOF, name);
4706
4707   /* Arrange to work out the maximum section end address.  */
4708   if (overlay_max == NULL)
4709     overlay_max = size;
4710   else
4711     overlay_max = exp_binop (MAX_K, overlay_max, size);
4712 }
4713
4714 /* Finish a section in an overlay.  There isn't any special to do
4715    here.  */
4716
4717 void
4718 lang_leave_overlay_section (fill_type *fill,
4719                             struct lang_output_section_phdr_list *phdrs)
4720 {
4721   const char *name;
4722   char *clean, *s2;
4723   const char *s1;
4724   char *buf;
4725
4726   name = current_section->name;
4727
4728   /* For now, assume that "*default*" is the run-time memory region and
4729      that no load-time region has been specified.  It doesn't really
4730      matter what we say here, since lang_leave_overlay will override it.  */
4731   lang_leave_output_section_statement (fill, "*default*", phdrs, 0);
4732
4733   /* Define the magic symbols.  */
4734
4735   clean = xmalloc (strlen (name) + 1);
4736   s2 = clean;
4737   for (s1 = name; *s1 != '\0'; s1++)
4738     if (ISALNUM (*s1) || *s1 == '_')
4739       *s2++ = *s1;
4740   *s2 = '\0';
4741
4742   buf = xmalloc (strlen (clean) + sizeof "__load_start_");
4743   sprintf (buf, "__load_start_%s", clean);
4744   lang_add_assignment (exp_assop ('=', buf,
4745                                   exp_nameop (LOADADDR, name)));
4746
4747   buf = xmalloc (strlen (clean) + sizeof "__load_stop_");
4748   sprintf (buf, "__load_stop_%s", clean);
4749   lang_add_assignment (exp_assop ('=', buf,
4750                                   exp_binop ('+',
4751                                              exp_nameop (LOADADDR, name),
4752                                              exp_nameop (SIZEOF, name))));
4753
4754   free (clean);
4755 }
4756
4757 /* Finish an overlay.  If there are any overlay wide settings, this
4758    looks through all the sections in the overlay and sets them.  */
4759
4760 void
4761 lang_leave_overlay (etree_type *lma_expr,
4762                     int nocrossrefs,
4763                     fill_type *fill,
4764                     const char *memspec,
4765                     struct lang_output_section_phdr_list *phdrs,
4766                     const char *lma_memspec)
4767 {
4768   lang_memory_region_type *region;
4769   lang_memory_region_type *lma_region;
4770   struct overlay_list *l;
4771   struct lang_nocrossref *nocrossref;
4772
4773   lang_get_regions (&region, &lma_region,
4774                     memspec, lma_memspec,
4775                     lma_expr != 0);
4776
4777   nocrossref = NULL;
4778
4779   /* After setting the size of the last section, set '.' to end of the
4780      overlay region.  */
4781   if (overlay_list != NULL)
4782     overlay_list->os->update_dot_tree
4783       = exp_assop ('=', ".", exp_binop ('+', overlay_vma, overlay_max));
4784
4785   l = overlay_list;
4786   while (l != NULL)
4787     {
4788       struct overlay_list *next;
4789
4790       if (fill != NULL && l->os->fill == NULL)
4791         l->os->fill = fill;
4792
4793       l->os->region = region;
4794       l->os->lma_region = lma_region;
4795
4796       /* The first section has the load address specified in the
4797          OVERLAY statement.  The rest are worked out from that.
4798          The base address is not needed (and should be null) if
4799          an LMA region was specified.  */
4800       if (l->next == 0)
4801         l->os->load_base = lma_expr;
4802       else if (lma_region == 0)
4803         l->os->load_base = exp_binop ('+',
4804                                       exp_nameop (LOADADDR, l->next->os->name),
4805                                       exp_nameop (SIZEOF, l->next->os->name));
4806
4807       if (phdrs != NULL && l->os->phdrs == NULL)
4808         l->os->phdrs = phdrs;
4809
4810       if (nocrossrefs)
4811         {
4812           struct lang_nocrossref *nc;
4813
4814           nc = xmalloc (sizeof *nc);
4815           nc->name = l->os->name;
4816           nc->next = nocrossref;
4817           nocrossref = nc;
4818         }
4819
4820       next = l->next;
4821       free (l);
4822       l = next;
4823     }
4824
4825   if (nocrossref != NULL)
4826     lang_add_nocrossref (nocrossref);
4827
4828   overlay_vma = NULL;
4829   overlay_list = NULL;
4830   overlay_max = NULL;
4831 }
4832 \f
4833 /* Version handling.  This is only useful for ELF.  */
4834
4835 /* This global variable holds the version tree that we build.  */
4836
4837 struct bfd_elf_version_tree *lang_elf_version_info;
4838
4839 static int
4840 lang_vers_match_lang_c (struct bfd_elf_version_expr *expr,
4841                         const char *sym)
4842 {
4843   if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
4844     return 1;
4845   return fnmatch (expr->pattern, sym, 0) == 0;
4846 }
4847
4848 static int
4849 lang_vers_match_lang_cplusplus (struct bfd_elf_version_expr *expr,
4850                                 const char *sym)
4851 {
4852   char *alt_sym;
4853   int result;
4854
4855   if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
4856     return 1;
4857
4858   alt_sym = cplus_demangle (sym, /* DMGL_NO_TPARAMS */ 0);
4859   if (!alt_sym)
4860     {
4861       /* cplus_demangle (also) returns NULL when it is not a C++ symbol.
4862          Should we early out FALSE in this case?  */
4863       result = fnmatch (expr->pattern, sym, 0) == 0;
4864     }
4865   else
4866     {
4867       result = fnmatch (expr->pattern, alt_sym, 0) == 0;
4868       free (alt_sym);
4869     }
4870
4871   return result;
4872 }
4873
4874 static int
4875 lang_vers_match_lang_java (struct bfd_elf_version_expr *expr,
4876                            const char *sym)
4877 {
4878   char *alt_sym;
4879   int result;
4880
4881   if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
4882     return 1;
4883
4884   alt_sym = cplus_demangle (sym, DMGL_JAVA);
4885   if (!alt_sym)
4886     {
4887       /* cplus_demangle (also) returns NULL when it is not a Java symbol.
4888          Should we early out FALSE in this case?  */
4889       result = fnmatch (expr->pattern, sym, 0) == 0;
4890     }
4891   else
4892     {
4893       result = fnmatch (expr->pattern, alt_sym, 0) == 0;
4894       free (alt_sym);
4895     }
4896
4897   return result;
4898 }
4899
4900 /* This is called for each variable name or match expression.  */
4901
4902 struct bfd_elf_version_expr *
4903 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
4904                        const char *new,
4905                        const char *lang)
4906 {
4907   struct bfd_elf_version_expr *ret;
4908
4909   ret = xmalloc (sizeof *ret);
4910   ret->next = orig;
4911   ret->pattern = new;
4912   ret->symver = 0;
4913   ret->script = 0;
4914
4915   if (lang == NULL || strcasecmp (lang, "C") == 0)
4916     ret->match = lang_vers_match_lang_c;
4917   else if (strcasecmp (lang, "C++") == 0)
4918     ret->match = lang_vers_match_lang_cplusplus;
4919   else if (strcasecmp (lang, "Java") == 0)
4920     ret->match = lang_vers_match_lang_java;
4921   else
4922     {
4923       einfo (_("%X%P: unknown language `%s' in version information\n"),
4924              lang);
4925       ret->match = lang_vers_match_lang_c;
4926     }
4927
4928   return ldemul_new_vers_pattern (ret);
4929 }
4930
4931 /* This is called for each set of variable names and match
4932    expressions.  */
4933
4934 struct bfd_elf_version_tree *
4935 lang_new_vers_node (struct bfd_elf_version_expr *globals,
4936                     struct bfd_elf_version_expr *locals)
4937 {
4938   struct bfd_elf_version_tree *ret;
4939
4940   ret = xmalloc (sizeof *ret);
4941   ret->next = NULL;
4942   ret->name = NULL;
4943   ret->vernum = 0;
4944   ret->globals = globals;
4945   ret->locals = locals;
4946   ret->deps = NULL;
4947   ret->name_indx = (unsigned int) -1;
4948   ret->used = 0;
4949   return ret;
4950 }
4951
4952 /* This static variable keeps track of version indices.  */
4953
4954 static int version_index;
4955
4956 /* This is called when we know the name and dependencies of the
4957    version.  */
4958
4959 void
4960 lang_register_vers_node (const char *name,
4961                          struct bfd_elf_version_tree *version,
4962                          struct bfd_elf_version_deps *deps)
4963 {
4964   struct bfd_elf_version_tree *t, **pp;
4965   struct bfd_elf_version_expr *e1;
4966
4967   if (name == NULL)
4968     name = "";
4969
4970   if ((name[0] == '\0' && lang_elf_version_info != NULL)
4971       || (lang_elf_version_info && lang_elf_version_info->name[0] == '\0'))
4972     {
4973       einfo (_("%X%P: anonymous version tag cannot be combined with other version tags\n"));
4974       free (version);
4975       return;
4976     }
4977
4978   /* Make sure this node has a unique name.  */
4979   for (t = lang_elf_version_info; t != NULL; t = t->next)
4980     if (strcmp (t->name, name) == 0)
4981       einfo (_("%X%P: duplicate version tag `%s'\n"), name);
4982
4983   /* Check the global and local match names, and make sure there
4984      aren't any duplicates.  */
4985
4986   for (e1 = version->globals; e1 != NULL; e1 = e1->next)
4987     {
4988       for (t = lang_elf_version_info; t != NULL; t = t->next)
4989         {
4990           struct bfd_elf_version_expr *e2;
4991
4992           for (e2 = t->locals; e2 != NULL; e2 = e2->next)
4993             if (strcmp (e1->pattern, e2->pattern) == 0)
4994               einfo (_("%X%P: duplicate expression `%s' in version information\n"),
4995                      e1->pattern);
4996         }
4997     }
4998
4999   for (e1 = version->locals; e1 != NULL; e1 = e1->next)
5000     {
5001       for (t = lang_elf_version_info; t != NULL; t = t->next)
5002         {
5003           struct bfd_elf_version_expr *e2;
5004
5005           for (e2 = t->globals; e2 != NULL; e2 = e2->next)
5006             if (strcmp (e1->pattern, e2->pattern) == 0)
5007               einfo (_("%X%P: duplicate expression `%s' in version information\n"),
5008                      e1->pattern);
5009         }
5010     }
5011
5012   version->deps = deps;
5013   version->name = name;
5014   if (name[0] != '\0')
5015     {
5016       ++version_index;
5017       version->vernum = version_index;
5018     }
5019   else
5020     version->vernum = 0;
5021
5022   for (pp = &lang_elf_version_info; *pp != NULL; pp = &(*pp)->next)
5023     ;
5024   *pp = version;
5025 }
5026
5027 /* This is called when we see a version dependency.  */
5028
5029 struct bfd_elf_version_deps *
5030 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
5031 {
5032   struct bfd_elf_version_deps *ret;
5033   struct bfd_elf_version_tree *t;
5034
5035   ret = xmalloc (sizeof *ret);
5036   ret->next = list;
5037
5038   for (t = lang_elf_version_info; t != NULL; t = t->next)
5039     {
5040       if (strcmp (t->name, name) == 0)
5041         {
5042           ret->version_needed = t;
5043           return ret;
5044         }
5045     }
5046
5047   einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
5048
5049   return ret;
5050 }
5051
5052 static void
5053 lang_do_version_exports_section (void)
5054 {
5055   struct bfd_elf_version_expr *greg = NULL, *lreg;
5056
5057   LANG_FOR_EACH_INPUT_STATEMENT (is)
5058     {
5059       asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
5060       char *contents, *p;
5061       bfd_size_type len;
5062
5063       if (sec == NULL)
5064         continue;
5065
5066       len = bfd_section_size (is->the_bfd, sec);
5067       contents = xmalloc (len);
5068       if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
5069         einfo (_("%X%P: unable to read .exports section contents\n"), sec);
5070
5071       p = contents;
5072       while (p < contents + len)
5073         {
5074           greg = lang_new_vers_pattern (greg, p, NULL);
5075           p = strchr (p, '\0') + 1;
5076         }
5077
5078       /* Do not free the contents, as we used them creating the regex.  */
5079
5080       /* Do not include this section in the link.  */
5081       bfd_set_section_flags (is->the_bfd, sec,
5082         bfd_get_section_flags (is->the_bfd, sec) | SEC_EXCLUDE);
5083     }
5084
5085   lreg = lang_new_vers_pattern (NULL, "*", NULL);
5086   lang_register_vers_node (command_line.version_exports_section,
5087                            lang_new_vers_node (greg, lreg), NULL);
5088 }
5089
5090 void
5091 lang_add_unique (const char *name)
5092 {
5093   struct unique_sections *ent;
5094
5095   for (ent = unique_section_list; ent; ent = ent->next)
5096     if (strcmp (ent->name, name) == 0)
5097       return;
5098
5099   ent = xmalloc (sizeof *ent);
5100   ent->name = xstrdup (name);
5101   ent->next = unique_section_list;
5102   unique_section_list = ent;
5103 }