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