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