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