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