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