ee85422b307b43f05ca75abc6d49c012d9c433ba
[external/binutils.git] / ld / ldlang.c
1 /* Linker command language support.
2    Copyright 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005
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, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 #include "bfd.h"
24 #include "sysdep.h"
25 #include "libiberty.h"
26 #include "safe-ctype.h"
27 #include "obstack.h"
28 #include "bfdlink.h"
29
30 #include "ld.h"
31 #include "ldmain.h"
32 #include "ldexp.h"
33 #include "ldlang.h"
34 #include <ldgram.h>
35 #include "ldlex.h"
36 #include "ldmisc.h"
37 #include "ldctor.h"
38 #include "ldfile.h"
39 #include "ldemul.h"
40 #include "fnmatch.h"
41 #include "demangle.h"
42 #include "hashtab.h"
43
44 #ifndef offsetof
45 #define offsetof(TYPE, MEMBER) ((size_t) & (((TYPE*) 0)->MEMBER))
46 #endif
47
48 /* Locals variables.  */
49 static struct obstack stat_obstack;
50 static struct obstack map_obstack;
51
52 #define obstack_chunk_alloc xmalloc
53 #define obstack_chunk_free free
54 static const char *startup_file;
55 static lang_statement_list_type input_file_chain;
56 static bfd_boolean placed_commons = FALSE;
57 static bfd_boolean stripped_excluded_sections = FALSE;
58 static lang_output_section_statement_type *default_common_section;
59 static bfd_boolean map_option_f;
60 static bfd_vma print_dot;
61 static lang_input_statement_type *first_file;
62 static const char *current_target;
63 static const char *output_target;
64 static lang_statement_list_type statement_list;
65 static struct lang_phdr *lang_phdr_list;
66 static struct bfd_hash_table lang_definedness_table;
67
68 /* Forward declarations.  */
69 static void exp_init_os (etree_type *);
70 static void init_map_userdata (bfd *, asection *, void *);
71 static lang_input_statement_type *lookup_name (const char *);
72 static bfd_boolean load_symbols (lang_input_statement_type *,
73                                  lang_statement_list_type *);
74 static struct bfd_hash_entry *lang_definedness_newfunc
75  (struct bfd_hash_entry *, struct bfd_hash_table *, const char *);
76 static void insert_undefined (const char *);
77 static void print_all_symbols (asection *);
78 static bfd_boolean sort_def_symbol (struct bfd_link_hash_entry *, void *);
79 static void print_statement (lang_statement_union_type *,
80                              lang_output_section_statement_type *);
81 static void print_statement_list (lang_statement_union_type *,
82                                   lang_output_section_statement_type *);
83 static void print_statements (void);
84 static bfd_boolean lang_one_common (struct bfd_link_hash_entry *, void *);
85 static void lang_record_phdrs (void);
86 static void lang_do_version_exports_section (void);
87
88 /* Exported variables.  */
89 lang_output_section_statement_type *abs_output_section;
90 lang_statement_list_type lang_output_section_statement;
91 lang_statement_list_type *stat_ptr = &statement_list;
92 lang_statement_list_type file_chain = { NULL, NULL };
93 struct bfd_sym_chain entry_symbol = { NULL, NULL };
94 const char *entry_section = ".text";
95 bfd_boolean entry_from_cmdline;
96 bfd_boolean lang_has_input_file = FALSE;
97 bfd_boolean had_output_filename = FALSE;
98 bfd_boolean lang_float_flag = FALSE;
99 bfd_boolean delete_output_file_on_failure = FALSE;
100 struct lang_nocrossrefs *nocrossref_list;
101 static struct unique_sections *unique_section_list;
102 static bfd_boolean ldlang_sysrooted_script = FALSE;
103 int lang_statement_iteration = 0;
104
105 etree_type *base; /* Relocation base - or null */
106
107 /* Return TRUE if the PATTERN argument is a wildcard pattern.
108    Although backslashes are treated specially if a pattern contains
109    wildcards, we do not consider the mere presence of a backslash to
110    be enough to cause the pattern to be treated as a wildcard.
111    That lets us handle DOS filenames more naturally.  */
112 #define wildcardp(pattern) (strpbrk ((pattern), "?*[") != NULL)
113
114 #define new_stat(x, y) \
115   (x##_type *) new_statement (x##_enum, sizeof (x##_type), y)
116
117 #define outside_section_address(q) \
118   ((q)->output_offset + (q)->output_section->vma)
119
120 #define outside_symbol_address(q) \
121   ((q)->value + outside_section_address (q->section))
122
123 #define SECTION_NAME_MAP_LENGTH (16)
124
125 void *
126 stat_alloc (size_t size)
127 {
128   return obstack_alloc (&stat_obstack, size);
129 }
130
131 bfd_boolean
132 unique_section_p (const asection *sec)
133 {
134   struct unique_sections *unam;
135   const char *secnam;
136
137   if (link_info.relocatable
138       && sec->owner != NULL
139       && bfd_is_group_section (sec->owner, sec))
140     return TRUE;
141
142   secnam = sec->name;
143   for (unam = unique_section_list; unam; unam = unam->next)
144     if (wildcardp (unam->name)
145         ? fnmatch (unam->name, secnam, 0) == 0
146         : strcmp (unam->name, secnam) == 0)
147       {
148         return TRUE;
149       }
150
151   return FALSE;
152 }
153
154 /* Generic traversal routines for finding matching sections.  */
155
156 /* Try processing a section against a wildcard.  This just calls
157    the callback unless the filename exclusion list is present
158    and excludes the file.  It's hardly ever present so this
159    function is very fast.  */
160
161 static void
162 walk_wild_consider_section (lang_wild_statement_type *ptr,
163                             lang_input_statement_type *file,
164                             asection *s,
165                             struct wildcard_list *sec,
166                             callback_t callback,
167                             void *data)
168 {
169   bfd_boolean skip = FALSE;
170   struct name_list *list_tmp;
171
172   /* Don't process sections from files which were
173      excluded.  */
174   for (list_tmp = sec->spec.exclude_name_list;
175        list_tmp;
176        list_tmp = list_tmp->next)
177     {
178       bfd_boolean is_wildcard = wildcardp (list_tmp->name);
179       if (is_wildcard)
180         skip = fnmatch (list_tmp->name, file->filename, 0) == 0;
181       else
182         skip = strcmp (list_tmp->name, file->filename) == 0;
183
184       /* If this file is part of an archive, and the archive is
185          excluded, exclude this file.  */
186       if (! skip && file->the_bfd != NULL
187           && file->the_bfd->my_archive != NULL
188           && file->the_bfd->my_archive->filename != NULL)
189         {
190           if (is_wildcard)
191             skip = fnmatch (list_tmp->name,
192                             file->the_bfd->my_archive->filename,
193                             0) == 0;
194           else
195             skip = strcmp (list_tmp->name,
196                            file->the_bfd->my_archive->filename) == 0;
197         }
198
199       if (skip)
200         break;
201     }
202
203   if (!skip)
204     (*callback) (ptr, sec, s, file, data);
205 }
206
207 /* Lowest common denominator routine that can handle everything correctly,
208    but slowly.  */
209
210 static void
211 walk_wild_section_general (lang_wild_statement_type *ptr,
212                            lang_input_statement_type *file,
213                            callback_t callback,
214                            void *data)
215 {
216   asection *s;
217   struct wildcard_list *sec;
218
219   for (s = file->the_bfd->sections; s != NULL; s = s->next)
220     {
221       sec = ptr->section_list;
222       if (sec == NULL)
223         (*callback) (ptr, sec, s, file, data);
224
225       while (sec != NULL)
226         {
227           bfd_boolean skip = FALSE;
228
229           if (sec->spec.name != NULL)
230             {
231               const char *sname = bfd_get_section_name (file->the_bfd, s);
232
233               if (wildcardp (sec->spec.name))
234                 skip = fnmatch (sec->spec.name, sname, 0) != 0;
235               else
236                 skip = strcmp (sec->spec.name, sname) != 0;
237             }
238
239           if (!skip)
240             walk_wild_consider_section (ptr, file, s, sec, callback, data);
241
242           sec = sec->next;
243         }
244     }
245 }
246
247 /* Routines to find a single section given its name.  If there's more
248    than one section with that name, we report that.  */
249
250 typedef struct
251 {
252   asection *found_section;
253   bfd_boolean multiple_sections_found;
254 } section_iterator_callback_data;
255
256 static bfd_boolean
257 section_iterator_callback (bfd *bfd ATTRIBUTE_UNUSED, asection *s, void *data)
258 {
259   section_iterator_callback_data *d = data;
260
261   if (d->found_section != NULL)
262     {
263       d->multiple_sections_found = TRUE;
264       return TRUE;
265     }
266
267   d->found_section = s;
268   return FALSE;
269 }
270
271 static asection *
272 find_section (lang_input_statement_type *file,
273               struct wildcard_list *sec,
274               bfd_boolean *multiple_sections_found)
275 {
276   section_iterator_callback_data cb_data = { NULL, FALSE };
277
278   bfd_get_section_by_name_if (file->the_bfd, sec->spec.name, 
279                               section_iterator_callback, &cb_data);
280   *multiple_sections_found = cb_data.multiple_sections_found;
281   return cb_data.found_section;
282 }
283
284 /* Code for handling simple wildcards without going through fnmatch,
285    which can be expensive because of charset translations etc.  */
286
287 /* A simple wild is a literal string followed by a single '*',
288    where the literal part is at least 4 characters long.  */
289
290 static bfd_boolean
291 is_simple_wild (const char *name)
292 {
293   size_t len = strcspn (name, "*?[");
294   return len >= 4 && name[len] == '*' && name[len + 1] == '\0';
295 }
296
297 static bfd_boolean
298 match_simple_wild (const char *pattern, const char *name)
299 {
300   /* The first four characters of the pattern are guaranteed valid
301      non-wildcard characters.  So we can go faster.  */
302   if (pattern[0] != name[0] || pattern[1] != name[1]
303       || pattern[2] != name[2] || pattern[3] != name[3])
304     return FALSE;
305
306   pattern += 4;
307   name += 4;
308   while (*pattern != '*')
309     if (*name++ != *pattern++)
310       return FALSE;
311
312   return TRUE;
313 }
314
315 /* Specialized, optimized routines for handling different kinds of
316    wildcards */
317
318 static void
319 walk_wild_section_specs1_wild0 (lang_wild_statement_type *ptr,
320                                 lang_input_statement_type *file,
321                                 callback_t callback,
322                                 void *data)
323 {
324   /* We can just do a hash lookup for the section with the right name.
325      But if that lookup discovers more than one section with the name
326      (should be rare), we fall back to the general algorithm because
327      we would otherwise have to sort the sections to make sure they
328      get processed in the bfd's order.  */
329   bfd_boolean multiple_sections_found;
330   struct wildcard_list *sec0 = ptr->handler_data[0];
331   asection *s0 = find_section (file, sec0, &multiple_sections_found);
332
333   if (multiple_sections_found)
334     walk_wild_section_general (ptr, file, callback, data);
335   else if (s0)
336     walk_wild_consider_section (ptr, file, s0, sec0, callback, data);
337 }
338
339 static void
340 walk_wild_section_specs1_wild1 (lang_wild_statement_type *ptr,
341                                 lang_input_statement_type *file,
342                                 callback_t callback,
343                                 void *data)
344 {
345   asection *s;
346   struct wildcard_list *wildsec0 = ptr->handler_data[0];
347
348   for (s = file->the_bfd->sections; s != NULL; s = s->next)
349     {
350       const char *sname = bfd_get_section_name (file->the_bfd, s);
351       bfd_boolean skip = !match_simple_wild (wildsec0->spec.name, sname);
352
353       if (!skip)
354         walk_wild_consider_section (ptr, file, s, wildsec0, callback, data);
355     }
356 }
357
358 static void
359 walk_wild_section_specs2_wild1 (lang_wild_statement_type *ptr,
360                                 lang_input_statement_type *file,
361                                 callback_t callback,
362                                 void *data)
363 {
364   asection *s;
365   struct wildcard_list *sec0 = ptr->handler_data[0];
366   struct wildcard_list *wildsec1 = ptr->handler_data[1];
367   bfd_boolean multiple_sections_found;
368   asection *s0 = find_section (file, sec0, &multiple_sections_found);
369
370   if (multiple_sections_found)
371     {
372       walk_wild_section_general (ptr, file, callback, data);
373       return;
374     }
375
376   /* Note that if the section was not found, s0 is NULL and
377      we'll simply never succeed the s == s0 test below.  */
378   for (s = file->the_bfd->sections; s != NULL; s = s->next)
379     {
380       /* Recall that in this code path, a section cannot satisfy more
381          than one spec, so if s == s0 then it cannot match
382          wildspec1.  */
383       if (s == s0)
384         walk_wild_consider_section (ptr, file, s, sec0, callback, data);
385       else
386         {
387           const char *sname = bfd_get_section_name (file->the_bfd, s);
388           bfd_boolean skip = !match_simple_wild (wildsec1->spec.name, sname);
389
390           if (!skip)
391             walk_wild_consider_section (ptr, file, s, wildsec1, callback,
392                                         data);
393         }
394     }
395 }
396
397 static void
398 walk_wild_section_specs3_wild2 (lang_wild_statement_type *ptr,
399                                 lang_input_statement_type *file,
400                                 callback_t callback,
401                                 void *data)
402 {
403   asection *s;
404   struct wildcard_list *sec0 = ptr->handler_data[0];
405   struct wildcard_list *wildsec1 = ptr->handler_data[1];
406   struct wildcard_list *wildsec2 = ptr->handler_data[2];
407   bfd_boolean multiple_sections_found;
408   asection *s0 = find_section (file, sec0, &multiple_sections_found);
409
410   if (multiple_sections_found)
411     {
412       walk_wild_section_general (ptr, file, callback, data);
413       return;
414     }
415
416   for (s = file->the_bfd->sections; s != NULL; s = s->next)
417     {
418       if (s == s0)
419         walk_wild_consider_section (ptr, file, s, sec0, callback, data);
420       else
421         {
422           const char *sname = bfd_get_section_name (file->the_bfd, s);
423           bfd_boolean skip = !match_simple_wild (wildsec1->spec.name, sname);
424
425           if (!skip)
426             walk_wild_consider_section (ptr, file, s, wildsec1, callback, data);
427           else
428             {
429               skip = !match_simple_wild (wildsec2->spec.name, sname);
430               if (!skip)
431                 walk_wild_consider_section (ptr, file, s, wildsec2, callback,
432                                             data);
433             }
434         }
435     }
436 }
437
438 static void
439 walk_wild_section_specs4_wild2 (lang_wild_statement_type *ptr,
440                                 lang_input_statement_type *file,
441                                 callback_t callback,
442                                 void *data)
443 {
444   asection *s;
445   struct wildcard_list *sec0 = ptr->handler_data[0];
446   struct wildcard_list *sec1 = ptr->handler_data[1];
447   struct wildcard_list *wildsec2 = ptr->handler_data[2];
448   struct wildcard_list *wildsec3 = ptr->handler_data[3];
449   bfd_boolean multiple_sections_found;
450   asection *s0 = find_section (file, sec0, &multiple_sections_found), *s1;
451
452   if (multiple_sections_found)
453     {
454       walk_wild_section_general (ptr, file, callback, data);
455       return;
456     }
457
458   s1 = find_section (file, sec1, &multiple_sections_found);
459   if (multiple_sections_found)
460     {
461       walk_wild_section_general (ptr, file, callback, data);
462       return;
463     }
464
465   for (s = file->the_bfd->sections; s != NULL; s = s->next)
466     {
467       if (s == s0)
468         walk_wild_consider_section (ptr, file, s, sec0, callback, data);
469       else
470         if (s == s1)
471           walk_wild_consider_section (ptr, file, s, sec1, callback, data);
472         else
473           {
474             const char *sname = bfd_get_section_name (file->the_bfd, s);
475             bfd_boolean skip = !match_simple_wild (wildsec2->spec.name,
476                                                    sname);
477
478             if (!skip)
479               walk_wild_consider_section (ptr, file, s, wildsec2, callback,
480                                           data);
481             else
482               {
483                 skip = !match_simple_wild (wildsec3->spec.name, sname);
484                 if (!skip)
485                   walk_wild_consider_section (ptr, file, s, wildsec3,
486                                               callback, data);
487               }
488           }
489     }
490 }
491
492 static void
493 walk_wild_section (lang_wild_statement_type *ptr,
494                    lang_input_statement_type *file,
495                    callback_t callback,
496                    void *data)
497 {
498   if (file->just_syms_flag)
499     return;
500
501   (*ptr->walk_wild_section_handler) (ptr, file, callback, data);
502 }
503
504 /* Returns TRUE when name1 is a wildcard spec that might match
505    something name2 can match.  We're conservative: we return FALSE
506    only if the prefixes of name1 and name2 are different up to the
507    first wildcard character.  */
508
509 static bfd_boolean
510 wild_spec_can_overlap (const char *name1, const char *name2)
511 {
512   size_t prefix1_len = strcspn (name1, "?*[");
513   size_t prefix2_len = strcspn (name2, "?*[");
514   size_t min_prefix_len;
515
516   /* Note that if there is no wildcard character, then we treat the
517      terminating 0 as part of the prefix.  Thus ".text" won't match
518      ".text." or ".text.*", for example.  */
519   if (name1[prefix1_len] == '\0')
520     prefix1_len++;
521   if (name2[prefix2_len] == '\0')
522     prefix2_len++;
523
524   min_prefix_len = prefix1_len < prefix2_len ? prefix1_len : prefix2_len;
525
526   return memcmp (name1, name2, min_prefix_len) == 0;
527 }
528
529 /* Select specialized code to handle various kinds of wildcard
530    statements.  */
531
532 static void
533 analyze_walk_wild_section_handler (lang_wild_statement_type *ptr)
534 {
535   int sec_count = 0;
536   int wild_name_count = 0;
537   struct wildcard_list *sec;
538   int signature;
539   int data_counter;
540
541   ptr->walk_wild_section_handler = walk_wild_section_general;
542
543   /* Count how many wildcard_specs there are, and how many of those
544      actually use wildcards in the name.  Also, bail out if any of the
545      wildcard names are NULL. (Can this actually happen?
546      walk_wild_section used to test for it.)  And bail out if any
547      of the wildcards are more complex than a simple string
548      ending in a single '*'.  */
549   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
550     {
551       ++sec_count;
552       if (sec->spec.name == NULL)
553         return;
554       if (wildcardp (sec->spec.name))
555         {
556           ++wild_name_count;
557           if (!is_simple_wild (sec->spec.name))
558             return;
559         }
560     }
561
562   /* The zero-spec case would be easy to optimize but it doesn't
563      happen in practice.  Likewise, more than 4 specs doesn't
564      happen in practice.  */
565   if (sec_count == 0 || sec_count > 4)
566     return;
567
568   /* Check that no two specs can match the same section.  */
569   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
570     {
571       struct wildcard_list *sec2;
572       for (sec2 = sec->next; sec2 != NULL; sec2 = sec2->next)
573         {
574           if (wild_spec_can_overlap (sec->spec.name, sec2->spec.name))
575             return;
576         }
577     }
578
579   signature = (sec_count << 8) + wild_name_count;
580   switch (signature)
581     {
582     case 0x0100:
583       ptr->walk_wild_section_handler = walk_wild_section_specs1_wild0;
584       break;
585     case 0x0101:
586       ptr->walk_wild_section_handler = walk_wild_section_specs1_wild1;
587       break;
588     case 0x0201:
589       ptr->walk_wild_section_handler = walk_wild_section_specs2_wild1;
590       break;
591     case 0x0302:
592       ptr->walk_wild_section_handler = walk_wild_section_specs3_wild2;
593       break;
594     case 0x0402:
595       ptr->walk_wild_section_handler = walk_wild_section_specs4_wild2;
596       break;
597     default:
598       return;
599     }
600
601   /* Now fill the data array with pointers to the specs, first the
602      specs with non-wildcard names, then the specs with wildcard
603      names.  It's OK to process the specs in different order from the
604      given order, because we've already determined that no section
605      will match more than one spec.  */
606   data_counter = 0;
607   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
608     if (!wildcardp (sec->spec.name))
609       ptr->handler_data[data_counter++] = sec;
610   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
611     if (wildcardp (sec->spec.name))
612       ptr->handler_data[data_counter++] = sec;
613 }
614
615 /* Handle a wild statement for a single file F.  */
616
617 static void
618 walk_wild_file (lang_wild_statement_type *s,
619                 lang_input_statement_type *f,
620                 callback_t callback,
621                 void *data)
622 {
623   if (f->the_bfd == NULL
624       || ! bfd_check_format (f->the_bfd, bfd_archive))
625     walk_wild_section (s, f, callback, data);
626   else
627     {
628       bfd *member;
629
630       /* This is an archive file.  We must map each member of the
631          archive separately.  */
632       member = bfd_openr_next_archived_file (f->the_bfd, NULL);
633       while (member != NULL)
634         {
635           /* When lookup_name is called, it will call the add_symbols
636              entry point for the archive.  For each element of the
637              archive which is included, BFD will call ldlang_add_file,
638              which will set the usrdata field of the member to the
639              lang_input_statement.  */
640           if (member->usrdata != NULL)
641             {
642               walk_wild_section (s, member->usrdata, callback, data);
643             }
644
645           member = bfd_openr_next_archived_file (f->the_bfd, member);
646         }
647     }
648 }
649
650 static void
651 walk_wild (lang_wild_statement_type *s, callback_t callback, void *data)
652 {
653   const char *file_spec = s->filename;
654
655   if (file_spec == NULL)
656     {
657       /* Perform the iteration over all files in the list.  */
658       LANG_FOR_EACH_INPUT_STATEMENT (f)
659         {
660           walk_wild_file (s, f, callback, data);
661         }
662     }
663   else if (wildcardp (file_spec))
664     {
665       LANG_FOR_EACH_INPUT_STATEMENT (f)
666         {
667           if (fnmatch (file_spec, f->filename, FNM_FILE_NAME) == 0)
668             walk_wild_file (s, f, callback, data);
669         }
670     }
671   else
672     {
673       lang_input_statement_type *f;
674
675       /* Perform the iteration over a single file.  */
676       f = lookup_name (file_spec);
677       if (f)
678         walk_wild_file (s, f, callback, data);
679     }
680 }
681
682 /* lang_for_each_statement walks the parse tree and calls the provided
683    function for each node.  */
684
685 static void
686 lang_for_each_statement_worker (void (*func) (lang_statement_union_type *),
687                                 lang_statement_union_type *s)
688 {
689   for (; s != NULL; s = s->header.next)
690     {
691       func (s);
692
693       switch (s->header.type)
694         {
695         case lang_constructors_statement_enum:
696           lang_for_each_statement_worker (func, constructor_list.head);
697           break;
698         case lang_output_section_statement_enum:
699           lang_for_each_statement_worker
700             (func, s->output_section_statement.children.head);
701           break;
702         case lang_wild_statement_enum:
703           lang_for_each_statement_worker (func,
704                                           s->wild_statement.children.head);
705           break;
706         case lang_group_statement_enum:
707           lang_for_each_statement_worker (func,
708                                           s->group_statement.children.head);
709           break;
710         case lang_data_statement_enum:
711         case lang_reloc_statement_enum:
712         case lang_object_symbols_statement_enum:
713         case lang_output_statement_enum:
714         case lang_target_statement_enum:
715         case lang_input_section_enum:
716         case lang_input_statement_enum:
717         case lang_assignment_statement_enum:
718         case lang_padding_statement_enum:
719         case lang_address_statement_enum:
720         case lang_fill_statement_enum:
721           break;
722         default:
723           FAIL ();
724           break;
725         }
726     }
727 }
728
729 void
730 lang_for_each_statement (void (*func) (lang_statement_union_type *))
731 {
732   lang_for_each_statement_worker (func, statement_list.head);
733 }
734
735 /*----------------------------------------------------------------------*/
736
737 void
738 lang_list_init (lang_statement_list_type *list)
739 {
740   list->head = NULL;
741   list->tail = &list->head;
742 }
743
744 /* Build a new statement node for the parse tree.  */
745
746 static lang_statement_union_type *
747 new_statement (enum statement_enum type,
748                size_t size,
749                lang_statement_list_type *list)
750 {
751   lang_statement_union_type *new;
752
753   new = stat_alloc (size);
754   new->header.type = type;
755   new->header.next = NULL;
756   lang_statement_append (list, new, &new->header.next);
757   return new;
758 }
759
760 /* Build a new input file node for the language.  There are several
761    ways in which we treat an input file, eg, we only look at symbols,
762    or prefix it with a -l etc.
763
764    We can be supplied with requests for input files more than once;
765    they may, for example be split over several lines like foo.o(.text)
766    foo.o(.data) etc, so when asked for a file we check that we haven't
767    got it already so we don't duplicate the bfd.  */
768
769 static lang_input_statement_type *
770 new_afile (const char *name,
771            lang_input_file_enum_type file_type,
772            const char *target,
773            bfd_boolean add_to_list)
774 {
775   lang_input_statement_type *p;
776
777   if (add_to_list)
778     p = new_stat (lang_input_statement, stat_ptr);
779   else
780     {
781       p = stat_alloc (sizeof (lang_input_statement_type));
782       p->header.next = NULL;
783     }
784
785   lang_has_input_file = TRUE;
786   p->target = target;
787   p->sysrooted = FALSE;
788   switch (file_type)
789     {
790     case lang_input_file_is_symbols_only_enum:
791       p->filename = name;
792       p->is_archive = FALSE;
793       p->real = TRUE;
794       p->local_sym_name = name;
795       p->just_syms_flag = TRUE;
796       p->search_dirs_flag = FALSE;
797       break;
798     case lang_input_file_is_fake_enum:
799       p->filename = name;
800       p->is_archive = FALSE;
801       p->real = FALSE;
802       p->local_sym_name = name;
803       p->just_syms_flag = FALSE;
804       p->search_dirs_flag = FALSE;
805       break;
806     case lang_input_file_is_l_enum:
807       p->is_archive = TRUE;
808       p->filename = name;
809       p->real = TRUE;
810       p->local_sym_name = concat ("-l", name, NULL);
811       p->just_syms_flag = FALSE;
812       p->search_dirs_flag = TRUE;
813       break;
814     case lang_input_file_is_marker_enum:
815       p->filename = name;
816       p->is_archive = FALSE;
817       p->real = FALSE;
818       p->local_sym_name = name;
819       p->just_syms_flag = FALSE;
820       p->search_dirs_flag = TRUE;
821       break;
822     case lang_input_file_is_search_file_enum:
823       p->sysrooted = ldlang_sysrooted_script;
824       p->filename = name;
825       p->is_archive = FALSE;
826       p->real = TRUE;
827       p->local_sym_name = name;
828       p->just_syms_flag = FALSE;
829       p->search_dirs_flag = TRUE;
830       break;
831     case lang_input_file_is_file_enum:
832       p->filename = name;
833       p->is_archive = FALSE;
834       p->real = TRUE;
835       p->local_sym_name = name;
836       p->just_syms_flag = FALSE;
837       p->search_dirs_flag = FALSE;
838       break;
839     default:
840       FAIL ();
841     }
842   p->the_bfd = NULL;
843   p->asymbols = NULL;
844   p->next_real_file = NULL;
845   p->next = NULL;
846   p->symbol_count = 0;
847   p->dynamic = config.dynamic_link;
848   p->add_needed = add_needed;
849   p->as_needed = as_needed;
850   p->whole_archive = whole_archive;
851   p->loaded = FALSE;
852   lang_statement_append (&input_file_chain,
853                          (lang_statement_union_type *) p,
854                          &p->next_real_file);
855   return p;
856 }
857
858 lang_input_statement_type *
859 lang_add_input_file (const char *name,
860                      lang_input_file_enum_type file_type,
861                      const char *target)
862 {
863   lang_has_input_file = TRUE;
864   return new_afile (name, file_type, target, TRUE);
865 }
866
867 /* Build enough state so that the parser can build its tree.  */
868
869 void
870 lang_init (void)
871 {
872   obstack_begin (&stat_obstack, 1000);
873
874   stat_ptr = &statement_list;
875
876   lang_list_init (stat_ptr);
877
878   lang_list_init (&input_file_chain);
879   lang_list_init (&lang_output_section_statement);
880   lang_list_init (&file_chain);
881   first_file = lang_add_input_file (NULL, lang_input_file_is_marker_enum,
882                                     NULL);
883   abs_output_section =
884     lang_output_section_statement_lookup (BFD_ABS_SECTION_NAME);
885
886   abs_output_section->bfd_section = bfd_abs_section_ptr;
887
888   /* The value "3" is ad-hoc, somewhat related to the expected number of
889      DEFINED expressions in a linker script.  For most default linker
890      scripts, there are none.  Why a hash table then?  Well, it's somewhat
891      simpler to re-use working machinery than using a linked list in terms
892      of code-complexity here in ld, besides the initialization which just
893      looks like other code here.  */
894   if (!bfd_hash_table_init_n (&lang_definedness_table,
895                               lang_definedness_newfunc, 3))
896     einfo (_("%P%F: out of memory during initialization"));
897
898   /* Callers of exp_fold_tree need to increment this.  */
899   lang_statement_iteration = 0;
900 }
901
902 /*----------------------------------------------------------------------
903   A region is an area of memory declared with the
904   MEMORY {  name:org=exp, len=exp ... }
905   syntax.
906
907   We maintain a list of all the regions here.
908
909   If no regions are specified in the script, then the default is used
910   which is created when looked up to be the entire data space.
911
912   If create is true we are creating a region inside a MEMORY block.
913   In this case it is probably an error to create a region that has
914   already been created.  If we are not inside a MEMORY block it is
915   dubious to use an undeclared region name (except DEFAULT_MEMORY_REGION)
916   and so we issue a warning.  */
917
918 static lang_memory_region_type *lang_memory_region_list;
919 static lang_memory_region_type **lang_memory_region_list_tail
920   = &lang_memory_region_list;
921
922 lang_memory_region_type *
923 lang_memory_region_lookup (const char *const name, bfd_boolean create)
924 {
925   lang_memory_region_type *p;
926   lang_memory_region_type *new;
927
928   /* NAME is NULL for LMA memspecs if no region was specified.  */
929   if (name == NULL)
930     return NULL;
931
932   for (p = lang_memory_region_list; p != NULL; p = p->next)
933     if (strcmp (p->name, name) == 0)
934       {
935         if (create)
936           einfo (_("%P:%S: warning: redeclaration of memory region '%s'\n"),
937                  name);
938         return p;
939       }
940
941   if (!create && strcmp (name, DEFAULT_MEMORY_REGION))
942     einfo (_("%P:%S: warning: memory region %s not declared\n"), name);
943
944   new = stat_alloc (sizeof (lang_memory_region_type));
945
946   new->name = xstrdup (name);
947   new->next = NULL;
948
949   *lang_memory_region_list_tail = new;
950   lang_memory_region_list_tail = &new->next;
951   new->origin = 0;
952   new->flags = 0;
953   new->not_flags = 0;
954   new->length = ~(bfd_size_type) 0;
955   new->current = 0;
956   new->had_full_message = FALSE;
957
958   return new;
959 }
960
961 static lang_memory_region_type *
962 lang_memory_default (asection *section)
963 {
964   lang_memory_region_type *p;
965
966   flagword sec_flags = section->flags;
967
968   /* Override SEC_DATA to mean a writable section.  */
969   if ((sec_flags & (SEC_ALLOC | SEC_READONLY | SEC_CODE)) == SEC_ALLOC)
970     sec_flags |= SEC_DATA;
971
972   for (p = lang_memory_region_list; p != NULL; p = p->next)
973     {
974       if ((p->flags & sec_flags) != 0
975           && (p->not_flags & sec_flags) == 0)
976         {
977           return p;
978         }
979     }
980   return lang_memory_region_lookup (DEFAULT_MEMORY_REGION, FALSE);
981 }
982
983 static lang_output_section_statement_type *
984 lang_output_section_find_1 (const char *const name, int constraint)
985 {
986   lang_output_section_statement_type *lookup;
987
988   for (lookup = &lang_output_section_statement.head->output_section_statement;
989        lookup != NULL;
990        lookup = lookup->next)
991     {
992       if (strcmp (name, lookup->name) == 0
993           && lookup->constraint != -1
994           && (constraint == 0
995               || (constraint == lookup->constraint
996                   && constraint != SPECIAL)))
997         return lookup;
998     }
999   return NULL;
1000 }
1001
1002 lang_output_section_statement_type *
1003 lang_output_section_find (const char *const name)
1004 {
1005   return lang_output_section_find_1 (name, 0);
1006 }
1007
1008 static lang_output_section_statement_type *
1009 lang_output_section_statement_lookup_1 (const char *const name, int constraint)
1010 {
1011   lang_output_section_statement_type *lookup;
1012
1013   lookup = lang_output_section_find_1 (name, constraint);
1014   if (lookup == NULL)
1015     {
1016       lookup = new_stat (lang_output_section_statement, stat_ptr);
1017       lookup->region = NULL;
1018       lookup->lma_region = NULL;
1019       lookup->fill = 0;
1020       lookup->block_value = 1;
1021       lookup->name = name;
1022
1023       lookup->next = NULL;
1024       lookup->bfd_section = NULL;
1025       lookup->processed = 0;
1026       lookup->constraint = constraint;
1027       lookup->sectype = normal_section;
1028       lookup->addr_tree = NULL;
1029       lang_list_init (&lookup->children);
1030
1031       lookup->memspec = NULL;
1032       lookup->flags = 0;
1033       lookup->subsection_alignment = -1;
1034       lookup->section_alignment = -1;
1035       lookup->load_base = NULL;
1036       lookup->update_dot_tree = NULL;
1037       lookup->phdrs = NULL;
1038
1039       lang_statement_append (&lang_output_section_statement,
1040                              (lang_statement_union_type *) lookup,
1041                              (lang_statement_union_type **) &lookup->next);
1042     }
1043   return lookup;
1044 }
1045
1046 lang_output_section_statement_type *
1047 lang_output_section_statement_lookup (const char *const name)
1048 {
1049   return lang_output_section_statement_lookup_1 (name, 0);
1050 }
1051
1052 /* A variant of lang_output_section_find used by place_orphan.
1053    Returns the output statement that should precede a new output
1054    statement for SEC.  If an exact match is found on certain flags,
1055    sets *EXACT too.  */
1056
1057 lang_output_section_statement_type *
1058 lang_output_section_find_by_flags (const asection *sec,
1059                                    lang_output_section_statement_type **exact)
1060 {
1061   lang_output_section_statement_type *first, *look, *found;
1062   flagword flags;
1063
1064   /* We know the first statement on this list is *ABS*.  May as well
1065      skip it.  */
1066   first = &lang_output_section_statement.head->output_section_statement;
1067   first = first->next;
1068
1069   /* First try for an exact match.  */
1070   found = NULL;
1071   for (look = first; look; look = look->next)
1072     {
1073       flags = look->flags;
1074       if (look->bfd_section != NULL)
1075         flags = look->bfd_section->flags;
1076       flags ^= sec->flags;
1077       if (!(flags & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY
1078                      | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1079         found = look;
1080     }
1081   if (found != NULL)
1082     {
1083       *exact = found;
1084       return found;
1085     }
1086
1087   if (sec->flags & SEC_CODE)
1088     {
1089       /* Try for a rw code section.  */
1090       for (look = first; look; look = look->next)
1091         {
1092           flags = look->flags;
1093           if (look->bfd_section != NULL)
1094             flags = look->bfd_section->flags;
1095           flags ^= sec->flags;
1096           if (!(flags & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1097                          | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1098             found = look;
1099         }
1100       return found;
1101     }
1102
1103   if (sec->flags & (SEC_READONLY | SEC_THREAD_LOCAL))
1104     {
1105       /* .rodata can go after .text, .sdata2 after .rodata.  */
1106       for (look = first; look; look = look->next)
1107         {
1108           flags = look->flags;
1109           if (look->bfd_section != NULL)
1110             flags = look->bfd_section->flags;
1111           flags ^= sec->flags;
1112           if (!(flags & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1113                          | SEC_READONLY))
1114               && !(look->flags & (SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1115             found = look;
1116         }
1117       return found;
1118     }
1119
1120   if (sec->flags & SEC_SMALL_DATA)
1121     {
1122       /* .sdata goes after .data, .sbss after .sdata.  */
1123       for (look = first; look; look = look->next)
1124         {
1125           flags = look->flags;
1126           if (look->bfd_section != NULL)
1127             flags = look->bfd_section->flags;
1128           flags ^= sec->flags;
1129           if (!(flags & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1130                          | SEC_THREAD_LOCAL))
1131               || ((look->flags & SEC_SMALL_DATA)
1132                   && !(sec->flags & SEC_HAS_CONTENTS)))
1133             found = look;
1134         }
1135       return found;
1136     }
1137
1138   if (sec->flags & SEC_HAS_CONTENTS)
1139     {
1140       /* .data goes after .rodata.  */
1141       for (look = first; look; look = look->next)
1142         {
1143           flags = look->flags;
1144           if (look->bfd_section != NULL)
1145             flags = look->bfd_section->flags;
1146           flags ^= sec->flags;
1147           if (!(flags & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1148                          | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1149             found = look;
1150         }
1151       return found;
1152     }
1153
1154   /* .bss goes last.  */
1155   for (look = first; look; look = look->next)
1156     {
1157       flags = look->flags;
1158       if (look->bfd_section != NULL)
1159         flags = look->bfd_section->flags;
1160       flags ^= sec->flags;
1161       if (!(flags & SEC_ALLOC))
1162         found = look;
1163     }
1164
1165   return found;
1166 }
1167
1168 /* Find the last output section before given output statement.
1169    Used by place_orphan.  */
1170
1171 static asection *
1172 output_prev_sec_find (lang_output_section_statement_type *os)
1173 {
1174   asection *s = (asection *) NULL;
1175   lang_output_section_statement_type *lookup;
1176
1177   for (lookup = &lang_output_section_statement.head->output_section_statement;
1178        lookup != NULL;
1179        lookup = lookup->next)
1180     {
1181       if (lookup->constraint == -1)
1182         continue;
1183       if (lookup == os)
1184         return s;
1185
1186       if (lookup->bfd_section != NULL && lookup->bfd_section->owner != NULL)
1187         s = lookup->bfd_section;
1188     }
1189
1190   return NULL;
1191 }
1192
1193 lang_output_section_statement_type *
1194 lang_insert_orphan (lang_input_statement_type *file,
1195                     asection *s,
1196                     const char *secname,
1197                     lang_output_section_statement_type *after,
1198                     struct orphan_save *place,
1199                     etree_type *address,
1200                     lang_statement_list_type *add_child)
1201 {
1202   lang_statement_list_type *old;
1203   lang_statement_list_type add;
1204   const char *ps;
1205   etree_type *load_base;
1206   lang_output_section_statement_type *os;
1207   lang_output_section_statement_type **os_tail;
1208
1209   /* Start building a list of statements for this section.
1210      First save the current statement pointer.  */
1211   old = stat_ptr;
1212
1213   /* If we have found an appropriate place for the output section
1214      statements for this orphan, add them to our own private list,
1215      inserting them later into the global statement list.  */
1216   if (after != NULL)
1217     {
1218       stat_ptr = &add;
1219       lang_list_init (stat_ptr);
1220     }
1221
1222   ps = NULL;
1223   if (config.build_constructors)
1224     {
1225       /* If the name of the section is representable in C, then create
1226          symbols to mark the start and the end of the section.  */
1227       for (ps = secname; *ps != '\0'; ps++)
1228         if (! ISALNUM ((unsigned char) *ps) && *ps != '_')
1229           break;
1230       if (*ps == '\0')
1231         {
1232           char *symname;
1233           etree_type *e_align;
1234
1235           symname = (char *) xmalloc (ps - secname + sizeof "__start_" + 1);
1236           symname[0] = bfd_get_symbol_leading_char (output_bfd);
1237           sprintf (symname + (symname[0] != 0), "__start_%s", secname);
1238           e_align = exp_unop (ALIGN_K,
1239                               exp_intop ((bfd_vma) 1 << s->alignment_power));
1240           lang_add_assignment (exp_assop ('=', ".", e_align));
1241           lang_add_assignment (exp_assop ('=', symname,
1242                                           exp_nameop (NAME, ".")));
1243         }
1244     }
1245
1246   if (link_info.relocatable || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0)
1247     address = exp_intop (0);
1248
1249   load_base = NULL;
1250   if (after != NULL && after->load_base != NULL)
1251     {
1252       etree_type *lma_from_vma;
1253       lma_from_vma = exp_binop ('-', after->load_base,
1254                                 exp_nameop (ADDR, after->name));
1255       load_base = exp_binop ('+', lma_from_vma,
1256                              exp_nameop (ADDR, secname));
1257     }
1258
1259   os_tail = ((lang_output_section_statement_type **)
1260              lang_output_section_statement.tail);
1261   os = lang_enter_output_section_statement (secname, address, 0, NULL, NULL,
1262                                             load_base, 0);
1263
1264   if (add_child == NULL)
1265     add_child = &os->children;
1266   lang_add_section (add_child, s, os, file);
1267
1268   lang_leave_output_section_statement (0, "*default*", NULL, NULL);
1269
1270   if (config.build_constructors && *ps == '\0')
1271     {
1272       char *symname;
1273
1274       /* lang_leave_ouput_section_statement resets stat_ptr.
1275          Put stat_ptr back where we want it.  */
1276       if (after != NULL)
1277         stat_ptr = &add;
1278
1279       symname = (char *) xmalloc (ps - secname + sizeof "__stop_" + 1);
1280       symname[0] = bfd_get_symbol_leading_char (output_bfd);
1281       sprintf (symname + (symname[0] != 0), "__stop_%s", secname);
1282       lang_add_assignment (exp_assop ('=', symname,
1283                                       exp_nameop (NAME, ".")));
1284     }
1285
1286   /* Restore the global list pointer.  */
1287   if (after != NULL)
1288     stat_ptr = old;
1289
1290   if (after != NULL && os->bfd_section != NULL)
1291     {
1292       asection *snew, *as;
1293
1294       snew = os->bfd_section;
1295
1296       /* Shuffle the bfd section list to make the output file look
1297          neater.  This is really only cosmetic.  */
1298       if (place->section == NULL
1299           && after != (&lang_output_section_statement.head
1300                        ->output_section_statement))
1301         {
1302           asection *bfd_section = after->bfd_section;
1303
1304           /* If the output statement hasn't been used to place any input
1305              sections (and thus doesn't have an output bfd_section),
1306              look for the closest prior output statement having an
1307              output section.  */
1308           if (bfd_section == NULL)
1309             bfd_section = output_prev_sec_find (after);
1310
1311           if (bfd_section != NULL && bfd_section != snew)
1312             place->section = &bfd_section->next;
1313         }
1314
1315       if (place->section == NULL)
1316         place->section = &output_bfd->sections;
1317
1318       as = *place->section;
1319       if (as != snew && as->prev != snew)
1320         {
1321           /* Unlink the section.  */
1322           bfd_section_list_remove (output_bfd, snew);
1323
1324           /* Now tack it back on in the right place.  */
1325           bfd_section_list_insert_before (output_bfd, as, snew);
1326         }
1327
1328       /* Save the end of this list.  Further ophans of this type will
1329          follow the one we've just added.  */
1330       place->section = &snew->next;
1331
1332       /* The following is non-cosmetic.  We try to put the output
1333          statements in some sort of reasonable order here, because they
1334          determine the final load addresses of the orphan sections.
1335          In addition, placing output statements in the wrong order may
1336          require extra segments.  For instance, given a typical
1337          situation of all read-only sections placed in one segment and
1338          following that a segment containing all the read-write
1339          sections, we wouldn't want to place an orphan read/write
1340          section before or amongst the read-only ones.  */
1341       if (add.head != NULL)
1342         {
1343           lang_output_section_statement_type *newly_added_os;
1344
1345           if (place->stmt == NULL)
1346             {
1347               lang_statement_union_type **where;
1348               lang_statement_union_type **assign = NULL;
1349
1350               /* Look for a suitable place for the new statement list.
1351                  The idea is to skip over anything that might be inside
1352                  a SECTIONS {} statement in a script, before we find
1353                  another output_section_statement.  Assignments to "dot"
1354                  before an output section statement are assumed to
1355                  belong to it.  */
1356               for (where = &after->header.next;
1357                    *where != NULL;
1358                    where = &(*where)->header.next)
1359                 {
1360                   switch ((*where)->header.type)
1361                     {
1362                     case lang_assignment_statement_enum:
1363                       if (assign == NULL)
1364                         {
1365                           lang_assignment_statement_type *ass;
1366                           ass = &(*where)->assignment_statement;
1367                           if (ass->exp->type.node_class != etree_assert
1368                               && ass->exp->assign.dst[0] == '.'
1369                               && ass->exp->assign.dst[1] == 0)
1370                             assign = where;
1371                         }
1372                       continue;
1373                     case lang_wild_statement_enum:
1374                     case lang_input_section_enum:
1375                     case lang_object_symbols_statement_enum:
1376                     case lang_fill_statement_enum:
1377                     case lang_data_statement_enum:
1378                     case lang_reloc_statement_enum:
1379                     case lang_padding_statement_enum:
1380                     case lang_constructors_statement_enum:
1381                       assign = NULL;
1382                       continue;
1383                     case lang_output_section_statement_enum:
1384                       if (assign != NULL)
1385                         where = assign;
1386                     case lang_input_statement_enum:
1387                     case lang_address_statement_enum:
1388                     case lang_target_statement_enum:
1389                     case lang_output_statement_enum:
1390                     case lang_group_statement_enum:
1391                     case lang_afile_asection_pair_statement_enum:
1392                       break;
1393                     }
1394                   break;
1395                 }
1396
1397               *add.tail = *where;
1398               *where = add.head;
1399
1400               place->os_tail = &after->next;
1401             }
1402           else
1403             {
1404               /* Put it after the last orphan statement we added.  */
1405               *add.tail = *place->stmt;
1406               *place->stmt = add.head;
1407             }
1408
1409           /* Fix the global list pointer if we happened to tack our
1410              new list at the tail.  */
1411           if (*old->tail == add.head)
1412             old->tail = add.tail;
1413
1414           /* Save the end of this list.  */
1415           place->stmt = add.tail;
1416
1417           /* Do the same for the list of output section statements.  */
1418           newly_added_os = *os_tail;
1419           *os_tail = NULL;
1420           newly_added_os->next = *place->os_tail;
1421           *place->os_tail = newly_added_os;
1422           place->os_tail = &newly_added_os->next;
1423
1424           /* Fixing the global list pointer here is a little different.
1425              We added to the list in lang_enter_output_section_statement,
1426              trimmed off the new output_section_statment above when
1427              assigning *os_tail = NULL, but possibly added it back in
1428              the same place when assigning *place->os_tail.  */
1429           if (*os_tail == NULL)
1430             lang_output_section_statement.tail
1431               = (lang_statement_union_type **) os_tail;
1432         }
1433     }
1434   return os;
1435 }
1436
1437 static void
1438 lang_map_flags (flagword flag)
1439 {
1440   if (flag & SEC_ALLOC)
1441     minfo ("a");
1442
1443   if (flag & SEC_CODE)
1444     minfo ("x");
1445
1446   if (flag & SEC_READONLY)
1447     minfo ("r");
1448
1449   if (flag & SEC_DATA)
1450     minfo ("w");
1451
1452   if (flag & SEC_LOAD)
1453     minfo ("l");
1454 }
1455
1456 void
1457 lang_map (void)
1458 {
1459   lang_memory_region_type *m;
1460   bfd *p;
1461
1462   minfo (_("\nMemory Configuration\n\n"));
1463   fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
1464            _("Name"), _("Origin"), _("Length"), _("Attributes"));
1465
1466   for (m = lang_memory_region_list; m != NULL; m = m->next)
1467     {
1468       char buf[100];
1469       int len;
1470
1471       fprintf (config.map_file, "%-16s ", m->name);
1472
1473       sprintf_vma (buf, m->origin);
1474       minfo ("0x%s ", buf);
1475       len = strlen (buf);
1476       while (len < 16)
1477         {
1478           print_space ();
1479           ++len;
1480         }
1481
1482       minfo ("0x%V", m->length);
1483       if (m->flags || m->not_flags)
1484         {
1485 #ifndef BFD64
1486           minfo ("        ");
1487 #endif
1488           if (m->flags)
1489             {
1490               print_space ();
1491               lang_map_flags (m->flags);
1492             }
1493
1494           if (m->not_flags)
1495             {
1496               minfo (" !");
1497               lang_map_flags (m->not_flags);
1498             }
1499         }
1500
1501       print_nl ();
1502     }
1503
1504   fprintf (config.map_file, _("\nLinker script and memory map\n\n"));
1505
1506   if (! command_line.reduce_memory_overheads)
1507     {
1508       obstack_begin (&map_obstack, 1000);
1509       for (p = link_info.input_bfds; p != (bfd *) NULL; p = p->link_next)
1510         bfd_map_over_sections (p, init_map_userdata, 0);
1511       bfd_link_hash_traverse (link_info.hash, sort_def_symbol, 0);
1512     }
1513   print_statements ();
1514 }
1515
1516 static void
1517 init_map_userdata (abfd, sec, data)
1518      bfd *abfd ATTRIBUTE_UNUSED;
1519      asection *sec;
1520      void *data ATTRIBUTE_UNUSED;
1521 {
1522   fat_section_userdata_type *new_data
1523     = ((fat_section_userdata_type *) (stat_alloc
1524                                       (sizeof (fat_section_userdata_type))));
1525
1526   ASSERT (get_userdata (sec) == NULL);
1527   get_userdata (sec) = new_data;
1528   new_data->map_symbol_def_tail = &new_data->map_symbol_def_head;
1529 }
1530
1531 static bfd_boolean
1532 sort_def_symbol (hash_entry, info)
1533      struct bfd_link_hash_entry *hash_entry;
1534      void *info ATTRIBUTE_UNUSED;
1535 {
1536   if (hash_entry->type == bfd_link_hash_defined
1537       || hash_entry->type == bfd_link_hash_defweak)
1538     {
1539       struct fat_user_section_struct *ud;
1540       struct map_symbol_def *def;
1541
1542       ud = get_userdata (hash_entry->u.def.section);
1543       if  (! ud)
1544         {
1545           /* ??? What do we have to do to initialize this beforehand?  */
1546           /* The first time we get here is bfd_abs_section...  */
1547           init_map_userdata (0, hash_entry->u.def.section, 0);
1548           ud = get_userdata (hash_entry->u.def.section);
1549         }
1550       else if  (!ud->map_symbol_def_tail)
1551         ud->map_symbol_def_tail = &ud->map_symbol_def_head;
1552
1553       def = obstack_alloc (&map_obstack, sizeof *def);
1554       def->entry = hash_entry;
1555       *(ud->map_symbol_def_tail) = def;
1556       ud->map_symbol_def_tail = &def->next;
1557     }
1558   return TRUE;
1559 }
1560
1561 /* Initialize an output section.  */
1562
1563 static void
1564 init_os (lang_output_section_statement_type *s)
1565 {
1566   if (s->bfd_section != NULL)
1567     return;
1568
1569   if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
1570     einfo (_("%P%F: Illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
1571
1572   s->bfd_section = bfd_get_section_by_name (output_bfd, s->name);
1573   if (s->bfd_section == NULL)
1574     s->bfd_section = bfd_make_section (output_bfd, s->name);
1575   if (s->bfd_section == NULL)
1576     {
1577       einfo (_("%P%F: output format %s cannot represent section called %s\n"),
1578              output_bfd->xvec->name, s->name);
1579     }
1580   s->bfd_section->output_section = s->bfd_section;
1581
1582   /* We initialize an output sections output offset to minus its own
1583      vma to allow us to output a section through itself.  */
1584   s->bfd_section->output_offset = 0;
1585   if (!command_line.reduce_memory_overheads)
1586     {
1587       fat_section_userdata_type *new
1588         = stat_alloc (sizeof (fat_section_userdata_type));
1589       memset (new, 0, sizeof (fat_section_userdata_type));
1590       get_userdata (s->bfd_section) = new;
1591     }
1592
1593
1594   /* If there is a base address, make sure that any sections it might
1595      mention are initialized.  */
1596   if (s->addr_tree != NULL)
1597     exp_init_os (s->addr_tree);
1598
1599   if (s->load_base != NULL)
1600     exp_init_os (s->load_base);
1601 }
1602
1603 /* Make sure that all output sections mentioned in an expression are
1604    initialized.  */
1605
1606 static void
1607 exp_init_os (etree_type *exp)
1608 {
1609   switch (exp->type.node_class)
1610     {
1611     case etree_assign:
1612       exp_init_os (exp->assign.src);
1613       break;
1614
1615     case etree_binary:
1616       exp_init_os (exp->binary.lhs);
1617       exp_init_os (exp->binary.rhs);
1618       break;
1619
1620     case etree_trinary:
1621       exp_init_os (exp->trinary.cond);
1622       exp_init_os (exp->trinary.lhs);
1623       exp_init_os (exp->trinary.rhs);
1624       break;
1625
1626     case etree_assert:
1627       exp_init_os (exp->assert_s.child);
1628       break;
1629
1630     case etree_unary:
1631       exp_init_os (exp->unary.child);
1632       break;
1633
1634     case etree_name:
1635       switch (exp->type.node_code)
1636         {
1637         case ADDR:
1638         case LOADADDR:
1639         case SIZEOF:
1640           {
1641             lang_output_section_statement_type *os;
1642
1643             os = lang_output_section_find (exp->name.name);
1644             if (os != NULL && os->bfd_section == NULL)
1645               init_os (os);
1646           }
1647         }
1648       break;
1649
1650     default:
1651       break;
1652     }
1653 }
1654 \f
1655 static void
1656 section_already_linked (bfd *abfd, asection *sec, void *data)
1657 {
1658   lang_input_statement_type *entry = data;
1659
1660   /* If we are only reading symbols from this object, then we want to
1661      discard all sections.  */
1662   if (entry->just_syms_flag)
1663     {
1664       bfd_link_just_syms (abfd, sec, &link_info);
1665       return;
1666     }
1667
1668   if (!(abfd->flags & DYNAMIC))
1669     bfd_section_already_linked (abfd, sec);
1670 }
1671 \f
1672 /* The wild routines.
1673
1674    These expand statements like *(.text) and foo.o to a list of
1675    explicit actions, like foo.o(.text), bar.o(.text) and
1676    foo.o(.text, .data).  */
1677
1678 /* Add SECTION to the output section OUTPUT.  Do this by creating a
1679    lang_input_section statement which is placed at PTR.  FILE is the
1680    input file which holds SECTION.  */
1681
1682 void
1683 lang_add_section (lang_statement_list_type *ptr,
1684                   asection *section,
1685                   lang_output_section_statement_type *output,
1686                   lang_input_statement_type *file)
1687 {
1688   flagword flags = section->flags;
1689   bfd_boolean discard;
1690
1691   /* Discard sections marked with SEC_EXCLUDE.  */
1692   discard = (flags & SEC_EXCLUDE) != 0;
1693
1694   /* Discard input sections which are assigned to a section named
1695      DISCARD_SECTION_NAME.  */
1696   if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
1697     discard = TRUE;
1698
1699   /* Discard debugging sections if we are stripping debugging
1700      information.  */
1701   if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
1702       && (flags & SEC_DEBUGGING) != 0)
1703     discard = TRUE;
1704
1705   if (discard)
1706     {
1707       if (section->output_section == NULL)
1708         {
1709           /* This prevents future calls from assigning this section.  */
1710           section->output_section = bfd_abs_section_ptr;
1711         }
1712       return;
1713     }
1714
1715   if (section->output_section == NULL)
1716     {
1717       bfd_boolean first;
1718       lang_input_section_type *new;
1719       flagword flags;
1720
1721       if (output->bfd_section == NULL)
1722         init_os (output);
1723
1724       first = ! output->bfd_section->linker_has_input;
1725       output->bfd_section->linker_has_input = 1;
1726
1727       if (!link_info.relocatable
1728           && !stripped_excluded_sections)
1729         {
1730           asection *s = output->bfd_section->map_tail.s;
1731           output->bfd_section->map_tail.s = section;
1732           section->map_head.s = NULL;
1733           section->map_tail.s = s;
1734           if (s != NULL)
1735             s->map_head.s = section;
1736           else
1737             output->bfd_section->map_head.s = section;
1738         }
1739
1740       /* Add a section reference to the list.  */
1741       new = new_stat (lang_input_section, ptr);
1742
1743       new->section = section;
1744       new->ifile = file;
1745       section->output_section = output->bfd_section;
1746
1747       flags = section->flags;
1748
1749       /* We don't copy the SEC_NEVER_LOAD flag from an input section
1750          to an output section, because we want to be able to include a
1751          SEC_NEVER_LOAD section in the middle of an otherwise loaded
1752          section (I don't know why we want to do this, but we do).
1753          build_link_order in ldwrite.c handles this case by turning
1754          the embedded SEC_NEVER_LOAD section into a fill.  */
1755
1756       flags &= ~ SEC_NEVER_LOAD;
1757
1758       /* If final link, don't copy the SEC_LINK_ONCE flags, they've
1759          already been processed.  One reason to do this is that on pe
1760          format targets, .text$foo sections go into .text and it's odd
1761          to see .text with SEC_LINK_ONCE set.  */
1762
1763       if (! link_info.relocatable)
1764         flags &= ~ (SEC_LINK_ONCE | SEC_LINK_DUPLICATES);
1765
1766       /* If this is not the first input section, and the SEC_READONLY
1767          flag is not currently set, then don't set it just because the
1768          input section has it set.  */
1769
1770       if (! first && (output->bfd_section->flags & SEC_READONLY) == 0)
1771         flags &= ~ SEC_READONLY;
1772
1773       /* Keep SEC_MERGE and SEC_STRINGS only if they are the same.  */
1774       if (! first
1775           && ((output->bfd_section->flags & (SEC_MERGE | SEC_STRINGS))
1776               != (flags & (SEC_MERGE | SEC_STRINGS))
1777               || ((flags & SEC_MERGE)
1778                   && output->bfd_section->entsize != section->entsize)))
1779         {
1780           output->bfd_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
1781           flags &= ~ (SEC_MERGE | SEC_STRINGS);
1782         }
1783
1784       output->bfd_section->flags |= flags;
1785
1786       if (flags & SEC_MERGE)
1787         output->bfd_section->entsize = section->entsize;
1788
1789       /* If SEC_READONLY is not set in the input section, then clear
1790          it from the output section.  */
1791       if ((section->flags & SEC_READONLY) == 0)
1792         output->bfd_section->flags &= ~SEC_READONLY;
1793
1794       switch (output->sectype)
1795         {
1796         case normal_section:
1797           break;
1798         case dsect_section:
1799         case copy_section:
1800         case info_section:
1801         case overlay_section:
1802           output->bfd_section->flags &= ~SEC_ALLOC;
1803           break;
1804         case noload_section:
1805           output->bfd_section->flags &= ~SEC_LOAD;
1806           output->bfd_section->flags |= SEC_NEVER_LOAD;
1807           break;
1808         }
1809
1810       /* Copy over SEC_SMALL_DATA.  */
1811       if (section->flags & SEC_SMALL_DATA)
1812         output->bfd_section->flags |= SEC_SMALL_DATA;
1813
1814       if (section->alignment_power > output->bfd_section->alignment_power)
1815         output->bfd_section->alignment_power = section->alignment_power;
1816
1817       /* If supplied an alignment, then force it.  */
1818       if (output->section_alignment != -1)
1819         output->bfd_section->alignment_power = output->section_alignment;
1820
1821       if (bfd_get_arch (section->owner) == bfd_arch_tic54x
1822           && (section->flags & SEC_TIC54X_BLOCK) != 0)
1823         {
1824           output->bfd_section->flags |= SEC_TIC54X_BLOCK;
1825           /* FIXME: This value should really be obtained from the bfd...  */
1826           output->block_value = 128;
1827         }
1828     }
1829 }
1830
1831 /* Compare sections ASEC and BSEC according to SORT.  */
1832
1833 static int
1834 compare_section (sort_type sort, asection *asec, asection *bsec)
1835 {
1836   int ret;
1837
1838   switch (sort)
1839     {
1840     default:
1841       abort ();
1842
1843     case by_alignment_name:
1844       ret = (bfd_section_alignment (bsec->owner, bsec)
1845              - bfd_section_alignment (asec->owner, asec));
1846       if (ret)
1847         break;
1848       /* Fall through.  */
1849
1850     case by_name:
1851       ret = strcmp (bfd_get_section_name (asec->owner, asec),
1852                     bfd_get_section_name (bsec->owner, bsec));
1853       break;
1854
1855     case by_name_alignment:
1856       ret = strcmp (bfd_get_section_name (asec->owner, asec),
1857                     bfd_get_section_name (bsec->owner, bsec));
1858       if (ret)
1859         break;
1860       /* Fall through.  */
1861
1862     case by_alignment:
1863       ret = (bfd_section_alignment (bsec->owner, bsec)
1864              - bfd_section_alignment (asec->owner, asec));
1865       break;
1866     }
1867
1868   return ret;
1869 }
1870
1871 /* Handle wildcard sorting.  This returns the lang_input_section which
1872    should follow the one we are going to create for SECTION and FILE,
1873    based on the sorting requirements of WILD.  It returns NULL if the
1874    new section should just go at the end of the current list.  */
1875
1876 static lang_statement_union_type *
1877 wild_sort (lang_wild_statement_type *wild,
1878            struct wildcard_list *sec,
1879            lang_input_statement_type *file,
1880            asection *section)
1881 {
1882   const char *section_name;
1883   lang_statement_union_type *l;
1884
1885   if (!wild->filenames_sorted
1886       && (sec == NULL || sec->spec.sorted == none))
1887     return NULL;
1888
1889   section_name = bfd_get_section_name (file->the_bfd, section);
1890   for (l = wild->children.head; l != NULL; l = l->header.next)
1891     {
1892       lang_input_section_type *ls;
1893
1894       if (l->header.type != lang_input_section_enum)
1895         continue;
1896       ls = &l->input_section;
1897
1898       /* Sorting by filename takes precedence over sorting by section
1899          name.  */
1900
1901       if (wild->filenames_sorted)
1902         {
1903           const char *fn, *ln;
1904           bfd_boolean fa, la;
1905           int i;
1906
1907           /* The PE support for the .idata section as generated by
1908              dlltool assumes that files will be sorted by the name of
1909              the archive and then the name of the file within the
1910              archive.  */
1911
1912           if (file->the_bfd != NULL
1913               && bfd_my_archive (file->the_bfd) != NULL)
1914             {
1915               fn = bfd_get_filename (bfd_my_archive (file->the_bfd));
1916               fa = TRUE;
1917             }
1918           else
1919             {
1920               fn = file->filename;
1921               fa = FALSE;
1922             }
1923
1924           if (ls->ifile->the_bfd != NULL
1925               && bfd_my_archive (ls->ifile->the_bfd) != NULL)
1926             {
1927               ln = bfd_get_filename (bfd_my_archive (ls->ifile->the_bfd));
1928               la = TRUE;
1929             }
1930           else
1931             {
1932               ln = ls->ifile->filename;
1933               la = FALSE;
1934             }
1935
1936           i = strcmp (fn, ln);
1937           if (i > 0)
1938             continue;
1939           else if (i < 0)
1940             break;
1941
1942           if (fa || la)
1943             {
1944               if (fa)
1945                 fn = file->filename;
1946               if (la)
1947                 ln = ls->ifile->filename;
1948
1949               i = strcmp (fn, ln);
1950               if (i > 0)
1951                 continue;
1952               else if (i < 0)
1953                 break;
1954             }
1955         }
1956
1957       /* Here either the files are not sorted by name, or we are
1958          looking at the sections for this file.  */
1959
1960       if (sec != NULL && sec->spec.sorted != none)
1961         {
1962           if (compare_section (sec->spec.sorted, section,
1963                                ls->section) < 0)
1964             break;
1965         }
1966     }
1967
1968   return l;
1969 }
1970
1971 /* Expand a wild statement for a particular FILE.  SECTION may be
1972    NULL, in which case it is a wild card.  */
1973
1974 static void
1975 output_section_callback (lang_wild_statement_type *ptr,
1976                          struct wildcard_list *sec,
1977                          asection *section,
1978                          lang_input_statement_type *file,
1979                          void *output)
1980 {
1981   lang_statement_union_type *before;
1982
1983   /* Exclude sections that match UNIQUE_SECTION_LIST.  */
1984   if (unique_section_p (section))
1985     return;
1986
1987   before = wild_sort (ptr, sec, file, section);
1988
1989   /* Here BEFORE points to the lang_input_section which
1990      should follow the one we are about to add.  If BEFORE
1991      is NULL, then the section should just go at the end
1992      of the current list.  */
1993
1994   if (before == NULL)
1995     lang_add_section (&ptr->children, section,
1996                       (lang_output_section_statement_type *) output,
1997                       file);
1998   else
1999     {
2000       lang_statement_list_type list;
2001       lang_statement_union_type **pp;
2002
2003       lang_list_init (&list);
2004       lang_add_section (&list, section,
2005                         (lang_output_section_statement_type *) output,
2006                         file);
2007
2008       /* If we are discarding the section, LIST.HEAD will
2009          be NULL.  */
2010       if (list.head != NULL)
2011         {
2012           ASSERT (list.head->header.next == NULL);
2013
2014           for (pp = &ptr->children.head;
2015                *pp != before;
2016                pp = &(*pp)->header.next)
2017             ASSERT (*pp != NULL);
2018
2019           list.head->header.next = *pp;
2020           *pp = list.head;
2021         }
2022     }
2023 }
2024
2025 /* Check if all sections in a wild statement for a particular FILE
2026    are readonly.  */
2027
2028 static void
2029 check_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
2030                         struct wildcard_list *sec ATTRIBUTE_UNUSED,
2031                         asection *section,
2032                         lang_input_statement_type *file ATTRIBUTE_UNUSED,
2033                         void *data)
2034 {
2035   /* Exclude sections that match UNIQUE_SECTION_LIST.  */
2036   if (unique_section_p (section))
2037     return;
2038
2039   if (section->output_section == NULL && (section->flags & SEC_READONLY) == 0)
2040     ((lang_output_section_statement_type *) data)->all_input_readonly = FALSE;
2041 }
2042
2043 /* This is passed a file name which must have been seen already and
2044    added to the statement tree.  We will see if it has been opened
2045    already and had its symbols read.  If not then we'll read it.  */
2046
2047 static lang_input_statement_type *
2048 lookup_name (const char *name)
2049 {
2050   lang_input_statement_type *search;
2051
2052   for (search = (lang_input_statement_type *) input_file_chain.head;
2053        search != NULL;
2054        search = (lang_input_statement_type *) search->next_real_file)
2055     {
2056       /* Use the local_sym_name as the name of the file that has
2057          already been loaded as filename might have been transformed
2058          via the search directory lookup mechanism.  */
2059       const char * filename = search->local_sym_name;
2060
2061       if (filename == NULL && name == NULL)
2062         return search;
2063       if (filename != NULL
2064           && name != NULL
2065           && strcmp (filename, name) == 0)
2066         break;
2067     }
2068
2069   if (search == NULL)
2070     search = new_afile (name, lang_input_file_is_search_file_enum,
2071                         default_target, FALSE);
2072
2073   /* If we have already added this file, or this file is not real
2074      (FIXME: can that ever actually happen?) or the name is NULL
2075      (FIXME: can that ever actually happen?) don't add this file.  */
2076   if (search->loaded
2077       || ! search->real
2078       || search->filename == NULL)
2079     return search;
2080
2081   if (! load_symbols (search, NULL))
2082     return NULL;
2083
2084   return search;
2085 }
2086
2087 /* Save LIST as a list of libraries whose symbols should not be exported.  */
2088
2089 struct excluded_lib
2090 {
2091   char *name;
2092   struct excluded_lib *next;
2093 };
2094 static struct excluded_lib *excluded_libs;
2095
2096 void
2097 add_excluded_libs (const char *list)
2098 {
2099   const char *p = list, *end;
2100
2101   while (*p != '\0')
2102     {
2103       struct excluded_lib *entry;
2104       end = strpbrk (p, ",:");
2105       if (end == NULL)
2106         end = p + strlen (p);
2107       entry = xmalloc (sizeof (*entry));
2108       entry->next = excluded_libs;
2109       entry->name = xmalloc (end - p + 1);
2110       memcpy (entry->name, p, end - p);
2111       entry->name[end - p] = '\0';
2112       excluded_libs = entry;
2113       if (*end == '\0')
2114         break;
2115       p = end + 1;
2116     }
2117 }
2118
2119 static void
2120 check_excluded_libs (bfd *abfd)
2121 {
2122   struct excluded_lib *lib = excluded_libs;
2123
2124   while (lib)
2125     {
2126       int len = strlen (lib->name);
2127       const char *filename = lbasename (abfd->filename);
2128
2129       if (strcmp (lib->name, "ALL") == 0)
2130         {
2131           abfd->no_export = TRUE;
2132           return;
2133         }
2134
2135       if (strncmp (lib->name, filename, len) == 0
2136           && (filename[len] == '\0'
2137               || (filename[len] == '.' && filename[len + 1] == 'a'
2138                   && filename[len + 2] == '\0')))
2139         {
2140           abfd->no_export = TRUE;
2141           return;
2142         }
2143
2144       lib = lib->next;
2145     }
2146 }
2147
2148 /* Get the symbols for an input file.  */
2149
2150 static bfd_boolean
2151 load_symbols (lang_input_statement_type *entry,
2152               lang_statement_list_type *place)
2153 {
2154   char **matching;
2155
2156   if (entry->loaded)
2157     return TRUE;
2158
2159   ldfile_open_file (entry);
2160
2161   if (! bfd_check_format (entry->the_bfd, bfd_archive)
2162       && ! bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
2163     {
2164       bfd_error_type err;
2165       lang_statement_list_type *hold;
2166       bfd_boolean bad_load = TRUE;
2167       bfd_boolean save_ldlang_sysrooted_script;
2168
2169       err = bfd_get_error ();
2170
2171       /* See if the emulation has some special knowledge.  */
2172       if (ldemul_unrecognized_file (entry))
2173         return TRUE;
2174
2175       if (err == bfd_error_file_ambiguously_recognized)
2176         {
2177           char **p;
2178
2179           einfo (_("%B: file not recognized: %E\n"), entry->the_bfd);
2180           einfo (_("%B: matching formats:"), entry->the_bfd);
2181           for (p = matching; *p != NULL; p++)
2182             einfo (" %s", *p);
2183           einfo ("%F\n");
2184         }
2185       else if (err != bfd_error_file_not_recognized
2186                || place == NULL)
2187           einfo (_("%F%B: file not recognized: %E\n"), entry->the_bfd);
2188       else
2189         bad_load = FALSE;
2190
2191       bfd_close (entry->the_bfd);
2192       entry->the_bfd = NULL;
2193
2194       /* Try to interpret the file as a linker script.  */
2195       ldfile_open_command_file (entry->filename);
2196
2197       hold = stat_ptr;
2198       stat_ptr = place;
2199       save_ldlang_sysrooted_script = ldlang_sysrooted_script;
2200       ldlang_sysrooted_script = entry->sysrooted;
2201
2202       ldfile_assumed_script = TRUE;
2203       parser_input = input_script;
2204       /* We want to use the same -Bdynamic/-Bstatic as the one for
2205          ENTRY.  */
2206       config.dynamic_link = entry->dynamic;
2207       yyparse ();
2208       ldfile_assumed_script = FALSE;
2209
2210       ldlang_sysrooted_script = save_ldlang_sysrooted_script;
2211       stat_ptr = hold;
2212
2213       return ! bad_load;
2214     }
2215
2216   if (ldemul_recognized_file (entry))
2217     return TRUE;
2218
2219   /* We don't call ldlang_add_file for an archive.  Instead, the
2220      add_symbols entry point will call ldlang_add_file, via the
2221      add_archive_element callback, for each element of the archive
2222      which is used.  */
2223   switch (bfd_get_format (entry->the_bfd))
2224     {
2225     default:
2226       break;
2227
2228     case bfd_object:
2229       ldlang_add_file (entry);
2230       if (trace_files || trace_file_tries)
2231         info_msg ("%I\n", entry);
2232       break;
2233
2234     case bfd_archive:
2235       check_excluded_libs (entry->the_bfd);
2236
2237       if (entry->whole_archive)
2238         {
2239           bfd *member = NULL;
2240           bfd_boolean loaded = TRUE;
2241
2242           for (;;)
2243             {
2244               member = bfd_openr_next_archived_file (entry->the_bfd, member);
2245
2246               if (member == NULL)
2247                 break;
2248
2249               if (! bfd_check_format (member, bfd_object))
2250                 {
2251                   einfo (_("%F%B: member %B in archive is not an object\n"),
2252                          entry->the_bfd, member);
2253                   loaded = FALSE;
2254                 }
2255
2256               if (! ((*link_info.callbacks->add_archive_element)
2257                      (&link_info, member, "--whole-archive")))
2258                 abort ();
2259
2260               if (! bfd_link_add_symbols (member, &link_info))
2261                 {
2262                   einfo (_("%F%B: could not read symbols: %E\n"), member);
2263                   loaded = FALSE;
2264                 }
2265             }
2266
2267           entry->loaded = loaded;
2268           return loaded;
2269         }
2270       break;
2271     }
2272
2273   if (bfd_link_add_symbols (entry->the_bfd, &link_info))
2274     entry->loaded = TRUE;
2275   else
2276     einfo (_("%F%B: could not read symbols: %E\n"), entry->the_bfd);
2277
2278   return entry->loaded;
2279 }
2280
2281 /* Handle a wild statement.  S->FILENAME or S->SECTION_LIST or both
2282    may be NULL, indicating that it is a wildcard.  Separate
2283    lang_input_section statements are created for each part of the
2284    expansion; they are added after the wild statement S.  OUTPUT is
2285    the output section.  */
2286
2287 static void
2288 wild (lang_wild_statement_type *s,
2289       const char *target ATTRIBUTE_UNUSED,
2290       lang_output_section_statement_type *output)
2291 {
2292   struct wildcard_list *sec;
2293
2294   walk_wild (s, output_section_callback, output);
2295
2296   for (sec = s->section_list; sec != NULL; sec = sec->next)
2297     {
2298       if (default_common_section != NULL)
2299         break;
2300       if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
2301         {
2302           /* Remember the section that common is going to in case we
2303              later get something which doesn't know where to put it.  */
2304           default_common_section = output;
2305         }
2306     }
2307 }
2308
2309 /* Return TRUE iff target is the sought target.  */
2310
2311 static int
2312 get_target (const bfd_target *target, void *data)
2313 {
2314   const char *sought = data;
2315
2316   return strcmp (target->name, sought) == 0;
2317 }
2318
2319 /* Like strcpy() but convert to lower case as well.  */
2320
2321 static void
2322 stricpy (char *dest, char *src)
2323 {
2324   char c;
2325
2326   while ((c = *src++) != 0)
2327     *dest++ = TOLOWER (c);
2328
2329   *dest = 0;
2330 }
2331
2332 /* Remove the first occurrence of needle (if any) in haystack
2333    from haystack.  */
2334
2335 static void
2336 strcut (char *haystack, char *needle)
2337 {
2338   haystack = strstr (haystack, needle);
2339
2340   if (haystack)
2341     {
2342       char *src;
2343
2344       for (src = haystack + strlen (needle); *src;)
2345         *haystack++ = *src++;
2346
2347       *haystack = 0;
2348     }
2349 }
2350
2351 /* Compare two target format name strings.
2352    Return a value indicating how "similar" they are.  */
2353
2354 static int
2355 name_compare (char *first, char *second)
2356 {
2357   char *copy1;
2358   char *copy2;
2359   int result;
2360
2361   copy1 = xmalloc (strlen (first) + 1);
2362   copy2 = xmalloc (strlen (second) + 1);
2363
2364   /* Convert the names to lower case.  */
2365   stricpy (copy1, first);
2366   stricpy (copy2, second);
2367
2368   /* Remove size and endian strings from the name.  */
2369   strcut (copy1, "big");
2370   strcut (copy1, "little");
2371   strcut (copy2, "big");
2372   strcut (copy2, "little");
2373
2374   /* Return a value based on how many characters match,
2375      starting from the beginning.   If both strings are
2376      the same then return 10 * their length.  */
2377   for (result = 0; copy1[result] == copy2[result]; result++)
2378     if (copy1[result] == 0)
2379       {
2380         result *= 10;
2381         break;
2382       }
2383
2384   free (copy1);
2385   free (copy2);
2386
2387   return result;
2388 }
2389
2390 /* Set by closest_target_match() below.  */
2391 static const bfd_target *winner;
2392
2393 /* Scan all the valid bfd targets looking for one that has the endianness
2394    requirement that was specified on the command line, and is the nearest
2395    match to the original output target.  */
2396
2397 static int
2398 closest_target_match (const bfd_target *target, void *data)
2399 {
2400   const bfd_target *original = data;
2401
2402   if (command_line.endian == ENDIAN_BIG
2403       && target->byteorder != BFD_ENDIAN_BIG)
2404     return 0;
2405
2406   if (command_line.endian == ENDIAN_LITTLE
2407       && target->byteorder != BFD_ENDIAN_LITTLE)
2408     return 0;
2409
2410   /* Must be the same flavour.  */
2411   if (target->flavour != original->flavour)
2412     return 0;
2413
2414   /* If we have not found a potential winner yet, then record this one.  */
2415   if (winner == NULL)
2416     {
2417       winner = target;
2418       return 0;
2419     }
2420
2421   /* Oh dear, we now have two potential candidates for a successful match.
2422      Compare their names and choose the better one.  */
2423   if (name_compare (target->name, original->name)
2424       > name_compare (winner->name, original->name))
2425     winner = target;
2426
2427   /* Keep on searching until wqe have checked them all.  */
2428   return 0;
2429 }
2430
2431 /* Return the BFD target format of the first input file.  */
2432
2433 static char *
2434 get_first_input_target (void)
2435 {
2436   char *target = NULL;
2437
2438   LANG_FOR_EACH_INPUT_STATEMENT (s)
2439     {
2440       if (s->header.type == lang_input_statement_enum
2441           && s->real)
2442         {
2443           ldfile_open_file (s);
2444
2445           if (s->the_bfd != NULL
2446               && bfd_check_format (s->the_bfd, bfd_object))
2447             {
2448               target = bfd_get_target (s->the_bfd);
2449
2450               if (target != NULL)
2451                 break;
2452             }
2453         }
2454     }
2455
2456   return target;
2457 }
2458
2459 const char *
2460 lang_get_output_target (void)
2461 {
2462   const char *target;
2463
2464   /* Has the user told us which output format to use?  */
2465   if (output_target != NULL)
2466     return output_target;
2467
2468   /* No - has the current target been set to something other than
2469      the default?  */
2470   if (current_target != default_target)
2471     return current_target;
2472
2473   /* No - can we determine the format of the first input file?  */
2474   target = get_first_input_target ();
2475   if (target != NULL)
2476     return target;
2477
2478   /* Failed - use the default output target.  */
2479   return default_target;
2480 }
2481
2482 /* Open the output file.  */
2483
2484 static bfd *
2485 open_output (const char *name)
2486 {
2487   bfd *output;
2488
2489   output_target = lang_get_output_target ();
2490
2491   /* Has the user requested a particular endianness on the command
2492      line?  */
2493   if (command_line.endian != ENDIAN_UNSET)
2494     {
2495       const bfd_target *target;
2496       enum bfd_endian desired_endian;
2497
2498       /* Get the chosen target.  */
2499       target = bfd_search_for_target (get_target, (void *) output_target);
2500
2501       /* If the target is not supported, we cannot do anything.  */
2502       if (target != NULL)
2503         {
2504           if (command_line.endian == ENDIAN_BIG)
2505             desired_endian = BFD_ENDIAN_BIG;
2506           else
2507             desired_endian = BFD_ENDIAN_LITTLE;
2508
2509           /* See if the target has the wrong endianness.  This should
2510              not happen if the linker script has provided big and
2511              little endian alternatives, but some scrips don't do
2512              this.  */
2513           if (target->byteorder != desired_endian)
2514             {
2515               /* If it does, then see if the target provides
2516                  an alternative with the correct endianness.  */
2517               if (target->alternative_target != NULL
2518                   && (target->alternative_target->byteorder == desired_endian))
2519                 output_target = target->alternative_target->name;
2520               else
2521                 {
2522                   /* Try to find a target as similar as possible to
2523                      the default target, but which has the desired
2524                      endian characteristic.  */
2525                   bfd_search_for_target (closest_target_match,
2526                                          (void *) target);
2527
2528                   /* Oh dear - we could not find any targets that
2529                      satisfy our requirements.  */
2530                   if (winner == NULL)
2531                     einfo (_("%P: warning: could not find any targets"
2532                              " that match endianness requirement\n"));
2533                   else
2534                     output_target = winner->name;
2535                 }
2536             }
2537         }
2538     }
2539
2540   output = bfd_openw (name, output_target);
2541
2542   if (output == NULL)
2543     {
2544       if (bfd_get_error () == bfd_error_invalid_target)
2545         einfo (_("%P%F: target %s not found\n"), output_target);
2546
2547       einfo (_("%P%F: cannot open output file %s: %E\n"), name);
2548     }
2549
2550   delete_output_file_on_failure = TRUE;
2551
2552   if (! bfd_set_format (output, bfd_object))
2553     einfo (_("%P%F:%s: can not make object file: %E\n"), name);
2554   if (! bfd_set_arch_mach (output,
2555                            ldfile_output_architecture,
2556                            ldfile_output_machine))
2557     einfo (_("%P%F:%s: can not set architecture: %E\n"), name);
2558
2559   link_info.hash = bfd_link_hash_table_create (output);
2560   if (link_info.hash == NULL)
2561     einfo (_("%P%F: can not create link hash table: %E\n"));
2562
2563   bfd_set_gp_size (output, g_switch_value);
2564   return output;
2565 }
2566
2567 static void
2568 ldlang_open_output (lang_statement_union_type *statement)
2569 {
2570   switch (statement->header.type)
2571     {
2572     case lang_output_statement_enum:
2573       ASSERT (output_bfd == NULL);
2574       output_bfd = open_output (statement->output_statement.name);
2575       ldemul_set_output_arch ();
2576       if (config.magic_demand_paged && !link_info.relocatable)
2577         output_bfd->flags |= D_PAGED;
2578       else
2579         output_bfd->flags &= ~D_PAGED;
2580       if (config.text_read_only)
2581         output_bfd->flags |= WP_TEXT;
2582       else
2583         output_bfd->flags &= ~WP_TEXT;
2584       if (link_info.traditional_format)
2585         output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
2586       else
2587         output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
2588       break;
2589
2590     case lang_target_statement_enum:
2591       current_target = statement->target_statement.target;
2592       break;
2593     default:
2594       break;
2595     }
2596 }
2597
2598 /* Convert between addresses in bytes and sizes in octets.
2599    For currently supported targets, octets_per_byte is always a power
2600    of two, so we can use shifts.  */
2601 #define TO_ADDR(X) ((X) >> opb_shift)
2602 #define TO_SIZE(X) ((X) << opb_shift)
2603
2604 /* Support the above.  */
2605 static unsigned int opb_shift = 0;
2606
2607 static void
2608 init_opb (void)
2609 {
2610   unsigned x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
2611                                               ldfile_output_machine);
2612   opb_shift = 0;
2613   if (x > 1)
2614     while ((x & 1) == 0)
2615       {
2616         x >>= 1;
2617         ++opb_shift;
2618       }
2619   ASSERT (x == 1);
2620 }
2621
2622 /* Open all the input files.  */
2623
2624 static void
2625 open_input_bfds (lang_statement_union_type *s, bfd_boolean force)
2626 {
2627   for (; s != NULL; s = s->header.next)
2628     {
2629       switch (s->header.type)
2630         {
2631         case lang_constructors_statement_enum:
2632           open_input_bfds (constructor_list.head, force);
2633           break;
2634         case lang_output_section_statement_enum:
2635           open_input_bfds (s->output_section_statement.children.head, force);
2636           break;
2637         case lang_wild_statement_enum:
2638           /* Maybe we should load the file's symbols.  */
2639           if (s->wild_statement.filename
2640               && ! wildcardp (s->wild_statement.filename))
2641             lookup_name (s->wild_statement.filename);
2642           open_input_bfds (s->wild_statement.children.head, force);
2643           break;
2644         case lang_group_statement_enum:
2645           {
2646             struct bfd_link_hash_entry *undefs;
2647
2648             /* We must continually search the entries in the group
2649                until no new symbols are added to the list of undefined
2650                symbols.  */
2651
2652             do
2653               {
2654                 undefs = link_info.hash->undefs_tail;
2655                 open_input_bfds (s->group_statement.children.head, TRUE);
2656               }
2657             while (undefs != link_info.hash->undefs_tail);
2658           }
2659           break;
2660         case lang_target_statement_enum:
2661           current_target = s->target_statement.target;
2662           break;
2663         case lang_input_statement_enum:
2664           if (s->input_statement.real)
2665             {
2666               lang_statement_list_type add;
2667
2668               s->input_statement.target = current_target;
2669
2670               /* If we are being called from within a group, and this
2671                  is an archive which has already been searched, then
2672                  force it to be researched unless the whole archive
2673                  has been loaded already.  */
2674               if (force
2675                   && !s->input_statement.whole_archive
2676                   && s->input_statement.loaded
2677                   && bfd_check_format (s->input_statement.the_bfd,
2678                                        bfd_archive))
2679                 s->input_statement.loaded = FALSE;
2680
2681               lang_list_init (&add);
2682
2683               if (! load_symbols (&s->input_statement, &add))
2684                 config.make_executable = FALSE;
2685
2686               if (add.head != NULL)
2687                 {
2688                   *add.tail = s->header.next;
2689                   s->header.next = add.head;
2690                 }
2691             }
2692           break;
2693         default:
2694           break;
2695         }
2696     }
2697 }
2698
2699 /* Add a symbol to a hash of symbols used in DEFINED (NAME) expressions.  */
2700
2701 void
2702 lang_track_definedness (const char *name)
2703 {
2704   if (bfd_hash_lookup (&lang_definedness_table, name, TRUE, FALSE) == NULL)
2705     einfo (_("%P%F: bfd_hash_lookup failed creating symbol %s\n"), name);
2706 }
2707
2708 /* New-function for the definedness hash table.  */
2709
2710 static struct bfd_hash_entry *
2711 lang_definedness_newfunc (struct bfd_hash_entry *entry,
2712                           struct bfd_hash_table *table ATTRIBUTE_UNUSED,
2713                           const char *name ATTRIBUTE_UNUSED)
2714 {
2715   struct lang_definedness_hash_entry *ret
2716     = (struct lang_definedness_hash_entry *) entry;
2717
2718   if (ret == NULL)
2719     ret = (struct lang_definedness_hash_entry *)
2720       bfd_hash_allocate (table, sizeof (struct lang_definedness_hash_entry));
2721
2722   if (ret == NULL)
2723     einfo (_("%P%F: bfd_hash_allocate failed creating symbol %s\n"), name);
2724
2725   ret->iteration = -1;
2726   return &ret->root;
2727 }
2728
2729 /* Return the iteration when the definition of NAME was last updated.  A
2730    value of -1 means that the symbol is not defined in the linker script
2731    or the command line, but may be defined in the linker symbol table.  */
2732
2733 int
2734 lang_symbol_definition_iteration (const char *name)
2735 {
2736   struct lang_definedness_hash_entry *defentry
2737     = (struct lang_definedness_hash_entry *)
2738     bfd_hash_lookup (&lang_definedness_table, name, FALSE, FALSE);
2739
2740   /* We've already created this one on the presence of DEFINED in the
2741      script, so it can't be NULL unless something is borked elsewhere in
2742      the code.  */
2743   if (defentry == NULL)
2744     FAIL ();
2745
2746   return defentry->iteration;
2747 }
2748
2749 /* Update the definedness state of NAME.  */
2750
2751 void
2752 lang_update_definedness (const char *name, struct bfd_link_hash_entry *h)
2753 {
2754   struct lang_definedness_hash_entry *defentry
2755     = (struct lang_definedness_hash_entry *)
2756     bfd_hash_lookup (&lang_definedness_table, name, FALSE, FALSE);
2757
2758   /* We don't keep track of symbols not tested with DEFINED.  */
2759   if (defentry == NULL)
2760     return;
2761
2762   /* If the symbol was already defined, and not from an earlier statement
2763      iteration, don't update the definedness iteration, because that'd
2764      make the symbol seem defined in the linker script at this point, and
2765      it wasn't; it was defined in some object.  If we do anyway, DEFINED
2766      would start to yield false before this point and the construct "sym =
2767      DEFINED (sym) ? sym : X;" would change sym to X despite being defined
2768      in an object.  */
2769   if (h->type != bfd_link_hash_undefined
2770       && h->type != bfd_link_hash_common
2771       && h->type != bfd_link_hash_new
2772       && defentry->iteration == -1)
2773     return;
2774
2775   defentry->iteration = lang_statement_iteration;
2776 }
2777
2778 /* Add the supplied name to the symbol table as an undefined reference.
2779    This is a two step process as the symbol table doesn't even exist at
2780    the time the ld command line is processed.  First we put the name
2781    on a list, then, once the output file has been opened, transfer the
2782    name to the symbol table.  */
2783
2784 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
2785
2786 #define ldlang_undef_chain_list_head entry_symbol.next
2787
2788 void
2789 ldlang_add_undef (const char *const name)
2790 {
2791   ldlang_undef_chain_list_type *new =
2792     stat_alloc (sizeof (ldlang_undef_chain_list_type));
2793
2794   new->next = ldlang_undef_chain_list_head;
2795   ldlang_undef_chain_list_head = new;
2796
2797   new->name = xstrdup (name);
2798
2799   if (output_bfd != NULL)
2800     insert_undefined (new->name);
2801 }
2802
2803 /* Insert NAME as undefined in the symbol table.  */
2804
2805 static void
2806 insert_undefined (const char *name)
2807 {
2808   struct bfd_link_hash_entry *h;
2809
2810   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, FALSE, TRUE);
2811   if (h == NULL)
2812     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
2813   if (h->type == bfd_link_hash_new)
2814     {
2815       h->type = bfd_link_hash_undefined;
2816       h->u.undef.abfd = NULL;
2817       bfd_link_add_undef (link_info.hash, h);
2818     }
2819 }
2820
2821 /* Run through the list of undefineds created above and place them
2822    into the linker hash table as undefined symbols belonging to the
2823    script file.  */
2824
2825 static void
2826 lang_place_undefineds (void)
2827 {
2828   ldlang_undef_chain_list_type *ptr;
2829
2830   for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
2831     insert_undefined (ptr->name);
2832 }
2833
2834 /* Check for all readonly or some readwrite sections.  */
2835
2836 static void
2837 check_input_sections
2838   (lang_statement_union_type *s,
2839    lang_output_section_statement_type *output_section_statement)
2840 {
2841   for (; s != (lang_statement_union_type *) NULL; s = s->header.next)
2842     {
2843       switch (s->header.type)
2844       {
2845       case lang_wild_statement_enum:
2846         walk_wild (&s->wild_statement, check_section_callback,
2847                    output_section_statement);
2848         if (! output_section_statement->all_input_readonly)
2849           return;
2850         break;
2851       case lang_constructors_statement_enum:
2852         check_input_sections (constructor_list.head,
2853                               output_section_statement);
2854         if (! output_section_statement->all_input_readonly)
2855           return;
2856         break;
2857       case lang_group_statement_enum:
2858         check_input_sections (s->group_statement.children.head,
2859                               output_section_statement);
2860         if (! output_section_statement->all_input_readonly)
2861           return;
2862         break;
2863       default:
2864         break;
2865       }
2866     }
2867 }
2868
2869 /* Update wildcard statements if needed.  */
2870
2871 static void
2872 update_wild_statements (lang_statement_union_type *s)
2873 {
2874   struct wildcard_list *sec;
2875
2876   switch (sort_section)
2877     {
2878     default:
2879       FAIL ();
2880
2881     case none:
2882       break;
2883
2884     case by_name:
2885     case by_alignment:
2886       for (; s != NULL; s = s->header.next)
2887         {
2888           switch (s->header.type)
2889             {
2890             default:
2891               break;
2892
2893             case lang_wild_statement_enum:
2894               sec = s->wild_statement.section_list;
2895               if (sec != NULL)
2896                 {
2897                   switch (sec->spec.sorted)
2898                     {
2899                     case none:
2900                       sec->spec.sorted = sort_section;
2901                       break;
2902                     case by_name:
2903                       if (sort_section == by_alignment)
2904                         sec->spec.sorted = by_name_alignment;
2905                       break;
2906                     case by_alignment:
2907                       if (sort_section == by_name)
2908                         sec->spec.sorted = by_alignment_name;
2909                       break;
2910                     default:
2911                       break;
2912                     }
2913                 }
2914               break;
2915
2916             case lang_constructors_statement_enum:
2917               update_wild_statements (constructor_list.head);
2918               break;
2919
2920             case lang_output_section_statement_enum:
2921               update_wild_statements
2922                 (s->output_section_statement.children.head);
2923               break;
2924
2925             case lang_group_statement_enum:
2926               update_wild_statements (s->group_statement.children.head);
2927               break;
2928             }
2929         }
2930       break;
2931     }
2932 }
2933
2934 /* Open input files and attach to output sections.  */
2935
2936 static void
2937 map_input_to_output_sections
2938   (lang_statement_union_type *s, const char *target,
2939    lang_output_section_statement_type *os)
2940 {
2941   for (; s != NULL; s = s->header.next)
2942     {
2943       switch (s->header.type)
2944         {
2945         case lang_wild_statement_enum:
2946           wild (&s->wild_statement, target, os);
2947           break;
2948         case lang_constructors_statement_enum:
2949           map_input_to_output_sections (constructor_list.head,
2950                                         target,
2951                                         os);
2952           break;
2953         case lang_output_section_statement_enum:
2954           if (s->output_section_statement.constraint)
2955             {
2956               if (s->output_section_statement.constraint != ONLY_IF_RW
2957                   && s->output_section_statement.constraint != ONLY_IF_RO)
2958                 break;
2959               s->output_section_statement.all_input_readonly = TRUE;
2960               check_input_sections (s->output_section_statement.children.head,
2961                                     &s->output_section_statement);
2962               if ((s->output_section_statement.all_input_readonly
2963                    && s->output_section_statement.constraint == ONLY_IF_RW)
2964                   || (!s->output_section_statement.all_input_readonly
2965                       && s->output_section_statement.constraint == ONLY_IF_RO))
2966                 {
2967                   s->output_section_statement.constraint = -1;
2968                   break;
2969                 }
2970             }
2971
2972           map_input_to_output_sections (s->output_section_statement.children.head,
2973                                         target,
2974                                         &s->output_section_statement);
2975           break;
2976         case lang_output_statement_enum:
2977           break;
2978         case lang_target_statement_enum:
2979           target = s->target_statement.target;
2980           break;
2981         case lang_group_statement_enum:
2982           map_input_to_output_sections (s->group_statement.children.head,
2983                                         target,
2984                                         os);
2985           break;
2986         case lang_data_statement_enum:
2987           /* Make sure that any sections mentioned in the expression
2988              are initialized.  */
2989           exp_init_os (s->data_statement.exp);
2990           if (os != NULL && os->bfd_section == NULL)
2991             init_os (os);
2992           /* The output section gets contents, and then we inspect for
2993              any flags set in the input script which override any ALLOC.  */
2994           os->bfd_section->flags |= SEC_HAS_CONTENTS;
2995           if (!(os->flags & SEC_NEVER_LOAD))
2996             os->bfd_section->flags |= SEC_ALLOC | SEC_LOAD;
2997           break;
2998         case lang_fill_statement_enum:
2999         case lang_input_section_enum:
3000         case lang_object_symbols_statement_enum:
3001         case lang_reloc_statement_enum:
3002         case lang_padding_statement_enum:
3003         case lang_input_statement_enum:
3004           if (os != NULL && os->bfd_section == NULL)
3005             init_os (os);
3006           break;
3007         case lang_assignment_statement_enum:
3008           if (os != NULL && os->bfd_section == NULL)
3009             init_os (os);
3010
3011           /* Make sure that any sections mentioned in the assignment
3012              are initialized.  */
3013           exp_init_os (s->assignment_statement.exp);
3014           break;
3015         case lang_afile_asection_pair_statement_enum:
3016           FAIL ();
3017           break;
3018         case lang_address_statement_enum:
3019           /* Mark the specified section with the supplied address.  
3020
3021              If this section was actually a segment marker, then the
3022              directive is ignored if the linker script explicitly
3023              processed the segment marker.  Originally, the linker
3024              treated segment directives (like -Ttext on the
3025              command-line) as section directives.  We honor the
3026              section directive semantics for backwards compatibilty;
3027              linker scripts that do not specifically check for
3028              SEGMENT_START automatically get the old semantics.  */
3029           if (!s->address_statement.segment 
3030               || !s->address_statement.segment->used)
3031             {
3032               lang_output_section_statement_type *aos
3033                 = (lang_output_section_statement_lookup
3034                    (s->address_statement.section_name));
3035               
3036               if (aos->bfd_section == NULL)
3037                 init_os (aos);
3038               aos->addr_tree = s->address_statement.address;
3039             }
3040           break;
3041         }
3042     }
3043 }
3044
3045 /* An output section might have been removed after its statement was
3046    added.  For example, ldemul_before_allocation can remove dynamic
3047    sections if they turn out to be not needed.  Clean them up here.  */
3048
3049 void
3050 strip_excluded_output_sections (void)
3051 {
3052   lang_output_section_statement_type *os;
3053
3054   for (os = &lang_output_section_statement.head->output_section_statement;
3055        os != NULL;
3056        os = os->next)
3057     {
3058       asection *s;
3059
3060       if (os->constraint == -1)
3061         continue;
3062
3063       if (os->bfd_section == NULL || os->bfd_section->map_head.s == NULL)
3064         continue;
3065
3066       for (s = os->bfd_section->map_head.s; s != NULL; s = s->map_head.s)
3067         if ((s->flags & SEC_EXCLUDE) == 0)
3068           break;
3069
3070       os->bfd_section->map_head.link_order = NULL;
3071       os->bfd_section->map_tail.link_order = NULL;
3072
3073       if (s == NULL)
3074         {
3075           s = os->bfd_section;
3076           os->bfd_section = NULL;
3077           if (!bfd_section_removed_from_list (output_bfd, s))
3078             {
3079               bfd_section_list_remove (output_bfd, s);
3080               output_bfd->section_count--;
3081             }
3082         }
3083     }
3084
3085   /* Stop future calls to lang_add_section from messing with map_head
3086      and map_tail link_order fields.  */
3087   stripped_excluded_sections = TRUE;
3088 }
3089
3090 static void
3091 print_output_section_statement
3092   (lang_output_section_statement_type *output_section_statement)
3093 {
3094   asection *section = output_section_statement->bfd_section;
3095   int len;
3096
3097   if (output_section_statement != abs_output_section)
3098     {
3099       minfo ("\n%s", output_section_statement->name);
3100
3101       if (section != NULL)
3102         {
3103           print_dot = section->vma;
3104
3105           len = strlen (output_section_statement->name);
3106           if (len >= SECTION_NAME_MAP_LENGTH - 1)
3107             {
3108               print_nl ();
3109               len = 0;
3110             }
3111           while (len < SECTION_NAME_MAP_LENGTH)
3112             {
3113               print_space ();
3114               ++len;
3115             }
3116
3117           minfo ("0x%V %W", section->vma, section->size);
3118
3119           if (output_section_statement->load_base != NULL)
3120             {
3121               bfd_vma addr;
3122
3123               addr = exp_get_abs_int (output_section_statement->load_base, 0,
3124                                       "load base", lang_final_phase_enum);
3125               minfo (_(" load address 0x%V"), addr);
3126             }
3127         }
3128
3129       print_nl ();
3130     }
3131
3132   print_statement_list (output_section_statement->children.head,
3133                         output_section_statement);
3134 }
3135
3136 /* Scan for the use of the destination in the right hand side
3137    of an expression.  In such cases we will not compute the
3138    correct expression, since the value of DST that is used on
3139    the right hand side will be its final value, not its value
3140    just before this expression is evaluated.  */
3141    
3142 static bfd_boolean
3143 scan_for_self_assignment (const char * dst, etree_type * rhs)
3144 {
3145   if (rhs == NULL || dst == NULL)
3146     return FALSE;
3147
3148   switch (rhs->type.node_class)
3149     {
3150     case etree_binary:
3151       return scan_for_self_assignment (dst, rhs->binary.lhs)
3152         ||   scan_for_self_assignment (dst, rhs->binary.rhs);
3153
3154     case etree_trinary:
3155       return scan_for_self_assignment (dst, rhs->trinary.lhs)
3156         ||   scan_for_self_assignment (dst, rhs->trinary.rhs);
3157
3158     case etree_assign:
3159     case etree_provided:
3160     case etree_provide:
3161       if (strcmp (dst, rhs->assign.dst) == 0)
3162         return TRUE;
3163       return scan_for_self_assignment (dst, rhs->assign.src);
3164
3165     case etree_unary:
3166       return scan_for_self_assignment (dst, rhs->unary.child);
3167
3168     case etree_value:
3169       if (rhs->value.str)
3170         return strcmp (dst, rhs->value.str) == 0;
3171       return FALSE;
3172
3173     case etree_name:
3174       if (rhs->name.name)
3175         return strcmp (dst, rhs->name.name) == 0;
3176       return FALSE;
3177
3178     default:
3179       break;
3180     }
3181
3182   return FALSE;
3183 }
3184
3185
3186 static void
3187 print_assignment (lang_assignment_statement_type *assignment,
3188                   lang_output_section_statement_type *output_section)
3189 {
3190   unsigned int i;
3191   bfd_boolean is_dot;
3192   bfd_boolean computation_is_valid = TRUE;
3193   etree_type *tree;
3194   etree_value_type result;
3195
3196   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
3197     print_space ();
3198
3199   if (assignment->exp->type.node_class == etree_assert)
3200     {
3201       is_dot = FALSE;
3202       tree = assignment->exp->assert_s.child;
3203       computation_is_valid = TRUE;
3204     }
3205   else
3206     {
3207       const char *dst = assignment->exp->assign.dst;
3208
3209       is_dot = (dst[0] == '.' && dst[1] == 0);
3210       tree = assignment->exp->assign.src;
3211       computation_is_valid = is_dot || (scan_for_self_assignment (dst, tree) == FALSE);
3212     }
3213
3214   result = exp_fold_tree (tree, output_section, lang_final_phase_enum,
3215                           print_dot, &print_dot);
3216   if (result.valid_p)
3217     {
3218       bfd_vma value;
3219
3220       if (computation_is_valid)
3221         {
3222           value = result.value;
3223
3224           if (result.section)
3225             value += result.section->bfd_section->vma;
3226
3227           minfo ("0x%V", value);
3228           if (is_dot)
3229             print_dot = value;
3230         }
3231       else
3232         {
3233           struct bfd_link_hash_entry *h;
3234
3235           h = bfd_link_hash_lookup (link_info.hash, assignment->exp->assign.dst,
3236                                     FALSE, FALSE, TRUE);
3237           if (h)
3238             {
3239               value = h->u.def.value;
3240
3241               if (result.section)
3242               value += result.section->bfd_section->vma;
3243
3244               minfo ("[0x%V]", value);
3245             }
3246           else
3247             minfo ("[unresolved]");
3248         }
3249     }
3250   else
3251     {
3252       minfo ("*undef*   ");
3253 #ifdef BFD64
3254       minfo ("        ");
3255 #endif
3256     }
3257
3258   minfo ("                ");
3259   exp_print_tree (assignment->exp);
3260   print_nl ();
3261 }
3262
3263 static void
3264 print_input_statement (lang_input_statement_type *statm)
3265 {
3266   if (statm->filename != NULL)
3267     {
3268       fprintf (config.map_file, "LOAD %s\n", statm->filename);
3269     }
3270 }
3271
3272 /* Print all symbols defined in a particular section.  This is called
3273    via bfd_link_hash_traverse, or by print_all_symbols.  */
3274
3275 static bfd_boolean
3276 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
3277 {
3278   asection *sec = ptr;
3279
3280   if ((hash_entry->type == bfd_link_hash_defined
3281        || hash_entry->type == bfd_link_hash_defweak)
3282       && sec == hash_entry->u.def.section)
3283     {
3284       int i;
3285
3286       for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
3287         print_space ();
3288       minfo ("0x%V   ",
3289              (hash_entry->u.def.value
3290               + hash_entry->u.def.section->output_offset
3291               + hash_entry->u.def.section->output_section->vma));
3292
3293       minfo ("             %T\n", hash_entry->root.string);
3294     }
3295
3296   return TRUE;
3297 }
3298
3299 static void
3300 print_all_symbols (sec)
3301      asection *sec;
3302 {
3303   struct fat_user_section_struct *ud = get_userdata (sec);
3304   struct map_symbol_def *def;
3305
3306   if (!ud)
3307     return;
3308
3309   *ud->map_symbol_def_tail = 0;
3310   for (def = ud->map_symbol_def_head; def; def = def->next)
3311     print_one_symbol (def->entry, sec);
3312 }
3313
3314 /* Print information about an input section to the map file.  */
3315
3316 static void
3317 print_input_section (lang_input_section_type *in)
3318 {
3319   asection *i = in->section;
3320   bfd_size_type size = i->size;
3321
3322   init_opb ();
3323   if (size != 0)
3324     {
3325       int len;
3326       bfd_vma addr;
3327
3328       print_space ();
3329       minfo ("%s", i->name);
3330
3331       len = 1 + strlen (i->name);
3332       if (len >= SECTION_NAME_MAP_LENGTH - 1)
3333         {
3334           print_nl ();
3335           len = 0;
3336         }
3337       while (len < SECTION_NAME_MAP_LENGTH)
3338         {
3339           print_space ();
3340           ++len;
3341         }
3342
3343       if (i->output_section != NULL && (i->flags & SEC_EXCLUDE) == 0)
3344         addr = i->output_section->vma + i->output_offset;
3345       else
3346         {
3347           addr = print_dot;
3348           size = 0;
3349         }
3350
3351       minfo ("0x%V %W %B\n", addr, TO_ADDR (size), i->owner);
3352
3353       if (size != i->rawsize && i->rawsize != 0)
3354         {
3355           len = SECTION_NAME_MAP_LENGTH + 3;
3356 #ifdef BFD64
3357           len += 16;
3358 #else
3359           len += 8;
3360 #endif
3361           while (len > 0)
3362             {
3363               print_space ();
3364               --len;
3365             }
3366
3367           minfo (_("%W (size before relaxing)\n"), i->rawsize);
3368         }
3369
3370       if (i->output_section != NULL && (i->flags & SEC_EXCLUDE) == 0)
3371         {
3372           if (command_line.reduce_memory_overheads)
3373             bfd_link_hash_traverse (link_info.hash, print_one_symbol, i);
3374           else
3375             print_all_symbols (i);
3376
3377           print_dot = addr + TO_ADDR (size);
3378         }
3379     }
3380 }
3381
3382 static void
3383 print_fill_statement (lang_fill_statement_type *fill)
3384 {
3385   size_t size;
3386   unsigned char *p;
3387   fputs (" FILL mask 0x", config.map_file);
3388   for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
3389     fprintf (config.map_file, "%02x", *p);
3390   fputs ("\n", config.map_file);
3391 }
3392
3393 static void
3394 print_data_statement (lang_data_statement_type *data)
3395 {
3396   int i;
3397   bfd_vma addr;
3398   bfd_size_type size;
3399   const char *name;
3400
3401   init_opb ();
3402   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
3403     print_space ();
3404
3405   addr = data->output_vma;
3406   if (data->output_section != NULL)
3407     addr += data->output_section->vma;
3408
3409   switch (data->type)
3410     {
3411     default:
3412       abort ();
3413     case BYTE:
3414       size = BYTE_SIZE;
3415       name = "BYTE";
3416       break;
3417     case SHORT:
3418       size = SHORT_SIZE;
3419       name = "SHORT";
3420       break;
3421     case LONG:
3422       size = LONG_SIZE;
3423       name = "LONG";
3424       break;
3425     case QUAD:
3426       size = QUAD_SIZE;
3427       name = "QUAD";
3428       break;
3429     case SQUAD:
3430       size = QUAD_SIZE;
3431       name = "SQUAD";
3432       break;
3433     }
3434
3435   minfo ("0x%V %W %s 0x%v", addr, size, name, data->value);
3436
3437   if (data->exp->type.node_class != etree_value)
3438     {
3439       print_space ();
3440       exp_print_tree (data->exp);
3441     }
3442
3443   print_nl ();
3444
3445   print_dot = addr + TO_ADDR (size);
3446 }
3447
3448 /* Print an address statement.  These are generated by options like
3449    -Ttext.  */
3450
3451 static void
3452 print_address_statement (lang_address_statement_type *address)
3453 {
3454   minfo (_("Address of section %s set to "), address->section_name);
3455   exp_print_tree (address->address);
3456   print_nl ();
3457 }
3458
3459 /* Print a reloc statement.  */
3460
3461 static void
3462 print_reloc_statement (lang_reloc_statement_type *reloc)
3463 {
3464   int i;
3465   bfd_vma addr;
3466   bfd_size_type size;
3467
3468   init_opb ();
3469   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
3470     print_space ();
3471
3472   addr = reloc->output_vma;
3473   if (reloc->output_section != NULL)
3474     addr += reloc->output_section->vma;
3475
3476   size = bfd_get_reloc_size (reloc->howto);
3477
3478   minfo ("0x%V %W RELOC %s ", addr, size, reloc->howto->name);
3479
3480   if (reloc->name != NULL)
3481     minfo ("%s+", reloc->name);
3482   else
3483     minfo ("%s+", reloc->section->name);
3484
3485   exp_print_tree (reloc->addend_exp);
3486
3487   print_nl ();
3488
3489   print_dot = addr + TO_ADDR (size);
3490 }
3491
3492 static void
3493 print_padding_statement (lang_padding_statement_type *s)
3494 {
3495   int len;
3496   bfd_vma addr;
3497
3498   init_opb ();
3499   minfo (" *fill*");
3500
3501   len = sizeof " *fill*" - 1;
3502   while (len < SECTION_NAME_MAP_LENGTH)
3503     {
3504       print_space ();
3505       ++len;
3506     }
3507
3508   addr = s->output_offset;
3509   if (s->output_section != NULL)
3510     addr += s->output_section->vma;
3511   minfo ("0x%V %W ", addr, (bfd_vma) s->size);
3512
3513   if (s->fill->size != 0)
3514     {
3515       size_t size;
3516       unsigned char *p;
3517       for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
3518         fprintf (config.map_file, "%02x", *p);
3519     }
3520
3521   print_nl ();
3522
3523   print_dot = addr + TO_ADDR (s->size);
3524 }
3525
3526 static void
3527 print_wild_statement (lang_wild_statement_type *w,
3528                       lang_output_section_statement_type *os)
3529 {
3530   struct wildcard_list *sec;
3531
3532   print_space ();
3533
3534   if (w->filenames_sorted)
3535     minfo ("SORT(");
3536   if (w->filename != NULL)
3537     minfo ("%s", w->filename);
3538   else
3539     minfo ("*");
3540   if (w->filenames_sorted)
3541     minfo (")");
3542
3543   minfo ("(");
3544   for (sec = w->section_list; sec; sec = sec->next)
3545     {
3546       if (sec->spec.sorted)
3547         minfo ("SORT(");
3548       if (sec->spec.exclude_name_list != NULL)
3549         {
3550           name_list *tmp;
3551           minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
3552           for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
3553             minfo (" %s", tmp->name);
3554           minfo (") ");
3555         }
3556       if (sec->spec.name != NULL)
3557         minfo ("%s", sec->spec.name);
3558       else
3559         minfo ("*");
3560       if (sec->spec.sorted)
3561         minfo (")");
3562       if (sec->next)
3563         minfo (" ");
3564     }
3565   minfo (")");
3566
3567   print_nl ();
3568
3569   print_statement_list (w->children.head, os);
3570 }
3571
3572 /* Print a group statement.  */
3573
3574 static void
3575 print_group (lang_group_statement_type *s,
3576              lang_output_section_statement_type *os)
3577 {
3578   fprintf (config.map_file, "START GROUP\n");
3579   print_statement_list (s->children.head, os);
3580   fprintf (config.map_file, "END GROUP\n");
3581 }
3582
3583 /* Print the list of statements in S.
3584    This can be called for any statement type.  */
3585
3586 static void
3587 print_statement_list (lang_statement_union_type *s,
3588                       lang_output_section_statement_type *os)
3589 {
3590   while (s != NULL)
3591     {
3592       print_statement (s, os);
3593       s = s->header.next;
3594     }
3595 }
3596
3597 /* Print the first statement in statement list S.
3598    This can be called for any statement type.  */
3599
3600 static void
3601 print_statement (lang_statement_union_type *s,
3602                  lang_output_section_statement_type *os)
3603 {
3604   switch (s->header.type)
3605     {
3606     default:
3607       fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
3608       FAIL ();
3609       break;
3610     case lang_constructors_statement_enum:
3611       if (constructor_list.head != NULL)
3612         {
3613           if (constructors_sorted)
3614             minfo (" SORT (CONSTRUCTORS)\n");
3615           else
3616             minfo (" CONSTRUCTORS\n");
3617           print_statement_list (constructor_list.head, os);
3618         }
3619       break;
3620     case lang_wild_statement_enum:
3621       print_wild_statement (&s->wild_statement, os);
3622       break;
3623     case lang_address_statement_enum:
3624       print_address_statement (&s->address_statement);
3625       break;
3626     case lang_object_symbols_statement_enum:
3627       minfo (" CREATE_OBJECT_SYMBOLS\n");
3628       break;
3629     case lang_fill_statement_enum:
3630       print_fill_statement (&s->fill_statement);
3631       break;
3632     case lang_data_statement_enum:
3633       print_data_statement (&s->data_statement);
3634       break;
3635     case lang_reloc_statement_enum:
3636       print_reloc_statement (&s->reloc_statement);
3637       break;
3638     case lang_input_section_enum:
3639       print_input_section (&s->input_section);
3640       break;
3641     case lang_padding_statement_enum:
3642       print_padding_statement (&s->padding_statement);
3643       break;
3644     case lang_output_section_statement_enum:
3645       print_output_section_statement (&s->output_section_statement);
3646       break;
3647     case lang_assignment_statement_enum:
3648       print_assignment (&s->assignment_statement, os);
3649       break;
3650     case lang_target_statement_enum:
3651       fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
3652       break;
3653     case lang_output_statement_enum:
3654       minfo ("OUTPUT(%s", s->output_statement.name);
3655       if (output_target != NULL)
3656         minfo (" %s", output_target);
3657       minfo (")\n");
3658       break;
3659     case lang_input_statement_enum:
3660       print_input_statement (&s->input_statement);
3661       break;
3662     case lang_group_statement_enum:
3663       print_group (&s->group_statement, os);
3664       break;
3665     case lang_afile_asection_pair_statement_enum:
3666       FAIL ();
3667       break;
3668     }
3669 }
3670
3671 static void
3672 print_statements (void)
3673 {
3674   print_statement_list (statement_list.head, abs_output_section);
3675 }
3676
3677 /* Print the first N statements in statement list S to STDERR.
3678    If N == 0, nothing is printed.
3679    If N < 0, the entire list is printed.
3680    Intended to be called from GDB.  */
3681
3682 void
3683 dprint_statement (lang_statement_union_type *s, int n)
3684 {
3685   FILE *map_save = config.map_file;
3686
3687   config.map_file = stderr;
3688
3689   if (n < 0)
3690     print_statement_list (s, abs_output_section);
3691   else
3692     {
3693       while (s && --n >= 0)
3694         {
3695           print_statement (s, abs_output_section);
3696           s = s->header.next;
3697         }
3698     }
3699
3700   config.map_file = map_save;
3701 }
3702
3703 static void
3704 insert_pad (lang_statement_union_type **ptr,
3705             fill_type *fill,
3706             unsigned int alignment_needed,
3707             asection *output_section,
3708             bfd_vma dot)
3709 {
3710   static fill_type zero_fill = { 1, { 0 } };
3711   lang_statement_union_type *pad;
3712
3713   pad = ((lang_statement_union_type *)
3714          ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
3715   if (ptr != &statement_list.head
3716       && pad->header.type == lang_padding_statement_enum
3717       && pad->padding_statement.output_section == output_section)
3718     {
3719       /* Use the existing pad statement.  The above test on output
3720          section is probably redundant, but it doesn't hurt to check.  */
3721     }
3722   else
3723     {
3724       /* Make a new padding statement, linked into existing chain.  */
3725       pad = stat_alloc (sizeof (lang_padding_statement_type));
3726       pad->header.next = *ptr;
3727       *ptr = pad;
3728       pad->header.type = lang_padding_statement_enum;
3729       pad->padding_statement.output_section = output_section;
3730       if (fill == NULL)
3731         fill = &zero_fill;
3732       pad->padding_statement.fill = fill;
3733     }
3734   pad->padding_statement.output_offset = dot - output_section->vma;
3735   pad->padding_statement.size = alignment_needed;
3736   output_section->size += alignment_needed;
3737 }
3738
3739 /* Work out how much this section will move the dot point.  */
3740
3741 static bfd_vma
3742 size_input_section
3743   (lang_statement_union_type **this_ptr,
3744    lang_output_section_statement_type *output_section_statement,
3745    fill_type *fill,
3746    bfd_vma dot)
3747 {
3748   lang_input_section_type *is = &((*this_ptr)->input_section);
3749   asection *i = is->section;
3750
3751   if (!is->ifile->just_syms_flag && (i->flags & SEC_EXCLUDE) == 0)
3752     {
3753       unsigned int alignment_needed;
3754       asection *o;
3755
3756       /* Align this section first to the input sections requirement,
3757          then to the output section's requirement.  If this alignment
3758          is greater than any seen before, then record it too.  Perform
3759          the alignment by inserting a magic 'padding' statement.  */
3760
3761       if (output_section_statement->subsection_alignment != -1)
3762         i->alignment_power = output_section_statement->subsection_alignment;
3763
3764       o = output_section_statement->bfd_section;
3765       if (o->alignment_power < i->alignment_power)
3766         o->alignment_power = i->alignment_power;
3767
3768       alignment_needed = align_power (dot, i->alignment_power) - dot;
3769
3770       if (alignment_needed != 0)
3771         {
3772           insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
3773           dot += alignment_needed;
3774         }
3775
3776       /* Remember where in the output section this input section goes.  */
3777
3778       i->output_offset = dot - o->vma;
3779
3780       /* Mark how big the output section must be to contain this now.  */
3781       dot += TO_ADDR (i->size);
3782       o->size = TO_SIZE (dot - o->vma);
3783     }
3784   else
3785     {
3786       i->output_offset = i->vma - output_section_statement->bfd_section->vma;
3787     }
3788
3789   return dot;
3790 }
3791
3792 static int
3793 sort_sections_by_lma (const void *arg1, const void *arg2)
3794 {
3795   const asection *sec1 = *(const asection **) arg1;
3796   const asection *sec2 = *(const asection **) arg2;
3797
3798   if (bfd_section_lma (sec1->owner, sec1)
3799       < bfd_section_lma (sec2->owner, sec2))
3800     return -1;
3801   else if (bfd_section_lma (sec1->owner, sec1)
3802            > bfd_section_lma (sec2->owner, sec2))
3803     return 1;
3804
3805   return 0;
3806 }
3807
3808 #define IGNORE_SECTION(s) \
3809   ((s->flags & SEC_NEVER_LOAD) != 0                             \
3810    || (s->flags & SEC_ALLOC) == 0                               \
3811    || ((s->flags & SEC_THREAD_LOCAL) != 0                       \
3812         && (s->flags & SEC_LOAD) == 0))
3813
3814 /* Check to see if any allocated sections overlap with other allocated
3815    sections.  This can happen if a linker script specifies the output
3816    section addresses of the two sections.  */
3817
3818 static void
3819 lang_check_section_addresses (void)
3820 {
3821   asection *s, *os;
3822   asection **sections, **spp;
3823   unsigned int count;
3824   bfd_vma s_start;
3825   bfd_vma s_end;
3826   bfd_vma os_start;
3827   bfd_vma os_end;
3828   bfd_size_type amt;
3829
3830   if (bfd_count_sections (output_bfd) <= 1)
3831     return;
3832
3833   amt = bfd_count_sections (output_bfd) * sizeof (asection *);
3834   sections = xmalloc (amt);
3835
3836   /* Scan all sections in the output list.  */
3837   count = 0;
3838   for (s = output_bfd->sections; s != NULL; s = s->next)
3839     {
3840       /* Only consider loadable sections with real contents.  */
3841       if (IGNORE_SECTION (s) || s->size == 0)
3842         continue;
3843
3844       sections[count] = s;
3845       count++;
3846     }
3847   
3848   if (count <= 1)
3849     return;
3850
3851   qsort (sections, (size_t) count, sizeof (asection *),
3852          sort_sections_by_lma);
3853
3854   spp = sections;
3855   s = *spp++;
3856   s_start = bfd_section_lma (output_bfd, s);
3857   s_end = s_start + TO_ADDR (s->size) - 1;
3858   for (count--; count; count--)
3859     {
3860       /* We must check the sections' LMA addresses not their VMA
3861          addresses because overlay sections can have overlapping VMAs
3862          but they must have distinct LMAs.  */
3863       os = s;
3864       os_start = s_start; 
3865       os_end = s_end;
3866       s = *spp++;
3867       s_start = bfd_section_lma (output_bfd, s);
3868       s_end = s_start + TO_ADDR (s->size) - 1;
3869
3870       /* Look for an overlap.  */
3871       if (s_end >= os_start && s_start <= os_end)
3872         einfo (_("%X%P: section %s [%V -> %V] overlaps section %s [%V -> %V]\n"),
3873                s->name, s_start, s_end, os->name, os_start, os_end);
3874     }
3875
3876   free (sections);
3877 }
3878
3879 /* Make sure the new address is within the region.  We explicitly permit the
3880    current address to be at the exact end of the region when the address is
3881    non-zero, in case the region is at the end of addressable memory and the
3882    calculation wraps around.  */
3883
3884 static void
3885 os_region_check (lang_output_section_statement_type *os,
3886                  lang_memory_region_type *region,
3887                  etree_type *tree,
3888                  bfd_vma base)
3889 {
3890   if ((region->current < region->origin
3891        || (region->current - region->origin > region->length))
3892       && ((region->current != region->origin + region->length)
3893           || base == 0))
3894     {
3895       if (tree != NULL)
3896         {
3897           einfo (_("%X%P: address 0x%v of %B section %s"
3898                    " is not within region %s\n"),
3899                  region->current,
3900                  os->bfd_section->owner,
3901                  os->bfd_section->name,
3902                  region->name);
3903         }
3904       else
3905         {
3906           einfo (_("%X%P: region %s is full (%B section %s)\n"),
3907                  region->name,
3908                  os->bfd_section->owner,
3909                  os->bfd_section->name);
3910         }
3911       /* Reset the region pointer.  */
3912       region->current = region->origin;
3913     }
3914 }
3915
3916 /* Set the sizes for all the output sections.  */
3917
3918 static bfd_vma
3919 lang_size_sections_1
3920   (lang_statement_union_type *s,
3921    lang_output_section_statement_type *output_section_statement,
3922    lang_statement_union_type **prev,
3923    fill_type *fill,
3924    bfd_vma dot,
3925    bfd_boolean *relax,
3926    bfd_boolean check_regions)
3927 {
3928   /* Size up the sections from their constituent parts.  */
3929   for (; s != NULL; s = s->header.next)
3930     {
3931       switch (s->header.type)
3932         {
3933         case lang_output_section_statement_enum:
3934           {
3935             bfd_vma after;
3936             lang_output_section_statement_type *os;
3937
3938             os = &s->output_section_statement;
3939             if (os->bfd_section == NULL)
3940               /* This section was never actually created.  */
3941               break;
3942
3943             /* If this is a COFF shared library section, use the size and
3944                address from the input section.  FIXME: This is COFF
3945                specific; it would be cleaner if there were some other way
3946                to do this, but nothing simple comes to mind.  */
3947             if ((bfd_get_flavour (output_bfd) == bfd_target_ecoff_flavour
3948                  || bfd_get_flavour (output_bfd) == bfd_target_coff_flavour)
3949                 && (os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
3950               {
3951                 asection *input;
3952
3953                 if (os->children.head == NULL
3954                     || os->children.head->header.next != NULL
3955                     || (os->children.head->header.type
3956                         != lang_input_section_enum))
3957                   einfo (_("%P%X: Internal error on COFF shared library"
3958                            " section %s\n"), os->name);
3959
3960                 input = os->children.head->input_section.section;
3961                 bfd_set_section_vma (os->bfd_section->owner,
3962                                      os->bfd_section,
3963                                      bfd_section_vma (input->owner, input));
3964                 os->bfd_section->size = input->size;
3965                 break;
3966               }
3967
3968             if (bfd_is_abs_section (os->bfd_section))
3969               {
3970                 /* No matter what happens, an abs section starts at zero.  */
3971                 ASSERT (os->bfd_section->vma == 0);
3972               }
3973             else
3974               {
3975                 if (os->addr_tree == NULL)
3976                   {
3977                     /* No address specified for this section, get one
3978                        from the region specification.  */
3979                     if (os->region == NULL
3980                         || ((os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))
3981                             && os->region->name[0] == '*'
3982                             && strcmp (os->region->name,
3983                                        DEFAULT_MEMORY_REGION) == 0))
3984                       {
3985                         os->region = lang_memory_default (os->bfd_section);
3986                       }
3987
3988                     /* If a loadable section is using the default memory
3989                        region, and some non default memory regions were
3990                        defined, issue an error message.  */
3991                     if (!IGNORE_SECTION (os->bfd_section)
3992                         && ! link_info.relocatable
3993                         && check_regions
3994                         && strcmp (os->region->name,
3995                                    DEFAULT_MEMORY_REGION) == 0
3996                         && lang_memory_region_list != NULL
3997                         && (strcmp (lang_memory_region_list->name,
3998                                     DEFAULT_MEMORY_REGION) != 0
3999                             || lang_memory_region_list->next != NULL))
4000                       {
4001                         /* By default this is an error rather than just a
4002                            warning because if we allocate the section to the
4003                            default memory region we can end up creating an
4004                            excessively large binary, or even seg faulting when
4005                            attempting to perform a negative seek.  See
4006                            sources.redhat.com/ml/binutils/2003-04/msg00423.html
4007                            for an example of this.  This behaviour can be
4008                            overridden by the using the --no-check-sections
4009                            switch.  */
4010                         if (command_line.check_section_addresses)
4011                           einfo (_("%P%F: error: no memory region specified"
4012                                    " for loadable section `%s'\n"),
4013                                  bfd_get_section_name (output_bfd,
4014                                                        os->bfd_section));
4015                         else
4016                           einfo (_("%P: warning: no memory region specified"
4017                                    " for loadable section `%s'\n"),
4018                                  bfd_get_section_name (output_bfd,
4019                                                        os->bfd_section));
4020                       }
4021
4022                     dot = os->region->current;
4023
4024                     if (os->section_alignment == -1)
4025                       {
4026                         bfd_vma olddot;
4027
4028                         olddot = dot;
4029                         dot = align_power (dot,
4030                                            os->bfd_section->alignment_power);
4031
4032                         if (dot != olddot && config.warn_section_align)
4033                           einfo (_("%P: warning: changing start of section"
4034                                    " %s by %u bytes\n"),
4035                                  os->name, (unsigned int) (dot - olddot));
4036                       }
4037                   }
4038                 else
4039                   {
4040                     etree_value_type r;
4041
4042                     os->processed = -1;
4043                     r = exp_fold_tree (os->addr_tree,
4044                                        abs_output_section,
4045                                        lang_allocating_phase_enum,
4046                                        dot, &dot);
4047                     os->processed = 0;
4048
4049                     if (!r.valid_p)
4050                       einfo (_("%F%S: non constant or forward reference"
4051                                " address expression for section %s\n"),
4052                              os->name);
4053
4054                     dot = r.value + r.section->bfd_section->vma;
4055                   }
4056
4057                 /* The section starts here.
4058                    First, align to what the section needs.  */
4059
4060                 if (os->section_alignment != -1)
4061                   dot = align_power (dot, os->section_alignment);
4062
4063                 bfd_set_section_vma (0, os->bfd_section, dot);
4064
4065                 os->bfd_section->output_offset = 0;
4066               }
4067
4068             lang_size_sections_1 (os->children.head, os, &os->children.head,
4069                                   os->fill, dot, relax, check_regions);
4070
4071             /* Put the section within the requested block size, or
4072                align at the block boundary.  */
4073             after = ((os->bfd_section->vma
4074                       + TO_ADDR (os->bfd_section->size)
4075                       + os->block_value - 1)
4076                      & - (bfd_vma) os->block_value);
4077
4078             if (bfd_is_abs_section (os->bfd_section))
4079               ASSERT (after == os->bfd_section->vma);
4080             else
4081               os->bfd_section->size
4082                 = TO_SIZE (after - os->bfd_section->vma);
4083
4084             dot = os->bfd_section->vma;
4085             /* .tbss sections effectively have zero size.  */
4086             if ((os->bfd_section->flags & SEC_HAS_CONTENTS) != 0
4087                 || (os->bfd_section->flags & SEC_THREAD_LOCAL) == 0
4088                 || link_info.relocatable)
4089               dot += TO_ADDR (os->bfd_section->size);
4090
4091             os->processed = 1;
4092
4093             if (os->update_dot_tree != 0)
4094               exp_fold_tree (os->update_dot_tree, abs_output_section,
4095                              lang_allocating_phase_enum, dot, &dot);
4096
4097             /* Update dot in the region ?
4098                We only do this if the section is going to be allocated,
4099                since unallocated sections do not contribute to the region's
4100                overall size in memory.
4101
4102                If the SEC_NEVER_LOAD bit is not set, it will affect the
4103                addresses of sections after it. We have to update
4104                dot.  */
4105             if (os->region != NULL
4106                 && ((os->bfd_section->flags & SEC_NEVER_LOAD) == 0
4107                     || (os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))))
4108               {
4109                 os->region->current = dot;
4110
4111                 if (check_regions)
4112                   /* Make sure the new address is within the region.  */
4113                   os_region_check (os, os->region, os->addr_tree,
4114                                    os->bfd_section->vma);
4115
4116                 /* If there's no load address specified, use the run
4117                    region as the load region.  */
4118                 if (os->lma_region == NULL && os->load_base == NULL)
4119                   os->lma_region = os->region;
4120
4121                 if (os->lma_region != NULL && os->lma_region != os->region)
4122                   {
4123                     /* Set load_base, which will be handled later.  */
4124                     os->load_base = exp_intop (os->lma_region->current);
4125                     os->lma_region->current +=
4126                       TO_ADDR (os->bfd_section->size);
4127                     if (check_regions)
4128                       os_region_check (os, os->lma_region, NULL,
4129                                        os->bfd_section->lma);
4130                   }
4131               }
4132           }
4133           break;
4134
4135         case lang_constructors_statement_enum:
4136           dot = lang_size_sections_1 (constructor_list.head,
4137                                       output_section_statement,
4138                                       &s->wild_statement.children.head,
4139                                       fill, dot, relax, check_regions);
4140           break;
4141
4142         case lang_data_statement_enum:
4143           {
4144             unsigned int size = 0;
4145
4146             s->data_statement.output_vma =
4147               dot - output_section_statement->bfd_section->vma;
4148             s->data_statement.output_section =
4149               output_section_statement->bfd_section;
4150
4151             /* We might refer to provided symbols in the expression, and
4152                need to mark them as needed.  */
4153             exp_fold_tree (s->data_statement.exp, abs_output_section,
4154                            lang_allocating_phase_enum, dot, &dot);
4155
4156             switch (s->data_statement.type)
4157               {
4158               default:
4159                 abort ();
4160               case QUAD:
4161               case SQUAD:
4162                 size = QUAD_SIZE;
4163                 break;
4164               case LONG:
4165                 size = LONG_SIZE;
4166                 break;
4167               case SHORT:
4168                 size = SHORT_SIZE;
4169                 break;
4170               case BYTE:
4171                 size = BYTE_SIZE;
4172                 break;
4173               }
4174             if (size < TO_SIZE ((unsigned) 1))
4175               size = TO_SIZE ((unsigned) 1);
4176             dot += TO_ADDR (size);
4177             output_section_statement->bfd_section->size += size;
4178           }
4179           break;
4180
4181         case lang_reloc_statement_enum:
4182           {
4183             int size;
4184
4185             s->reloc_statement.output_vma =
4186               dot - output_section_statement->bfd_section->vma;
4187             s->reloc_statement.output_section =
4188               output_section_statement->bfd_section;
4189             size = bfd_get_reloc_size (s->reloc_statement.howto);
4190             dot += TO_ADDR (size);
4191             output_section_statement->bfd_section->size += size;
4192           }
4193           break;
4194
4195         case lang_wild_statement_enum:
4196
4197           dot = lang_size_sections_1 (s->wild_statement.children.head,
4198                                       output_section_statement,
4199                                       &s->wild_statement.children.head,
4200                                       fill, dot, relax, check_regions);
4201
4202           break;
4203
4204         case lang_object_symbols_statement_enum:
4205           link_info.create_object_symbols_section =
4206             output_section_statement->bfd_section;
4207           break;
4208         case lang_output_statement_enum:
4209         case lang_target_statement_enum:
4210           break;
4211         case lang_input_section_enum:
4212           {
4213             asection *i;
4214
4215             i = (*prev)->input_section.section;
4216             if (relax)
4217               {
4218                 bfd_boolean again;
4219
4220                 if (! bfd_relax_section (i->owner, i, &link_info, &again))
4221                   einfo (_("%P%F: can't relax section: %E\n"));
4222                 if (again)
4223                   *relax = TRUE;
4224               }
4225             dot = size_input_section (prev, output_section_statement,
4226                                       output_section_statement->fill, dot);
4227           }
4228           break;
4229         case lang_input_statement_enum:
4230           break;
4231         case lang_fill_statement_enum:
4232           s->fill_statement.output_section =
4233             output_section_statement->bfd_section;
4234
4235           fill = s->fill_statement.fill;
4236           break;
4237         case lang_assignment_statement_enum:
4238           {
4239             bfd_vma newdot = dot;
4240
4241             exp_fold_tree (s->assignment_statement.exp,
4242                            output_section_statement,
4243                            lang_allocating_phase_enum,
4244                            dot,
4245                            &newdot);
4246
4247             if (newdot != dot)
4248               {
4249                 if (output_section_statement == abs_output_section)
4250                   {
4251                     /* If we don't have an output section, then just adjust
4252                        the default memory address.  */
4253                     lang_memory_region_lookup (DEFAULT_MEMORY_REGION,
4254                                                FALSE)->current = newdot;
4255                   }
4256                 else
4257                   {
4258                     /* Insert a pad after this statement.  We can't
4259                        put the pad before when relaxing, in case the
4260                        assignment references dot.  */
4261                     insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
4262                                 output_section_statement->bfd_section, dot);
4263
4264                     /* Don't neuter the pad below when relaxing.  */
4265                     s = s->header.next;
4266                   }
4267
4268                 /* If dot is advanced, this implies that the section should
4269                    have space allocated to it, unless the user has explicitly
4270                    stated that the section should never be loaded.  */
4271                 if (!(output_section_statement->flags
4272                       & (SEC_NEVER_LOAD | SEC_ALLOC)))
4273                   output_section_statement->bfd_section->flags |= SEC_ALLOC;
4274
4275                 dot = newdot;
4276               }
4277           }
4278           break;
4279
4280         case lang_padding_statement_enum:
4281           /* If this is the first time lang_size_sections is called,
4282              we won't have any padding statements.  If this is the
4283              second or later passes when relaxing, we should allow
4284              padding to shrink.  If padding is needed on this pass, it
4285              will be added back in.  */
4286           s->padding_statement.size = 0;
4287
4288           /* Make sure output_offset is valid.  If relaxation shrinks
4289              the section and this pad isn't needed, it's possible to
4290              have output_offset larger than the final size of the
4291              section.  bfd_set_section_contents will complain even for
4292              a pad size of zero.  */
4293           s->padding_statement.output_offset
4294             = dot - output_section_statement->bfd_section->vma;
4295           break;
4296
4297         case lang_group_statement_enum:
4298           dot = lang_size_sections_1 (s->group_statement.children.head,
4299                                       output_section_statement,
4300                                       &s->group_statement.children.head,
4301                                       fill, dot, relax, check_regions);
4302           break;
4303
4304         default:
4305           FAIL ();
4306           break;
4307
4308           /* We can only get here when relaxing is turned on.  */
4309         case lang_address_statement_enum:
4310           break;
4311         }
4312       prev = &s->header.next;
4313     }
4314   return dot;
4315 }
4316
4317 bfd_vma
4318 lang_size_sections
4319   (lang_statement_union_type *s,
4320    lang_output_section_statement_type *output_section_statement,
4321    lang_statement_union_type **prev,
4322    fill_type *fill,
4323    bfd_vma dot,
4324    bfd_boolean *relax,
4325    bfd_boolean check_regions)
4326 {
4327   bfd_vma result;
4328
4329   /* Callers of exp_fold_tree need to increment this.  */
4330   lang_statement_iteration++;
4331
4332   exp_data_seg.phase = exp_dataseg_none;
4333   result = lang_size_sections_1 (s, output_section_statement, prev, fill,
4334                                  dot, relax, check_regions);
4335   if (exp_data_seg.phase == exp_dataseg_end_seen
4336       && link_info.relro && exp_data_seg.relro_end)
4337     {
4338       /* If DATA_SEGMENT_ALIGN DATA_SEGMENT_RELRO_END pair was seen, try
4339          to put exp_data_seg.relro on a (common) page boundary.  */
4340       bfd_vma old_min_base, relro_end, maxpage;
4341
4342       exp_data_seg.phase = exp_dataseg_relro_adjust;
4343       old_min_base = exp_data_seg.min_base;
4344       maxpage = exp_data_seg.maxpagesize;
4345       exp_data_seg.base += (-exp_data_seg.relro_end
4346                             & (exp_data_seg.pagesize - 1));
4347       /* Compute the expected PT_GNU_RELRO segment end.  */
4348       relro_end = (exp_data_seg.relro_end + exp_data_seg.pagesize - 1)
4349                   & ~(exp_data_seg.pagesize - 1);
4350       if (old_min_base + maxpage < exp_data_seg.base)
4351         {
4352           exp_data_seg.base -= maxpage;
4353           relro_end -= maxpage;
4354         }
4355       result = lang_size_sections_1 (s, output_section_statement, prev, fill,
4356                                      dot, relax, check_regions);
4357       if (exp_data_seg.relro_end > relro_end)
4358         {
4359           /* The alignment of sections between DATA_SEGMENT_ALIGN
4360              and DATA_SEGMENT_RELRO_END caused huge padding to be
4361              inserted at DATA_SEGMENT_RELRO_END.  Try some other base.  */
4362           asection *sec;
4363           unsigned int max_alignment_power = 0;
4364
4365           /* Find maximum alignment power of sections between
4366              DATA_SEGMENT_ALIGN and DATA_SEGMENT_RELRO_END.  */
4367           for (sec = output_bfd->sections; sec; sec = sec->next)
4368             if (sec->vma >= exp_data_seg.base
4369                 && sec->vma < exp_data_seg.relro_end
4370                 && sec->alignment_power > max_alignment_power)
4371               max_alignment_power = sec->alignment_power;
4372
4373           if (((bfd_vma) 1 << max_alignment_power) < exp_data_seg.pagesize)
4374             {
4375               if (exp_data_seg.base - (1 << max_alignment_power)
4376                   < old_min_base)
4377                 exp_data_seg.base += exp_data_seg.pagesize;
4378               exp_data_seg.base -= (1 << max_alignment_power);
4379               result = lang_size_sections_1 (s, output_section_statement,
4380                                              prev, fill, dot, relax,
4381                                              check_regions);
4382             }
4383         }
4384       link_info.relro_start = exp_data_seg.base;
4385       link_info.relro_end = exp_data_seg.relro_end;
4386     }
4387   else if (exp_data_seg.phase == exp_dataseg_end_seen)
4388     {
4389       /* If DATA_SEGMENT_ALIGN DATA_SEGMENT_END pair was seen, check whether
4390          a page could be saved in the data segment.  */
4391       bfd_vma first, last;
4392
4393       first = -exp_data_seg.base & (exp_data_seg.pagesize - 1);
4394       last = exp_data_seg.end & (exp_data_seg.pagesize - 1);
4395       if (first && last
4396           && ((exp_data_seg.base & ~(exp_data_seg.pagesize - 1))
4397               != (exp_data_seg.end & ~(exp_data_seg.pagesize - 1)))
4398           && first + last <= exp_data_seg.pagesize)
4399         {
4400           exp_data_seg.phase = exp_dataseg_adjust;
4401           lang_statement_iteration++;
4402           result = lang_size_sections_1 (s, output_section_statement, prev,
4403                                          fill, dot, relax, check_regions);
4404         }
4405     }
4406
4407   return result;
4408 }
4409
4410 /* Worker function for lang_do_assignments.  Recursiveness goes here.  */
4411
4412 static bfd_vma
4413 lang_do_assignments_1
4414   (lang_statement_union_type *s,
4415    lang_output_section_statement_type *output_section_statement,
4416    fill_type *fill,
4417    bfd_vma dot)
4418 {
4419   for (; s != NULL; s = s->header.next)
4420     {
4421       switch (s->header.type)
4422         {
4423         case lang_constructors_statement_enum:
4424           dot = lang_do_assignments_1 (constructor_list.head,
4425                                        output_section_statement,
4426                                        fill,
4427                                        dot);
4428           break;
4429
4430         case lang_output_section_statement_enum:
4431           {
4432             lang_output_section_statement_type *os;
4433
4434             os = &(s->output_section_statement);
4435             if (os->bfd_section != NULL)
4436               {
4437                 dot = os->bfd_section->vma;
4438                 lang_do_assignments_1 (os->children.head, os, os->fill, dot);
4439                 /* .tbss sections effectively have zero size.  */
4440                 if ((os->bfd_section->flags & SEC_HAS_CONTENTS) != 0
4441                     || (os->bfd_section->flags & SEC_THREAD_LOCAL) == 0
4442                     || link_info.relocatable)
4443                   dot += TO_ADDR (os->bfd_section->size);
4444               }
4445             if (os->load_base)
4446               {
4447                 /* If nothing has been placed into the output section then
4448                    it won't have a bfd_section.  */
4449                 if (os->bfd_section)
4450                   {
4451                     os->bfd_section->lma
4452                       = exp_get_abs_int (os->load_base, 0, "load base",
4453                                          lang_final_phase_enum);
4454                   }
4455               }
4456           }
4457           break;
4458         case lang_wild_statement_enum:
4459
4460           dot = lang_do_assignments_1 (s->wild_statement.children.head,
4461                                        output_section_statement,
4462                                        fill, dot);
4463
4464           break;
4465
4466         case lang_object_symbols_statement_enum:
4467         case lang_output_statement_enum:
4468         case lang_target_statement_enum:
4469           break;
4470         case lang_data_statement_enum:
4471           {
4472             etree_value_type value;
4473
4474             value = exp_fold_tree (s->data_statement.exp,
4475                                    abs_output_section,
4476                                    lang_final_phase_enum, dot, &dot);
4477             if (!value.valid_p)
4478               einfo (_("%F%P: invalid data statement\n"));
4479             s->data_statement.value
4480               = value.value + value.section->bfd_section->vma;
4481           }
4482           {
4483             unsigned int size;
4484             switch (s->data_statement.type)
4485               {
4486               default:
4487                 abort ();
4488               case QUAD:
4489               case SQUAD:
4490                 size = QUAD_SIZE;
4491                 break;
4492               case LONG:
4493                 size = LONG_SIZE;
4494                 break;
4495               case SHORT:
4496                 size = SHORT_SIZE;
4497                 break;
4498               case BYTE:
4499                 size = BYTE_SIZE;
4500                 break;
4501               }
4502             if (size < TO_SIZE ((unsigned) 1))
4503               size = TO_SIZE ((unsigned) 1);
4504             dot += TO_ADDR (size);
4505           }
4506           break;
4507
4508         case lang_reloc_statement_enum:
4509           {
4510             etree_value_type value;
4511
4512             value = exp_fold_tree (s->reloc_statement.addend_exp,
4513                                    abs_output_section,
4514                                    lang_final_phase_enum, dot, &dot);
4515             s->reloc_statement.addend_value = value.value;
4516             if (!value.valid_p)
4517               einfo (_("%F%P: invalid reloc statement\n"));
4518           }
4519           dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
4520           break;
4521
4522         case lang_input_section_enum:
4523           {
4524             asection *in = s->input_section.section;
4525
4526             if ((in->flags & SEC_EXCLUDE) == 0)
4527               dot += TO_ADDR (in->size);
4528           }
4529           break;
4530
4531         case lang_input_statement_enum:
4532           break;
4533         case lang_fill_statement_enum:
4534           fill = s->fill_statement.fill;
4535           break;
4536         case lang_assignment_statement_enum:
4537           {
4538             exp_fold_tree (s->assignment_statement.exp,
4539                            output_section_statement,
4540                            lang_final_phase_enum,
4541                            dot,
4542                            &dot);
4543           }
4544
4545           break;
4546         case lang_padding_statement_enum:
4547           dot += TO_ADDR (s->padding_statement.size);
4548           break;
4549
4550         case lang_group_statement_enum:
4551           dot = lang_do_assignments_1 (s->group_statement.children.head,
4552                                        output_section_statement,
4553                                        fill, dot);
4554
4555           break;
4556
4557         default:
4558           FAIL ();
4559           break;
4560         case lang_address_statement_enum:
4561           break;
4562         }
4563
4564     }
4565   return dot;
4566 }
4567
4568 void
4569 lang_do_assignments
4570   (lang_statement_union_type *s,
4571    lang_output_section_statement_type *output_section_statement,
4572    fill_type *fill,
4573    bfd_vma dot)
4574 {
4575   /* Callers of exp_fold_tree need to increment this.  */
4576   lang_statement_iteration++;
4577   lang_do_assignments_1 (s, output_section_statement, fill, dot);
4578 }
4579
4580 /* Fix any .startof. or .sizeof. symbols.  When the assemblers see the
4581    operator .startof. (section_name), it produces an undefined symbol
4582    .startof.section_name.  Similarly, when it sees
4583    .sizeof. (section_name), it produces an undefined symbol
4584    .sizeof.section_name.  For all the output sections, we look for
4585    such symbols, and set them to the correct value.  */
4586
4587 static void
4588 lang_set_startof (void)
4589 {
4590   asection *s;
4591
4592   if (link_info.relocatable)
4593     return;
4594
4595   for (s = output_bfd->sections; s != NULL; s = s->next)
4596     {
4597       const char *secname;
4598       char *buf;
4599       struct bfd_link_hash_entry *h;
4600
4601       secname = bfd_get_section_name (output_bfd, s);
4602       buf = xmalloc (10 + strlen (secname));
4603
4604       sprintf (buf, ".startof.%s", secname);
4605       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
4606       if (h != NULL && h->type == bfd_link_hash_undefined)
4607         {
4608           h->type = bfd_link_hash_defined;
4609           h->u.def.value = bfd_get_section_vma (output_bfd, s);
4610           h->u.def.section = bfd_abs_section_ptr;
4611         }
4612
4613       sprintf (buf, ".sizeof.%s", secname);
4614       h = bfd_link_hash_lookup (link_info.hash, buf, FALSE, FALSE, TRUE);
4615       if (h != NULL && h->type == bfd_link_hash_undefined)
4616         {
4617           h->type = bfd_link_hash_defined;
4618           h->u.def.value = TO_ADDR (s->size);
4619           h->u.def.section = bfd_abs_section_ptr;
4620         }
4621
4622       free (buf);
4623     }
4624 }
4625
4626 static void
4627 lang_finish (void)
4628 {
4629   struct bfd_link_hash_entry *h;
4630   bfd_boolean warn;
4631
4632   if (link_info.relocatable || link_info.shared)
4633     warn = FALSE;
4634   else
4635     warn = TRUE;
4636
4637   if (entry_symbol.name == NULL)
4638     {
4639       /* No entry has been specified.  Look for start, but don't warn
4640          if we don't find it.  */
4641       entry_symbol.name = "start";
4642       warn = FALSE;
4643     }
4644
4645   h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
4646                             FALSE, FALSE, TRUE);
4647   if (h != NULL
4648       && (h->type == bfd_link_hash_defined
4649           || h->type == bfd_link_hash_defweak)
4650       && h->u.def.section->output_section != NULL)
4651     {
4652       bfd_vma val;
4653
4654       val = (h->u.def.value
4655              + bfd_get_section_vma (output_bfd,
4656                                     h->u.def.section->output_section)
4657              + h->u.def.section->output_offset);
4658       if (! bfd_set_start_address (output_bfd, val))
4659         einfo (_("%P%F:%s: can't set start address\n"), entry_symbol.name);
4660     }
4661   else
4662     {
4663       bfd_vma val;
4664       const char *send;
4665
4666       /* We couldn't find the entry symbol.  Try parsing it as a
4667          number.  */
4668       val = bfd_scan_vma (entry_symbol.name, &send, 0);
4669       if (*send == '\0')
4670         {
4671           if (! bfd_set_start_address (output_bfd, val))
4672             einfo (_("%P%F: can't set start address\n"));
4673         }
4674       else
4675         {
4676           asection *ts;
4677
4678           /* Can't find the entry symbol, and it's not a number.  Use
4679              the first address in the text section.  */
4680           ts = bfd_get_section_by_name (output_bfd, entry_section);
4681           if (ts != NULL)
4682             {
4683               if (warn)
4684                 einfo (_("%P: warning: cannot find entry symbol %s;"
4685                          " defaulting to %V\n"),
4686                        entry_symbol.name,
4687                        bfd_get_section_vma (output_bfd, ts));
4688               if (! bfd_set_start_address (output_bfd,
4689                                            bfd_get_section_vma (output_bfd,
4690                                                                 ts)))
4691                 einfo (_("%P%F: can't set start address\n"));
4692             }
4693           else
4694             {
4695               if (warn)
4696                 einfo (_("%P: warning: cannot find entry symbol %s;"
4697                          " not setting start address\n"),
4698                        entry_symbol.name);
4699             }
4700         }
4701     }
4702
4703   /* Don't bfd_hash_table_free (&lang_definedness_table);
4704      map file output may result in a call of lang_track_definedness.  */
4705 }
4706
4707 /* This is a small function used when we want to ignore errors from
4708    BFD.  */
4709
4710 static void
4711 ignore_bfd_errors (const char *s ATTRIBUTE_UNUSED, ...)
4712 {
4713   /* Don't do anything.  */
4714 }
4715
4716 /* Check that the architecture of all the input files is compatible
4717    with the output file.  Also call the backend to let it do any
4718    other checking that is needed.  */
4719
4720 static void
4721 lang_check (void)
4722 {
4723   lang_statement_union_type *file;
4724   bfd *input_bfd;
4725   const bfd_arch_info_type *compatible;
4726
4727   for (file = file_chain.head; file != NULL; file = file->input_statement.next)
4728     {
4729       input_bfd = file->input_statement.the_bfd;
4730       compatible
4731         = bfd_arch_get_compatible (input_bfd, output_bfd,
4732                                    command_line.accept_unknown_input_arch);
4733
4734       /* In general it is not possible to perform a relocatable
4735          link between differing object formats when the input
4736          file has relocations, because the relocations in the
4737          input format may not have equivalent representations in
4738          the output format (and besides BFD does not translate
4739          relocs for other link purposes than a final link).  */
4740       if ((link_info.relocatable || link_info.emitrelocations)
4741           && (compatible == NULL
4742               || bfd_get_flavour (input_bfd) != bfd_get_flavour (output_bfd))
4743           && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
4744         {
4745           einfo (_("%P%F: Relocatable linking with relocations from"
4746                    " format %s (%B) to format %s (%B) is not supported\n"),
4747                  bfd_get_target (input_bfd), input_bfd,
4748                  bfd_get_target (output_bfd), output_bfd);
4749           /* einfo with %F exits.  */
4750         }
4751
4752       if (compatible == NULL)
4753         {
4754           if (command_line.warn_mismatch)
4755             einfo (_("%P: warning: %s architecture of input file `%B'"
4756                      " is incompatible with %s output\n"),
4757                    bfd_printable_name (input_bfd), input_bfd,
4758                    bfd_printable_name (output_bfd));
4759         }
4760       else if (bfd_count_sections (input_bfd))
4761         {
4762           /* If the input bfd has no contents, it shouldn't set the
4763              private data of the output bfd.  */
4764
4765           bfd_error_handler_type pfn = NULL;
4766
4767           /* If we aren't supposed to warn about mismatched input
4768              files, temporarily set the BFD error handler to a
4769              function which will do nothing.  We still want to call
4770              bfd_merge_private_bfd_data, since it may set up
4771              information which is needed in the output file.  */
4772           if (! command_line.warn_mismatch)
4773             pfn = bfd_set_error_handler (ignore_bfd_errors);
4774           if (! bfd_merge_private_bfd_data (input_bfd, output_bfd))
4775             {
4776               if (command_line.warn_mismatch)
4777                 einfo (_("%P%X: failed to merge target specific data"
4778                          " of file %B\n"), input_bfd);
4779             }
4780           if (! command_line.warn_mismatch)
4781             bfd_set_error_handler (pfn);
4782         }
4783     }
4784 }
4785
4786 /* Look through all the global common symbols and attach them to the
4787    correct section.  The -sort-common command line switch may be used
4788    to roughly sort the entries by size.  */
4789
4790 static void
4791 lang_common (void)
4792 {
4793   if (command_line.inhibit_common_definition)
4794     return;
4795   if (link_info.relocatable
4796       && ! command_line.force_common_definition)
4797     return;
4798
4799   if (! config.sort_common)
4800     bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
4801   else
4802     {
4803       int power;
4804
4805       for (power = 4; power >= 0; power--)
4806         bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
4807     }
4808 }
4809
4810 /* Place one common symbol in the correct section.  */
4811
4812 static bfd_boolean
4813 lang_one_common (struct bfd_link_hash_entry *h, void *info)
4814 {
4815   unsigned int power_of_two;
4816   bfd_vma size;
4817   asection *section;
4818
4819   if (h->type != bfd_link_hash_common)
4820     return TRUE;
4821
4822   size = h->u.c.size;
4823   power_of_two = h->u.c.p->alignment_power;
4824
4825   if (config.sort_common
4826       && power_of_two < (unsigned int) *(int *) info)
4827     return TRUE;
4828
4829   section = h->u.c.p->section;
4830
4831   /* Increase the size of the section to align the common sym.  */
4832   section->size += ((bfd_vma) 1 << (power_of_two + opb_shift)) - 1;
4833   section->size &= (- (bfd_vma) 1 << (power_of_two + opb_shift));
4834
4835   /* Adjust the alignment if necessary.  */
4836   if (power_of_two > section->alignment_power)
4837     section->alignment_power = power_of_two;
4838
4839   /* Change the symbol from common to defined.  */
4840   h->type = bfd_link_hash_defined;
4841   h->u.def.section = section;
4842   h->u.def.value = section->size;
4843
4844   /* Increase the size of the section.  */
4845   section->size += size;
4846
4847   /* Make sure the section is allocated in memory, and make sure that
4848      it is no longer a common section.  */
4849   section->flags |= SEC_ALLOC;
4850   section->flags &= ~SEC_IS_COMMON;
4851
4852   if (config.map_file != NULL)
4853     {
4854       static bfd_boolean header_printed;
4855       int len;
4856       char *name;
4857       char buf[50];
4858
4859       if (! header_printed)
4860         {
4861           minfo (_("\nAllocating common symbols\n"));
4862           minfo (_("Common symbol       size              file\n\n"));
4863           header_printed = TRUE;
4864         }
4865
4866       name = demangle (h->root.string);
4867       minfo ("%s", name);
4868       len = strlen (name);
4869       free (name);
4870
4871       if (len >= 19)
4872         {
4873           print_nl ();
4874           len = 0;
4875         }
4876       while (len < 20)
4877         {
4878           print_space ();
4879           ++len;
4880         }
4881
4882       minfo ("0x");
4883       if (size <= 0xffffffff)
4884         sprintf (buf, "%lx", (unsigned long) size);
4885       else
4886         sprintf_vma (buf, size);
4887       minfo ("%s", buf);
4888       len = strlen (buf);
4889
4890       while (len < 16)
4891         {
4892           print_space ();
4893           ++len;
4894         }
4895
4896       minfo ("%B\n", section->owner);
4897     }
4898
4899   return TRUE;
4900 }
4901
4902 /* Run through the input files and ensure that every input section has
4903    somewhere to go.  If one is found without a destination then create
4904    an input request and place it into the statement tree.  */
4905
4906 static void
4907 lang_place_orphans (void)
4908 {
4909   LANG_FOR_EACH_INPUT_STATEMENT (file)
4910     {
4911       asection *s;
4912
4913       for (s = file->the_bfd->sections; s != NULL; s = s->next)
4914         {
4915           if (s->output_section == NULL)
4916             {
4917               /* This section of the file is not attached, root
4918                  around for a sensible place for it to go.  */
4919
4920               if (file->just_syms_flag)
4921                 bfd_link_just_syms (file->the_bfd, s, &link_info);
4922               else if ((s->flags & SEC_EXCLUDE) != 0)
4923                 s->output_section = bfd_abs_section_ptr;
4924               else if (strcmp (s->name, "COMMON") == 0)
4925                 {
4926                   /* This is a lonely common section which must have
4927                      come from an archive.  We attach to the section
4928                      with the wildcard.  */
4929                   if (! link_info.relocatable
4930                       || command_line.force_common_definition)
4931                     {
4932                       if (default_common_section == NULL)
4933                         {
4934                           default_common_section =
4935                             lang_output_section_statement_lookup (".bss");
4936
4937                         }
4938                       lang_add_section (&default_common_section->children, s,
4939                                         default_common_section, file);
4940                     }
4941                 }
4942               else if (ldemul_place_orphan (file, s))
4943                 ;
4944               else
4945                 {
4946                   lang_output_section_statement_type *os;
4947
4948                   os = lang_output_section_statement_lookup (s->name);
4949                   lang_add_section (&os->children, s, os, file);
4950                 }
4951             }
4952         }
4953     }
4954 }
4955
4956 void
4957 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
4958 {
4959   flagword *ptr_flags;
4960
4961   ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
4962   while (*flags)
4963     {
4964       switch (*flags)
4965         {
4966         case 'A': case 'a':
4967           *ptr_flags |= SEC_ALLOC;
4968           break;
4969
4970         case 'R': case 'r':
4971           *ptr_flags |= SEC_READONLY;
4972           break;
4973
4974         case 'W': case 'w':
4975           *ptr_flags |= SEC_DATA;
4976           break;
4977
4978         case 'X': case 'x':
4979           *ptr_flags |= SEC_CODE;
4980           break;
4981
4982         case 'L': case 'l':
4983         case 'I': case 'i':
4984           *ptr_flags |= SEC_LOAD;
4985           break;
4986
4987         default:
4988           einfo (_("%P%F: invalid syntax in flags\n"));
4989           break;
4990         }
4991       flags++;
4992     }
4993 }
4994
4995 /* Call a function on each input file.  This function will be called
4996    on an archive, but not on the elements.  */
4997
4998 void
4999 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
5000 {
5001   lang_input_statement_type *f;
5002
5003   for (f = (lang_input_statement_type *) input_file_chain.head;
5004        f != NULL;
5005        f = (lang_input_statement_type *) f->next_real_file)
5006     func (f);
5007 }
5008
5009 /* Call a function on each file.  The function will be called on all
5010    the elements of an archive which are included in the link, but will
5011    not be called on the archive file itself.  */
5012
5013 void
5014 lang_for_each_file (void (*func) (lang_input_statement_type *))
5015 {
5016   LANG_FOR_EACH_INPUT_STATEMENT (f)
5017     {
5018       func (f);
5019     }
5020 }
5021
5022 void
5023 ldlang_add_file (lang_input_statement_type *entry)
5024 {
5025   bfd **pp;
5026
5027   lang_statement_append (&file_chain,
5028                          (lang_statement_union_type *) entry,
5029                          &entry->next);
5030
5031   /* The BFD linker needs to have a list of all input BFDs involved in
5032      a link.  */
5033   ASSERT (entry->the_bfd->link_next == NULL);
5034   ASSERT (entry->the_bfd != output_bfd);
5035   for (pp = &link_info.input_bfds; *pp != NULL; pp = &(*pp)->link_next)
5036     ;
5037   *pp = entry->the_bfd;
5038   entry->the_bfd->usrdata = entry;
5039   bfd_set_gp_size (entry->the_bfd, g_switch_value);
5040
5041   /* Look through the sections and check for any which should not be
5042      included in the link.  We need to do this now, so that we can
5043      notice when the backend linker tries to report multiple
5044      definition errors for symbols which are in sections we aren't
5045      going to link.  FIXME: It might be better to entirely ignore
5046      symbols which are defined in sections which are going to be
5047      discarded.  This would require modifying the backend linker for
5048      each backend which might set the SEC_LINK_ONCE flag.  If we do
5049      this, we should probably handle SEC_EXCLUDE in the same way.  */
5050
5051   bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
5052 }
5053
5054 void
5055 lang_add_output (const char *name, int from_script)
5056 {
5057   /* Make -o on command line override OUTPUT in script.  */
5058   if (!had_output_filename || !from_script)
5059     {
5060       output_filename = name;
5061       had_output_filename = TRUE;
5062     }
5063 }
5064
5065 static lang_output_section_statement_type *current_section;
5066
5067 static int
5068 topower (int x)
5069 {
5070   unsigned int i = 1;
5071   int l;
5072
5073   if (x < 0)
5074     return -1;
5075
5076   for (l = 0; l < 32; l++)
5077     {
5078       if (i >= (unsigned int) x)
5079         return l;
5080       i <<= 1;
5081     }
5082
5083   return 0;
5084 }
5085
5086 lang_output_section_statement_type *
5087 lang_enter_output_section_statement (const char *output_section_statement_name,
5088                                      etree_type *address_exp,
5089                                      enum section_type sectype,
5090                                      etree_type *align,
5091                                      etree_type *subalign,
5092                                      etree_type *ebase,
5093                                      int constraint)
5094 {
5095   lang_output_section_statement_type *os;
5096
5097   current_section =
5098    os =
5099     lang_output_section_statement_lookup_1 (output_section_statement_name,
5100                                             constraint);
5101
5102   /* Make next things chain into subchain of this.  */
5103
5104   if (os->addr_tree == NULL)
5105     {
5106       os->addr_tree = address_exp;
5107     }
5108   os->sectype = sectype;
5109   if (sectype != noload_section)
5110     os->flags = SEC_NO_FLAGS;
5111   else
5112     os->flags = SEC_NEVER_LOAD;
5113   os->block_value = 1;
5114   stat_ptr = &os->children;
5115
5116   os->subsection_alignment =
5117     topower (exp_get_value_int (subalign, -1, "subsection alignment", 0));
5118   os->section_alignment =
5119     topower (exp_get_value_int (align, -1, "section alignment", 0));
5120
5121   os->load_base = ebase;
5122   return os;
5123 }
5124
5125 void
5126 lang_final (void)
5127 {
5128   lang_output_statement_type *new =
5129     new_stat (lang_output_statement, stat_ptr);
5130
5131   new->name = output_filename;
5132 }
5133
5134 /* Reset the current counters in the regions.  */
5135
5136 void
5137 lang_reset_memory_regions (void)
5138 {
5139   lang_memory_region_type *p = lang_memory_region_list;
5140   asection *o;
5141
5142   for (p = lang_memory_region_list; p != NULL; p = p->next)
5143     {
5144       p->old_length = (bfd_size_type) (p->current - p->origin);
5145       p->current = p->origin;
5146     }
5147
5148   for (o = output_bfd->sections; o != NULL; o = o->next)
5149     {
5150       /* Save the last size for possible use by bfd_relax_section.  */
5151       o->rawsize = o->size;
5152       o->size = 0;
5153     }
5154 }
5155
5156 /* Worker for lang_gc_sections_1.  */
5157
5158 static void
5159 gc_section_callback (lang_wild_statement_type *ptr,
5160                      struct wildcard_list *sec ATTRIBUTE_UNUSED,
5161                      asection *section,
5162                      lang_input_statement_type *file ATTRIBUTE_UNUSED,
5163                      void *data ATTRIBUTE_UNUSED)
5164 {
5165   /* If the wild pattern was marked KEEP, the member sections
5166      should be as well.  */
5167   if (ptr->keep_sections)
5168     section->flags |= SEC_KEEP;
5169 }
5170
5171 /* Iterate over sections marking them against GC.  */
5172
5173 static void
5174 lang_gc_sections_1 (lang_statement_union_type *s)
5175 {
5176   for (; s != NULL; s = s->header.next)
5177     {
5178       switch (s->header.type)
5179         {
5180         case lang_wild_statement_enum:
5181           walk_wild (&s->wild_statement, gc_section_callback, NULL);
5182           break;
5183         case lang_constructors_statement_enum:
5184           lang_gc_sections_1 (constructor_list.head);
5185           break;
5186         case lang_output_section_statement_enum:
5187           lang_gc_sections_1 (s->output_section_statement.children.head);
5188           break;
5189         case lang_group_statement_enum:
5190           lang_gc_sections_1 (s->group_statement.children.head);
5191           break;
5192         default:
5193           break;
5194         }
5195     }
5196 }
5197
5198 static void
5199 lang_gc_sections (void)
5200 {
5201   struct bfd_link_hash_entry *h;
5202   ldlang_undef_chain_list_type *ulist;
5203
5204   /* Keep all sections so marked in the link script.  */
5205
5206   lang_gc_sections_1 (statement_list.head);
5207
5208   /* Keep all sections containing symbols undefined on the command-line,
5209      and the section containing the entry symbol.  */
5210
5211   for (ulist = link_info.gc_sym_list; ulist; ulist = ulist->next)
5212     {
5213       h = bfd_link_hash_lookup (link_info.hash, ulist->name,
5214                                 FALSE, FALSE, FALSE);
5215
5216       if (h != NULL
5217           && (h->type == bfd_link_hash_defined
5218               || h->type == bfd_link_hash_defweak)
5219           && ! bfd_is_abs_section (h->u.def.section))
5220         {
5221           h->u.def.section->flags |= SEC_KEEP;
5222         }
5223     }
5224
5225   /* SEC_EXCLUDE is ignored when doing a relocatable link, except in
5226      the special case of debug info.  (See bfd/stabs.c)
5227      Twiddle the flag here, to simplify later linker code.  */
5228   if (link_info.relocatable)
5229     {
5230       LANG_FOR_EACH_INPUT_STATEMENT (f)
5231         {
5232           asection *sec;
5233           for (sec = f->the_bfd->sections; sec != NULL; sec = sec->next)
5234             if ((sec->flags & SEC_DEBUGGING) == 0)
5235               sec->flags &= ~SEC_EXCLUDE;
5236         }
5237     }
5238
5239   if (link_info.gc_sections)
5240     bfd_gc_sections (output_bfd, &link_info);
5241 }
5242
5243 static void
5244 lang_mark_used_section (void)
5245 {
5246   unsigned int gc_sections = link_info.gc_sections;
5247
5248   link_info.gc_sections = 0;
5249   bfd_gc_sections (output_bfd, &link_info);
5250   link_info.gc_sections = gc_sections;
5251 }
5252
5253 void
5254 lang_process (void)
5255 {
5256   current_target = default_target;
5257
5258   /* Open the output file.  */
5259   lang_for_each_statement (ldlang_open_output);
5260   init_opb ();
5261
5262   ldemul_create_output_section_statements ();
5263
5264   /* Add to the hash table all undefineds on the command line.  */
5265   lang_place_undefineds ();
5266
5267   if (!bfd_section_already_linked_table_init ())
5268     einfo (_("%P%F: Failed to create hash table\n"));
5269
5270   /* Create a bfd for each input file.  */
5271   current_target = default_target;
5272   open_input_bfds (statement_list.head, FALSE);
5273
5274   link_info.gc_sym_list = &entry_symbol;
5275   if (entry_symbol.name == NULL)
5276     link_info.gc_sym_list = ldlang_undef_chain_list_head;
5277
5278   ldemul_after_open ();
5279
5280   bfd_section_already_linked_table_free ();
5281
5282   /* Make sure that we're not mixing architectures.  We call this
5283      after all the input files have been opened, but before we do any
5284      other processing, so that any operations merge_private_bfd_data
5285      does on the output file will be known during the rest of the
5286      link.  */
5287   lang_check ();
5288
5289   /* Handle .exports instead of a version script if we're told to do so.  */
5290   if (command_line.version_exports_section)
5291     lang_do_version_exports_section ();
5292
5293   /* Build all sets based on the information gathered from the input
5294      files.  */
5295   ldctor_build_sets ();
5296
5297   /* Remove unreferenced sections if asked to.  */
5298   lang_gc_sections ();
5299
5300   /* Size up the common data.  */
5301   lang_common ();
5302
5303   /* Update wild statements.  */
5304   update_wild_statements (statement_list.head);
5305
5306   /* Run through the contours of the script and attach input sections
5307      to the correct output sections.  */
5308   map_input_to_output_sections (statement_list.head, NULL, NULL);
5309
5310   /* Find any sections not attached explicitly and handle them.  */
5311   lang_place_orphans ();
5312
5313   if (! link_info.relocatable)
5314     {
5315       asection *found;
5316
5317       /* Merge SEC_MERGE sections.  This has to be done after GC of
5318          sections, so that GCed sections are not merged, but before
5319          assigning dynamic symbols, since removing whole input sections
5320          is hard then.  */
5321       bfd_merge_sections (output_bfd, &link_info);
5322
5323       /* Look for a text section and set the readonly attribute in it.  */
5324       found = bfd_get_section_by_name (output_bfd, ".text");
5325
5326       if (found != NULL)
5327         {
5328           if (config.text_read_only)
5329             found->flags |= SEC_READONLY;
5330           else
5331             found->flags &= ~SEC_READONLY;
5332         }
5333     }
5334
5335   /* Do anything special before sizing sections.  This is where ELF
5336      and other back-ends size dynamic sections.  */
5337   ldemul_before_allocation ();
5338
5339   /* We must record the program headers before we try to fix the
5340      section positions, since they will affect SIZEOF_HEADERS.  */
5341   lang_record_phdrs ();
5342
5343   /* Size up the sections.  */
5344   lang_size_sections (statement_list.head, abs_output_section,
5345                       &statement_list.head, 0, 0, NULL,
5346                       command_line.relax ? FALSE : TRUE);
5347
5348   /* Now run around and relax if we can.  */
5349   if (command_line.relax)
5350     {
5351       /* Keep relaxing until bfd_relax_section gives up.  */
5352       bfd_boolean relax_again;
5353
5354       do
5355         {
5356           relax_again = FALSE;
5357
5358           /* Note: pe-dll.c does something like this also.  If you find
5359              you need to change this code, you probably need to change
5360              pe-dll.c also.  DJ  */
5361
5362           /* Do all the assignments with our current guesses as to
5363              section sizes.  */
5364           lang_do_assignments (statement_list.head, abs_output_section,
5365                                NULL, 0);
5366
5367           /* We must do this after lang_do_assignments, because it uses
5368              size.  */
5369           lang_reset_memory_regions ();
5370
5371           /* Perform another relax pass - this time we know where the
5372              globals are, so can make a better guess.  */
5373           lang_size_sections (statement_list.head, abs_output_section,
5374                               &statement_list.head, 0, 0, &relax_again, FALSE);
5375
5376           /* If the normal relax is done and the relax finalize pass
5377              is not performed yet, we perform another relax pass.  */
5378           if (!relax_again && link_info.need_relax_finalize)
5379             {
5380               link_info.need_relax_finalize = FALSE;
5381               relax_again = TRUE;
5382             }
5383         }
5384       while (relax_again);
5385
5386       /* Final extra sizing to report errors.  */
5387       lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
5388       lang_reset_memory_regions ();
5389       lang_size_sections (statement_list.head, abs_output_section,
5390                           &statement_list.head, 0, 0, NULL, TRUE);
5391     }
5392
5393   /* See if anything special should be done now we know how big
5394      everything is.  */
5395   ldemul_after_allocation ();
5396
5397   /* Fix any .startof. or .sizeof. symbols.  */
5398   lang_set_startof ();
5399
5400   /* Do all the assignments, now that we know the final resting places
5401      of all the symbols.  */
5402
5403   lang_do_assignments (statement_list.head, abs_output_section, NULL, 0);
5404
5405   /* Make sure that the section addresses make sense.  */
5406   if (! link_info.relocatable
5407       && command_line.check_section_addresses)
5408     lang_check_section_addresses ();
5409
5410   /* Final stuffs.  */
5411   lang_mark_used_section ();
5412   ldemul_finish ();
5413   lang_finish ();
5414 }
5415
5416 /* EXPORTED TO YACC */
5417
5418 void
5419 lang_add_wild (struct wildcard_spec *filespec,
5420                struct wildcard_list *section_list,
5421                bfd_boolean keep_sections)
5422 {
5423   struct wildcard_list *curr, *next;
5424   lang_wild_statement_type *new;
5425
5426   /* Reverse the list as the parser puts it back to front.  */
5427   for (curr = section_list, section_list = NULL;
5428        curr != NULL;
5429        section_list = curr, curr = next)
5430     {
5431       if (curr->spec.name != NULL && strcmp (curr->spec.name, "COMMON") == 0)
5432         placed_commons = TRUE;
5433
5434       next = curr->next;
5435       curr->next = section_list;
5436     }
5437
5438   if (filespec != NULL && filespec->name != NULL)
5439     {
5440       if (strcmp (filespec->name, "*") == 0)
5441         filespec->name = NULL;
5442       else if (! wildcardp (filespec->name))
5443         lang_has_input_file = TRUE;
5444     }
5445
5446   new = new_stat (lang_wild_statement, stat_ptr);
5447   new->filename = NULL;
5448   new->filenames_sorted = FALSE;
5449   if (filespec != NULL)
5450     {
5451       new->filename = filespec->name;
5452       new->filenames_sorted = filespec->sorted == by_name;
5453     }
5454   new->section_list = section_list;
5455   new->keep_sections = keep_sections;
5456   lang_list_init (&new->children);
5457   analyze_walk_wild_section_handler (new);
5458 }
5459
5460 void
5461 lang_section_start (const char *name, etree_type *address,
5462                     const segment_type *segment)
5463 {
5464   lang_address_statement_type *ad;
5465
5466   ad = new_stat (lang_address_statement, stat_ptr);
5467   ad->section_name = name;
5468   ad->address = address;
5469   ad->segment = segment;
5470 }
5471
5472 /* Set the start symbol to NAME.  CMDLINE is nonzero if this is called
5473    because of a -e argument on the command line, or zero if this is
5474    called by ENTRY in a linker script.  Command line arguments take
5475    precedence.  */
5476
5477 void
5478 lang_add_entry (const char *name, bfd_boolean cmdline)
5479 {
5480   if (entry_symbol.name == NULL
5481       || cmdline
5482       || ! entry_from_cmdline)
5483     {
5484       entry_symbol.name = name;
5485       entry_from_cmdline = cmdline;
5486     }
5487 }
5488
5489 void
5490 lang_add_target (const char *name)
5491 {
5492   lang_target_statement_type *new = new_stat (lang_target_statement,
5493                                               stat_ptr);
5494
5495   new->target = name;
5496
5497 }
5498
5499 void
5500 lang_add_map (const char *name)
5501 {
5502   while (*name)
5503     {
5504       switch (*name)
5505         {
5506         case 'F':
5507           map_option_f = TRUE;
5508           break;
5509         }
5510       name++;
5511     }
5512 }
5513
5514 void
5515 lang_add_fill (fill_type *fill)
5516 {
5517   lang_fill_statement_type *new = new_stat (lang_fill_statement,
5518                                             stat_ptr);
5519
5520   new->fill = fill;
5521 }
5522
5523 void
5524 lang_add_data (int type, union etree_union *exp)
5525 {
5526
5527   lang_data_statement_type *new = new_stat (lang_data_statement,
5528                                             stat_ptr);
5529
5530   new->exp = exp;
5531   new->type = type;
5532
5533 }
5534
5535 /* Create a new reloc statement.  RELOC is the BFD relocation type to
5536    generate.  HOWTO is the corresponding howto structure (we could
5537    look this up, but the caller has already done so).  SECTION is the
5538    section to generate a reloc against, or NAME is the name of the
5539    symbol to generate a reloc against.  Exactly one of SECTION and
5540    NAME must be NULL.  ADDEND is an expression for the addend.  */
5541
5542 void
5543 lang_add_reloc (bfd_reloc_code_real_type reloc,
5544                 reloc_howto_type *howto,
5545                 asection *section,
5546                 const char *name,
5547                 union etree_union *addend)
5548 {
5549   lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
5550
5551   p->reloc = reloc;
5552   p->howto = howto;
5553   p->section = section;
5554   p->name = name;
5555   p->addend_exp = addend;
5556
5557   p->addend_value = 0;
5558   p->output_section = NULL;
5559   p->output_vma = 0;
5560 }
5561
5562 lang_assignment_statement_type *
5563 lang_add_assignment (etree_type *exp)
5564 {
5565   lang_assignment_statement_type *new = new_stat (lang_assignment_statement,
5566                                                   stat_ptr);
5567
5568   new->exp = exp;
5569   return new;
5570 }
5571
5572 void
5573 lang_add_attribute (enum statement_enum attribute)
5574 {
5575   new_statement (attribute, sizeof (lang_statement_union_type), stat_ptr);
5576 }
5577
5578 void
5579 lang_startup (const char *name)
5580 {
5581   if (startup_file != NULL)
5582     {
5583       einfo (_("%P%Fmultiple STARTUP files\n"));
5584     }
5585   first_file->filename = name;
5586   first_file->local_sym_name = name;
5587   first_file->real = TRUE;
5588
5589   startup_file = name;
5590 }
5591
5592 void
5593 lang_float (bfd_boolean maybe)
5594 {
5595   lang_float_flag = maybe;
5596 }
5597
5598
5599 /* Work out the load- and run-time regions from a script statement, and
5600    store them in *LMA_REGION and *REGION respectively.
5601
5602    MEMSPEC is the name of the run-time region, or the value of
5603    DEFAULT_MEMORY_REGION if the statement didn't specify one.
5604    LMA_MEMSPEC is the name of the load-time region, or null if the
5605    statement didn't specify one.HAVE_LMA_P is TRUE if the statement
5606    had an explicit load address.
5607
5608    It is an error to specify both a load region and a load address.  */
5609
5610 static void
5611 lang_get_regions (lang_memory_region_type **region,
5612                   lang_memory_region_type **lma_region,
5613                   const char *memspec,
5614                   const char *lma_memspec,
5615                   bfd_boolean have_lma,
5616                   bfd_boolean have_vma)
5617 {
5618   *lma_region = lang_memory_region_lookup (lma_memspec, FALSE);
5619
5620   /* If no runtime region or VMA has been specified, but the load region
5621      has been specified, then use the load region for the runtime region
5622      as well.  */
5623   if (lma_memspec != NULL
5624       && ! have_vma
5625       && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
5626     *region = *lma_region;
5627   else
5628     *region = lang_memory_region_lookup (memspec, FALSE);
5629
5630   if (have_lma && lma_memspec != 0)
5631     einfo (_("%X%P:%S: section has both a load address and a load region\n"));
5632 }
5633
5634 void
5635 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
5636                                      lang_output_section_phdr_list *phdrs,
5637                                      const char *lma_memspec)
5638 {
5639   lang_get_regions (&current_section->region,
5640                     &current_section->lma_region,
5641                     memspec, lma_memspec,
5642                     current_section->load_base != NULL,
5643                     current_section->addr_tree != NULL);
5644   current_section->fill = fill;
5645   current_section->phdrs = phdrs;
5646   stat_ptr = &statement_list;
5647 }
5648
5649 /* Create an absolute symbol with the given name with the value of the
5650    address of first byte of the section named.
5651
5652    If the symbol already exists, then do nothing.  */
5653
5654 void
5655 lang_abs_symbol_at_beginning_of (const char *secname, const char *name)
5656 {
5657   struct bfd_link_hash_entry *h;
5658
5659   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
5660   if (h == NULL)
5661     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
5662
5663   if (h->type == bfd_link_hash_new
5664       || h->type == bfd_link_hash_undefined)
5665     {
5666       asection *sec;
5667
5668       h->type = bfd_link_hash_defined;
5669
5670       sec = bfd_get_section_by_name (output_bfd, secname);
5671       if (sec == NULL)
5672         h->u.def.value = 0;
5673       else
5674         h->u.def.value = bfd_get_section_vma (output_bfd, sec);
5675
5676       h->u.def.section = bfd_abs_section_ptr;
5677     }
5678 }
5679
5680 /* Create an absolute symbol with the given name with the value of the
5681    address of the first byte after the end of the section named.
5682
5683    If the symbol already exists, then do nothing.  */
5684
5685 void
5686 lang_abs_symbol_at_end_of (const char *secname, const char *name)
5687 {
5688   struct bfd_link_hash_entry *h;
5689
5690   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, TRUE, TRUE);
5691   if (h == NULL)
5692     einfo (_("%P%F: bfd_link_hash_lookup failed: %E\n"));
5693
5694   if (h->type == bfd_link_hash_new
5695       || h->type == bfd_link_hash_undefined)
5696     {
5697       asection *sec;
5698
5699       h->type = bfd_link_hash_defined;
5700
5701       sec = bfd_get_section_by_name (output_bfd, secname);
5702       if (sec == NULL)
5703         h->u.def.value = 0;
5704       else
5705         h->u.def.value = (bfd_get_section_vma (output_bfd, sec)
5706                           + TO_ADDR (sec->size));
5707
5708       h->u.def.section = bfd_abs_section_ptr;
5709     }
5710 }
5711
5712 void
5713 lang_statement_append (lang_statement_list_type *list,
5714                        lang_statement_union_type *element,
5715                        lang_statement_union_type **field)
5716 {
5717   *(list->tail) = element;
5718   list->tail = field;
5719 }
5720
5721 /* Set the output format type.  -oformat overrides scripts.  */
5722
5723 void
5724 lang_add_output_format (const char *format,
5725                         const char *big,
5726                         const char *little,
5727                         int from_script)
5728 {
5729   if (output_target == NULL || !from_script)
5730     {
5731       if (command_line.endian == ENDIAN_BIG
5732           && big != NULL)
5733         format = big;
5734       else if (command_line.endian == ENDIAN_LITTLE
5735                && little != NULL)
5736         format = little;
5737
5738       output_target = format;
5739     }
5740 }
5741
5742 /* Enter a group.  This creates a new lang_group_statement, and sets
5743    stat_ptr to build new statements within the group.  */
5744
5745 void
5746 lang_enter_group (void)
5747 {
5748   lang_group_statement_type *g;
5749
5750   g = new_stat (lang_group_statement, stat_ptr);
5751   lang_list_init (&g->children);
5752   stat_ptr = &g->children;
5753 }
5754
5755 /* Leave a group.  This just resets stat_ptr to start writing to the
5756    regular list of statements again.  Note that this will not work if
5757    groups can occur inside anything else which can adjust stat_ptr,
5758    but currently they can't.  */
5759
5760 void
5761 lang_leave_group (void)
5762 {
5763   stat_ptr = &statement_list;
5764 }
5765
5766 /* Add a new program header.  This is called for each entry in a PHDRS
5767    command in a linker script.  */
5768
5769 void
5770 lang_new_phdr (const char *name,
5771                etree_type *type,
5772                bfd_boolean filehdr,
5773                bfd_boolean phdrs,
5774                etree_type *at,
5775                etree_type *flags)
5776 {
5777   struct lang_phdr *n, **pp;
5778
5779   n = stat_alloc (sizeof (struct lang_phdr));
5780   n->next = NULL;
5781   n->name = name;
5782   n->type = exp_get_value_int (type, 0, "program header type",
5783                                lang_final_phase_enum);
5784   n->filehdr = filehdr;
5785   n->phdrs = phdrs;
5786   n->at = at;
5787   n->flags = flags;
5788
5789   for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
5790     ;
5791   *pp = n;
5792 }
5793
5794 /* Record the program header information in the output BFD.  FIXME: We
5795    should not be calling an ELF specific function here.  */
5796
5797 static void
5798 lang_record_phdrs (void)
5799 {
5800   unsigned int alc;
5801   asection **secs;
5802   lang_output_section_phdr_list *last;
5803   struct lang_phdr *l;
5804   lang_output_section_statement_type *os;
5805
5806   alc = 10;
5807   secs = xmalloc (alc * sizeof (asection *));
5808   last = NULL;
5809   for (l = lang_phdr_list; l != NULL; l = l->next)
5810     {
5811       unsigned int c;
5812       flagword flags;
5813       bfd_vma at;
5814
5815       c = 0;
5816       for (os = &lang_output_section_statement.head->output_section_statement;
5817            os != NULL;
5818            os = os->next)
5819         {
5820           lang_output_section_phdr_list *pl;
5821
5822           if (os->constraint == -1)
5823             continue;
5824
5825           pl = os->phdrs;
5826           if (pl != NULL)
5827             last = pl;
5828           else
5829             {
5830               if (os->sectype == noload_section
5831                   || os->bfd_section == NULL
5832                   || (os->bfd_section->flags & SEC_ALLOC) == 0)
5833                 continue;
5834               pl = last;
5835             }
5836
5837           if (os->bfd_section == NULL)
5838             continue;
5839
5840           for (; pl != NULL; pl = pl->next)
5841             {
5842               if (strcmp (pl->name, l->name) == 0)
5843                 {
5844                   if (c >= alc)
5845                     {
5846                       alc *= 2;
5847                       secs = xrealloc (secs, alc * sizeof (asection *));
5848                     }
5849                   secs[c] = os->bfd_section;
5850                   ++c;
5851                   pl->used = TRUE;
5852                 }
5853             }
5854         }
5855
5856       if (l->flags == NULL)
5857         flags = 0;
5858       else
5859         flags = exp_get_vma (l->flags, 0, "phdr flags",
5860                              lang_final_phase_enum);
5861
5862       if (l->at == NULL)
5863         at = 0;
5864       else
5865         at = exp_get_vma (l->at, 0, "phdr load address",
5866                           lang_final_phase_enum);
5867
5868       if (! bfd_record_phdr (output_bfd, l->type,
5869                              l->flags != NULL, flags, l->at != NULL,
5870                              at, l->filehdr, l->phdrs, c, secs))
5871         einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
5872     }
5873
5874   free (secs);
5875
5876   /* Make sure all the phdr assignments succeeded.  */
5877   for (os = &lang_output_section_statement.head->output_section_statement;
5878        os != NULL;
5879        os = os->next)
5880     {
5881       lang_output_section_phdr_list *pl;
5882
5883       if (os->constraint == -1
5884           || os->bfd_section == NULL)
5885         continue;
5886
5887       for (pl = os->phdrs;
5888            pl != NULL;
5889            pl = pl->next)
5890         if (! pl->used && strcmp (pl->name, "NONE") != 0)
5891           einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
5892                  os->name, pl->name);
5893     }
5894 }
5895
5896 /* Record a list of sections which may not be cross referenced.  */
5897
5898 void
5899 lang_add_nocrossref (lang_nocrossref_type *l)
5900 {
5901   struct lang_nocrossrefs *n;
5902
5903   n = xmalloc (sizeof *n);
5904   n->next = nocrossref_list;
5905   n->list = l;
5906   nocrossref_list = n;
5907
5908   /* Set notice_all so that we get informed about all symbols.  */
5909   link_info.notice_all = TRUE;
5910 }
5911 \f
5912 /* Overlay handling.  We handle overlays with some static variables.  */
5913
5914 /* The overlay virtual address.  */
5915 static etree_type *overlay_vma;
5916 /* And subsection alignment.  */
5917 static etree_type *overlay_subalign;
5918
5919 /* An expression for the maximum section size seen so far.  */
5920 static etree_type *overlay_max;
5921
5922 /* A list of all the sections in this overlay.  */
5923
5924 struct overlay_list {
5925   struct overlay_list *next;
5926   lang_output_section_statement_type *os;
5927 };
5928
5929 static struct overlay_list *overlay_list;
5930
5931 /* Start handling an overlay.  */
5932
5933 void
5934 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
5935 {
5936   /* The grammar should prevent nested overlays from occurring.  */
5937   ASSERT (overlay_vma == NULL
5938           && overlay_subalign == NULL
5939           && overlay_max == NULL);
5940
5941   overlay_vma = vma_expr;
5942   overlay_subalign = subalign;
5943 }
5944
5945 /* Start a section in an overlay.  We handle this by calling
5946    lang_enter_output_section_statement with the correct VMA.
5947    lang_leave_overlay sets up the LMA and memory regions.  */
5948
5949 void
5950 lang_enter_overlay_section (const char *name)
5951 {
5952   struct overlay_list *n;
5953   etree_type *size;
5954
5955   lang_enter_output_section_statement (name, overlay_vma, normal_section,
5956                                        0, overlay_subalign, 0, 0);
5957
5958   /* If this is the first section, then base the VMA of future
5959      sections on this one.  This will work correctly even if `.' is
5960      used in the addresses.  */
5961   if (overlay_list == NULL)
5962     overlay_vma = exp_nameop (ADDR, name);
5963
5964   /* Remember the section.  */
5965   n = xmalloc (sizeof *n);
5966   n->os = current_section;
5967   n->next = overlay_list;
5968   overlay_list = n;
5969
5970   size = exp_nameop (SIZEOF, name);
5971
5972   /* Arrange to work out the maximum section end address.  */
5973   if (overlay_max == NULL)
5974     overlay_max = size;
5975   else
5976     overlay_max = exp_binop (MAX_K, overlay_max, size);
5977 }
5978
5979 /* Finish a section in an overlay.  There isn't any special to do
5980    here.  */
5981
5982 void
5983 lang_leave_overlay_section (fill_type *fill,
5984                             lang_output_section_phdr_list *phdrs)
5985 {
5986   const char *name;
5987   char *clean, *s2;
5988   const char *s1;
5989   char *buf;
5990
5991   name = current_section->name;
5992
5993   /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
5994      region and that no load-time region has been specified.  It doesn't
5995      really matter what we say here, since lang_leave_overlay will
5996      override it.  */
5997   lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
5998
5999   /* Define the magic symbols.  */
6000
6001   clean = xmalloc (strlen (name) + 1);
6002   s2 = clean;
6003   for (s1 = name; *s1 != '\0'; s1++)
6004     if (ISALNUM (*s1) || *s1 == '_')
6005       *s2++ = *s1;
6006   *s2 = '\0';
6007
6008   buf = xmalloc (strlen (clean) + sizeof "__load_start_");
6009   sprintf (buf, "__load_start_%s", clean);
6010   lang_add_assignment (exp_assop ('=', buf,
6011                                   exp_nameop (LOADADDR, name)));
6012
6013   buf = xmalloc (strlen (clean) + sizeof "__load_stop_");
6014   sprintf (buf, "__load_stop_%s", clean);
6015   lang_add_assignment (exp_assop ('=', buf,
6016                                   exp_binop ('+',
6017                                              exp_nameop (LOADADDR, name),
6018                                              exp_nameop (SIZEOF, name))));
6019
6020   free (clean);
6021 }
6022
6023 /* Finish an overlay.  If there are any overlay wide settings, this
6024    looks through all the sections in the overlay and sets them.  */
6025
6026 void
6027 lang_leave_overlay (etree_type *lma_expr,
6028                     int nocrossrefs,
6029                     fill_type *fill,
6030                     const char *memspec,
6031                     lang_output_section_phdr_list *phdrs,
6032                     const char *lma_memspec)
6033 {
6034   lang_memory_region_type *region;
6035   lang_memory_region_type *lma_region;
6036   struct overlay_list *l;
6037   lang_nocrossref_type *nocrossref;
6038
6039   lang_get_regions (&region, &lma_region,
6040                     memspec, lma_memspec,
6041                     lma_expr != NULL, FALSE);
6042
6043   nocrossref = NULL;
6044
6045   /* After setting the size of the last section, set '.' to end of the
6046      overlay region.  */
6047   if (overlay_list != NULL)
6048     overlay_list->os->update_dot_tree
6049       = exp_assop ('=', ".", exp_binop ('+', overlay_vma, overlay_max));
6050
6051   l = overlay_list;
6052   while (l != NULL)
6053     {
6054       struct overlay_list *next;
6055
6056       if (fill != NULL && l->os->fill == NULL)
6057         l->os->fill = fill;
6058
6059       l->os->region = region;
6060       l->os->lma_region = lma_region;
6061
6062       /* The first section has the load address specified in the
6063          OVERLAY statement.  The rest are worked out from that.
6064          The base address is not needed (and should be null) if
6065          an LMA region was specified.  */
6066       if (l->next == 0)
6067         l->os->load_base = lma_expr;
6068       else if (lma_region == 0)
6069         l->os->load_base = exp_binop ('+',
6070                                       exp_nameop (LOADADDR, l->next->os->name),
6071                                       exp_nameop (SIZEOF, l->next->os->name));
6072
6073       if (phdrs != NULL && l->os->phdrs == NULL)
6074         l->os->phdrs = phdrs;
6075
6076       if (nocrossrefs)
6077         {
6078           lang_nocrossref_type *nc;
6079
6080           nc = xmalloc (sizeof *nc);
6081           nc->name = l->os->name;
6082           nc->next = nocrossref;
6083           nocrossref = nc;
6084         }
6085
6086       next = l->next;
6087       free (l);
6088       l = next;
6089     }
6090
6091   if (nocrossref != NULL)
6092     lang_add_nocrossref (nocrossref);
6093
6094   overlay_vma = NULL;
6095   overlay_list = NULL;
6096   overlay_max = NULL;
6097 }
6098 \f
6099 /* Version handling.  This is only useful for ELF.  */
6100
6101 /* This global variable holds the version tree that we build.  */
6102
6103 struct bfd_elf_version_tree *lang_elf_version_info;
6104
6105 /* If PREV is NULL, return first version pattern matching particular symbol.
6106    If PREV is non-NULL, return first version pattern matching particular
6107    symbol after PREV (previously returned by lang_vers_match).  */
6108
6109 static struct bfd_elf_version_expr *
6110 lang_vers_match (struct bfd_elf_version_expr_head *head,
6111                  struct bfd_elf_version_expr *prev,
6112                  const char *sym)
6113 {
6114   const char *cxx_sym = sym;
6115   const char *java_sym = sym;
6116   struct bfd_elf_version_expr *expr = NULL;
6117
6118   if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
6119     {
6120       cxx_sym = cplus_demangle (sym, DMGL_PARAMS | DMGL_ANSI);
6121       if (!cxx_sym)
6122         cxx_sym = sym;
6123     }
6124   if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
6125     {
6126       java_sym = cplus_demangle (sym, DMGL_JAVA);
6127       if (!java_sym)
6128         java_sym = sym;
6129     }
6130
6131   if (head->htab && (prev == NULL || prev->symbol))
6132     {
6133       struct bfd_elf_version_expr e;
6134
6135       switch (prev ? prev->mask : 0)
6136         {
6137           case 0:
6138             if (head->mask & BFD_ELF_VERSION_C_TYPE)
6139               {
6140                 e.symbol = sym;
6141                 expr = htab_find (head->htab, &e);
6142                 while (expr && strcmp (expr->symbol, sym) == 0)
6143                   if (expr->mask == BFD_ELF_VERSION_C_TYPE)
6144                     goto out_ret;
6145                 else
6146                   expr = expr->next;
6147               }
6148             /* Fallthrough */
6149           case BFD_ELF_VERSION_C_TYPE:
6150             if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
6151               {
6152                 e.symbol = cxx_sym;
6153                 expr = htab_find (head->htab, &e);
6154                 while (expr && strcmp (expr->symbol, cxx_sym) == 0)
6155                   if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
6156                     goto out_ret;
6157                 else
6158                   expr = expr->next;
6159               }
6160             /* Fallthrough */
6161           case BFD_ELF_VERSION_CXX_TYPE:
6162             if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
6163               {
6164                 e.symbol = java_sym;
6165                 expr = htab_find (head->htab, &e);
6166                 while (expr && strcmp (expr->symbol, java_sym) == 0)
6167                   if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
6168                     goto out_ret;
6169                 else
6170                   expr = expr->next;
6171               }
6172             /* Fallthrough */
6173           default:
6174             break;
6175         }
6176     }
6177
6178   /* Finally, try the wildcards.  */
6179   if (prev == NULL || prev->symbol)
6180     expr = head->remaining;
6181   else
6182     expr = prev->next;
6183   while (expr)
6184     {
6185       const char *s;
6186
6187       if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
6188         break;
6189
6190       if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
6191         s = java_sym;
6192       else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
6193         s = cxx_sym;
6194       else
6195         s = sym;
6196       if (fnmatch (expr->pattern, s, 0) == 0)
6197         break;
6198       expr = expr->next;
6199     }
6200
6201 out_ret:
6202   if (cxx_sym != sym)
6203     free ((char *) cxx_sym);
6204   if (java_sym != sym)
6205     free ((char *) java_sym);
6206   return expr;
6207 }
6208
6209 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
6210    return a string pointing to the symbol name.  */
6211
6212 static const char *
6213 realsymbol (const char *pattern)
6214 {
6215   const char *p;
6216   bfd_boolean changed = FALSE, backslash = FALSE;
6217   char *s, *symbol = xmalloc (strlen (pattern) + 1);
6218
6219   for (p = pattern, s = symbol; *p != '\0'; ++p)
6220     {
6221       /* It is a glob pattern only if there is no preceding
6222          backslash.  */
6223       if (! backslash && (*p == '?' || *p == '*' || *p == '['))
6224         {
6225           free (symbol);
6226           return NULL;
6227         }
6228
6229       if (backslash)
6230         {
6231           /* Remove the preceding backslash.  */
6232           *(s - 1) = *p;
6233           changed = TRUE;
6234         }
6235       else
6236         *s++ = *p;
6237
6238       backslash = *p == '\\';
6239     }
6240
6241   if (changed)
6242     {
6243       *s = '\0';
6244       return symbol;
6245     }
6246   else
6247     {
6248       free (symbol);
6249       return pattern;
6250     }
6251 }
6252
6253 /* This is called for each variable name or match expression.  */
6254
6255 struct bfd_elf_version_expr *
6256 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
6257                        const char *new,
6258                        const char *lang)
6259 {
6260   struct bfd_elf_version_expr *ret;
6261
6262   ret = xmalloc (sizeof *ret);
6263   ret->next = orig;
6264   ret->pattern = new;
6265   ret->symver = 0;
6266   ret->script = 0;
6267   ret->symbol = realsymbol (new);
6268
6269   if (lang == NULL || strcasecmp (lang, "C") == 0)
6270     ret->mask = BFD_ELF_VERSION_C_TYPE;
6271   else if (strcasecmp (lang, "C++") == 0)
6272     ret->mask = BFD_ELF_VERSION_CXX_TYPE;
6273   else if (strcasecmp (lang, "Java") == 0)
6274     ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
6275   else
6276     {
6277       einfo (_("%X%P: unknown language `%s' in version information\n"),
6278              lang);
6279       ret->mask = BFD_ELF_VERSION_C_TYPE;
6280     }
6281
6282   return ldemul_new_vers_pattern (ret);
6283 }
6284
6285 /* This is called for each set of variable names and match
6286    expressions.  */
6287
6288 struct bfd_elf_version_tree *
6289 lang_new_vers_node (struct bfd_elf_version_expr *globals,
6290                     struct bfd_elf_version_expr *locals)
6291 {
6292   struct bfd_elf_version_tree *ret;
6293
6294   ret = xcalloc (1, sizeof *ret);
6295   ret->globals.list = globals;
6296   ret->locals.list = locals;
6297   ret->match = lang_vers_match;
6298   ret->name_indx = (unsigned int) -1;
6299   return ret;
6300 }
6301
6302 /* This static variable keeps track of version indices.  */
6303
6304 static int version_index;
6305
6306 static hashval_t
6307 version_expr_head_hash (const void *p)
6308 {
6309   const struct bfd_elf_version_expr *e = p;
6310
6311   return htab_hash_string (e->symbol);
6312 }
6313
6314 static int
6315 version_expr_head_eq (const void *p1, const void *p2)
6316 {
6317   const struct bfd_elf_version_expr *e1 = p1;
6318   const struct bfd_elf_version_expr *e2 = p2;
6319
6320   return strcmp (e1->symbol, e2->symbol) == 0;
6321 }
6322
6323 static void
6324 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
6325 {
6326   size_t count = 0;
6327   struct bfd_elf_version_expr *e, *next;
6328   struct bfd_elf_version_expr **list_loc, **remaining_loc;
6329
6330   for (e = head->list; e; e = e->next)
6331     {
6332       if (e->symbol)
6333         count++;
6334       head->mask |= e->mask;
6335     }
6336
6337   if (count)
6338     {
6339       head->htab = htab_create (count * 2, version_expr_head_hash,
6340                                 version_expr_head_eq, NULL);
6341       list_loc = &head->list;
6342       remaining_loc = &head->remaining;
6343       for (e = head->list; e; e = next)
6344         {
6345           next = e->next;
6346           if (!e->symbol)
6347             {
6348               *remaining_loc = e;
6349               remaining_loc = &e->next;
6350             }
6351           else
6352             {
6353               void **loc = htab_find_slot (head->htab, e, INSERT);
6354
6355               if (*loc)
6356                 {
6357                   struct bfd_elf_version_expr *e1, *last;
6358
6359                   e1 = *loc;
6360                   last = NULL;
6361                   do
6362                     {
6363                       if (e1->mask == e->mask)
6364                         {
6365                           last = NULL;
6366                           break;
6367                         }
6368                       last = e1;
6369                       e1 = e1->next;
6370                     }
6371                   while (e1 && strcmp (e1->symbol, e->symbol) == 0);
6372
6373                   if (last == NULL)
6374                     {
6375                       /* This is a duplicate.  */
6376                       /* FIXME: Memory leak.  Sometimes pattern is not
6377                          xmalloced alone, but in larger chunk of memory.  */
6378                       /* free (e->symbol); */
6379                       free (e);
6380                     }
6381                   else
6382                     {
6383                       e->next = last->next;
6384                       last->next = e;
6385                     }
6386                 }
6387               else
6388                 {
6389                   *loc = e;
6390                   *list_loc = e;
6391                   list_loc = &e->next;
6392                 }
6393             }
6394         }
6395       *remaining_loc = NULL;
6396       *list_loc = head->remaining;
6397     }
6398   else
6399     head->remaining = head->list;
6400 }
6401
6402 /* This is called when we know the name and dependencies of the
6403    version.  */
6404
6405 void
6406 lang_register_vers_node (const char *name,
6407                          struct bfd_elf_version_tree *version,
6408                          struct bfd_elf_version_deps *deps)
6409 {
6410   struct bfd_elf_version_tree *t, **pp;
6411   struct bfd_elf_version_expr *e1;
6412
6413   if (name == NULL)
6414     name = "";
6415
6416   if ((name[0] == '\0' && lang_elf_version_info != NULL)
6417       || (lang_elf_version_info && lang_elf_version_info->name[0] == '\0'))
6418     {
6419       einfo (_("%X%P: anonymous version tag cannot be combined"
6420                " with other version tags\n"));
6421       free (version);
6422       return;
6423     }
6424
6425   /* Make sure this node has a unique name.  */
6426   for (t = lang_elf_version_info; t != NULL; t = t->next)
6427     if (strcmp (t->name, name) == 0)
6428       einfo (_("%X%P: duplicate version tag `%s'\n"), name);
6429
6430   lang_finalize_version_expr_head (&version->globals);
6431   lang_finalize_version_expr_head (&version->locals);
6432
6433   /* Check the global and local match names, and make sure there
6434      aren't any duplicates.  */
6435
6436   for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
6437     {
6438       for (t = lang_elf_version_info; t != NULL; t = t->next)
6439         {
6440           struct bfd_elf_version_expr *e2;
6441
6442           if (t->locals.htab && e1->symbol)
6443             {
6444               e2 = htab_find (t->locals.htab, e1);
6445               while (e2 && strcmp (e1->symbol, e2->symbol) == 0)
6446                 {
6447                   if (e1->mask == e2->mask)
6448                     einfo (_("%X%P: duplicate expression `%s'"
6449                              " in version information\n"), e1->symbol);
6450                   e2 = e2->next;
6451                 }
6452             }
6453           else if (!e1->symbol)
6454             for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
6455               if (strcmp (e1->pattern, e2->pattern) == 0
6456                   && e1->mask == e2->mask)
6457                 einfo (_("%X%P: duplicate expression `%s'"
6458                          " in version information\n"), e1->pattern);
6459         }
6460     }
6461
6462   for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
6463     {
6464       for (t = lang_elf_version_info; t != NULL; t = t->next)
6465         {
6466           struct bfd_elf_version_expr *e2;
6467
6468           if (t->globals.htab && e1->symbol)
6469             {
6470               e2 = htab_find (t->globals.htab, e1);
6471               while (e2 && strcmp (e1->symbol, e2->symbol) == 0)
6472                 {
6473                   if (e1->mask == e2->mask)
6474                     einfo (_("%X%P: duplicate expression `%s'"
6475                              " in version information\n"),
6476                            e1->symbol);
6477                   e2 = e2->next;
6478                 }
6479             }
6480           else if (!e1->symbol)
6481             for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
6482               if (strcmp (e1->pattern, e2->pattern) == 0
6483                   && e1->mask == e2->mask)
6484                 einfo (_("%X%P: duplicate expression `%s'"
6485                          " in version information\n"), e1->pattern);
6486         }
6487     }
6488
6489   version->deps = deps;
6490   version->name = name;
6491   if (name[0] != '\0')
6492     {
6493       ++version_index;
6494       version->vernum = version_index;
6495     }
6496   else
6497     version->vernum = 0;
6498
6499   for (pp = &lang_elf_version_info; *pp != NULL; pp = &(*pp)->next)
6500     ;
6501   *pp = version;
6502 }
6503
6504 /* This is called when we see a version dependency.  */
6505
6506 struct bfd_elf_version_deps *
6507 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
6508 {
6509   struct bfd_elf_version_deps *ret;
6510   struct bfd_elf_version_tree *t;
6511
6512   ret = xmalloc (sizeof *ret);
6513   ret->next = list;
6514
6515   for (t = lang_elf_version_info; t != NULL; t = t->next)
6516     {
6517       if (strcmp (t->name, name) == 0)
6518         {
6519           ret->version_needed = t;
6520           return ret;
6521         }
6522     }
6523
6524   einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
6525
6526   return ret;
6527 }
6528
6529 static void
6530 lang_do_version_exports_section (void)
6531 {
6532   struct bfd_elf_version_expr *greg = NULL, *lreg;
6533
6534   LANG_FOR_EACH_INPUT_STATEMENT (is)
6535     {
6536       asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
6537       char *contents, *p;
6538       bfd_size_type len;
6539
6540       if (sec == NULL)
6541         continue;
6542
6543       len = sec->size;
6544       contents = xmalloc (len);
6545       if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
6546         einfo (_("%X%P: unable to read .exports section contents\n"), sec);
6547
6548       p = contents;
6549       while (p < contents + len)
6550         {
6551           greg = lang_new_vers_pattern (greg, p, NULL);
6552           p = strchr (p, '\0') + 1;
6553         }
6554
6555       /* Do not free the contents, as we used them creating the regex.  */
6556
6557       /* Do not include this section in the link.  */
6558       sec->flags |= SEC_EXCLUDE;
6559     }
6560
6561   lreg = lang_new_vers_pattern (NULL, "*", NULL);
6562   lang_register_vers_node (command_line.version_exports_section,
6563                            lang_new_vers_node (greg, lreg), NULL);
6564 }
6565
6566 void
6567 lang_add_unique (const char *name)
6568 {
6569   struct unique_sections *ent;
6570
6571   for (ent = unique_section_list; ent; ent = ent->next)
6572     if (strcmp (ent->name, name) == 0)
6573       return;
6574
6575   ent = xmalloc (sizeof *ent);
6576   ent->name = xstrdup (name);
6577   ent->next = unique_section_list;
6578   unique_section_list = ent;
6579 }