xref: /netbsd/external/gpl3/gdb.old/dist/ld/ldlang.c (revision 56bb7041)
1 /* Linker command language support.
2    Copyright (C) 1991-2020 Free Software Foundation, Inc.
3 
4    This file is part of the GNU Binutils.
5 
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20 
21 #include "sysdep.h"
22 #include <limits.h>
23 #include "bfd.h"
24 #include "libiberty.h"
25 #include "filenames.h"
26 #include "safe-ctype.h"
27 #include "obstack.h"
28 #include "bfdlink.h"
29 #include "ctf-api.h"
30 
31 #include "ld.h"
32 #include "ldmain.h"
33 #include "ldexp.h"
34 #include "ldlang.h"
35 #include <ldgram.h>
36 #include "ldlex.h"
37 #include "ldmisc.h"
38 #include "ldctor.h"
39 #include "ldfile.h"
40 #include "ldemul.h"
41 #include "fnmatch.h"
42 #include "demangle.h"
43 #include "hashtab.h"
44 #include "elf-bfd.h"
45 #if BFD_SUPPORTS_PLUGINS
46 #include "plugin.h"
47 #endif /* BFD_SUPPORTS_PLUGINS */
48 
49 #ifndef offsetof
50 #define offsetof(TYPE, MEMBER) ((size_t) & (((TYPE*) 0)->MEMBER))
51 #endif
52 
53 /* Convert between addresses in bytes and sizes in octets.
54    For currently supported targets, octets_per_byte is always a power
55    of two, so we can use shifts.  */
56 #define TO_ADDR(X) ((X) >> opb_shift)
57 #define TO_SIZE(X) ((X) << opb_shift)
58 
59 /* Local variables.  */
60 static struct obstack stat_obstack;
61 static struct obstack map_obstack;
62 
63 #define obstack_chunk_alloc xmalloc
64 #define obstack_chunk_free free
65 static const char *entry_symbol_default = "start";
66 static bfd_boolean map_head_is_link_order = FALSE;
67 static lang_output_section_statement_type *default_common_section;
68 static bfd_boolean map_option_f;
69 static bfd_vma print_dot;
70 static lang_input_statement_type *first_file;
71 static const char *current_target;
72 /* Header for list of statements corresponding to any files involved in the
73    link, either specified from the command-line or added implicitely (eg.
74    archive member used to resolved undefined symbol, wildcard statement from
75    linker script, etc.).  Next pointer is in next field of a
76    lang_statement_header_type (reached via header field in a
77    lang_statement_union).  */
78 static lang_statement_list_type statement_list;
79 static lang_statement_list_type *stat_save[10];
80 static lang_statement_list_type **stat_save_ptr = &stat_save[0];
81 static struct unique_sections *unique_section_list;
82 static struct asneeded_minfo *asneeded_list_head;
83 static unsigned int opb_shift = 0;
84 
85 /* Forward declarations.  */
86 static void exp_init_os (etree_type *);
87 static lang_input_statement_type *lookup_name (const char *);
88 static void insert_undefined (const char *);
89 static bfd_boolean sort_def_symbol (struct bfd_link_hash_entry *, void *);
90 static void print_statement (lang_statement_union_type *,
91 			     lang_output_section_statement_type *);
92 static void print_statement_list (lang_statement_union_type *,
93 				  lang_output_section_statement_type *);
94 static void print_statements (void);
95 static void print_input_section (asection *, bfd_boolean);
96 static bfd_boolean lang_one_common (struct bfd_link_hash_entry *, void *);
97 static void lang_record_phdrs (void);
98 static void lang_do_version_exports_section (void);
99 static void lang_finalize_version_expr_head
100   (struct bfd_elf_version_expr_head *);
101 static void lang_do_memory_regions (void);
102 
103 /* Exported variables.  */
104 const char *output_target;
105 lang_output_section_statement_type *abs_output_section;
106 lang_statement_list_type lang_os_list;
107 lang_statement_list_type *stat_ptr = &statement_list;
108 /* Header for list of statements corresponding to files used in the final
109    executable.  This can be either object file specified on the command-line
110    or library member resolving an undefined reference.  Next pointer is in next
111    field of a lang_input_statement_type (reached via input_statement field in a
112    lang_statement_union).  */
113 lang_statement_list_type file_chain = { NULL, NULL };
114 /* Header for list of statements corresponding to files specified on the
115    command-line for linking.  It thus contains real object files and archive
116    but not archive members.  Next pointer is in next_real_file field of a
117    lang_input_statement_type statement (reached via input_statement field in a
118    lang_statement_union).  */
119 lang_statement_list_type input_file_chain;
120 static const char *current_input_file;
121 struct bfd_elf_dynamic_list **current_dynamic_list_p;
122 struct bfd_sym_chain entry_symbol = { NULL, NULL };
123 const char *entry_section = ".text";
124 struct lang_input_statement_flags input_flags;
125 bfd_boolean entry_from_cmdline;
126 bfd_boolean lang_has_input_file = FALSE;
127 bfd_boolean had_output_filename = FALSE;
128 bfd_boolean lang_float_flag = FALSE;
129 bfd_boolean delete_output_file_on_failure = FALSE;
130 struct lang_phdr *lang_phdr_list;
131 struct lang_nocrossrefs *nocrossref_list;
132 struct asneeded_minfo **asneeded_list_tail;
133 #ifdef ENABLE_LIBCTF
134 static ctf_file_t *ctf_output;
135 #endif
136 
137 /* Functions that traverse the linker script and might evaluate
138    DEFINED() need to increment this at the start of the traversal.  */
139 int lang_statement_iteration = 0;
140 
141 /* Count times through one_lang_size_sections_pass after mark phase.  */
142 static int lang_sizing_iteration = 0;
143 
144 /* Return TRUE if the PATTERN argument is a wildcard pattern.
145    Although backslashes are treated specially if a pattern contains
146    wildcards, we do not consider the mere presence of a backslash to
147    be enough to cause the pattern to be treated as a wildcard.
148    That lets us handle DOS filenames more naturally.  */
149 #define wildcardp(pattern) (strpbrk ((pattern), "?*[") != NULL)
150 
151 #define new_stat(x, y) \
152   (x##_type *) new_statement (x##_enum, sizeof (x##_type), y)
153 
154 #define outside_section_address(q) \
155   ((q)->output_offset + (q)->output_section->vma)
156 
157 #define outside_symbol_address(q) \
158   ((q)->value + outside_section_address (q->section))
159 
160 /* CTF sections smaller than this are not compressed: compression of
161    dictionaries this small doesn't gain much, and this lets consumers mmap the
162    sections directly out of the ELF file and use them with no decompression
163    overhead if they want to.  */
164 #define CTF_COMPRESSION_THRESHOLD 4096
165 
166 void *
stat_alloc(size_t size)167 stat_alloc (size_t size)
168 {
169   return obstack_alloc (&stat_obstack, size);
170 }
171 
172 static int
name_match(const char * pattern,const char * name)173 name_match (const char *pattern, const char *name)
174 {
175   if (wildcardp (pattern))
176     return fnmatch (pattern, name, 0);
177   return strcmp (pattern, name);
178 }
179 
180 static char *
ldirname(const char * name)181 ldirname (const char *name)
182 {
183   const char *base = lbasename (name);
184   char *dirname;
185 
186   while (base > name && IS_DIR_SEPARATOR (base[-1]))
187     --base;
188   if (base == name)
189     return strdup (".");
190   dirname = strdup (name);
191   dirname[base - name] = '\0';
192   return dirname;
193 }
194 
195 /* If PATTERN is of the form archive:file, return a pointer to the
196    separator.  If not, return NULL.  */
197 
198 static char *
archive_path(const char * pattern)199 archive_path (const char *pattern)
200 {
201   char *p = NULL;
202 
203   if (link_info.path_separator == 0)
204     return p;
205 
206   p = strchr (pattern, link_info.path_separator);
207 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
208   if (p == NULL || link_info.path_separator != ':')
209     return p;
210 
211   /* Assume a match on the second char is part of drive specifier,
212      as in "c:\silly.dos".  */
213   if (p == pattern + 1 && ISALPHA (*pattern))
214     p = strchr (p + 1, link_info.path_separator);
215 #endif
216   return p;
217 }
218 
219 /* Given that FILE_SPEC results in a non-NULL SEP result from archive_path,
220    return whether F matches FILE_SPEC.  */
221 
222 static bfd_boolean
input_statement_is_archive_path(const char * file_spec,char * sep,lang_input_statement_type * f)223 input_statement_is_archive_path (const char *file_spec, char *sep,
224 				 lang_input_statement_type *f)
225 {
226   bfd_boolean match = FALSE;
227 
228   if ((*(sep + 1) == 0
229        || name_match (sep + 1, f->filename) == 0)
230       && ((sep != file_spec)
231 	  == (f->the_bfd != NULL && f->the_bfd->my_archive != NULL)))
232     {
233       match = TRUE;
234 
235       if (sep != file_spec)
236 	{
237 	  const char *aname = bfd_get_filename (f->the_bfd->my_archive);
238 	  *sep = 0;
239 	  match = name_match (file_spec, aname) == 0;
240 	  *sep = link_info.path_separator;
241 	}
242     }
243   return match;
244 }
245 
246 static bfd_boolean
unique_section_p(const asection * sec,const lang_output_section_statement_type * os)247 unique_section_p (const asection *sec,
248 		  const lang_output_section_statement_type *os)
249 {
250   struct unique_sections *unam;
251   const char *secnam;
252 
253   if (!link_info.resolve_section_groups
254       && sec->owner != NULL
255       && bfd_is_group_section (sec->owner, sec))
256     return !(os != NULL
257 	     && strcmp (os->name, DISCARD_SECTION_NAME) == 0);
258 
259   secnam = sec->name;
260   for (unam = unique_section_list; unam; unam = unam->next)
261     if (name_match (unam->name, secnam) == 0)
262       return TRUE;
263 
264   return FALSE;
265 }
266 
267 /* Generic traversal routines for finding matching sections.  */
268 
269 /* Return true if FILE matches a pattern in EXCLUDE_LIST, otherwise return
270    false.  */
271 
272 static bfd_boolean
walk_wild_file_in_exclude_list(struct name_list * exclude_list,lang_input_statement_type * file)273 walk_wild_file_in_exclude_list (struct name_list *exclude_list,
274 				lang_input_statement_type *file)
275 {
276   struct name_list *list_tmp;
277 
278   for (list_tmp = exclude_list;
279        list_tmp;
280        list_tmp = list_tmp->next)
281     {
282       char *p = archive_path (list_tmp->name);
283 
284       if (p != NULL)
285 	{
286 	  if (input_statement_is_archive_path (list_tmp->name, p, file))
287 	    return TRUE;
288 	}
289 
290       else if (name_match (list_tmp->name, file->filename) == 0)
291 	return TRUE;
292 
293       /* FIXME: Perhaps remove the following at some stage?  Matching
294 	 unadorned archives like this was never documented and has
295 	 been superceded by the archive:path syntax.  */
296       else if (file->the_bfd != NULL
297 	       && file->the_bfd->my_archive != NULL
298 	       && name_match (list_tmp->name,
299 			      bfd_get_filename (file->the_bfd->my_archive)) == 0)
300 	return TRUE;
301     }
302 
303   return FALSE;
304 }
305 
306 /* Try processing a section against a wildcard.  This just calls
307    the callback unless the filename exclusion list is present
308    and excludes the file.  It's hardly ever present so this
309    function is very fast.  */
310 
311 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)312 walk_wild_consider_section (lang_wild_statement_type *ptr,
313 			    lang_input_statement_type *file,
314 			    asection *s,
315 			    struct wildcard_list *sec,
316 			    callback_t callback,
317 			    void *data)
318 {
319   /* Don't process sections from files which were excluded.  */
320   if (walk_wild_file_in_exclude_list (sec->spec.exclude_name_list, file))
321     return;
322 
323   (*callback) (ptr, sec, s, ptr->section_flag_list, file, data);
324 }
325 
326 /* Lowest common denominator routine that can handle everything correctly,
327    but slowly.  */
328 
329 static void
walk_wild_section_general(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)330 walk_wild_section_general (lang_wild_statement_type *ptr,
331 			   lang_input_statement_type *file,
332 			   callback_t callback,
333 			   void *data)
334 {
335   asection *s;
336   struct wildcard_list *sec;
337 
338   for (s = file->the_bfd->sections; s != NULL; s = s->next)
339     {
340       sec = ptr->section_list;
341       if (sec == NULL)
342 	(*callback) (ptr, sec, s, ptr->section_flag_list, file, data);
343 
344       while (sec != NULL)
345 	{
346 	  bfd_boolean skip = FALSE;
347 
348 	  if (sec->spec.name != NULL)
349 	    {
350 	      const char *sname = bfd_section_name (s);
351 
352 	      skip = name_match (sec->spec.name, sname) != 0;
353 	    }
354 
355 	  if (!skip)
356 	    walk_wild_consider_section (ptr, file, s, sec, callback, data);
357 
358 	  sec = sec->next;
359 	}
360     }
361 }
362 
363 /* Routines to find a single section given its name.  If there's more
364    than one section with that name, we report that.  */
365 
366 typedef struct
367 {
368   asection *found_section;
369   bfd_boolean multiple_sections_found;
370 } section_iterator_callback_data;
371 
372 static bfd_boolean
section_iterator_callback(bfd * abfd ATTRIBUTE_UNUSED,asection * s,void * data)373 section_iterator_callback (bfd *abfd ATTRIBUTE_UNUSED, asection *s, void *data)
374 {
375   section_iterator_callback_data *d = (section_iterator_callback_data *) data;
376 
377   if (d->found_section != NULL)
378     {
379       d->multiple_sections_found = TRUE;
380       return TRUE;
381     }
382 
383   d->found_section = s;
384   return FALSE;
385 }
386 
387 static asection *
find_section(lang_input_statement_type * file,struct wildcard_list * sec,bfd_boolean * multiple_sections_found)388 find_section (lang_input_statement_type *file,
389 	      struct wildcard_list *sec,
390 	      bfd_boolean *multiple_sections_found)
391 {
392   section_iterator_callback_data cb_data = { NULL, FALSE };
393 
394   bfd_get_section_by_name_if (file->the_bfd, sec->spec.name,
395 			      section_iterator_callback, &cb_data);
396   *multiple_sections_found = cb_data.multiple_sections_found;
397   return cb_data.found_section;
398 }
399 
400 /* Code for handling simple wildcards without going through fnmatch,
401    which can be expensive because of charset translations etc.  */
402 
403 /* A simple wild is a literal string followed by a single '*',
404    where the literal part is at least 4 characters long.  */
405 
406 static bfd_boolean
is_simple_wild(const char * name)407 is_simple_wild (const char *name)
408 {
409   size_t len = strcspn (name, "*?[");
410   return len >= 4 && name[len] == '*' && name[len + 1] == '\0';
411 }
412 
413 static bfd_boolean
match_simple_wild(const char * pattern,const char * name)414 match_simple_wild (const char *pattern, const char *name)
415 {
416   /* The first four characters of the pattern are guaranteed valid
417      non-wildcard characters.  So we can go faster.  */
418   if (pattern[0] != name[0] || pattern[1] != name[1]
419       || pattern[2] != name[2] || pattern[3] != name[3])
420     return FALSE;
421 
422   pattern += 4;
423   name += 4;
424   while (*pattern != '*')
425     if (*name++ != *pattern++)
426       return FALSE;
427 
428   return TRUE;
429 }
430 
431 /* Return the numerical value of the init_priority attribute from
432    section name NAME.  */
433 
434 static int
get_init_priority(const asection * sec)435 get_init_priority (const asection *sec)
436 {
437   const char *name = bfd_section_name (sec);
438   const char *dot;
439 
440   /* GCC uses the following section names for the init_priority
441      attribute with numerical values 101 to 65535 inclusive. A
442      lower value means a higher priority.
443 
444      1: .init_array.NNNNN/.fini_array.NNNNN: Where NNNNN is the
445 	decimal numerical value of the init_priority attribute.
446 	The order of execution in .init_array is forward and
447 	.fini_array is backward.
448      2: .ctors.NNNNN/.dtors.NNNNN: Where NNNNN is 65535 minus the
449 	decimal numerical value of the init_priority attribute.
450 	The order of execution in .ctors is backward and .dtors
451 	is forward.
452 
453      .init_array.NNNNN sections would normally be placed in an output
454      .init_array section, .fini_array.NNNNN in .fini_array,
455      .ctors.NNNNN in .ctors, and .dtors.NNNNN in .dtors.  This means
456      we should sort by increasing number (and could just use
457      SORT_BY_NAME in scripts).  However if .ctors.NNNNN sections are
458      being placed in .init_array (which may also contain
459      .init_array.NNNNN sections) or .dtors.NNNNN sections are being
460      placed in .fini_array then we need to extract the init_priority
461      attribute and sort on that.  */
462   dot = strrchr (name, '.');
463   if (dot != NULL && ISDIGIT (dot[1]))
464     {
465       char *end;
466       unsigned long init_priority = strtoul (dot + 1, &end, 10);
467       if (*end == 0)
468 	{
469 	  if (dot == name + 6
470 	      && (strncmp (name, ".ctors", 6) == 0
471 		  || strncmp (name, ".dtors", 6) == 0))
472 	    init_priority = 65535 - init_priority;
473 	  if (init_priority <= INT_MAX)
474 	    return init_priority;
475 	}
476     }
477   return -1;
478 }
479 
480 /* Compare sections ASEC and BSEC according to SORT.  */
481 
482 static int
compare_section(sort_type sort,asection * asec,asection * bsec)483 compare_section (sort_type sort, asection *asec, asection *bsec)
484 {
485   int ret;
486   int a_priority, b_priority;
487 
488   switch (sort)
489     {
490     default:
491       abort ();
492 
493     case by_init_priority:
494       a_priority = get_init_priority (asec);
495       b_priority = get_init_priority (bsec);
496       if (a_priority < 0 || b_priority < 0)
497 	goto sort_by_name;
498       ret = a_priority - b_priority;
499       if (ret)
500 	break;
501       else
502 	goto sort_by_name;
503 
504     case by_alignment_name:
505       ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
506       if (ret)
507 	break;
508       /* Fall through.  */
509 
510     case by_name:
511     sort_by_name:
512       ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
513       break;
514 
515     case by_name_alignment:
516       ret = strcmp (bfd_section_name (asec), bfd_section_name (bsec));
517       if (ret)
518 	break;
519       /* Fall through.  */
520 
521     case by_alignment:
522       ret = bfd_section_alignment (bsec) - bfd_section_alignment (asec);
523       break;
524     }
525 
526   return ret;
527 }
528 
529 /* Build a Binary Search Tree to sort sections, unlike insertion sort
530    used in wild_sort(). BST is considerably faster if the number of
531    of sections are large.  */
532 
533 static lang_section_bst_type **
wild_sort_fast(lang_wild_statement_type * wild,struct wildcard_list * sec,lang_input_statement_type * file ATTRIBUTE_UNUSED,asection * section)534 wild_sort_fast (lang_wild_statement_type *wild,
535 		struct wildcard_list *sec,
536 		lang_input_statement_type *file ATTRIBUTE_UNUSED,
537 		asection *section)
538 {
539   lang_section_bst_type **tree;
540 
541   tree = &wild->tree;
542   if (!wild->filenames_sorted
543       && (sec == NULL || sec->spec.sorted == none))
544     {
545       /* Append at the right end of tree.  */
546       while (*tree)
547 	tree = &((*tree)->right);
548       return tree;
549     }
550 
551   while (*tree)
552     {
553       /* Find the correct node to append this section.  */
554       if (compare_section (sec->spec.sorted, section, (*tree)->section) < 0)
555 	tree = &((*tree)->left);
556       else
557 	tree = &((*tree)->right);
558     }
559 
560   return tree;
561 }
562 
563 /* Use wild_sort_fast to build a BST to sort sections.  */
564 
565 static void
output_section_callback_fast(lang_wild_statement_type * ptr,struct wildcard_list * sec,asection * section,struct flag_info * sflag_list ATTRIBUTE_UNUSED,lang_input_statement_type * file,void * output)566 output_section_callback_fast (lang_wild_statement_type *ptr,
567 			      struct wildcard_list *sec,
568 			      asection *section,
569 			      struct flag_info *sflag_list ATTRIBUTE_UNUSED,
570 			      lang_input_statement_type *file,
571 			      void *output)
572 {
573   lang_section_bst_type *node;
574   lang_section_bst_type **tree;
575   lang_output_section_statement_type *os;
576 
577   os = (lang_output_section_statement_type *) output;
578 
579   if (unique_section_p (section, os))
580     return;
581 
582   node = (lang_section_bst_type *) xmalloc (sizeof (lang_section_bst_type));
583   node->left = 0;
584   node->right = 0;
585   node->section = section;
586 
587   tree = wild_sort_fast (ptr, sec, file, section);
588   if (tree != NULL)
589     *tree = node;
590 }
591 
592 /* Convert a sorted sections' BST back to list form.  */
593 
594 static void
output_section_callback_tree_to_list(lang_wild_statement_type * ptr,lang_section_bst_type * tree,void * output)595 output_section_callback_tree_to_list (lang_wild_statement_type *ptr,
596 				      lang_section_bst_type *tree,
597 				      void *output)
598 {
599   if (tree->left)
600     output_section_callback_tree_to_list (ptr, tree->left, output);
601 
602   lang_add_section (&ptr->children, tree->section, NULL,
603 		    (lang_output_section_statement_type *) output);
604 
605   if (tree->right)
606     output_section_callback_tree_to_list (ptr, tree->right, output);
607 
608   free (tree);
609 }
610 
611 /* Specialized, optimized routines for handling different kinds of
612    wildcards */
613 
614 static void
walk_wild_section_specs1_wild0(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)615 walk_wild_section_specs1_wild0 (lang_wild_statement_type *ptr,
616 				lang_input_statement_type *file,
617 				callback_t callback,
618 				void *data)
619 {
620   /* We can just do a hash lookup for the section with the right name.
621      But if that lookup discovers more than one section with the name
622      (should be rare), we fall back to the general algorithm because
623      we would otherwise have to sort the sections to make sure they
624      get processed in the bfd's order.  */
625   bfd_boolean multiple_sections_found;
626   struct wildcard_list *sec0 = ptr->handler_data[0];
627   asection *s0 = find_section (file, sec0, &multiple_sections_found);
628 
629   if (multiple_sections_found)
630     walk_wild_section_general (ptr, file, callback, data);
631   else if (s0)
632     walk_wild_consider_section (ptr, file, s0, sec0, callback, data);
633 }
634 
635 static void
walk_wild_section_specs1_wild1(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)636 walk_wild_section_specs1_wild1 (lang_wild_statement_type *ptr,
637 				lang_input_statement_type *file,
638 				callback_t callback,
639 				void *data)
640 {
641   asection *s;
642   struct wildcard_list *wildsec0 = ptr->handler_data[0];
643 
644   for (s = file->the_bfd->sections; s != NULL; s = s->next)
645     {
646       const char *sname = bfd_section_name (s);
647       bfd_boolean skip = !match_simple_wild (wildsec0->spec.name, sname);
648 
649       if (!skip)
650 	walk_wild_consider_section (ptr, file, s, wildsec0, callback, data);
651     }
652 }
653 
654 static void
walk_wild_section_specs2_wild1(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)655 walk_wild_section_specs2_wild1 (lang_wild_statement_type *ptr,
656 				lang_input_statement_type *file,
657 				callback_t callback,
658 				void *data)
659 {
660   asection *s;
661   struct wildcard_list *sec0 = ptr->handler_data[0];
662   struct wildcard_list *wildsec1 = ptr->handler_data[1];
663   bfd_boolean multiple_sections_found;
664   asection *s0 = find_section (file, sec0, &multiple_sections_found);
665 
666   if (multiple_sections_found)
667     {
668       walk_wild_section_general (ptr, file, callback, data);
669       return;
670     }
671 
672   /* Note that if the section was not found, s0 is NULL and
673      we'll simply never succeed the s == s0 test below.  */
674   for (s = file->the_bfd->sections; s != NULL; s = s->next)
675     {
676       /* Recall that in this code path, a section cannot satisfy more
677 	 than one spec, so if s == s0 then it cannot match
678 	 wildspec1.  */
679       if (s == s0)
680 	walk_wild_consider_section (ptr, file, s, sec0, callback, data);
681       else
682 	{
683 	  const char *sname = bfd_section_name (s);
684 	  bfd_boolean skip = !match_simple_wild (wildsec1->spec.name, sname);
685 
686 	  if (!skip)
687 	    walk_wild_consider_section (ptr, file, s, wildsec1, callback,
688 					data);
689 	}
690     }
691 }
692 
693 static void
walk_wild_section_specs3_wild2(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)694 walk_wild_section_specs3_wild2 (lang_wild_statement_type *ptr,
695 				lang_input_statement_type *file,
696 				callback_t callback,
697 				void *data)
698 {
699   asection *s;
700   struct wildcard_list *sec0 = ptr->handler_data[0];
701   struct wildcard_list *wildsec1 = ptr->handler_data[1];
702   struct wildcard_list *wildsec2 = ptr->handler_data[2];
703   bfd_boolean multiple_sections_found;
704   asection *s0 = find_section (file, sec0, &multiple_sections_found);
705 
706   if (multiple_sections_found)
707     {
708       walk_wild_section_general (ptr, file, callback, data);
709       return;
710     }
711 
712   for (s = file->the_bfd->sections; s != NULL; s = s->next)
713     {
714       if (s == s0)
715 	walk_wild_consider_section (ptr, file, s, sec0, callback, data);
716       else
717 	{
718 	  const char *sname = bfd_section_name (s);
719 	  bfd_boolean skip = !match_simple_wild (wildsec1->spec.name, sname);
720 
721 	  if (!skip)
722 	    walk_wild_consider_section (ptr, file, s, wildsec1, callback, data);
723 	  else
724 	    {
725 	      skip = !match_simple_wild (wildsec2->spec.name, sname);
726 	      if (!skip)
727 		walk_wild_consider_section (ptr, file, s, wildsec2, callback,
728 					    data);
729 	    }
730 	}
731     }
732 }
733 
734 static void
walk_wild_section_specs4_wild2(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)735 walk_wild_section_specs4_wild2 (lang_wild_statement_type *ptr,
736 				lang_input_statement_type *file,
737 				callback_t callback,
738 				void *data)
739 {
740   asection *s;
741   struct wildcard_list *sec0 = ptr->handler_data[0];
742   struct wildcard_list *sec1 = ptr->handler_data[1];
743   struct wildcard_list *wildsec2 = ptr->handler_data[2];
744   struct wildcard_list *wildsec3 = ptr->handler_data[3];
745   bfd_boolean multiple_sections_found;
746   asection *s0 = find_section (file, sec0, &multiple_sections_found), *s1;
747 
748   if (multiple_sections_found)
749     {
750       walk_wild_section_general (ptr, file, callback, data);
751       return;
752     }
753 
754   s1 = find_section (file, sec1, &multiple_sections_found);
755   if (multiple_sections_found)
756     {
757       walk_wild_section_general (ptr, file, callback, data);
758       return;
759     }
760 
761   for (s = file->the_bfd->sections; s != NULL; s = s->next)
762     {
763       if (s == s0)
764 	walk_wild_consider_section (ptr, file, s, sec0, callback, data);
765       else
766 	if (s == s1)
767 	  walk_wild_consider_section (ptr, file, s, sec1, callback, data);
768 	else
769 	  {
770 	    const char *sname = bfd_section_name (s);
771 	    bfd_boolean skip = !match_simple_wild (wildsec2->spec.name,
772 						   sname);
773 
774 	    if (!skip)
775 	      walk_wild_consider_section (ptr, file, s, wildsec2, callback,
776 					  data);
777 	    else
778 	      {
779 		skip = !match_simple_wild (wildsec3->spec.name, sname);
780 		if (!skip)
781 		  walk_wild_consider_section (ptr, file, s, wildsec3,
782 					      callback, data);
783 	      }
784 	  }
785     }
786 }
787 
788 static void
walk_wild_section(lang_wild_statement_type * ptr,lang_input_statement_type * file,callback_t callback,void * data)789 walk_wild_section (lang_wild_statement_type *ptr,
790 		   lang_input_statement_type *file,
791 		   callback_t callback,
792 		   void *data)
793 {
794   if (file->flags.just_syms)
795     return;
796 
797   (*ptr->walk_wild_section_handler) (ptr, file, callback, data);
798 }
799 
800 /* Returns TRUE when name1 is a wildcard spec that might match
801    something name2 can match.  We're conservative: we return FALSE
802    only if the prefixes of name1 and name2 are different up to the
803    first wildcard character.  */
804 
805 static bfd_boolean
wild_spec_can_overlap(const char * name1,const char * name2)806 wild_spec_can_overlap (const char *name1, const char *name2)
807 {
808   size_t prefix1_len = strcspn (name1, "?*[");
809   size_t prefix2_len = strcspn (name2, "?*[");
810   size_t min_prefix_len;
811 
812   /* Note that if there is no wildcard character, then we treat the
813      terminating 0 as part of the prefix.  Thus ".text" won't match
814      ".text." or ".text.*", for example.  */
815   if (name1[prefix1_len] == '\0')
816     prefix1_len++;
817   if (name2[prefix2_len] == '\0')
818     prefix2_len++;
819 
820   min_prefix_len = prefix1_len < prefix2_len ? prefix1_len : prefix2_len;
821 
822   return memcmp (name1, name2, min_prefix_len) == 0;
823 }
824 
825 /* Select specialized code to handle various kinds of wildcard
826    statements.  */
827 
828 static void
analyze_walk_wild_section_handler(lang_wild_statement_type * ptr)829 analyze_walk_wild_section_handler (lang_wild_statement_type *ptr)
830 {
831   int sec_count = 0;
832   int wild_name_count = 0;
833   struct wildcard_list *sec;
834   int signature;
835   int data_counter;
836 
837   ptr->walk_wild_section_handler = walk_wild_section_general;
838   ptr->handler_data[0] = NULL;
839   ptr->handler_data[1] = NULL;
840   ptr->handler_data[2] = NULL;
841   ptr->handler_data[3] = NULL;
842   ptr->tree = NULL;
843 
844   /* Count how many wildcard_specs there are, and how many of those
845      actually use wildcards in the name.  Also, bail out if any of the
846      wildcard names are NULL. (Can this actually happen?
847      walk_wild_section used to test for it.)  And bail out if any
848      of the wildcards are more complex than a simple string
849      ending in a single '*'.  */
850   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
851     {
852       ++sec_count;
853       if (sec->spec.name == NULL)
854 	return;
855       if (wildcardp (sec->spec.name))
856 	{
857 	  ++wild_name_count;
858 	  if (!is_simple_wild (sec->spec.name))
859 	    return;
860 	}
861     }
862 
863   /* The zero-spec case would be easy to optimize but it doesn't
864      happen in practice.  Likewise, more than 4 specs doesn't
865      happen in practice.  */
866   if (sec_count == 0 || sec_count > 4)
867     return;
868 
869   /* Check that no two specs can match the same section.  */
870   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
871     {
872       struct wildcard_list *sec2;
873       for (sec2 = sec->next; sec2 != NULL; sec2 = sec2->next)
874 	{
875 	  if (wild_spec_can_overlap (sec->spec.name, sec2->spec.name))
876 	    return;
877 	}
878     }
879 
880   signature = (sec_count << 8) + wild_name_count;
881   switch (signature)
882     {
883     case 0x0100:
884       ptr->walk_wild_section_handler = walk_wild_section_specs1_wild0;
885       break;
886     case 0x0101:
887       ptr->walk_wild_section_handler = walk_wild_section_specs1_wild1;
888       break;
889     case 0x0201:
890       ptr->walk_wild_section_handler = walk_wild_section_specs2_wild1;
891       break;
892     case 0x0302:
893       ptr->walk_wild_section_handler = walk_wild_section_specs3_wild2;
894       break;
895     case 0x0402:
896       ptr->walk_wild_section_handler = walk_wild_section_specs4_wild2;
897       break;
898     default:
899       return;
900     }
901 
902   /* Now fill the data array with pointers to the specs, first the
903      specs with non-wildcard names, then the specs with wildcard
904      names.  It's OK to process the specs in different order from the
905      given order, because we've already determined that no section
906      will match more than one spec.  */
907   data_counter = 0;
908   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
909     if (!wildcardp (sec->spec.name))
910       ptr->handler_data[data_counter++] = sec;
911   for (sec = ptr->section_list; sec != NULL; sec = sec->next)
912     if (wildcardp (sec->spec.name))
913       ptr->handler_data[data_counter++] = sec;
914 }
915 
916 /* Handle a wild statement for a single file F.  */
917 
918 static void
walk_wild_file(lang_wild_statement_type * s,lang_input_statement_type * f,callback_t callback,void * data)919 walk_wild_file (lang_wild_statement_type *s,
920 		lang_input_statement_type *f,
921 		callback_t callback,
922 		void *data)
923 {
924   if (walk_wild_file_in_exclude_list (s->exclude_name_list, f))
925     return;
926 
927   if (f->the_bfd == NULL
928       || !bfd_check_format (f->the_bfd, bfd_archive))
929     walk_wild_section (s, f, callback, data);
930   else
931     {
932       bfd *member;
933 
934       /* This is an archive file.  We must map each member of the
935 	 archive separately.  */
936       member = bfd_openr_next_archived_file (f->the_bfd, NULL);
937       while (member != NULL)
938 	{
939 	  /* When lookup_name is called, it will call the add_symbols
940 	     entry point for the archive.  For each element of the
941 	     archive which is included, BFD will call ldlang_add_file,
942 	     which will set the usrdata field of the member to the
943 	     lang_input_statement.  */
944 	  if (bfd_usrdata (member) != NULL)
945 	    walk_wild_section (s, bfd_usrdata (member), callback, data);
946 
947 	  member = bfd_openr_next_archived_file (f->the_bfd, member);
948 	}
949     }
950 }
951 
952 static void
walk_wild(lang_wild_statement_type * s,callback_t callback,void * data)953 walk_wild (lang_wild_statement_type *s, callback_t callback, void *data)
954 {
955   const char *file_spec = s->filename;
956   char *p;
957 
958   if (file_spec == NULL)
959     {
960       /* Perform the iteration over all files in the list.  */
961       LANG_FOR_EACH_INPUT_STATEMENT (f)
962 	{
963 	  walk_wild_file (s, f, callback, data);
964 	}
965     }
966   else if ((p = archive_path (file_spec)) != NULL)
967     {
968       LANG_FOR_EACH_INPUT_STATEMENT (f)
969 	{
970 	  if (input_statement_is_archive_path (file_spec, p, f))
971 	    walk_wild_file (s, f, callback, data);
972 	}
973     }
974   else if (wildcardp (file_spec))
975     {
976       LANG_FOR_EACH_INPUT_STATEMENT (f)
977 	{
978 	  if (fnmatch (file_spec, f->filename, 0) == 0)
979 	    walk_wild_file (s, f, callback, data);
980 	}
981     }
982   else
983     {
984       lang_input_statement_type *f;
985 
986       /* Perform the iteration over a single file.  */
987       f = lookup_name (file_spec);
988       if (f)
989 	walk_wild_file (s, f, callback, data);
990     }
991 }
992 
993 /* lang_for_each_statement walks the parse tree and calls the provided
994    function for each node, except those inside output section statements
995    with constraint set to -1.  */
996 
997 void
lang_for_each_statement_worker(void (* func)(lang_statement_union_type *),lang_statement_union_type * s)998 lang_for_each_statement_worker (void (*func) (lang_statement_union_type *),
999 				lang_statement_union_type *s)
1000 {
1001   for (; s != NULL; s = s->header.next)
1002     {
1003       func (s);
1004 
1005       switch (s->header.type)
1006 	{
1007 	case lang_constructors_statement_enum:
1008 	  lang_for_each_statement_worker (func, constructor_list.head);
1009 	  break;
1010 	case lang_output_section_statement_enum:
1011 	  if (s->output_section_statement.constraint != -1)
1012 	    lang_for_each_statement_worker
1013 	      (func, s->output_section_statement.children.head);
1014 	  break;
1015 	case lang_wild_statement_enum:
1016 	  lang_for_each_statement_worker (func,
1017 					  s->wild_statement.children.head);
1018 	  break;
1019 	case lang_group_statement_enum:
1020 	  lang_for_each_statement_worker (func,
1021 					  s->group_statement.children.head);
1022 	  break;
1023 	case lang_data_statement_enum:
1024 	case lang_reloc_statement_enum:
1025 	case lang_object_symbols_statement_enum:
1026 	case lang_output_statement_enum:
1027 	case lang_target_statement_enum:
1028 	case lang_input_section_enum:
1029 	case lang_input_statement_enum:
1030 	case lang_assignment_statement_enum:
1031 	case lang_padding_statement_enum:
1032 	case lang_address_statement_enum:
1033 	case lang_fill_statement_enum:
1034 	case lang_insert_statement_enum:
1035 	  break;
1036 	default:
1037 	  FAIL ();
1038 	  break;
1039 	}
1040     }
1041 }
1042 
1043 void
lang_for_each_statement(void (* func)(lang_statement_union_type *))1044 lang_for_each_statement (void (*func) (lang_statement_union_type *))
1045 {
1046   lang_for_each_statement_worker (func, statement_list.head);
1047 }
1048 
1049 /*----------------------------------------------------------------------*/
1050 
1051 void
lang_list_init(lang_statement_list_type * list)1052 lang_list_init (lang_statement_list_type *list)
1053 {
1054   list->head = NULL;
1055   list->tail = &list->head;
1056 }
1057 
1058 static void
lang_statement_append(lang_statement_list_type * list,void * element,void * field)1059 lang_statement_append (lang_statement_list_type *list,
1060 		       void *element,
1061 		       void *field)
1062 {
1063   *(list->tail) = element;
1064   list->tail = field;
1065 }
1066 
1067 void
push_stat_ptr(lang_statement_list_type * new_ptr)1068 push_stat_ptr (lang_statement_list_type *new_ptr)
1069 {
1070   if (stat_save_ptr >= stat_save + sizeof (stat_save) / sizeof (stat_save[0]))
1071     abort ();
1072   *stat_save_ptr++ = stat_ptr;
1073   stat_ptr = new_ptr;
1074 }
1075 
1076 void
pop_stat_ptr(void)1077 pop_stat_ptr (void)
1078 {
1079   if (stat_save_ptr <= stat_save)
1080     abort ();
1081   stat_ptr = *--stat_save_ptr;
1082 }
1083 
1084 /* Build a new statement node for the parse tree.  */
1085 
1086 static lang_statement_union_type *
new_statement(enum statement_enum type,size_t size,lang_statement_list_type * list)1087 new_statement (enum statement_enum type,
1088 	       size_t size,
1089 	       lang_statement_list_type *list)
1090 {
1091   lang_statement_union_type *new_stmt;
1092 
1093   new_stmt = stat_alloc (size);
1094   new_stmt->header.type = type;
1095   new_stmt->header.next = NULL;
1096   lang_statement_append (list, new_stmt, &new_stmt->header.next);
1097   return new_stmt;
1098 }
1099 
1100 /* Build a new input file node for the language.  There are several
1101    ways in which we treat an input file, eg, we only look at symbols,
1102    or prefix it with a -l etc.
1103 
1104    We can be supplied with requests for input files more than once;
1105    they may, for example be split over several lines like foo.o(.text)
1106    foo.o(.data) etc, so when asked for a file we check that we haven't
1107    got it already so we don't duplicate the bfd.  */
1108 
1109 static lang_input_statement_type *
new_afile(const char * name,lang_input_file_enum_type file_type,const char * target,const char * from_filename)1110 new_afile (const char *name,
1111 	   lang_input_file_enum_type file_type,
1112 	   const char *target,
1113 	   const char *from_filename)
1114 {
1115   lang_input_statement_type *p;
1116 
1117   lang_has_input_file = TRUE;
1118 
1119   p = new_stat (lang_input_statement, stat_ptr);
1120   memset (&p->the_bfd, 0,
1121 	  sizeof (*p) - offsetof (lang_input_statement_type, the_bfd));
1122   p->extra_search_path = NULL;
1123   p->target = target;
1124   p->flags.dynamic = input_flags.dynamic;
1125   p->flags.add_DT_NEEDED_for_dynamic = input_flags.add_DT_NEEDED_for_dynamic;
1126   p->flags.add_DT_NEEDED_for_regular = input_flags.add_DT_NEEDED_for_regular;
1127   p->flags.whole_archive = input_flags.whole_archive;
1128   p->flags.sysrooted = input_flags.sysrooted;
1129 
1130   switch (file_type)
1131     {
1132     case lang_input_file_is_symbols_only_enum:
1133       p->filename = name;
1134       p->local_sym_name = name;
1135       p->flags.real = TRUE;
1136       p->flags.just_syms = TRUE;
1137       break;
1138     case lang_input_file_is_fake_enum:
1139       p->filename = name;
1140       p->local_sym_name = name;
1141       break;
1142     case lang_input_file_is_l_enum:
1143       if (name[0] == ':' && name[1] != '\0')
1144 	{
1145 	  p->filename = name + 1;
1146 	  p->flags.full_name_provided = TRUE;
1147 	}
1148       else
1149 	p->filename = name;
1150       p->local_sym_name = concat ("-l", name, (const char *) NULL);
1151       p->flags.maybe_archive = TRUE;
1152       p->flags.real = TRUE;
1153       p->flags.search_dirs = TRUE;
1154       break;
1155     case lang_input_file_is_marker_enum:
1156       p->filename = name;
1157       p->local_sym_name = name;
1158       p->flags.search_dirs = TRUE;
1159       break;
1160     case lang_input_file_is_search_file_enum:
1161       p->filename = name;
1162       p->local_sym_name = name;
1163       /* If name is a relative path, search the directory of the current linker
1164          script first. */
1165       if (from_filename && !IS_ABSOLUTE_PATH (name))
1166         p->extra_search_path = ldirname (from_filename);
1167       p->flags.real = TRUE;
1168       p->flags.search_dirs = TRUE;
1169       break;
1170     case lang_input_file_is_file_enum:
1171       p->filename = name;
1172       p->local_sym_name = name;
1173       p->flags.real = TRUE;
1174       break;
1175     default:
1176       FAIL ();
1177     }
1178 
1179   lang_statement_append (&input_file_chain, p, &p->next_real_file);
1180   return p;
1181 }
1182 
1183 lang_input_statement_type *
lang_add_input_file(const char * name,lang_input_file_enum_type file_type,const char * target)1184 lang_add_input_file (const char *name,
1185 		     lang_input_file_enum_type file_type,
1186 		     const char *target)
1187 {
1188   if (name != NULL
1189       && (*name == '=' || CONST_STRNEQ (name, "$SYSROOT")))
1190     {
1191       lang_input_statement_type *ret;
1192       char *sysrooted_name
1193 	= concat (ld_sysroot,
1194 		  name + (*name == '=' ? 1 : strlen ("$SYSROOT")),
1195 		  (const char *) NULL);
1196 
1197       /* We've now forcibly prepended the sysroot, making the input
1198 	 file independent of the context.  Therefore, temporarily
1199 	 force a non-sysrooted context for this statement, so it won't
1200 	 get the sysroot prepended again when opened.  (N.B. if it's a
1201 	 script, any child nodes with input files starting with "/"
1202 	 will be handled as "sysrooted" as they'll be found to be
1203 	 within the sysroot subdirectory.)  */
1204       unsigned int outer_sysrooted = input_flags.sysrooted;
1205       input_flags.sysrooted = 0;
1206       ret = new_afile (sysrooted_name, file_type, target, NULL);
1207       input_flags.sysrooted = outer_sysrooted;
1208       return ret;
1209     }
1210 
1211   return new_afile (name, file_type, target, current_input_file);
1212 }
1213 
1214 struct out_section_hash_entry
1215 {
1216   struct bfd_hash_entry root;
1217   lang_statement_union_type s;
1218 };
1219 
1220 /* The hash table.  */
1221 
1222 static struct bfd_hash_table output_section_statement_table;
1223 
1224 /* Support routines for the hash table used by lang_output_section_find,
1225    initialize the table, fill in an entry and remove the table.  */
1226 
1227 static struct bfd_hash_entry *
output_section_statement_newfunc(struct bfd_hash_entry * entry,struct bfd_hash_table * table,const char * string)1228 output_section_statement_newfunc (struct bfd_hash_entry *entry,
1229 				  struct bfd_hash_table *table,
1230 				  const char *string)
1231 {
1232   lang_output_section_statement_type **nextp;
1233   struct out_section_hash_entry *ret;
1234 
1235   if (entry == NULL)
1236     {
1237       entry = (struct bfd_hash_entry *) bfd_hash_allocate (table,
1238 							   sizeof (*ret));
1239       if (entry == NULL)
1240 	return entry;
1241     }
1242 
1243   entry = bfd_hash_newfunc (entry, table, string);
1244   if (entry == NULL)
1245     return entry;
1246 
1247   ret = (struct out_section_hash_entry *) entry;
1248   memset (&ret->s, 0, sizeof (ret->s));
1249   ret->s.header.type = lang_output_section_statement_enum;
1250   ret->s.output_section_statement.subsection_alignment = NULL;
1251   ret->s.output_section_statement.section_alignment = NULL;
1252   ret->s.output_section_statement.block_value = 1;
1253   lang_list_init (&ret->s.output_section_statement.children);
1254   lang_statement_append (stat_ptr, &ret->s, &ret->s.header.next);
1255 
1256   /* For every output section statement added to the list, except the
1257      first one, lang_os_list.tail points to the "next"
1258      field of the last element of the list.  */
1259   if (lang_os_list.head != NULL)
1260     ret->s.output_section_statement.prev
1261       = ((lang_output_section_statement_type *)
1262 	 ((char *) lang_os_list.tail
1263 	  - offsetof (lang_output_section_statement_type, next)));
1264 
1265   /* GCC's strict aliasing rules prevent us from just casting the
1266      address, so we store the pointer in a variable and cast that
1267      instead.  */
1268   nextp = &ret->s.output_section_statement.next;
1269   lang_statement_append (&lang_os_list, &ret->s, nextp);
1270   return &ret->root;
1271 }
1272 
1273 static void
output_section_statement_table_init(void)1274 output_section_statement_table_init (void)
1275 {
1276   if (!bfd_hash_table_init_n (&output_section_statement_table,
1277 			      output_section_statement_newfunc,
1278 			      sizeof (struct out_section_hash_entry),
1279 			      61))
1280     einfo (_("%F%P: can not create hash table: %E\n"));
1281 }
1282 
1283 static void
output_section_statement_table_free(void)1284 output_section_statement_table_free (void)
1285 {
1286   bfd_hash_table_free (&output_section_statement_table);
1287 }
1288 
1289 /* Build enough state so that the parser can build its tree.  */
1290 
1291 void
lang_init(void)1292 lang_init (void)
1293 {
1294   obstack_begin (&stat_obstack, 1000);
1295 
1296   stat_ptr = &statement_list;
1297 
1298   output_section_statement_table_init ();
1299 
1300   lang_list_init (stat_ptr);
1301 
1302   lang_list_init (&input_file_chain);
1303   lang_list_init (&lang_os_list);
1304   lang_list_init (&file_chain);
1305   first_file = lang_add_input_file (NULL, lang_input_file_is_marker_enum,
1306 				    NULL);
1307   abs_output_section =
1308     lang_output_section_statement_lookup (BFD_ABS_SECTION_NAME, 0, TRUE);
1309 
1310   abs_output_section->bfd_section = bfd_abs_section_ptr;
1311 
1312   asneeded_list_head = NULL;
1313   asneeded_list_tail = &asneeded_list_head;
1314 }
1315 
1316 void
lang_finish(void)1317 lang_finish (void)
1318 {
1319   output_section_statement_table_free ();
1320 }
1321 
1322 /*----------------------------------------------------------------------
1323   A region is an area of memory declared with the
1324   MEMORY {  name:org=exp, len=exp ... }
1325   syntax.
1326 
1327   We maintain a list of all the regions here.
1328 
1329   If no regions are specified in the script, then the default is used
1330   which is created when looked up to be the entire data space.
1331 
1332   If create is true we are creating a region inside a MEMORY block.
1333   In this case it is probably an error to create a region that has
1334   already been created.  If we are not inside a MEMORY block it is
1335   dubious to use an undeclared region name (except DEFAULT_MEMORY_REGION)
1336   and so we issue a warning.
1337 
1338   Each region has at least one name.  The first name is either
1339   DEFAULT_MEMORY_REGION or the name given in the MEMORY block.  You can add
1340   alias names to an existing region within a script with
1341   REGION_ALIAS (alias, region_name).  Each name corresponds to at most one
1342   region.  */
1343 
1344 static lang_memory_region_type *lang_memory_region_list;
1345 static lang_memory_region_type **lang_memory_region_list_tail
1346   = &lang_memory_region_list;
1347 
1348 lang_memory_region_type *
lang_memory_region_lookup(const char * const name,bfd_boolean create)1349 lang_memory_region_lookup (const char *const name, bfd_boolean create)
1350 {
1351   lang_memory_region_name *n;
1352   lang_memory_region_type *r;
1353   lang_memory_region_type *new_region;
1354 
1355   /* NAME is NULL for LMA memspecs if no region was specified.  */
1356   if (name == NULL)
1357     return NULL;
1358 
1359   for (r = lang_memory_region_list; r != NULL; r = r->next)
1360     for (n = &r->name_list; n != NULL; n = n->next)
1361       if (strcmp (n->name, name) == 0)
1362 	{
1363 	  if (create)
1364 	    einfo (_("%P:%pS: warning: redeclaration of memory region `%s'\n"),
1365 		   NULL, name);
1366 	  return r;
1367 	}
1368 
1369   if (!create && strcmp (name, DEFAULT_MEMORY_REGION))
1370     einfo (_("%P:%pS: warning: memory region `%s' not declared\n"),
1371 	   NULL, name);
1372 
1373   new_region = stat_alloc (sizeof (lang_memory_region_type));
1374 
1375   new_region->name_list.name = xstrdup (name);
1376   new_region->name_list.next = NULL;
1377   new_region->next = NULL;
1378   new_region->origin_exp = NULL;
1379   new_region->origin = 0;
1380   new_region->length_exp = NULL;
1381   new_region->length = ~(bfd_size_type) 0;
1382   new_region->current = 0;
1383   new_region->last_os = NULL;
1384   new_region->flags = 0;
1385   new_region->not_flags = 0;
1386   new_region->had_full_message = FALSE;
1387 
1388   *lang_memory_region_list_tail = new_region;
1389   lang_memory_region_list_tail = &new_region->next;
1390 
1391   return new_region;
1392 }
1393 
1394 void
lang_memory_region_alias(const char * alias,const char * region_name)1395 lang_memory_region_alias (const char *alias, const char *region_name)
1396 {
1397   lang_memory_region_name *n;
1398   lang_memory_region_type *r;
1399   lang_memory_region_type *region;
1400 
1401   /* The default region must be unique.  This ensures that it is not necessary
1402      to iterate through the name list if someone wants the check if a region is
1403      the default memory region.  */
1404   if (strcmp (region_name, DEFAULT_MEMORY_REGION) == 0
1405       || strcmp (alias, DEFAULT_MEMORY_REGION) == 0)
1406     einfo (_("%F%P:%pS: error: alias for default memory region\n"), NULL);
1407 
1408   /* Look for the target region and check if the alias is not already
1409      in use.  */
1410   region = NULL;
1411   for (r = lang_memory_region_list; r != NULL; r = r->next)
1412     for (n = &r->name_list; n != NULL; n = n->next)
1413       {
1414 	if (region == NULL && strcmp (n->name, region_name) == 0)
1415 	  region = r;
1416 	if (strcmp (n->name, alias) == 0)
1417 	  einfo (_("%F%P:%pS: error: redefinition of memory region "
1418 		   "alias `%s'\n"),
1419 		 NULL, alias);
1420       }
1421 
1422   /* Check if the target region exists.  */
1423   if (region == NULL)
1424     einfo (_("%F%P:%pS: error: memory region `%s' "
1425 	     "for alias `%s' does not exist\n"),
1426 	   NULL, region_name, alias);
1427 
1428   /* Add alias to region name list.  */
1429   n = stat_alloc (sizeof (lang_memory_region_name));
1430   n->name = xstrdup (alias);
1431   n->next = region->name_list.next;
1432   region->name_list.next = n;
1433 }
1434 
1435 static lang_memory_region_type *
lang_memory_default(asection * section)1436 lang_memory_default (asection *section)
1437 {
1438   lang_memory_region_type *p;
1439 
1440   flagword sec_flags = section->flags;
1441 
1442   /* Override SEC_DATA to mean a writable section.  */
1443   if ((sec_flags & (SEC_ALLOC | SEC_READONLY | SEC_CODE)) == SEC_ALLOC)
1444     sec_flags |= SEC_DATA;
1445 
1446   for (p = lang_memory_region_list; p != NULL; p = p->next)
1447     {
1448       if ((p->flags & sec_flags) != 0
1449 	  && (p->not_flags & sec_flags) == 0)
1450 	{
1451 	  return p;
1452 	}
1453     }
1454   return lang_memory_region_lookup (DEFAULT_MEMORY_REGION, FALSE);
1455 }
1456 
1457 /* Get the output section statement directly from the userdata.  */
1458 
1459 lang_output_section_statement_type *
lang_output_section_get(const asection * output_section)1460 lang_output_section_get (const asection *output_section)
1461 {
1462   return bfd_section_userdata (output_section);
1463 }
1464 
1465 /* Find or create an output_section_statement with the given NAME.
1466    If CONSTRAINT is non-zero match one with that constraint, otherwise
1467    match any non-negative constraint.  If CREATE, always make a
1468    new output_section_statement for SPECIAL CONSTRAINT.  */
1469 
1470 lang_output_section_statement_type *
lang_output_section_statement_lookup(const char * name,int constraint,bfd_boolean create)1471 lang_output_section_statement_lookup (const char *name,
1472 				      int constraint,
1473 				      bfd_boolean create)
1474 {
1475   struct out_section_hash_entry *entry;
1476 
1477   entry = ((struct out_section_hash_entry *)
1478 	   bfd_hash_lookup (&output_section_statement_table, name,
1479 			    create, FALSE));
1480   if (entry == NULL)
1481     {
1482       if (create)
1483 	einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1484       return NULL;
1485     }
1486 
1487   if (entry->s.output_section_statement.name != NULL)
1488     {
1489       /* We have a section of this name, but it might not have the correct
1490 	 constraint.  */
1491       struct out_section_hash_entry *last_ent;
1492 
1493       name = entry->s.output_section_statement.name;
1494       if (create && constraint == SPECIAL)
1495 	/* Not traversing to the end reverses the order of the second
1496 	   and subsequent SPECIAL sections in the hash table chain,
1497 	   but that shouldn't matter.  */
1498 	last_ent = entry;
1499       else
1500 	do
1501 	  {
1502 	    if (constraint == entry->s.output_section_statement.constraint
1503 		|| (constraint == 0
1504 		    && entry->s.output_section_statement.constraint >= 0))
1505 	      return &entry->s.output_section_statement;
1506 	    last_ent = entry;
1507 	    entry = (struct out_section_hash_entry *) entry->root.next;
1508 	  }
1509 	while (entry != NULL
1510 	       && name == entry->s.output_section_statement.name);
1511 
1512       if (!create)
1513 	return NULL;
1514 
1515       entry
1516 	= ((struct out_section_hash_entry *)
1517 	   output_section_statement_newfunc (NULL,
1518 					     &output_section_statement_table,
1519 					     name));
1520       if (entry == NULL)
1521 	{
1522 	  einfo (_("%F%P: failed creating section `%s': %E\n"), name);
1523 	  return NULL;
1524 	}
1525       entry->root = last_ent->root;
1526       last_ent->root.next = &entry->root;
1527     }
1528 
1529   entry->s.output_section_statement.name = name;
1530   entry->s.output_section_statement.constraint = constraint;
1531   return &entry->s.output_section_statement;
1532 }
1533 
1534 /* Find the next output_section_statement with the same name as OS.
1535    If CONSTRAINT is non-zero, find one with that constraint otherwise
1536    match any non-negative constraint.  */
1537 
1538 lang_output_section_statement_type *
next_matching_output_section_statement(lang_output_section_statement_type * os,int constraint)1539 next_matching_output_section_statement (lang_output_section_statement_type *os,
1540 					int constraint)
1541 {
1542   /* All output_section_statements are actually part of a
1543      struct out_section_hash_entry.  */
1544   struct out_section_hash_entry *entry = (struct out_section_hash_entry *)
1545     ((char *) os
1546      - offsetof (struct out_section_hash_entry, s.output_section_statement));
1547   const char *name = os->name;
1548 
1549   ASSERT (name == entry->root.string);
1550   do
1551     {
1552       entry = (struct out_section_hash_entry *) entry->root.next;
1553       if (entry == NULL
1554 	  || name != entry->s.output_section_statement.name)
1555 	return NULL;
1556     }
1557   while (constraint != entry->s.output_section_statement.constraint
1558 	 && (constraint != 0
1559 	     || entry->s.output_section_statement.constraint < 0));
1560 
1561   return &entry->s.output_section_statement;
1562 }
1563 
1564 /* A variant of lang_output_section_find used by place_orphan.
1565    Returns the output statement that should precede a new output
1566    statement for SEC.  If an exact match is found on certain flags,
1567    sets *EXACT too.  */
1568 
1569 lang_output_section_statement_type *
lang_output_section_find_by_flags(const asection * sec,flagword sec_flags,lang_output_section_statement_type ** exact,lang_match_sec_type_func match_type)1570 lang_output_section_find_by_flags (const asection *sec,
1571 				   flagword sec_flags,
1572 				   lang_output_section_statement_type **exact,
1573 				   lang_match_sec_type_func match_type)
1574 {
1575   lang_output_section_statement_type *first, *look, *found;
1576   flagword look_flags, differ;
1577 
1578   /* We know the first statement on this list is *ABS*.  May as well
1579      skip it.  */
1580   first = (void *) lang_os_list.head;
1581   first = first->next;
1582 
1583   /* First try for an exact match.  */
1584   found = NULL;
1585   for (look = first; look; look = look->next)
1586     {
1587       look_flags = look->flags;
1588       if (look->bfd_section != NULL)
1589 	{
1590 	  look_flags = look->bfd_section->flags;
1591 	  if (match_type && !match_type (link_info.output_bfd,
1592 					 look->bfd_section,
1593 					 sec->owner, sec))
1594 	    continue;
1595 	}
1596       differ = look_flags ^ sec_flags;
1597       if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY
1598 		      | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1599 	found = look;
1600     }
1601   if (found != NULL)
1602     {
1603       if (exact != NULL)
1604 	*exact = found;
1605       return found;
1606     }
1607 
1608   if ((sec_flags & SEC_CODE) != 0
1609       && (sec_flags & SEC_ALLOC) != 0)
1610     {
1611       /* Try for a rw code section.  */
1612       for (look = first; look; look = look->next)
1613 	{
1614 	  look_flags = look->flags;
1615 	  if (look->bfd_section != NULL)
1616 	    {
1617 	      look_flags = look->bfd_section->flags;
1618 	      if (match_type && !match_type (link_info.output_bfd,
1619 					     look->bfd_section,
1620 					     sec->owner, sec))
1621 		continue;
1622 	    }
1623 	  differ = look_flags ^ sec_flags;
1624 	  if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1625 			  | SEC_CODE | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1626 	    found = look;
1627 	}
1628     }
1629   else if ((sec_flags & SEC_READONLY) != 0
1630 	   && (sec_flags & SEC_ALLOC) != 0)
1631     {
1632       /* .rodata can go after .text, .sdata2 after .rodata.  */
1633       for (look = first; look; look = look->next)
1634 	{
1635 	  look_flags = look->flags;
1636 	  if (look->bfd_section != NULL)
1637 	    {
1638 	      look_flags = look->bfd_section->flags;
1639 	      if (match_type && !match_type (link_info.output_bfd,
1640 					     look->bfd_section,
1641 					     sec->owner, sec))
1642 		continue;
1643 	    }
1644 	  differ = look_flags ^ sec_flags;
1645 	  if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1646 			  | SEC_READONLY | SEC_SMALL_DATA))
1647 	      || (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1648 			      | SEC_READONLY))
1649 		  && !(look_flags & SEC_SMALL_DATA)))
1650 	    found = look;
1651 	}
1652     }
1653   else if ((sec_flags & SEC_THREAD_LOCAL) != 0
1654 	   && (sec_flags & SEC_ALLOC) != 0)
1655     {
1656       /* .tdata can go after .data, .tbss after .tdata.  Treat .tbss
1657 	 as if it were a loaded section, and don't use match_type.  */
1658       bfd_boolean seen_thread_local = FALSE;
1659 
1660       match_type = NULL;
1661       for (look = first; look; look = look->next)
1662 	{
1663 	  look_flags = look->flags;
1664 	  if (look->bfd_section != NULL)
1665 	    look_flags = look->bfd_section->flags;
1666 
1667 	  differ = look_flags ^ (sec_flags | SEC_LOAD | SEC_HAS_CONTENTS);
1668 	  if (!(differ & (SEC_THREAD_LOCAL | SEC_ALLOC)))
1669 	    {
1670 	      /* .tdata and .tbss must be adjacent and in that order.  */
1671 	      if (!(look_flags & SEC_LOAD)
1672 		  && (sec_flags & SEC_LOAD))
1673 		/* ..so if we're at a .tbss section and we're placing
1674 		   a .tdata section stop looking and return the
1675 		   previous section.  */
1676 		break;
1677 	      found = look;
1678 	      seen_thread_local = TRUE;
1679 	    }
1680 	  else if (seen_thread_local)
1681 	    break;
1682 	  else if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD)))
1683 	    found = look;
1684 	}
1685     }
1686   else if ((sec_flags & SEC_SMALL_DATA) != 0
1687 	   && (sec_flags & SEC_ALLOC) != 0)
1688     {
1689       /* .sdata goes after .data, .sbss after .sdata.  */
1690       for (look = first; look; look = look->next)
1691 	{
1692 	  look_flags = look->flags;
1693 	  if (look->bfd_section != NULL)
1694 	    {
1695 	      look_flags = look->bfd_section->flags;
1696 	      if (match_type && !match_type (link_info.output_bfd,
1697 					     look->bfd_section,
1698 					     sec->owner, sec))
1699 		continue;
1700 	    }
1701 	  differ = look_flags ^ sec_flags;
1702 	  if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1703 			  | SEC_THREAD_LOCAL))
1704 	      || ((look_flags & SEC_SMALL_DATA)
1705 		  && !(sec_flags & SEC_HAS_CONTENTS)))
1706 	    found = look;
1707 	}
1708     }
1709   else if ((sec_flags & SEC_HAS_CONTENTS) != 0
1710 	   && (sec_flags & SEC_ALLOC) != 0)
1711     {
1712       /* .data goes after .rodata.  */
1713       for (look = first; look; look = look->next)
1714 	{
1715 	  look_flags = look->flags;
1716 	  if (look->bfd_section != NULL)
1717 	    {
1718 	      look_flags = look->bfd_section->flags;
1719 	      if (match_type && !match_type (link_info.output_bfd,
1720 					     look->bfd_section,
1721 					     sec->owner, sec))
1722 		continue;
1723 	    }
1724 	  differ = look_flags ^ sec_flags;
1725 	  if (!(differ & (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD
1726 			  | SEC_SMALL_DATA | SEC_THREAD_LOCAL)))
1727 	    found = look;
1728 	}
1729     }
1730   else if ((sec_flags & SEC_ALLOC) != 0)
1731     {
1732       /* .bss goes after any other alloc section.  */
1733       for (look = first; look; look = look->next)
1734 	{
1735 	  look_flags = look->flags;
1736 	  if (look->bfd_section != NULL)
1737 	    {
1738 	      look_flags = look->bfd_section->flags;
1739 	      if (match_type && !match_type (link_info.output_bfd,
1740 					     look->bfd_section,
1741 					     sec->owner, sec))
1742 		continue;
1743 	    }
1744 	  differ = look_flags ^ sec_flags;
1745 	  if (!(differ & SEC_ALLOC))
1746 	    found = look;
1747 	}
1748     }
1749   else
1750     {
1751       /* non-alloc go last.  */
1752       for (look = first; look; look = look->next)
1753 	{
1754 	  look_flags = look->flags;
1755 	  if (look->bfd_section != NULL)
1756 	    look_flags = look->bfd_section->flags;
1757 	  differ = look_flags ^ sec_flags;
1758 	  if (!(differ & SEC_DEBUGGING))
1759 	    found = look;
1760 	}
1761       return found;
1762     }
1763 
1764   if (found || !match_type)
1765     return found;
1766 
1767   return lang_output_section_find_by_flags (sec, sec_flags, NULL, NULL);
1768 }
1769 
1770 /* Find the last output section before given output statement.
1771    Used by place_orphan.  */
1772 
1773 static asection *
output_prev_sec_find(lang_output_section_statement_type * os)1774 output_prev_sec_find (lang_output_section_statement_type *os)
1775 {
1776   lang_output_section_statement_type *lookup;
1777 
1778   for (lookup = os->prev; lookup != NULL; lookup = lookup->prev)
1779     {
1780       if (lookup->constraint < 0)
1781 	continue;
1782 
1783       if (lookup->bfd_section != NULL && lookup->bfd_section->owner != NULL)
1784 	return lookup->bfd_section;
1785     }
1786 
1787   return NULL;
1788 }
1789 
1790 /* Look for a suitable place for a new output section statement.  The
1791    idea is to skip over anything that might be inside a SECTIONS {}
1792    statement in a script, before we find another output section
1793    statement.  Assignments to "dot" before an output section statement
1794    are assumed to belong to it, except in two cases;  The first
1795    assignment to dot, and assignments before non-alloc sections.
1796    Otherwise we might put an orphan before . = . + SIZEOF_HEADERS or
1797    similar assignments that set the initial address, or we might
1798    insert non-alloc note sections among assignments setting end of
1799    image symbols.  */
1800 
1801 static lang_statement_union_type **
insert_os_after(lang_output_section_statement_type * after)1802 insert_os_after (lang_output_section_statement_type *after)
1803 {
1804   lang_statement_union_type **where;
1805   lang_statement_union_type **assign = NULL;
1806   bfd_boolean ignore_first;
1807 
1808   ignore_first = after == (void *) lang_os_list.head;
1809 
1810   for (where = &after->header.next;
1811        *where != NULL;
1812        where = &(*where)->header.next)
1813     {
1814       switch ((*where)->header.type)
1815 	{
1816 	case lang_assignment_statement_enum:
1817 	  if (assign == NULL)
1818 	    {
1819 	      lang_assignment_statement_type *ass;
1820 
1821 	      ass = &(*where)->assignment_statement;
1822 	      if (ass->exp->type.node_class != etree_assert
1823 		  && ass->exp->assign.dst[0] == '.'
1824 		  && ass->exp->assign.dst[1] == 0)
1825 		{
1826 		  if (!ignore_first)
1827 		    assign = where;
1828 		  ignore_first = FALSE;
1829 		}
1830 	    }
1831 	  continue;
1832 	case lang_wild_statement_enum:
1833 	case lang_input_section_enum:
1834 	case lang_object_symbols_statement_enum:
1835 	case lang_fill_statement_enum:
1836 	case lang_data_statement_enum:
1837 	case lang_reloc_statement_enum:
1838 	case lang_padding_statement_enum:
1839 	case lang_constructors_statement_enum:
1840 	  assign = NULL;
1841 	  ignore_first = FALSE;
1842 	  continue;
1843 	case lang_output_section_statement_enum:
1844 	  if (assign != NULL)
1845 	    {
1846 	      asection *s = (*where)->output_section_statement.bfd_section;
1847 
1848 	      if (s == NULL
1849 		  || s->map_head.s == NULL
1850 		  || (s->flags & SEC_ALLOC) != 0)
1851 		where = assign;
1852 	    }
1853 	  break;
1854 	case lang_input_statement_enum:
1855 	case lang_address_statement_enum:
1856 	case lang_target_statement_enum:
1857 	case lang_output_statement_enum:
1858 	case lang_group_statement_enum:
1859 	case lang_insert_statement_enum:
1860 	  continue;
1861 	}
1862       break;
1863     }
1864 
1865   return where;
1866 }
1867 
1868 lang_output_section_statement_type *
lang_insert_orphan(asection * s,const char * secname,int constraint,lang_output_section_statement_type * after,struct orphan_save * place,etree_type * address,lang_statement_list_type * add_child)1869 lang_insert_orphan (asection *s,
1870 		    const char *secname,
1871 		    int constraint,
1872 		    lang_output_section_statement_type *after,
1873 		    struct orphan_save *place,
1874 		    etree_type *address,
1875 		    lang_statement_list_type *add_child)
1876 {
1877   lang_statement_list_type add;
1878   lang_output_section_statement_type *os;
1879   lang_output_section_statement_type **os_tail;
1880 
1881   /* If we have found an appropriate place for the output section
1882      statements for this orphan, add them to our own private list,
1883      inserting them later into the global statement list.  */
1884   if (after != NULL)
1885     {
1886       lang_list_init (&add);
1887       push_stat_ptr (&add);
1888     }
1889 
1890   if (bfd_link_relocatable (&link_info)
1891       || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0)
1892     address = exp_intop (0);
1893 
1894   os_tail = (lang_output_section_statement_type **) lang_os_list.tail;
1895   os = lang_enter_output_section_statement (secname, address, normal_section,
1896 					    NULL, NULL, NULL, constraint, 0);
1897 
1898   if (add_child == NULL)
1899     add_child = &os->children;
1900   lang_add_section (add_child, s, NULL, os);
1901 
1902   if (after && (s->flags & (SEC_LOAD | SEC_ALLOC)) != 0)
1903     {
1904       const char *region = (after->region
1905 			    ? after->region->name_list.name
1906 			    : DEFAULT_MEMORY_REGION);
1907       const char *lma_region = (after->lma_region
1908 				? after->lma_region->name_list.name
1909 				: NULL);
1910       lang_leave_output_section_statement (NULL, region, after->phdrs,
1911 					   lma_region);
1912     }
1913   else
1914     lang_leave_output_section_statement (NULL, DEFAULT_MEMORY_REGION, NULL,
1915 					 NULL);
1916 
1917   /* Restore the global list pointer.  */
1918   if (after != NULL)
1919     pop_stat_ptr ();
1920 
1921   if (after != NULL && os->bfd_section != NULL)
1922     {
1923       asection *snew, *as;
1924       bfd_boolean place_after = place->stmt == NULL;
1925       bfd_boolean insert_after = TRUE;
1926 
1927       snew = os->bfd_section;
1928 
1929       /* Shuffle the bfd section list to make the output file look
1930 	 neater.  This is really only cosmetic.  */
1931       if (place->section == NULL
1932 	  && after != (void *) lang_os_list.head)
1933 	{
1934 	  asection *bfd_section = after->bfd_section;
1935 
1936 	  /* If the output statement hasn't been used to place any input
1937 	     sections (and thus doesn't have an output bfd_section),
1938 	     look for the closest prior output statement having an
1939 	     output section.  */
1940 	  if (bfd_section == NULL)
1941 	    bfd_section = output_prev_sec_find (after);
1942 
1943 	  if (bfd_section != NULL && bfd_section != snew)
1944 	    place->section = &bfd_section->next;
1945 	}
1946 
1947       if (place->section == NULL)
1948 	place->section = &link_info.output_bfd->sections;
1949 
1950       as = *place->section;
1951 
1952       if (!as)
1953 	{
1954 	  /* Put the section at the end of the list.  */
1955 
1956 	  /* Unlink the section.  */
1957 	  bfd_section_list_remove (link_info.output_bfd, snew);
1958 
1959 	  /* Now tack it back on in the right place.  */
1960 	  bfd_section_list_append (link_info.output_bfd, snew);
1961 	}
1962       else if ((bfd_get_flavour (link_info.output_bfd)
1963 		== bfd_target_elf_flavour)
1964 	       && (bfd_get_flavour (s->owner)
1965 		   == bfd_target_elf_flavour)
1966 	       && ((elf_section_type (s) == SHT_NOTE
1967 		    && (s->flags & SEC_LOAD) != 0)
1968 		   || (elf_section_type (as) == SHT_NOTE
1969 		       && (as->flags & SEC_LOAD) != 0)))
1970 	{
1971 	  /* Make sure that output note sections are grouped and sorted
1972 	     by alignments when inserting a note section or insert a
1973 	     section after a note section,  */
1974 	  asection *sec;
1975 	  /* A specific section after which the output note section
1976 	     should be placed.  */
1977 	  asection *after_sec;
1978 	  /* True if we need to insert the orphan section after a
1979 	     specific section to maintain output note section order.  */
1980 	  bfd_boolean after_sec_note = FALSE;
1981 
1982 	  static asection *first_orphan_note = NULL;
1983 
1984 	  /* Group and sort output note section by alignments in
1985 	     ascending order.  */
1986 	  after_sec = NULL;
1987 	  if (elf_section_type (s) == SHT_NOTE
1988 	      && (s->flags & SEC_LOAD) != 0)
1989 	    {
1990 	      /* Search from the beginning for the last output note
1991 		 section with equal or larger alignments.  NB: Don't
1992 		 place orphan note section after non-note sections.  */
1993 
1994 	      first_orphan_note = NULL;
1995 	      for (sec = link_info.output_bfd->sections;
1996 		   (sec != NULL
1997 		    && !bfd_is_abs_section (sec));
1998 		   sec = sec->next)
1999 		if (sec != snew
2000 		    && elf_section_type (sec) == SHT_NOTE
2001 		    && (sec->flags & SEC_LOAD) != 0)
2002 		  {
2003 		    if (!first_orphan_note)
2004 		      first_orphan_note = sec;
2005 		    if (sec->alignment_power >= s->alignment_power)
2006 		      after_sec = sec;
2007 		  }
2008 		else if (first_orphan_note)
2009 		  {
2010 		    /* Stop if there is non-note section after the first
2011 		       orphan note section.  */
2012 		    break;
2013 		  }
2014 
2015 	      /* If this will be the first orphan note section, it can
2016 		 be placed at the default location.  */
2017 	      after_sec_note = first_orphan_note != NULL;
2018 	      if (after_sec == NULL && after_sec_note)
2019 		{
2020 		  /* If all output note sections have smaller
2021 		     alignments, place the section before all
2022 		     output orphan note sections.  */
2023 		  after_sec = first_orphan_note;
2024 		  insert_after = FALSE;
2025 		}
2026 	    }
2027 	  else if (first_orphan_note)
2028 	    {
2029 	      /* Don't place non-note sections in the middle of orphan
2030 	         note sections.  */
2031 	      after_sec_note = TRUE;
2032 	      after_sec = as;
2033 	      for (sec = as->next;
2034 		   (sec != NULL
2035 		    && !bfd_is_abs_section (sec));
2036 		   sec = sec->next)
2037 		if (elf_section_type (sec) == SHT_NOTE
2038 		    && (sec->flags & SEC_LOAD) != 0)
2039 		  after_sec = sec;
2040 	    }
2041 
2042 	  if (after_sec_note)
2043 	    {
2044 	      if (after_sec)
2045 		{
2046 		  /* Search forward to insert OS after AFTER_SEC output
2047 		     statement.  */
2048 		  lang_output_section_statement_type *stmt, *next;
2049 		  bfd_boolean found = FALSE;
2050 		  for (stmt = after; stmt != NULL; stmt = next)
2051 		    {
2052 		      next = stmt->next;
2053 		      if (insert_after)
2054 			{
2055 			  if (stmt->bfd_section == after_sec)
2056 			    {
2057 			      place_after = TRUE;
2058 			      found = TRUE;
2059 			      after = stmt;
2060 			      break;
2061 			    }
2062 			}
2063 		      else
2064 			{
2065 			  /* If INSERT_AFTER is FALSE, place OS before
2066 			     AFTER_SEC output statement.  */
2067 			  if (next && next->bfd_section == after_sec)
2068 			    {
2069 			      place_after = TRUE;
2070 			      found = TRUE;
2071 			      after = stmt;
2072 			      break;
2073 			    }
2074 			}
2075 		    }
2076 
2077 		  /* Search backward to insert OS after AFTER_SEC output
2078 		     statement.  */
2079 		  if (!found)
2080 		    for (stmt = after; stmt != NULL; stmt = stmt->prev)
2081 		      {
2082 			if (insert_after)
2083 			  {
2084 			    if (stmt->bfd_section == after_sec)
2085 			      {
2086 				place_after = TRUE;
2087 				after = stmt;
2088 				break;
2089 			      }
2090 			  }
2091 			else
2092 			  {
2093 			    /* If INSERT_AFTER is FALSE, place OS before
2094 			       AFTER_SEC output statement.  */
2095 			    if (stmt->next->bfd_section == after_sec)
2096 			      {
2097 				place_after = TRUE;
2098 				after = stmt;
2099 				break;
2100 			      }
2101 			  }
2102 		      }
2103 		}
2104 
2105 	      if (after_sec == NULL
2106 		  || (insert_after && after_sec->next != snew)
2107 		  || (!insert_after && after_sec->prev != snew))
2108 		{
2109 		  /* Unlink the section.  */
2110 		  bfd_section_list_remove (link_info.output_bfd, snew);
2111 
2112 		  /* Place SNEW after AFTER_SEC.  If AFTER_SEC is NULL,
2113 		     prepend SNEW.  */
2114 		  if (after_sec)
2115 		    {
2116 		      if (insert_after)
2117 			bfd_section_list_insert_after (link_info.output_bfd,
2118 						       after_sec, snew);
2119 		      else
2120 			bfd_section_list_insert_before (link_info.output_bfd,
2121 						       after_sec, snew);
2122 		    }
2123 		  else
2124 		    bfd_section_list_prepend (link_info.output_bfd, snew);
2125 		}
2126 	    }
2127 	  else if (as != snew && as->prev != snew)
2128 	    {
2129 	      /* Unlink the section.  */
2130 	      bfd_section_list_remove (link_info.output_bfd, snew);
2131 
2132 	      /* Now tack it back on in the right place.  */
2133 	      bfd_section_list_insert_before (link_info.output_bfd,
2134 					      as, snew);
2135 	    }
2136 	}
2137       else if (as != snew && as->prev != snew)
2138 	{
2139 	  /* Unlink the section.  */
2140 	  bfd_section_list_remove (link_info.output_bfd, snew);
2141 
2142 	  /* Now tack it back on in the right place.  */
2143 	  bfd_section_list_insert_before (link_info.output_bfd, as, snew);
2144 	}
2145 
2146       /* Save the end of this list.  Further ophans of this type will
2147 	 follow the one we've just added.  */
2148       place->section = &snew->next;
2149 
2150       /* The following is non-cosmetic.  We try to put the output
2151 	 statements in some sort of reasonable order here, because they
2152 	 determine the final load addresses of the orphan sections.
2153 	 In addition, placing output statements in the wrong order may
2154 	 require extra segments.  For instance, given a typical
2155 	 situation of all read-only sections placed in one segment and
2156 	 following that a segment containing all the read-write
2157 	 sections, we wouldn't want to place an orphan read/write
2158 	 section before or amongst the read-only ones.  */
2159       if (add.head != NULL)
2160 	{
2161 	  lang_output_section_statement_type *newly_added_os;
2162 
2163 	  /* Place OS after AFTER if AFTER_NOTE is TRUE.  */
2164 	  if (place_after)
2165 	    {
2166 	      lang_statement_union_type **where = insert_os_after (after);
2167 
2168 	      *add.tail = *where;
2169 	      *where = add.head;
2170 
2171 	      place->os_tail = &after->next;
2172 	    }
2173 	  else
2174 	    {
2175 	      /* Put it after the last orphan statement we added.  */
2176 	      *add.tail = *place->stmt;
2177 	      *place->stmt = add.head;
2178 	    }
2179 
2180 	  /* Fix the global list pointer if we happened to tack our
2181 	     new list at the tail.  */
2182 	  if (*stat_ptr->tail == add.head)
2183 	    stat_ptr->tail = add.tail;
2184 
2185 	  /* Save the end of this list.  */
2186 	  place->stmt = add.tail;
2187 
2188 	  /* Do the same for the list of output section statements.  */
2189 	  newly_added_os = *os_tail;
2190 	  *os_tail = NULL;
2191 	  newly_added_os->prev = (lang_output_section_statement_type *)
2192 	    ((char *) place->os_tail
2193 	     - offsetof (lang_output_section_statement_type, next));
2194 	  newly_added_os->next = *place->os_tail;
2195 	  if (newly_added_os->next != NULL)
2196 	    newly_added_os->next->prev = newly_added_os;
2197 	  *place->os_tail = newly_added_os;
2198 	  place->os_tail = &newly_added_os->next;
2199 
2200 	  /* Fixing the global list pointer here is a little different.
2201 	     We added to the list in lang_enter_output_section_statement,
2202 	     trimmed off the new output_section_statment above when
2203 	     assigning *os_tail = NULL, but possibly added it back in
2204 	     the same place when assigning *place->os_tail.  */
2205 	  if (*os_tail == NULL)
2206 	    lang_os_list.tail = (lang_statement_union_type **) os_tail;
2207 	}
2208     }
2209   return os;
2210 }
2211 
2212 static void
lang_print_asneeded(void)2213 lang_print_asneeded (void)
2214 {
2215   struct asneeded_minfo *m;
2216 
2217   if (asneeded_list_head == NULL)
2218     return;
2219 
2220   minfo (_("\nAs-needed library included to satisfy reference by file (symbol)\n\n"));
2221 
2222   for (m = asneeded_list_head; m != NULL; m = m->next)
2223     {
2224       size_t len;
2225 
2226       minfo ("%s", m->soname);
2227       len = strlen (m->soname);
2228 
2229       if (len >= 29)
2230 	{
2231 	  print_nl ();
2232 	  len = 0;
2233 	}
2234       while (len < 30)
2235 	{
2236 	  print_space ();
2237 	  ++len;
2238 	}
2239 
2240       if (m->ref != NULL)
2241 	minfo ("%pB ", m->ref);
2242       minfo ("(%pT)\n", m->name);
2243     }
2244 }
2245 
2246 static void
lang_map_flags(flagword flag)2247 lang_map_flags (flagword flag)
2248 {
2249   if (flag & SEC_ALLOC)
2250     minfo ("a");
2251 
2252   if (flag & SEC_CODE)
2253     minfo ("x");
2254 
2255   if (flag & SEC_READONLY)
2256     minfo ("r");
2257 
2258   if (flag & SEC_DATA)
2259     minfo ("w");
2260 
2261   if (flag & SEC_LOAD)
2262     minfo ("l");
2263 }
2264 
2265 void
lang_map(void)2266 lang_map (void)
2267 {
2268   lang_memory_region_type *m;
2269   bfd_boolean dis_header_printed = FALSE;
2270 
2271   LANG_FOR_EACH_INPUT_STATEMENT (file)
2272     {
2273       asection *s;
2274 
2275       if ((file->the_bfd->flags & (BFD_LINKER_CREATED | DYNAMIC)) != 0
2276 	  || file->flags.just_syms)
2277 	continue;
2278 
2279       if (config.print_map_discarded)
2280 	for (s = file->the_bfd->sections; s != NULL; s = s->next)
2281 	  if ((s->output_section == NULL
2282 	       || s->output_section->owner != link_info.output_bfd)
2283 	      && (s->flags & (SEC_LINKER_CREATED | SEC_KEEP)) == 0)
2284 	    {
2285 	      if (! dis_header_printed)
2286 		{
2287 		  fprintf (config.map_file, _("\nDiscarded input sections\n\n"));
2288 		  dis_header_printed = TRUE;
2289 		}
2290 
2291 	      print_input_section (s, TRUE);
2292 	    }
2293     }
2294 
2295   minfo (_("\nMemory Configuration\n\n"));
2296   fprintf (config.map_file, "%-16s %-18s %-18s %s\n",
2297 	   _("Name"), _("Origin"), _("Length"), _("Attributes"));
2298 
2299   for (m = lang_memory_region_list; m != NULL; m = m->next)
2300     {
2301       char buf[100];
2302       int len;
2303 
2304       fprintf (config.map_file, "%-16s ", m->name_list.name);
2305 
2306       sprintf_vma (buf, m->origin);
2307       minfo ("0x%s ", buf);
2308       len = strlen (buf);
2309       while (len < 16)
2310 	{
2311 	  print_space ();
2312 	  ++len;
2313 	}
2314 
2315       minfo ("0x%V", m->length);
2316       if (m->flags || m->not_flags)
2317 	{
2318 #ifndef BFD64
2319 	  minfo ("        ");
2320 #endif
2321 	  if (m->flags)
2322 	    {
2323 	      print_space ();
2324 	      lang_map_flags (m->flags);
2325 	    }
2326 
2327 	  if (m->not_flags)
2328 	    {
2329 	      minfo (" !");
2330 	      lang_map_flags (m->not_flags);
2331 	    }
2332 	}
2333 
2334       print_nl ();
2335     }
2336 
2337   fprintf (config.map_file, _("\nLinker script and memory map\n\n"));
2338 
2339   if (!link_info.reduce_memory_overheads)
2340     {
2341       obstack_begin (&map_obstack, 1000);
2342       bfd_link_hash_traverse (link_info.hash, sort_def_symbol, 0);
2343     }
2344   expld.phase = lang_fixed_phase_enum;
2345   lang_statement_iteration++;
2346   print_statements ();
2347 
2348   ldemul_extra_map_file_text (link_info.output_bfd, &link_info,
2349 			      config.map_file);
2350 }
2351 
2352 static bfd_boolean
sort_def_symbol(struct bfd_link_hash_entry * hash_entry,void * info ATTRIBUTE_UNUSED)2353 sort_def_symbol (struct bfd_link_hash_entry *hash_entry,
2354 		 void *info ATTRIBUTE_UNUSED)
2355 {
2356   if ((hash_entry->type == bfd_link_hash_defined
2357        || hash_entry->type == bfd_link_hash_defweak)
2358       && hash_entry->u.def.section->owner != link_info.output_bfd
2359       && hash_entry->u.def.section->owner != NULL)
2360     {
2361       input_section_userdata_type *ud;
2362       struct map_symbol_def *def;
2363 
2364       ud = bfd_section_userdata (hash_entry->u.def.section);
2365       if (!ud)
2366 	{
2367 	  ud = stat_alloc (sizeof (*ud));
2368 	  bfd_set_section_userdata (hash_entry->u.def.section, ud);
2369 	  ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2370 	  ud->map_symbol_def_count = 0;
2371 	}
2372       else if (!ud->map_symbol_def_tail)
2373 	ud->map_symbol_def_tail = &ud->map_symbol_def_head;
2374 
2375       def = (struct map_symbol_def *) obstack_alloc (&map_obstack, sizeof *def);
2376       def->entry = hash_entry;
2377       *(ud->map_symbol_def_tail) = def;
2378       ud->map_symbol_def_tail = &def->next;
2379       ud->map_symbol_def_count++;
2380     }
2381   return TRUE;
2382 }
2383 
2384 /* Initialize an output section.  */
2385 
2386 static void
init_os(lang_output_section_statement_type * s,flagword flags)2387 init_os (lang_output_section_statement_type *s, flagword flags)
2388 {
2389   if (strcmp (s->name, DISCARD_SECTION_NAME) == 0)
2390     einfo (_("%F%P: illegal use of `%s' section\n"), DISCARD_SECTION_NAME);
2391 
2392   if (s->constraint != SPECIAL)
2393     s->bfd_section = bfd_get_section_by_name (link_info.output_bfd, s->name);
2394   if (s->bfd_section == NULL)
2395     s->bfd_section = bfd_make_section_anyway_with_flags (link_info.output_bfd,
2396 							 s->name, flags);
2397   if (s->bfd_section == NULL)
2398     {
2399       einfo (_("%F%P: output format %s cannot represent section"
2400 	       " called %s: %E\n"),
2401 	     link_info.output_bfd->xvec->name, s->name);
2402     }
2403   s->bfd_section->output_section = s->bfd_section;
2404   s->bfd_section->output_offset = 0;
2405 
2406   /* Set the userdata of the output section to the output section
2407      statement to avoid lookup.  */
2408   bfd_set_section_userdata (s->bfd_section, s);
2409 
2410   /* If there is a base address, make sure that any sections it might
2411      mention are initialized.  */
2412   if (s->addr_tree != NULL)
2413     exp_init_os (s->addr_tree);
2414 
2415   if (s->load_base != NULL)
2416     exp_init_os (s->load_base);
2417 
2418   /* If supplied an alignment, set it.  */
2419   if (s->section_alignment != NULL)
2420     s->bfd_section->alignment_power = exp_get_power (s->section_alignment,
2421 						     "section alignment");
2422 }
2423 
2424 /* Make sure that all output sections mentioned in an expression are
2425    initialized.  */
2426 
2427 static void
exp_init_os(etree_type * exp)2428 exp_init_os (etree_type *exp)
2429 {
2430   switch (exp->type.node_class)
2431     {
2432     case etree_assign:
2433     case etree_provide:
2434     case etree_provided:
2435       exp_init_os (exp->assign.src);
2436       break;
2437 
2438     case etree_binary:
2439       exp_init_os (exp->binary.lhs);
2440       exp_init_os (exp->binary.rhs);
2441       break;
2442 
2443     case etree_trinary:
2444       exp_init_os (exp->trinary.cond);
2445       exp_init_os (exp->trinary.lhs);
2446       exp_init_os (exp->trinary.rhs);
2447       break;
2448 
2449     case etree_assert:
2450       exp_init_os (exp->assert_s.child);
2451       break;
2452 
2453     case etree_unary:
2454       exp_init_os (exp->unary.child);
2455       break;
2456 
2457     case etree_name:
2458       switch (exp->type.node_code)
2459 	{
2460 	case ADDR:
2461 	case LOADADDR:
2462 	case SIZEOF:
2463 	  {
2464 	    lang_output_section_statement_type *os;
2465 
2466 	    os = lang_output_section_find (exp->name.name);
2467 	    if (os != NULL && os->bfd_section == NULL)
2468 	      init_os (os, 0);
2469 	  }
2470 	}
2471       break;
2472 
2473     default:
2474       break;
2475     }
2476 }
2477 
2478 static void
section_already_linked(bfd * abfd,asection * sec,void * data)2479 section_already_linked (bfd *abfd, asection *sec, void *data)
2480 {
2481   lang_input_statement_type *entry = (lang_input_statement_type *) data;
2482 
2483   /* If we are only reading symbols from this object, then we want to
2484      discard all sections.  */
2485   if (entry->flags.just_syms)
2486     {
2487       bfd_link_just_syms (abfd, sec, &link_info);
2488       return;
2489     }
2490 
2491   /* Deal with SHF_EXCLUDE ELF sections.  */
2492   if (!bfd_link_relocatable (&link_info)
2493       && (abfd->flags & BFD_PLUGIN) == 0
2494       && (sec->flags & (SEC_GROUP | SEC_KEEP | SEC_EXCLUDE)) == SEC_EXCLUDE)
2495     sec->output_section = bfd_abs_section_ptr;
2496 
2497   if (!(abfd->flags & DYNAMIC))
2498     bfd_section_already_linked (abfd, sec, &link_info);
2499 }
2500 
2501 
2502 /* Returns true if SECTION is one we know will be discarded based on its
2503    section flags, otherwise returns false.  */
2504 
2505 static bfd_boolean
lang_discard_section_p(asection * section)2506 lang_discard_section_p (asection *section)
2507 {
2508   bfd_boolean discard;
2509   flagword flags = section->flags;
2510 
2511   /* Discard sections marked with SEC_EXCLUDE.  */
2512   discard = (flags & SEC_EXCLUDE) != 0;
2513 
2514   /* Discard the group descriptor sections when we're finally placing the
2515      sections from within the group.  */
2516   if ((flags & SEC_GROUP) != 0
2517       && link_info.resolve_section_groups)
2518     discard = TRUE;
2519 
2520   /* Discard debugging sections if we are stripping debugging
2521      information.  */
2522   if ((link_info.strip == strip_debugger || link_info.strip == strip_all)
2523       && (flags & SEC_DEBUGGING) != 0)
2524     discard = TRUE;
2525 
2526   return discard;
2527 }
2528 
2529 /* The wild routines.
2530 
2531    These expand statements like *(.text) and foo.o to a list of
2532    explicit actions, like foo.o(.text), bar.o(.text) and
2533    foo.o(.text, .data).  */
2534 
2535 /* Add SECTION to the output section OUTPUT.  Do this by creating a
2536    lang_input_section statement which is placed at PTR.  */
2537 
2538 void
lang_add_section(lang_statement_list_type * ptr,asection * section,struct flag_info * sflag_info,lang_output_section_statement_type * output)2539 lang_add_section (lang_statement_list_type *ptr,
2540 		  asection *section,
2541 		  struct flag_info *sflag_info,
2542 		  lang_output_section_statement_type *output)
2543 {
2544   flagword flags = section->flags;
2545 
2546   bfd_boolean discard;
2547   lang_input_section_type *new_section;
2548   bfd *abfd = link_info.output_bfd;
2549 
2550   /* Is this section one we know should be discarded?  */
2551   discard = lang_discard_section_p (section);
2552 
2553   /* Discard input sections which are assigned to a section named
2554      DISCARD_SECTION_NAME.  */
2555   if (strcmp (output->name, DISCARD_SECTION_NAME) == 0)
2556     discard = TRUE;
2557 
2558   if (discard)
2559     {
2560       if (section->output_section == NULL)
2561 	{
2562 	  /* This prevents future calls from assigning this section.  */
2563 	  section->output_section = bfd_abs_section_ptr;
2564 	}
2565       else if (link_info.non_contiguous_regions_warnings)
2566 	einfo (_("%P:%pS: warning: --enable-non-contiguous-regions makes "
2567 		 "section `%pA' from '%pB' match /DISCARD/ clause.\n"),
2568 	       NULL, section, section->owner);
2569 
2570       return;
2571     }
2572 
2573   if (sflag_info)
2574     {
2575       bfd_boolean keep;
2576 
2577       keep = bfd_lookup_section_flags (&link_info, sflag_info, section);
2578       if (!keep)
2579 	return;
2580     }
2581 
2582   if (section->output_section != NULL)
2583     {
2584       if (!link_info.non_contiguous_regions)
2585 	return;
2586 
2587       /* SECTION has already been handled in a special way
2588 	 (eg. LINK_ONCE): skip it.  */
2589       if (bfd_is_abs_section (section->output_section))
2590 	return;
2591 
2592       /* Already assigned to the same output section, do not process
2593 	 it again, to avoid creating loops between duplicate sections
2594 	 later.  */
2595       if (section->output_section == output->bfd_section)
2596 	return;
2597 
2598       if (link_info.non_contiguous_regions_warnings && output->bfd_section)
2599 	einfo (_("%P:%pS: warning: --enable-non-contiguous-regions may "
2600 		 "change behaviour for section `%pA' from '%pB' (assigned to "
2601 		 "%pA, but additional match: %pA)\n"),
2602 	       NULL, section, section->owner, section->output_section,
2603 	       output->bfd_section);
2604 
2605       /* SECTION has already been assigned to an output section, but
2606 	 the user allows it to be mapped to another one in case it
2607 	 overflows. We'll later update the actual output section in
2608 	 size_input_section as appropriate.  */
2609     }
2610 
2611   /* We don't copy the SEC_NEVER_LOAD flag from an input section
2612      to an output section, because we want to be able to include a
2613      SEC_NEVER_LOAD section in the middle of an otherwise loaded
2614      section (I don't know why we want to do this, but we do).
2615      build_link_order in ldwrite.c handles this case by turning
2616      the embedded SEC_NEVER_LOAD section into a fill.  */
2617   flags &= ~ SEC_NEVER_LOAD;
2618 
2619   /* If final link, don't copy the SEC_LINK_ONCE flags, they've
2620      already been processed.  One reason to do this is that on pe
2621      format targets, .text$foo sections go into .text and it's odd
2622      to see .text with SEC_LINK_ONCE set.  */
2623   if ((flags & (SEC_LINK_ONCE | SEC_GROUP)) == (SEC_LINK_ONCE | SEC_GROUP))
2624     {
2625       if (link_info.resolve_section_groups)
2626 	flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2627       else
2628 	flags &= ~(SEC_LINK_DUPLICATES | SEC_RELOC);
2629     }
2630   else if (!bfd_link_relocatable (&link_info))
2631     flags &= ~(SEC_LINK_ONCE | SEC_LINK_DUPLICATES | SEC_RELOC);
2632 
2633   switch (output->sectype)
2634     {
2635     case normal_section:
2636     case overlay_section:
2637     case first_overlay_section:
2638       break;
2639     case noalloc_section:
2640       flags &= ~SEC_ALLOC;
2641       break;
2642     case noload_section:
2643       flags &= ~SEC_LOAD;
2644       flags |= SEC_NEVER_LOAD;
2645       /* Unfortunately GNU ld has managed to evolve two different
2646 	 meanings to NOLOAD in scripts.  ELF gets a .bss style noload,
2647 	 alloc, no contents section.  All others get a noload, noalloc
2648 	 section.  */
2649       if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
2650 	flags &= ~SEC_HAS_CONTENTS;
2651       else
2652 	flags &= ~SEC_ALLOC;
2653       break;
2654     }
2655 
2656   if (output->bfd_section == NULL)
2657     init_os (output, flags);
2658 
2659   /* If SEC_READONLY is not set in the input section, then clear
2660      it from the output section.  */
2661   output->bfd_section->flags &= flags | ~SEC_READONLY;
2662 
2663   if (output->bfd_section->linker_has_input)
2664     {
2665       /* Only set SEC_READONLY flag on the first input section.  */
2666       flags &= ~ SEC_READONLY;
2667 
2668       /* Keep SEC_MERGE and SEC_STRINGS only if they are the same.  */
2669       if ((output->bfd_section->flags & (SEC_MERGE | SEC_STRINGS))
2670 	  != (flags & (SEC_MERGE | SEC_STRINGS))
2671 	  || ((flags & SEC_MERGE) != 0
2672 	      && output->bfd_section->entsize != section->entsize))
2673 	{
2674 	  output->bfd_section->flags &= ~ (SEC_MERGE | SEC_STRINGS);
2675 	  flags &= ~ (SEC_MERGE | SEC_STRINGS);
2676 	}
2677     }
2678   output->bfd_section->flags |= flags;
2679 
2680   if (!output->bfd_section->linker_has_input)
2681     {
2682       output->bfd_section->linker_has_input = 1;
2683       /* This must happen after flags have been updated.  The output
2684 	 section may have been created before we saw its first input
2685 	 section, eg. for a data statement.  */
2686       bfd_init_private_section_data (section->owner, section,
2687 				     link_info.output_bfd,
2688 				     output->bfd_section,
2689 				     &link_info);
2690       if ((flags & SEC_MERGE) != 0)
2691 	output->bfd_section->entsize = section->entsize;
2692     }
2693 
2694   if ((flags & SEC_TIC54X_BLOCK) != 0
2695       && bfd_get_arch (section->owner) == bfd_arch_tic54x)
2696     {
2697       /* FIXME: This value should really be obtained from the bfd...  */
2698       output->block_value = 128;
2699     }
2700 
2701   if (section->alignment_power > output->bfd_section->alignment_power)
2702     output->bfd_section->alignment_power = section->alignment_power;
2703 
2704   section->output_section = output->bfd_section;
2705 
2706   if (!map_head_is_link_order)
2707     {
2708       asection *s = output->bfd_section->map_tail.s;
2709       output->bfd_section->map_tail.s = section;
2710       section->map_head.s = NULL;
2711       section->map_tail.s = s;
2712       if (s != NULL)
2713 	s->map_head.s = section;
2714       else
2715 	output->bfd_section->map_head.s = section;
2716     }
2717 
2718   /* Add a section reference to the list.  */
2719   new_section = new_stat (lang_input_section, ptr);
2720   new_section->section = section;
2721 }
2722 
2723 /* Handle wildcard sorting.  This returns the lang_input_section which
2724    should follow the one we are going to create for SECTION and FILE,
2725    based on the sorting requirements of WILD.  It returns NULL if the
2726    new section should just go at the end of the current list.  */
2727 
2728 static lang_statement_union_type *
wild_sort(lang_wild_statement_type * wild,struct wildcard_list * sec,lang_input_statement_type * file,asection * section)2729 wild_sort (lang_wild_statement_type *wild,
2730 	   struct wildcard_list *sec,
2731 	   lang_input_statement_type *file,
2732 	   asection *section)
2733 {
2734   lang_statement_union_type *l;
2735 
2736   if (!wild->filenames_sorted
2737       && (sec == NULL || sec->spec.sorted == none))
2738     return NULL;
2739 
2740   for (l = wild->children.head; l != NULL; l = l->header.next)
2741     {
2742       lang_input_section_type *ls;
2743 
2744       if (l->header.type != lang_input_section_enum)
2745 	continue;
2746       ls = &l->input_section;
2747 
2748       /* Sorting by filename takes precedence over sorting by section
2749 	 name.  */
2750 
2751       if (wild->filenames_sorted)
2752 	{
2753 	  const char *fn, *ln;
2754 	  bfd_boolean fa, la;
2755 	  int i;
2756 
2757 	  /* The PE support for the .idata section as generated by
2758 	     dlltool assumes that files will be sorted by the name of
2759 	     the archive and then the name of the file within the
2760 	     archive.  */
2761 
2762 	  if (file->the_bfd != NULL
2763 	      && file->the_bfd->my_archive != NULL)
2764 	    {
2765 	      fn = bfd_get_filename (file->the_bfd->my_archive);
2766 	      fa = TRUE;
2767 	    }
2768 	  else
2769 	    {
2770 	      fn = file->filename;
2771 	      fa = FALSE;
2772 	    }
2773 
2774 	  if (ls->section->owner->my_archive != NULL)
2775 	    {
2776 	      ln = bfd_get_filename (ls->section->owner->my_archive);
2777 	      la = TRUE;
2778 	    }
2779 	  else
2780 	    {
2781 	      ln = bfd_get_filename (ls->section->owner);
2782 	      la = FALSE;
2783 	    }
2784 
2785 	  i = filename_cmp (fn, ln);
2786 	  if (i > 0)
2787 	    continue;
2788 	  else if (i < 0)
2789 	    break;
2790 
2791 	  if (fa || la)
2792 	    {
2793 	      if (fa)
2794 		fn = file->filename;
2795 	      if (la)
2796 		ln = bfd_get_filename (ls->section->owner);
2797 
2798 	      i = filename_cmp (fn, ln);
2799 	      if (i > 0)
2800 		continue;
2801 	      else if (i < 0)
2802 		break;
2803 	    }
2804 	}
2805 
2806       /* Here either the files are not sorted by name, or we are
2807 	 looking at the sections for this file.  */
2808 
2809       if (sec != NULL
2810 	  && sec->spec.sorted != none
2811 	  && sec->spec.sorted != by_none)
2812 	if (compare_section (sec->spec.sorted, section, ls->section) < 0)
2813 	  break;
2814     }
2815 
2816   return l;
2817 }
2818 
2819 /* Expand a wild statement for a particular FILE.  SECTION may be
2820    NULL, in which case it is a wild card.  */
2821 
2822 static void
output_section_callback(lang_wild_statement_type * ptr,struct wildcard_list * sec,asection * section,struct flag_info * sflag_info,lang_input_statement_type * file,void * output)2823 output_section_callback (lang_wild_statement_type *ptr,
2824 			 struct wildcard_list *sec,
2825 			 asection *section,
2826 			 struct flag_info *sflag_info,
2827 			 lang_input_statement_type *file,
2828 			 void *output)
2829 {
2830   lang_statement_union_type *before;
2831   lang_output_section_statement_type *os;
2832 
2833   os = (lang_output_section_statement_type *) output;
2834 
2835   /* Exclude sections that match UNIQUE_SECTION_LIST.  */
2836   if (unique_section_p (section, os))
2837     return;
2838 
2839   before = wild_sort (ptr, sec, file, section);
2840 
2841   /* Here BEFORE points to the lang_input_section which
2842      should follow the one we are about to add.  If BEFORE
2843      is NULL, then the section should just go at the end
2844      of the current list.  */
2845 
2846   if (before == NULL)
2847     lang_add_section (&ptr->children, section, sflag_info, os);
2848   else
2849     {
2850       lang_statement_list_type list;
2851       lang_statement_union_type **pp;
2852 
2853       lang_list_init (&list);
2854       lang_add_section (&list, section, sflag_info, os);
2855 
2856       /* If we are discarding the section, LIST.HEAD will
2857 	 be NULL.  */
2858       if (list.head != NULL)
2859 	{
2860 	  ASSERT (list.head->header.next == NULL);
2861 
2862 	  for (pp = &ptr->children.head;
2863 	       *pp != before;
2864 	       pp = &(*pp)->header.next)
2865 	    ASSERT (*pp != NULL);
2866 
2867 	  list.head->header.next = *pp;
2868 	  *pp = list.head;
2869 	}
2870     }
2871 }
2872 
2873 /* Check if all sections in a wild statement for a particular FILE
2874    are readonly.  */
2875 
2876 static void
check_section_callback(lang_wild_statement_type * ptr ATTRIBUTE_UNUSED,struct wildcard_list * sec ATTRIBUTE_UNUSED,asection * section,struct flag_info * sflag_info ATTRIBUTE_UNUSED,lang_input_statement_type * file ATTRIBUTE_UNUSED,void * output)2877 check_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
2878 			struct wildcard_list *sec ATTRIBUTE_UNUSED,
2879 			asection *section,
2880 			struct flag_info *sflag_info ATTRIBUTE_UNUSED,
2881 			lang_input_statement_type *file ATTRIBUTE_UNUSED,
2882 			void *output)
2883 {
2884   lang_output_section_statement_type *os;
2885 
2886   os = (lang_output_section_statement_type *) output;
2887 
2888   /* Exclude sections that match UNIQUE_SECTION_LIST.  */
2889   if (unique_section_p (section, os))
2890     return;
2891 
2892   if (section->output_section == NULL && (section->flags & SEC_READONLY) == 0)
2893     os->all_input_readonly = FALSE;
2894 }
2895 
2896 /* This is passed a file name which must have been seen already and
2897    added to the statement tree.  We will see if it has been opened
2898    already and had its symbols read.  If not then we'll read it.  */
2899 
2900 static lang_input_statement_type *
lookup_name(const char * name)2901 lookup_name (const char *name)
2902 {
2903   lang_input_statement_type *search;
2904 
2905   for (search = (void *) input_file_chain.head;
2906        search != NULL;
2907        search = search->next_real_file)
2908     {
2909       /* Use the local_sym_name as the name of the file that has
2910 	 already been loaded as filename might have been transformed
2911 	 via the search directory lookup mechanism.  */
2912       const char *filename = search->local_sym_name;
2913 
2914       if (filename != NULL
2915 	  && filename_cmp (filename, name) == 0)
2916 	break;
2917     }
2918 
2919   if (search == NULL)
2920     {
2921       /* Arrange to splice the input statement added by new_afile into
2922 	 statement_list after the current input_file_chain tail.
2923 	 We know input_file_chain is not an empty list, and that
2924 	 lookup_name was called via open_input_bfds.  Later calls to
2925 	 lookup_name should always match an existing input_statement.  */
2926       lang_statement_union_type **tail = stat_ptr->tail;
2927       lang_statement_union_type **after
2928 	= (void *) ((char *) input_file_chain.tail
2929 		    - offsetof (lang_input_statement_type, next_real_file)
2930 		    + offsetof (lang_input_statement_type, header.next));
2931       lang_statement_union_type *rest = *after;
2932       stat_ptr->tail = after;
2933       search = new_afile (name, lang_input_file_is_search_file_enum,
2934 			  default_target, NULL);
2935       *stat_ptr->tail = rest;
2936       if (*tail == NULL)
2937 	stat_ptr->tail = tail;
2938     }
2939 
2940   /* If we have already added this file, or this file is not real
2941      don't add this file.  */
2942   if (search->flags.loaded || !search->flags.real)
2943     return search;
2944 
2945   if (!load_symbols (search, NULL))
2946     return NULL;
2947 
2948   return search;
2949 }
2950 
2951 /* Save LIST as a list of libraries whose symbols should not be exported.  */
2952 
2953 struct excluded_lib
2954 {
2955   char *name;
2956   struct excluded_lib *next;
2957 };
2958 static struct excluded_lib *excluded_libs;
2959 
2960 void
add_excluded_libs(const char * list)2961 add_excluded_libs (const char *list)
2962 {
2963   const char *p = list, *end;
2964 
2965   while (*p != '\0')
2966     {
2967       struct excluded_lib *entry;
2968       end = strpbrk (p, ",:");
2969       if (end == NULL)
2970 	end = p + strlen (p);
2971       entry = (struct excluded_lib *) xmalloc (sizeof (*entry));
2972       entry->next = excluded_libs;
2973       entry->name = (char *) xmalloc (end - p + 1);
2974       memcpy (entry->name, p, end - p);
2975       entry->name[end - p] = '\0';
2976       excluded_libs = entry;
2977       if (*end == '\0')
2978 	break;
2979       p = end + 1;
2980     }
2981 }
2982 
2983 static void
check_excluded_libs(bfd * abfd)2984 check_excluded_libs (bfd *abfd)
2985 {
2986   struct excluded_lib *lib = excluded_libs;
2987 
2988   while (lib)
2989     {
2990       int len = strlen (lib->name);
2991       const char *filename = lbasename (bfd_get_filename (abfd));
2992 
2993       if (strcmp (lib->name, "ALL") == 0)
2994 	{
2995 	  abfd->no_export = TRUE;
2996 	  return;
2997 	}
2998 
2999       if (filename_ncmp (lib->name, filename, len) == 0
3000 	  && (filename[len] == '\0'
3001 	      || (filename[len] == '.' && filename[len + 1] == 'a'
3002 		  && filename[len + 2] == '\0')))
3003 	{
3004 	  abfd->no_export = TRUE;
3005 	  return;
3006 	}
3007 
3008       lib = lib->next;
3009     }
3010 }
3011 
3012 /* Get the symbols for an input file.  */
3013 
3014 bfd_boolean
load_symbols(lang_input_statement_type * entry,lang_statement_list_type * place)3015 load_symbols (lang_input_statement_type *entry,
3016 	      lang_statement_list_type *place)
3017 {
3018   char **matching;
3019 
3020   if (entry->flags.loaded)
3021     return TRUE;
3022 
3023   ldfile_open_file (entry);
3024 
3025   /* Do not process further if the file was missing.  */
3026   if (entry->flags.missing_file)
3027     return TRUE;
3028 
3029   if (trace_files || verbose)
3030     info_msg ("%pI\n", entry);
3031 
3032   if (!bfd_check_format (entry->the_bfd, bfd_archive)
3033       && !bfd_check_format_matches (entry->the_bfd, bfd_object, &matching))
3034     {
3035       bfd_error_type err;
3036       struct lang_input_statement_flags save_flags;
3037       extern FILE *yyin;
3038 
3039       err = bfd_get_error ();
3040 
3041       /* See if the emulation has some special knowledge.  */
3042       if (ldemul_unrecognized_file (entry))
3043 	return TRUE;
3044 
3045       if (err == bfd_error_file_ambiguously_recognized)
3046 	{
3047 	  char **p;
3048 
3049 	  einfo (_("%P: %pB: file not recognized: %E;"
3050 		   " matching formats:"), entry->the_bfd);
3051 	  for (p = matching; *p != NULL; p++)
3052 	    einfo (" %s", *p);
3053 	  einfo ("%F\n");
3054 	}
3055       else if (err != bfd_error_file_not_recognized
3056 	       || place == NULL)
3057 	einfo (_("%F%P: %pB: file not recognized: %E\n"), entry->the_bfd);
3058 
3059       bfd_close (entry->the_bfd);
3060       entry->the_bfd = NULL;
3061 
3062       /* Try to interpret the file as a linker script.  */
3063       save_flags = input_flags;
3064       ldfile_open_command_file (entry->filename);
3065 
3066       push_stat_ptr (place);
3067       input_flags.add_DT_NEEDED_for_regular
3068 	= entry->flags.add_DT_NEEDED_for_regular;
3069       input_flags.add_DT_NEEDED_for_dynamic
3070 	= entry->flags.add_DT_NEEDED_for_dynamic;
3071       input_flags.whole_archive = entry->flags.whole_archive;
3072       input_flags.dynamic = entry->flags.dynamic;
3073 
3074       ldfile_assumed_script = TRUE;
3075       parser_input = input_script;
3076       current_input_file = entry->filename;
3077       yyparse ();
3078       current_input_file = NULL;
3079       ldfile_assumed_script = FALSE;
3080 
3081       /* missing_file is sticky.  sysrooted will already have been
3082 	 restored when seeing EOF in yyparse, but no harm to restore
3083 	 again.  */
3084       save_flags.missing_file |= input_flags.missing_file;
3085       input_flags = save_flags;
3086       pop_stat_ptr ();
3087       fclose (yyin);
3088       yyin = NULL;
3089       entry->flags.loaded = TRUE;
3090 
3091       return TRUE;
3092     }
3093 
3094   if (ldemul_recognized_file (entry))
3095     return TRUE;
3096 
3097   /* We don't call ldlang_add_file for an archive.  Instead, the
3098      add_symbols entry point will call ldlang_add_file, via the
3099      add_archive_element callback, for each element of the archive
3100      which is used.  */
3101   switch (bfd_get_format (entry->the_bfd))
3102     {
3103     default:
3104       break;
3105 
3106     case bfd_object:
3107       if (!entry->flags.reload)
3108 	ldlang_add_file (entry);
3109       break;
3110 
3111     case bfd_archive:
3112       check_excluded_libs (entry->the_bfd);
3113 
3114       bfd_set_usrdata (entry->the_bfd, entry);
3115       if (entry->flags.whole_archive)
3116 	{
3117 	  bfd *member = NULL;
3118 	  bfd_boolean loaded = TRUE;
3119 
3120 	  for (;;)
3121 	    {
3122 	      bfd *subsbfd;
3123 	      member = bfd_openr_next_archived_file (entry->the_bfd, member);
3124 
3125 	      if (member == NULL)
3126 		break;
3127 
3128 	      if (!bfd_check_format (member, bfd_object))
3129 		{
3130 		  einfo (_("%F%P: %pB: member %pB in archive is not an object\n"),
3131 			 entry->the_bfd, member);
3132 		  loaded = FALSE;
3133 		}
3134 
3135 	      subsbfd = member;
3136 	      if (!(*link_info.callbacks
3137 		    ->add_archive_element) (&link_info, member,
3138 					    "--whole-archive", &subsbfd))
3139 		abort ();
3140 
3141 	      /* Potentially, the add_archive_element hook may have set a
3142 		 substitute BFD for us.  */
3143 	      if (!bfd_link_add_symbols (subsbfd, &link_info))
3144 		{
3145 		  einfo (_("%F%P: %pB: error adding symbols: %E\n"), member);
3146 		  loaded = FALSE;
3147 		}
3148 	    }
3149 
3150 	  entry->flags.loaded = loaded;
3151 	  return loaded;
3152 	}
3153       break;
3154     }
3155 
3156   if (bfd_link_add_symbols (entry->the_bfd, &link_info))
3157     entry->flags.loaded = TRUE;
3158   else
3159     einfo (_("%F%P: %pB: error adding symbols: %E\n"), entry->the_bfd);
3160 
3161   return entry->flags.loaded;
3162 }
3163 
3164 /* Handle a wild statement.  S->FILENAME or S->SECTION_LIST or both
3165    may be NULL, indicating that it is a wildcard.  Separate
3166    lang_input_section statements are created for each part of the
3167    expansion; they are added after the wild statement S.  OUTPUT is
3168    the output section.  */
3169 
3170 static void
wild(lang_wild_statement_type * s,const char * target ATTRIBUTE_UNUSED,lang_output_section_statement_type * output)3171 wild (lang_wild_statement_type *s,
3172       const char *target ATTRIBUTE_UNUSED,
3173       lang_output_section_statement_type *output)
3174 {
3175   struct wildcard_list *sec;
3176 
3177   if (s->handler_data[0]
3178       && s->handler_data[0]->spec.sorted == by_name
3179       && !s->filenames_sorted)
3180     {
3181       lang_section_bst_type *tree;
3182 
3183       walk_wild (s, output_section_callback_fast, output);
3184 
3185       tree = s->tree;
3186       if (tree)
3187 	{
3188 	  output_section_callback_tree_to_list (s, tree, output);
3189 	  s->tree = NULL;
3190 	}
3191     }
3192   else
3193     walk_wild (s, output_section_callback, output);
3194 
3195   if (default_common_section == NULL)
3196     for (sec = s->section_list; sec != NULL; sec = sec->next)
3197       if (sec->spec.name != NULL && strcmp (sec->spec.name, "COMMON") == 0)
3198 	{
3199 	  /* Remember the section that common is going to in case we
3200 	     later get something which doesn't know where to put it.  */
3201 	  default_common_section = output;
3202 	  break;
3203 	}
3204 }
3205 
3206 /* Return TRUE iff target is the sought target.  */
3207 
3208 static int
get_target(const bfd_target * target,void * data)3209 get_target (const bfd_target *target, void *data)
3210 {
3211   const char *sought = (const char *) data;
3212 
3213   return strcmp (target->name, sought) == 0;
3214 }
3215 
3216 /* Like strcpy() but convert to lower case as well.  */
3217 
3218 static void
stricpy(char * dest,const char * src)3219 stricpy (char *dest, const char *src)
3220 {
3221   char c;
3222 
3223   while ((c = *src++) != 0)
3224     *dest++ = TOLOWER (c);
3225 
3226   *dest = 0;
3227 }
3228 
3229 /* Remove the first occurrence of needle (if any) in haystack
3230    from haystack.  */
3231 
3232 static void
strcut(char * haystack,const char * needle)3233 strcut (char *haystack, const char *needle)
3234 {
3235   haystack = strstr (haystack, needle);
3236 
3237   if (haystack)
3238     {
3239       char *src;
3240 
3241       for (src = haystack + strlen (needle); *src;)
3242 	*haystack++ = *src++;
3243 
3244       *haystack = 0;
3245     }
3246 }
3247 
3248 /* Compare two target format name strings.
3249    Return a value indicating how "similar" they are.  */
3250 
3251 static int
name_compare(const char * first,const char * second)3252 name_compare (const char *first, const char *second)
3253 {
3254   char *copy1;
3255   char *copy2;
3256   int result;
3257 
3258   copy1 = (char *) xmalloc (strlen (first) + 1);
3259   copy2 = (char *) xmalloc (strlen (second) + 1);
3260 
3261   /* Convert the names to lower case.  */
3262   stricpy (copy1, first);
3263   stricpy (copy2, second);
3264 
3265   /* Remove size and endian strings from the name.  */
3266   strcut (copy1, "big");
3267   strcut (copy1, "little");
3268   strcut (copy2, "big");
3269   strcut (copy2, "little");
3270 
3271   /* Return a value based on how many characters match,
3272      starting from the beginning.   If both strings are
3273      the same then return 10 * their length.  */
3274   for (result = 0; copy1[result] == copy2[result]; result++)
3275     if (copy1[result] == 0)
3276       {
3277 	result *= 10;
3278 	break;
3279       }
3280 
3281   free (copy1);
3282   free (copy2);
3283 
3284   return result;
3285 }
3286 
3287 /* Set by closest_target_match() below.  */
3288 static const bfd_target *winner;
3289 
3290 /* Scan all the valid bfd targets looking for one that has the endianness
3291    requirement that was specified on the command line, and is the nearest
3292    match to the original output target.  */
3293 
3294 static int
closest_target_match(const bfd_target * target,void * data)3295 closest_target_match (const bfd_target *target, void *data)
3296 {
3297   const bfd_target *original = (const bfd_target *) data;
3298 
3299   if (command_line.endian == ENDIAN_BIG
3300       && target->byteorder != BFD_ENDIAN_BIG)
3301     return 0;
3302 
3303   if (command_line.endian == ENDIAN_LITTLE
3304       && target->byteorder != BFD_ENDIAN_LITTLE)
3305     return 0;
3306 
3307   /* Must be the same flavour.  */
3308   if (target->flavour != original->flavour)
3309     return 0;
3310 
3311   /* Ignore generic big and little endian elf vectors.  */
3312   if (strcmp (target->name, "elf32-big") == 0
3313       || strcmp (target->name, "elf64-big") == 0
3314       || strcmp (target->name, "elf32-little") == 0
3315       || strcmp (target->name, "elf64-little") == 0)
3316     return 0;
3317 
3318   /* If we have not found a potential winner yet, then record this one.  */
3319   if (winner == NULL)
3320     {
3321       winner = target;
3322       return 0;
3323     }
3324 
3325   /* Oh dear, we now have two potential candidates for a successful match.
3326      Compare their names and choose the better one.  */
3327   if (name_compare (target->name, original->name)
3328       > name_compare (winner->name, original->name))
3329     winner = target;
3330 
3331   /* Keep on searching until wqe have checked them all.  */
3332   return 0;
3333 }
3334 
3335 /* Return the BFD target format of the first input file.  */
3336 
3337 static const char *
get_first_input_target(void)3338 get_first_input_target (void)
3339 {
3340   const char *target = NULL;
3341 
3342   LANG_FOR_EACH_INPUT_STATEMENT (s)
3343     {
3344       if (s->header.type == lang_input_statement_enum
3345 	  && s->flags.real)
3346 	{
3347 	  ldfile_open_file (s);
3348 
3349 	  if (s->the_bfd != NULL
3350 	      && bfd_check_format (s->the_bfd, bfd_object))
3351 	    {
3352 	      target = bfd_get_target (s->the_bfd);
3353 
3354 	      if (target != NULL)
3355 		break;
3356 	    }
3357 	}
3358     }
3359 
3360   return target;
3361 }
3362 
3363 const char *
lang_get_output_target(void)3364 lang_get_output_target (void)
3365 {
3366   const char *target;
3367 
3368   /* Has the user told us which output format to use?  */
3369   if (output_target != NULL)
3370     return output_target;
3371 
3372   /* No - has the current target been set to something other than
3373      the default?  */
3374   if (current_target != default_target && current_target != NULL)
3375     return current_target;
3376 
3377   /* No - can we determine the format of the first input file?  */
3378   target = get_first_input_target ();
3379   if (target != NULL)
3380     return target;
3381 
3382   /* Failed - use the default output target.  */
3383   return default_target;
3384 }
3385 
3386 /* Open the output file.  */
3387 
3388 static void
open_output(const char * name)3389 open_output (const char *name)
3390 {
3391   output_target = lang_get_output_target ();
3392 
3393   /* Has the user requested a particular endianness on the command
3394      line?  */
3395   if (command_line.endian != ENDIAN_UNSET)
3396     {
3397       /* Get the chosen target.  */
3398       const bfd_target *target
3399 	= bfd_iterate_over_targets (get_target, (void *) output_target);
3400 
3401       /* If the target is not supported, we cannot do anything.  */
3402       if (target != NULL)
3403 	{
3404 	  enum bfd_endian desired_endian;
3405 
3406 	  if (command_line.endian == ENDIAN_BIG)
3407 	    desired_endian = BFD_ENDIAN_BIG;
3408 	  else
3409 	    desired_endian = BFD_ENDIAN_LITTLE;
3410 
3411 	  /* See if the target has the wrong endianness.  This should
3412 	     not happen if the linker script has provided big and
3413 	     little endian alternatives, but some scrips don't do
3414 	     this.  */
3415 	  if (target->byteorder != desired_endian)
3416 	    {
3417 	      /* If it does, then see if the target provides
3418 		 an alternative with the correct endianness.  */
3419 	      if (target->alternative_target != NULL
3420 		  && (target->alternative_target->byteorder == desired_endian))
3421 		output_target = target->alternative_target->name;
3422 	      else
3423 		{
3424 		  /* Try to find a target as similar as possible to
3425 		     the default target, but which has the desired
3426 		     endian characteristic.  */
3427 		  bfd_iterate_over_targets (closest_target_match,
3428 					    (void *) target);
3429 
3430 		  /* Oh dear - we could not find any targets that
3431 		     satisfy our requirements.  */
3432 		  if (winner == NULL)
3433 		    einfo (_("%P: warning: could not find any targets"
3434 			     " that match endianness requirement\n"));
3435 		  else
3436 		    output_target = winner->name;
3437 		}
3438 	    }
3439 	}
3440     }
3441 
3442   link_info.output_bfd = bfd_openw (name, output_target);
3443 
3444   if (link_info.output_bfd == NULL)
3445     {
3446       if (bfd_get_error () == bfd_error_invalid_target)
3447 	einfo (_("%F%P: target %s not found\n"), output_target);
3448 
3449       einfo (_("%F%P: cannot open output file %s: %E\n"), name);
3450     }
3451 
3452   delete_output_file_on_failure = TRUE;
3453 
3454   if (!bfd_set_format (link_info.output_bfd, bfd_object))
3455     einfo (_("%F%P: %s: can not make object file: %E\n"), name);
3456   if (!bfd_set_arch_mach (link_info.output_bfd,
3457 			   ldfile_output_architecture,
3458 			   ldfile_output_machine))
3459     einfo (_("%F%P: %s: can not set architecture: %E\n"), name);
3460 
3461   link_info.hash = bfd_link_hash_table_create (link_info.output_bfd);
3462   if (link_info.hash == NULL)
3463     einfo (_("%F%P: can not create hash table: %E\n"));
3464 
3465   bfd_set_gp_size (link_info.output_bfd, g_switch_value);
3466 }
3467 
3468 static void
ldlang_open_output(lang_statement_union_type * statement)3469 ldlang_open_output (lang_statement_union_type *statement)
3470 {
3471   switch (statement->header.type)
3472     {
3473     case lang_output_statement_enum:
3474       ASSERT (link_info.output_bfd == NULL);
3475       open_output (statement->output_statement.name);
3476       ldemul_set_output_arch ();
3477       if (config.magic_demand_paged
3478 	  && !bfd_link_relocatable (&link_info))
3479 	link_info.output_bfd->flags |= D_PAGED;
3480       else
3481 	link_info.output_bfd->flags &= ~D_PAGED;
3482       if (config.text_read_only)
3483 	link_info.output_bfd->flags |= WP_TEXT;
3484       else
3485 	link_info.output_bfd->flags &= ~WP_TEXT;
3486       if (link_info.traditional_format)
3487 	link_info.output_bfd->flags |= BFD_TRADITIONAL_FORMAT;
3488       else
3489 	link_info.output_bfd->flags &= ~BFD_TRADITIONAL_FORMAT;
3490       break;
3491 
3492     case lang_target_statement_enum:
3493       current_target = statement->target_statement.target;
3494       break;
3495     default:
3496       break;
3497     }
3498 }
3499 
3500 static void
init_opb(asection * s)3501 init_opb (asection *s)
3502 {
3503   unsigned int x;
3504 
3505   opb_shift = 0;
3506   if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour
3507       && s != NULL
3508       && (s->flags & SEC_ELF_OCTETS) != 0)
3509     return;
3510 
3511   x = bfd_arch_mach_octets_per_byte (ldfile_output_architecture,
3512 				     ldfile_output_machine);
3513   if (x > 1)
3514     while ((x & 1) == 0)
3515       {
3516 	x >>= 1;
3517 	++opb_shift;
3518       }
3519   ASSERT (x == 1);
3520 }
3521 
3522 /* Open all the input files.  */
3523 
3524 enum open_bfd_mode
3525   {
3526     OPEN_BFD_NORMAL = 0,
3527     OPEN_BFD_FORCE = 1,
3528     OPEN_BFD_RESCAN = 2
3529   };
3530 #if BFD_SUPPORTS_PLUGINS
3531 static lang_input_statement_type *plugin_insert = NULL;
3532 static struct bfd_link_hash_entry *plugin_undefs = NULL;
3533 #endif
3534 
3535 static void
open_input_bfds(lang_statement_union_type * s,enum open_bfd_mode mode)3536 open_input_bfds (lang_statement_union_type *s, enum open_bfd_mode mode)
3537 {
3538   for (; s != NULL; s = s->header.next)
3539     {
3540       switch (s->header.type)
3541 	{
3542 	case lang_constructors_statement_enum:
3543 	  open_input_bfds (constructor_list.head, mode);
3544 	  break;
3545 	case lang_output_section_statement_enum:
3546 	  open_input_bfds (s->output_section_statement.children.head, mode);
3547 	  break;
3548 	case lang_wild_statement_enum:
3549 	  /* Maybe we should load the file's symbols.  */
3550 	  if ((mode & OPEN_BFD_RESCAN) == 0
3551 	      && s->wild_statement.filename
3552 	      && !wildcardp (s->wild_statement.filename)
3553 	      && !archive_path (s->wild_statement.filename))
3554 	    lookup_name (s->wild_statement.filename);
3555 	  open_input_bfds (s->wild_statement.children.head, mode);
3556 	  break;
3557 	case lang_group_statement_enum:
3558 	  {
3559 	    struct bfd_link_hash_entry *undefs;
3560 #if BFD_SUPPORTS_PLUGINS
3561 	    lang_input_statement_type *plugin_insert_save;
3562 #endif
3563 
3564 	    /* We must continually search the entries in the group
3565 	       until no new symbols are added to the list of undefined
3566 	       symbols.  */
3567 
3568 	    do
3569 	      {
3570 #if BFD_SUPPORTS_PLUGINS
3571 		plugin_insert_save = plugin_insert;
3572 #endif
3573 		undefs = link_info.hash->undefs_tail;
3574 		open_input_bfds (s->group_statement.children.head,
3575 				 mode | OPEN_BFD_FORCE);
3576 	      }
3577 	    while (undefs != link_info.hash->undefs_tail
3578 #if BFD_SUPPORTS_PLUGINS
3579 		   /* Objects inserted by a plugin, which are loaded
3580 		      before we hit this loop, may have added new
3581 		      undefs.  */
3582 		   || (plugin_insert != plugin_insert_save && plugin_undefs)
3583 #endif
3584 		   );
3585 	  }
3586 	  break;
3587 	case lang_target_statement_enum:
3588 	  current_target = s->target_statement.target;
3589 	  break;
3590 	case lang_input_statement_enum:
3591 	  if (s->input_statement.flags.real)
3592 	    {
3593 	      lang_statement_union_type **os_tail;
3594 	      lang_statement_list_type add;
3595 	      bfd *abfd;
3596 
3597 	      s->input_statement.target = current_target;
3598 
3599 	      /* If we are being called from within a group, and this
3600 		 is an archive which has already been searched, then
3601 		 force it to be researched unless the whole archive
3602 		 has been loaded already.  Do the same for a rescan.
3603 		 Likewise reload --as-needed shared libs.  */
3604 	      if (mode != OPEN_BFD_NORMAL
3605 #if BFD_SUPPORTS_PLUGINS
3606 		  && ((mode & OPEN_BFD_RESCAN) == 0
3607 		      || plugin_insert == NULL)
3608 #endif
3609 		  && s->input_statement.flags.loaded
3610 		  && (abfd = s->input_statement.the_bfd) != NULL
3611 		  && ((bfd_get_format (abfd) == bfd_archive
3612 		       && !s->input_statement.flags.whole_archive)
3613 		      || (bfd_get_format (abfd) == bfd_object
3614 			  && ((abfd->flags) & DYNAMIC) != 0
3615 			  && s->input_statement.flags.add_DT_NEEDED_for_regular
3616 			  && bfd_get_flavour (abfd) == bfd_target_elf_flavour
3617 			  && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)))
3618 		{
3619 		  s->input_statement.flags.loaded = FALSE;
3620 		  s->input_statement.flags.reload = TRUE;
3621 		}
3622 
3623 	      os_tail = lang_os_list.tail;
3624 	      lang_list_init (&add);
3625 
3626 	      if (!load_symbols (&s->input_statement, &add))
3627 		config.make_executable = FALSE;
3628 
3629 	      if (add.head != NULL)
3630 		{
3631 		  /* If this was a script with output sections then
3632 		     tack any added statements on to the end of the
3633 		     list.  This avoids having to reorder the output
3634 		     section statement list.  Very likely the user
3635 		     forgot -T, and whatever we do here will not meet
3636 		     naive user expectations.  */
3637 		  if (os_tail != lang_os_list.tail)
3638 		    {
3639 		      einfo (_("%P: warning: %s contains output sections;"
3640 			       " did you forget -T?\n"),
3641 			     s->input_statement.filename);
3642 		      *stat_ptr->tail = add.head;
3643 		      stat_ptr->tail = add.tail;
3644 		    }
3645 		  else
3646 		    {
3647 		      *add.tail = s->header.next;
3648 		      s->header.next = add.head;
3649 		    }
3650 		}
3651 	    }
3652 #if BFD_SUPPORTS_PLUGINS
3653 	  /* If we have found the point at which a plugin added new
3654 	     files, clear plugin_insert to enable archive rescan.  */
3655 	  if (&s->input_statement == plugin_insert)
3656 	    plugin_insert = NULL;
3657 #endif
3658 	  break;
3659 	case lang_assignment_statement_enum:
3660 	  if (s->assignment_statement.exp->type.node_class != etree_assert)
3661 	    exp_fold_tree_no_dot (s->assignment_statement.exp);
3662 	  break;
3663 	default:
3664 	  break;
3665 	}
3666     }
3667 
3668   /* Exit if any of the files were missing.  */
3669   if (input_flags.missing_file)
3670     einfo ("%F");
3671 }
3672 
3673 #ifdef ENABLE_LIBCTF
3674 /* Emit CTF errors and warnings.  fp can be NULL to report errors/warnings
3675    that happened specifically at CTF open time.  */
3676 static void
lang_ctf_errs_warnings(ctf_file_t * fp)3677 lang_ctf_errs_warnings (ctf_file_t *fp)
3678 {
3679   ctf_next_t *i = NULL;
3680   char *text;
3681   int is_warning;
3682   int err;
3683 
3684   while ((text = ctf_errwarning_next (fp, &i, &is_warning, &err)) != NULL)
3685     {
3686       einfo (_("%s: %s\n"), is_warning ? _("CTF warning"): _("CTF error"),
3687 	     text);
3688       free (text);
3689     }
3690   if (err != ECTF_NEXT_END)
3691     {
3692       einfo (_("CTF error: cannot get CTF errors: `%s'\n"),
3693 	     ctf_errmsg (err));
3694     }
3695 
3696   /* `err' returns errors from the error/warning iterator in particular.
3697      These never assert.  But if we have an fp, that could have recorded
3698      an assertion failure: assert if it has done so.  */
3699   ASSERT (!fp || ctf_errno (fp) != ECTF_INTERNAL);
3700 }
3701 
3702 /* Open the CTF sections in the input files with libctf: if any were opened,
3703    create a fake input file that we'll write the merged CTF data to later
3704    on.  */
3705 
3706 static void
ldlang_open_ctf(void)3707 ldlang_open_ctf (void)
3708 {
3709   int any_ctf = 0;
3710   int err;
3711 
3712   LANG_FOR_EACH_INPUT_STATEMENT (file)
3713     {
3714       asection *sect;
3715 
3716       /* Incoming files from the compiler have a single ctf_file_t in them
3717 	 (which is presented to us by the libctf API in a ctf_archive_t
3718 	 wrapper): files derived from a previous relocatable link have a CTF
3719 	 archive containing possibly many CTF files.  */
3720 
3721       if ((file->the_ctf = ctf_bfdopen (file->the_bfd, &err)) == NULL)
3722 	{
3723 	  if (err != ECTF_NOCTFDATA)
3724 	    {
3725 	      lang_ctf_errs_warnings (NULL);
3726 	      einfo (_("%P: warning: CTF section in %pB not loaded; "
3727 		       "its types will be discarded: %s\n"), file->the_bfd,
3728 		     ctf_errmsg (err));
3729 	    }
3730 	  continue;
3731 	}
3732 
3733       /* Prevent the contents of this section from being written, while
3734 	 requiring the section itself to be duplicated in the output, but only
3735 	 once.  */
3736       /* This section must exist if ctf_bfdopen() succeeded.  */
3737       sect = bfd_get_section_by_name (file->the_bfd, ".ctf");
3738       sect->size = 0;
3739       sect->flags |= SEC_NEVER_LOAD | SEC_HAS_CONTENTS | SEC_LINKER_CREATED;
3740 
3741       if (any_ctf)
3742 	sect->flags |= SEC_EXCLUDE;
3743       any_ctf = 1;
3744     }
3745 
3746   if (!any_ctf)
3747     {
3748       ctf_output = NULL;
3749       return;
3750     }
3751 
3752   if ((ctf_output = ctf_create (&err)) != NULL)
3753     return;
3754 
3755   einfo (_("%P: warning: CTF output not created: `%s'\n"),
3756 	 ctf_errmsg (err));
3757 
3758   LANG_FOR_EACH_INPUT_STATEMENT (errfile)
3759     ctf_close (errfile->the_ctf);
3760 }
3761 
3762 /* Merge together CTF sections.  After this, only the symtab-dependent
3763    function and data object sections need adjustment.  */
3764 
3765 static void
lang_merge_ctf(void)3766 lang_merge_ctf (void)
3767 {
3768   asection *output_sect;
3769   int flags = 0;
3770 
3771   if (!ctf_output)
3772     return;
3773 
3774   output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3775 
3776   /* If the section was discarded, don't waste time merging.  */
3777   if (output_sect == NULL)
3778     {
3779       ctf_file_close (ctf_output);
3780       ctf_output = NULL;
3781 
3782       LANG_FOR_EACH_INPUT_STATEMENT (file)
3783 	{
3784 	  ctf_close (file->the_ctf);
3785 	  file->the_ctf = NULL;
3786 	}
3787       return;
3788     }
3789 
3790   LANG_FOR_EACH_INPUT_STATEMENT (file)
3791     {
3792       if (!file->the_ctf)
3793 	continue;
3794 
3795       /* Takes ownership of file->the_ctf.  */
3796       if (ctf_link_add_ctf (ctf_output, file->the_ctf, file->filename) < 0)
3797 	{
3798 	  einfo (_("%P: warning: CTF section in %pB cannot be linked: `%s'\n"),
3799 		 file->the_bfd, ctf_errmsg (ctf_errno (ctf_output)));
3800 	  ctf_close (file->the_ctf);
3801 	  file->the_ctf = NULL;
3802 	  continue;
3803 	}
3804     }
3805 
3806   if (!config.ctf_share_duplicated)
3807     flags = CTF_LINK_SHARE_UNCONFLICTED;
3808   else
3809     flags = CTF_LINK_SHARE_DUPLICATED;
3810   if (!config.ctf_variables)
3811     flags |= CTF_LINK_OMIT_VARIABLES_SECTION;
3812 
3813   if (ctf_link (ctf_output, flags) < 0)
3814     {
3815       lang_ctf_errs_warnings (ctf_output);
3816       einfo (_("%P: warning: CTF linking failed; "
3817 	       "output will have no CTF section: %s\n"),
3818 	     ctf_errmsg (ctf_errno (ctf_output)));
3819       if (output_sect)
3820 	{
3821 	  output_sect->size = 0;
3822 	  output_sect->flags |= SEC_EXCLUDE;
3823 	}
3824     }
3825   /* Output any lingering errors that didn't come from ctf_link.  */
3826   lang_ctf_errs_warnings (ctf_output);
3827 }
3828 
3829 /* Let the emulation examine the symbol table and strtab to help it optimize the
3830    CTF, if supported.  */
3831 
3832 void
ldlang_ctf_apply_strsym(struct elf_sym_strtab * syms,bfd_size_type symcount,struct elf_strtab_hash * symstrtab)3833 ldlang_ctf_apply_strsym (struct elf_sym_strtab *syms, bfd_size_type symcount,
3834 			 struct elf_strtab_hash *symstrtab)
3835 {
3836   ldemul_examine_strtab_for_ctf (ctf_output, syms, symcount, symstrtab);
3837 }
3838 
3839 /* Write out the CTF section.  Called early, if the emulation isn't going to
3840    need to dedup against the strtab and symtab, then possibly called from the
3841    target linker code if the dedup has happened.  */
3842 static void
lang_write_ctf(int late)3843 lang_write_ctf (int late)
3844 {
3845   size_t output_size;
3846   asection *output_sect;
3847 
3848   if (!ctf_output)
3849     return;
3850 
3851   if (late)
3852     {
3853       /* Emit CTF late if this emulation says it can do so.  */
3854       if (ldemul_emit_ctf_early ())
3855 	return;
3856     }
3857   else
3858     {
3859       if (!ldemul_emit_ctf_early ())
3860 	return;
3861     }
3862 
3863   /* Emit CTF.  */
3864 
3865   output_sect = bfd_get_section_by_name (link_info.output_bfd, ".ctf");
3866   if (output_sect)
3867     {
3868       output_sect->contents = ctf_link_write (ctf_output, &output_size,
3869 					      CTF_COMPRESSION_THRESHOLD);
3870       output_sect->size = output_size;
3871       output_sect->flags |= SEC_IN_MEMORY | SEC_KEEP;
3872 
3873       lang_ctf_errs_warnings (ctf_output);
3874       if (!output_sect->contents)
3875 	{
3876 	  einfo (_("%P: warning: CTF section emission failed; "
3877 		   "output will have no CTF section: %s\n"),
3878 		 ctf_errmsg (ctf_errno (ctf_output)));
3879 	  output_sect->size = 0;
3880 	  output_sect->flags |= SEC_EXCLUDE;
3881 	}
3882     }
3883 
3884   /* This also closes every CTF input file used in the link.  */
3885   ctf_file_close (ctf_output);
3886   ctf_output = NULL;
3887 
3888   LANG_FOR_EACH_INPUT_STATEMENT (file)
3889     file->the_ctf = NULL;
3890 }
3891 
3892 /* Write out the CTF section late, if the emulation needs that.  */
3893 
3894 void
ldlang_write_ctf_late(void)3895 ldlang_write_ctf_late (void)
3896 {
3897   /* Trigger a "late call", if the emulation needs one.  */
3898 
3899   lang_write_ctf (1);
3900 }
3901 #else
3902 static void
ldlang_open_ctf(void)3903 ldlang_open_ctf (void)
3904 {
3905   LANG_FOR_EACH_INPUT_STATEMENT (file)
3906     {
3907       asection *sect;
3908 
3909       /* If built without CTF, warn and delete all CTF sections from the output.
3910 	 (The alternative would be to simply concatenate them, which does not
3911 	 yield a valid CTF section.)  */
3912 
3913       if ((sect = bfd_get_section_by_name (file->the_bfd, ".ctf")) != NULL)
3914 	{
3915 	    einfo (_("%P: warning: CTF section in %pB not linkable: "
3916 		     "%P was built without support for CTF\n"), file->the_bfd);
3917 	    sect->size = 0;
3918 	    sect->flags |= SEC_EXCLUDE;
3919 	}
3920     }
3921 }
3922 
lang_merge_ctf(void)3923 static void lang_merge_ctf (void) {}
3924 void
ldlang_ctf_apply_strsym(struct elf_sym_strtab * syms ATTRIBUTE_UNUSED,bfd_size_type symcount ATTRIBUTE_UNUSED,struct elf_strtab_hash * symstrtab ATTRIBUTE_UNUSED)3925 ldlang_ctf_apply_strsym (struct elf_sym_strtab *syms ATTRIBUTE_UNUSED,
3926 			 bfd_size_type symcount ATTRIBUTE_UNUSED,
3927 			 struct elf_strtab_hash *symstrtab ATTRIBUTE_UNUSED)
3928 {
3929 }
lang_write_ctf(int late ATTRIBUTE_UNUSED)3930 static void lang_write_ctf (int late ATTRIBUTE_UNUSED) {}
ldlang_write_ctf_late(void)3931 void ldlang_write_ctf_late (void) {}
3932 #endif
3933 
3934 /* Add the supplied name to the symbol table as an undefined reference.
3935    This is a two step process as the symbol table doesn't even exist at
3936    the time the ld command line is processed.  First we put the name
3937    on a list, then, once the output file has been opened, transfer the
3938    name to the symbol table.  */
3939 
3940 typedef struct bfd_sym_chain ldlang_undef_chain_list_type;
3941 
3942 #define ldlang_undef_chain_list_head entry_symbol.next
3943 
3944 void
ldlang_add_undef(const char * const name,bfd_boolean cmdline ATTRIBUTE_UNUSED)3945 ldlang_add_undef (const char *const name, bfd_boolean cmdline ATTRIBUTE_UNUSED)
3946 {
3947   ldlang_undef_chain_list_type *new_undef;
3948 
3949   new_undef = stat_alloc (sizeof (*new_undef));
3950   new_undef->next = ldlang_undef_chain_list_head;
3951   ldlang_undef_chain_list_head = new_undef;
3952 
3953   new_undef->name = xstrdup (name);
3954 
3955   if (link_info.output_bfd != NULL)
3956     insert_undefined (new_undef->name);
3957 }
3958 
3959 /* Insert NAME as undefined in the symbol table.  */
3960 
3961 static void
insert_undefined(const char * name)3962 insert_undefined (const char *name)
3963 {
3964   struct bfd_link_hash_entry *h;
3965 
3966   h = bfd_link_hash_lookup (link_info.hash, name, TRUE, FALSE, TRUE);
3967   if (h == NULL)
3968     einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
3969   if (h->type == bfd_link_hash_new)
3970     {
3971       h->type = bfd_link_hash_undefined;
3972       h->u.undef.abfd = NULL;
3973       h->non_ir_ref_regular = TRUE;
3974       if (is_elf_hash_table (link_info.hash))
3975 	((struct elf_link_hash_entry *) h)->mark = 1;
3976       bfd_link_add_undef (link_info.hash, h);
3977     }
3978 }
3979 
3980 /* Run through the list of undefineds created above and place them
3981    into the linker hash table as undefined symbols belonging to the
3982    script file.  */
3983 
3984 static void
lang_place_undefineds(void)3985 lang_place_undefineds (void)
3986 {
3987   ldlang_undef_chain_list_type *ptr;
3988 
3989   for (ptr = ldlang_undef_chain_list_head; ptr != NULL; ptr = ptr->next)
3990     insert_undefined (ptr->name);
3991 }
3992 
3993 /* Structure used to build the list of symbols that the user has required
3994    be defined.  */
3995 
3996 struct require_defined_symbol
3997 {
3998   const char *name;
3999   struct require_defined_symbol *next;
4000 };
4001 
4002 /* The list of symbols that the user has required be defined.  */
4003 
4004 static struct require_defined_symbol *require_defined_symbol_list;
4005 
4006 /* Add a new symbol NAME to the list of symbols that are required to be
4007    defined.  */
4008 
4009 void
ldlang_add_require_defined(const char * const name)4010 ldlang_add_require_defined (const char *const name)
4011 {
4012   struct require_defined_symbol *ptr;
4013 
4014   ldlang_add_undef (name, TRUE);
4015   ptr = stat_alloc (sizeof (*ptr));
4016   ptr->next = require_defined_symbol_list;
4017   ptr->name = strdup (name);
4018   require_defined_symbol_list = ptr;
4019 }
4020 
4021 /* Check that all symbols the user required to be defined, are defined,
4022    raise an error if we find a symbol that is not defined.  */
4023 
4024 static void
ldlang_check_require_defined_symbols(void)4025 ldlang_check_require_defined_symbols (void)
4026 {
4027   struct require_defined_symbol *ptr;
4028 
4029   for (ptr = require_defined_symbol_list; ptr != NULL; ptr = ptr->next)
4030     {
4031       struct bfd_link_hash_entry *h;
4032 
4033       h = bfd_link_hash_lookup (link_info.hash, ptr->name,
4034 				FALSE, FALSE, TRUE);
4035       if (h == NULL
4036 	  || (h->type != bfd_link_hash_defined
4037 	      && h->type != bfd_link_hash_defweak))
4038 	einfo(_("%X%P: required symbol `%s' not defined\n"), ptr->name);
4039     }
4040 }
4041 
4042 /* Check for all readonly or some readwrite sections.  */
4043 
4044 static void
check_input_sections(lang_statement_union_type * s,lang_output_section_statement_type * output_section_statement)4045 check_input_sections
4046   (lang_statement_union_type *s,
4047    lang_output_section_statement_type *output_section_statement)
4048 {
4049   for (; s != NULL; s = s->header.next)
4050     {
4051       switch (s->header.type)
4052 	{
4053 	case lang_wild_statement_enum:
4054 	  walk_wild (&s->wild_statement, check_section_callback,
4055 		     output_section_statement);
4056 	  if (!output_section_statement->all_input_readonly)
4057 	    return;
4058 	  break;
4059 	case lang_constructors_statement_enum:
4060 	  check_input_sections (constructor_list.head,
4061 				output_section_statement);
4062 	  if (!output_section_statement->all_input_readonly)
4063 	    return;
4064 	  break;
4065 	case lang_group_statement_enum:
4066 	  check_input_sections (s->group_statement.children.head,
4067 				output_section_statement);
4068 	  if (!output_section_statement->all_input_readonly)
4069 	    return;
4070 	  break;
4071 	default:
4072 	  break;
4073 	}
4074     }
4075 }
4076 
4077 /* Update wildcard statements if needed.  */
4078 
4079 static void
update_wild_statements(lang_statement_union_type * s)4080 update_wild_statements (lang_statement_union_type *s)
4081 {
4082   struct wildcard_list *sec;
4083 
4084   switch (sort_section)
4085     {
4086     default:
4087       FAIL ();
4088 
4089     case none:
4090       break;
4091 
4092     case by_name:
4093     case by_alignment:
4094       for (; s != NULL; s = s->header.next)
4095 	{
4096 	  switch (s->header.type)
4097 	    {
4098 	    default:
4099 	      break;
4100 
4101 	    case lang_wild_statement_enum:
4102 	      for (sec = s->wild_statement.section_list; sec != NULL;
4103 		   sec = sec->next)
4104 		/* Don't sort .init/.fini sections.  */
4105 		if (strcmp (sec->spec.name, ".init") != 0
4106 		    && strcmp (sec->spec.name, ".fini") != 0)
4107 		  switch (sec->spec.sorted)
4108 		    {
4109 		    case none:
4110 		      sec->spec.sorted = sort_section;
4111 		      break;
4112 		    case by_name:
4113 		      if (sort_section == by_alignment)
4114 			sec->spec.sorted = by_name_alignment;
4115 		      break;
4116 		    case by_alignment:
4117 		      if (sort_section == by_name)
4118 			sec->spec.sorted = by_alignment_name;
4119 		      break;
4120 		    default:
4121 		      break;
4122 		    }
4123 	      break;
4124 
4125 	    case lang_constructors_statement_enum:
4126 	      update_wild_statements (constructor_list.head);
4127 	      break;
4128 
4129 	    case lang_output_section_statement_enum:
4130 	      update_wild_statements
4131 		(s->output_section_statement.children.head);
4132 	      break;
4133 
4134 	    case lang_group_statement_enum:
4135 	      update_wild_statements (s->group_statement.children.head);
4136 	      break;
4137 	    }
4138 	}
4139       break;
4140     }
4141 }
4142 
4143 /* Open input files and attach to output sections.  */
4144 
4145 static void
map_input_to_output_sections(lang_statement_union_type * s,const char * target,lang_output_section_statement_type * os)4146 map_input_to_output_sections
4147   (lang_statement_union_type *s, const char *target,
4148    lang_output_section_statement_type *os)
4149 {
4150   for (; s != NULL; s = s->header.next)
4151     {
4152       lang_output_section_statement_type *tos;
4153       flagword flags;
4154 
4155       switch (s->header.type)
4156 	{
4157 	case lang_wild_statement_enum:
4158 	  wild (&s->wild_statement, target, os);
4159 	  break;
4160 	case lang_constructors_statement_enum:
4161 	  map_input_to_output_sections (constructor_list.head,
4162 					target,
4163 					os);
4164 	  break;
4165 	case lang_output_section_statement_enum:
4166 	  tos = &s->output_section_statement;
4167 	  if (tos->constraint != 0)
4168 	    {
4169 	      if (tos->constraint != ONLY_IF_RW
4170 		  && tos->constraint != ONLY_IF_RO)
4171 		break;
4172 	      tos->all_input_readonly = TRUE;
4173 	      check_input_sections (tos->children.head, tos);
4174 	      if (tos->all_input_readonly != (tos->constraint == ONLY_IF_RO))
4175 		{
4176 		  tos->constraint = -1;
4177 		  break;
4178 		}
4179 	    }
4180 	  map_input_to_output_sections (tos->children.head,
4181 					target,
4182 					tos);
4183 	  break;
4184 	case lang_output_statement_enum:
4185 	  break;
4186 	case lang_target_statement_enum:
4187 	  target = s->target_statement.target;
4188 	  break;
4189 	case lang_group_statement_enum:
4190 	  map_input_to_output_sections (s->group_statement.children.head,
4191 					target,
4192 					os);
4193 	  break;
4194 	case lang_data_statement_enum:
4195 	  /* Make sure that any sections mentioned in the expression
4196 	     are initialized.  */
4197 	  exp_init_os (s->data_statement.exp);
4198 	  /* The output section gets CONTENTS, ALLOC and LOAD, but
4199 	     these may be overridden by the script.  */
4200 	  flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD;
4201 	  switch (os->sectype)
4202 	    {
4203 	    case normal_section:
4204 	    case overlay_section:
4205 	    case first_overlay_section:
4206 	      break;
4207 	    case noalloc_section:
4208 	      flags = SEC_HAS_CONTENTS;
4209 	      break;
4210 	    case noload_section:
4211 	      if (bfd_get_flavour (link_info.output_bfd)
4212 		  == bfd_target_elf_flavour)
4213 		flags = SEC_NEVER_LOAD | SEC_ALLOC;
4214 	      else
4215 		flags = SEC_NEVER_LOAD | SEC_HAS_CONTENTS;
4216 	      break;
4217 	    }
4218 	  if (os->bfd_section == NULL)
4219 	    init_os (os, flags);
4220 	  else
4221 	    os->bfd_section->flags |= flags;
4222 	  break;
4223 	case lang_input_section_enum:
4224 	  break;
4225 	case lang_fill_statement_enum:
4226 	case lang_object_symbols_statement_enum:
4227 	case lang_reloc_statement_enum:
4228 	case lang_padding_statement_enum:
4229 	case lang_input_statement_enum:
4230 	  if (os != NULL && os->bfd_section == NULL)
4231 	    init_os (os, 0);
4232 	  break;
4233 	case lang_assignment_statement_enum:
4234 	  if (os != NULL && os->bfd_section == NULL)
4235 	    init_os (os, 0);
4236 
4237 	  /* Make sure that any sections mentioned in the assignment
4238 	     are initialized.  */
4239 	  exp_init_os (s->assignment_statement.exp);
4240 	  break;
4241 	case lang_address_statement_enum:
4242 	  /* Mark the specified section with the supplied address.
4243 	     If this section was actually a segment marker, then the
4244 	     directive is ignored if the linker script explicitly
4245 	     processed the segment marker.  Originally, the linker
4246 	     treated segment directives (like -Ttext on the
4247 	     command-line) as section directives.  We honor the
4248 	     section directive semantics for backwards compatibility;
4249 	     linker scripts that do not specifically check for
4250 	     SEGMENT_START automatically get the old semantics.  */
4251 	  if (!s->address_statement.segment
4252 	      || !s->address_statement.segment->used)
4253 	    {
4254 	      const char *name = s->address_statement.section_name;
4255 
4256 	      /* Create the output section statement here so that
4257 		 orphans with a set address will be placed after other
4258 		 script sections.  If we let the orphan placement code
4259 		 place them in amongst other sections then the address
4260 		 will affect following script sections, which is
4261 		 likely to surprise naive users.  */
4262 	      tos = lang_output_section_statement_lookup (name, 0, TRUE);
4263 	      tos->addr_tree = s->address_statement.address;
4264 	      if (tos->bfd_section == NULL)
4265 		init_os (tos, 0);
4266 	    }
4267 	  break;
4268 	case lang_insert_statement_enum:
4269 	  break;
4270 	}
4271     }
4272 }
4273 
4274 /* An insert statement snips out all the linker statements from the
4275    start of the list and places them after the output section
4276    statement specified by the insert.  This operation is complicated
4277    by the fact that we keep a doubly linked list of output section
4278    statements as well as the singly linked list of all statements.
4279    FIXME someday: Twiddling with the list not only moves statements
4280    from the user's script but also input and group statements that are
4281    built from command line object files and --start-group.  We only
4282    get away with this because the list pointers used by file_chain
4283    and input_file_chain are not reordered, and processing via
4284    statement_list after this point mostly ignores input statements.
4285    One exception is the map file, where LOAD and START GROUP/END GROUP
4286    can end up looking odd.  */
4287 
4288 static void
process_insert_statements(lang_statement_union_type ** start)4289 process_insert_statements (lang_statement_union_type **start)
4290 {
4291   lang_statement_union_type **s;
4292   lang_output_section_statement_type *first_os = NULL;
4293   lang_output_section_statement_type *last_os = NULL;
4294   lang_output_section_statement_type *os;
4295 
4296   s = start;
4297   while (*s != NULL)
4298     {
4299       if ((*s)->header.type == lang_output_section_statement_enum)
4300 	{
4301 	  /* Keep pointers to the first and last output section
4302 	     statement in the sequence we may be about to move.  */
4303 	  os = &(*s)->output_section_statement;
4304 
4305 	  ASSERT (last_os == NULL || last_os->next == os);
4306 	  last_os = os;
4307 
4308 	  /* Set constraint negative so that lang_output_section_find
4309 	     won't match this output section statement.  At this
4310 	     stage in linking constraint has values in the range
4311 	     [-1, ONLY_IN_RW].  */
4312 	  last_os->constraint = -2 - last_os->constraint;
4313 	  if (first_os == NULL)
4314 	    first_os = last_os;
4315 	}
4316       else if ((*s)->header.type == lang_group_statement_enum)
4317 	{
4318 	  /* A user might put -T between --start-group and
4319 	     --end-group.  One way this odd construct might arise is
4320 	     from a wrapper around ld to change library search
4321 	     behaviour.  For example:
4322 	     #! /bin/sh
4323 	     exec real_ld --start-group "$@" --end-group
4324 	     This isn't completely unreasonable so go looking inside a
4325 	     group statement for insert statements.  */
4326 	  process_insert_statements (&(*s)->group_statement.children.head);
4327 	}
4328       else if ((*s)->header.type == lang_insert_statement_enum)
4329 	{
4330 	  lang_insert_statement_type *i = &(*s)->insert_statement;
4331 	  lang_output_section_statement_type *where;
4332 	  lang_statement_union_type **ptr;
4333 	  lang_statement_union_type *first;
4334 
4335 	  if (link_info.non_contiguous_regions)
4336 	    {
4337 	      einfo (_("warning: INSERT statement in linker script is "
4338 		       "incompatible with --enable-non-contiguous-regions.\n"));
4339 	    }
4340 
4341 	  where = lang_output_section_find (i->where);
4342 	  if (where != NULL && i->is_before)
4343 	    {
4344 	      do
4345 		where = where->prev;
4346 	      while (where != NULL && where->constraint < 0);
4347 	    }
4348 	  if (where == NULL)
4349 	    {
4350 	      einfo (_("%F%P: %s not found for insert\n"), i->where);
4351 	      return;
4352 	    }
4353 
4354 	  /* Deal with reordering the output section statement list.  */
4355 	  if (last_os != NULL)
4356 	    {
4357 	      asection *first_sec, *last_sec;
4358 	      struct lang_output_section_statement_struct **next;
4359 
4360 	      /* Snip out the output sections we are moving.  */
4361 	      first_os->prev->next = last_os->next;
4362 	      if (last_os->next == NULL)
4363 		{
4364 		  next = &first_os->prev->next;
4365 		  lang_os_list.tail = (lang_statement_union_type **) next;
4366 		}
4367 	      else
4368 		last_os->next->prev = first_os->prev;
4369 	      /* Add them in at the new position.  */
4370 	      last_os->next = where->next;
4371 	      if (where->next == NULL)
4372 		{
4373 		  next = &last_os->next;
4374 		  lang_os_list.tail = (lang_statement_union_type **) next;
4375 		}
4376 	      else
4377 		where->next->prev = last_os;
4378 	      first_os->prev = where;
4379 	      where->next = first_os;
4380 
4381 	      /* Move the bfd sections in the same way.  */
4382 	      first_sec = NULL;
4383 	      last_sec = NULL;
4384 	      for (os = first_os; os != NULL; os = os->next)
4385 		{
4386 		  os->constraint = -2 - os->constraint;
4387 		  if (os->bfd_section != NULL
4388 		      && os->bfd_section->owner != NULL)
4389 		    {
4390 		      last_sec = os->bfd_section;
4391 		      if (first_sec == NULL)
4392 			first_sec = last_sec;
4393 		    }
4394 		  if (os == last_os)
4395 		    break;
4396 		}
4397 	      if (last_sec != NULL)
4398 		{
4399 		  asection *sec = where->bfd_section;
4400 		  if (sec == NULL)
4401 		    sec = output_prev_sec_find (where);
4402 
4403 		  /* The place we want to insert must come after the
4404 		     sections we are moving.  So if we find no
4405 		     section or if the section is the same as our
4406 		     last section, then no move is needed.  */
4407 		  if (sec != NULL && sec != last_sec)
4408 		    {
4409 		      /* Trim them off.  */
4410 		      if (first_sec->prev != NULL)
4411 			first_sec->prev->next = last_sec->next;
4412 		      else
4413 			link_info.output_bfd->sections = last_sec->next;
4414 		      if (last_sec->next != NULL)
4415 			last_sec->next->prev = first_sec->prev;
4416 		      else
4417 			link_info.output_bfd->section_last = first_sec->prev;
4418 		      /* Add back.  */
4419 		      last_sec->next = sec->next;
4420 		      if (sec->next != NULL)
4421 			sec->next->prev = last_sec;
4422 		      else
4423 			link_info.output_bfd->section_last = last_sec;
4424 		      first_sec->prev = sec;
4425 		      sec->next = first_sec;
4426 		    }
4427 		}
4428 
4429 	      first_os = NULL;
4430 	      last_os = NULL;
4431 	    }
4432 
4433 	  ptr = insert_os_after (where);
4434 	  /* Snip everything from the start of the list, up to and
4435 	     including the insert statement we are currently processing.  */
4436 	  first = *start;
4437 	  *start = (*s)->header.next;
4438 	  /* Add them back where they belong, minus the insert.  */
4439 	  *s = *ptr;
4440 	  if (*s == NULL)
4441 	    statement_list.tail = s;
4442 	  *ptr = first;
4443 	  s = start;
4444 	  continue;
4445 	}
4446       s = &(*s)->header.next;
4447     }
4448 
4449   /* Undo constraint twiddling.  */
4450   for (os = first_os; os != NULL; os = os->next)
4451     {
4452       os->constraint = -2 - os->constraint;
4453       if (os == last_os)
4454 	break;
4455     }
4456 }
4457 
4458 /* An output section might have been removed after its statement was
4459    added.  For example, ldemul_before_allocation can remove dynamic
4460    sections if they turn out to be not needed.  Clean them up here.  */
4461 
4462 void
strip_excluded_output_sections(void)4463 strip_excluded_output_sections (void)
4464 {
4465   lang_output_section_statement_type *os;
4466 
4467   /* Run lang_size_sections (if not already done).  */
4468   if (expld.phase != lang_mark_phase_enum)
4469     {
4470       expld.phase = lang_mark_phase_enum;
4471       expld.dataseg.phase = exp_seg_none;
4472       one_lang_size_sections_pass (NULL, FALSE);
4473       lang_reset_memory_regions ();
4474     }
4475 
4476   for (os = (void *) lang_os_list.head;
4477        os != NULL;
4478        os = os->next)
4479     {
4480       asection *output_section;
4481       bfd_boolean exclude;
4482 
4483       if (os->constraint < 0)
4484 	continue;
4485 
4486       output_section = os->bfd_section;
4487       if (output_section == NULL)
4488 	continue;
4489 
4490       exclude = (output_section->rawsize == 0
4491 		 && (output_section->flags & SEC_KEEP) == 0
4492 		 && !bfd_section_removed_from_list (link_info.output_bfd,
4493 						    output_section));
4494 
4495       /* Some sections have not yet been sized, notably .gnu.version,
4496 	 .dynsym, .dynstr and .hash.  These all have SEC_LINKER_CREATED
4497 	 input sections, so don't drop output sections that have such
4498 	 input sections unless they are also marked SEC_EXCLUDE.  */
4499       if (exclude && output_section->map_head.s != NULL)
4500 	{
4501 	  asection *s;
4502 
4503 	  for (s = output_section->map_head.s; s != NULL; s = s->map_head.s)
4504 	    if ((s->flags & SEC_EXCLUDE) == 0
4505 		&& ((s->flags & SEC_LINKER_CREATED) != 0
4506 		    || link_info.emitrelocations))
4507 	      {
4508 		exclude = FALSE;
4509 		break;
4510 	      }
4511 	}
4512 
4513       if (exclude)
4514 	{
4515 	  /* We don't set bfd_section to NULL since bfd_section of the
4516 	     removed output section statement may still be used.  */
4517 	  if (!os->update_dot)
4518 	    os->ignored = TRUE;
4519 	  output_section->flags |= SEC_EXCLUDE;
4520 	  bfd_section_list_remove (link_info.output_bfd, output_section);
4521 	  link_info.output_bfd->section_count--;
4522 	}
4523     }
4524 }
4525 
4526 /* Called from ldwrite to clear out asection.map_head and
4527    asection.map_tail for use as link_orders in ldwrite.  */
4528 
4529 void
lang_clear_os_map(void)4530 lang_clear_os_map (void)
4531 {
4532   lang_output_section_statement_type *os;
4533 
4534   if (map_head_is_link_order)
4535     return;
4536 
4537   for (os = (void *) lang_os_list.head;
4538        os != NULL;
4539        os = os->next)
4540     {
4541       asection *output_section;
4542 
4543       if (os->constraint < 0)
4544 	continue;
4545 
4546       output_section = os->bfd_section;
4547       if (output_section == NULL)
4548 	continue;
4549 
4550       /* TODO: Don't just junk map_head.s, turn them into link_orders.  */
4551       output_section->map_head.link_order = NULL;
4552       output_section->map_tail.link_order = NULL;
4553     }
4554 
4555   /* Stop future calls to lang_add_section from messing with map_head
4556      and map_tail link_order fields.  */
4557   map_head_is_link_order = TRUE;
4558 }
4559 
4560 static void
print_output_section_statement(lang_output_section_statement_type * output_section_statement)4561 print_output_section_statement
4562   (lang_output_section_statement_type *output_section_statement)
4563 {
4564   asection *section = output_section_statement->bfd_section;
4565   int len;
4566 
4567   if (output_section_statement != abs_output_section)
4568     {
4569       minfo ("\n%s", output_section_statement->name);
4570 
4571       if (section != NULL)
4572 	{
4573 	  print_dot = section->vma;
4574 
4575 	  len = strlen (output_section_statement->name);
4576 	  if (len >= SECTION_NAME_MAP_LENGTH - 1)
4577 	    {
4578 	      print_nl ();
4579 	      len = 0;
4580 	    }
4581 	  while (len < SECTION_NAME_MAP_LENGTH)
4582 	    {
4583 	      print_space ();
4584 	      ++len;
4585 	    }
4586 
4587 	  minfo ("0x%V %W", section->vma, TO_ADDR (section->size));
4588 
4589 	  if (section->vma != section->lma)
4590 	    minfo (_(" load address 0x%V"), section->lma);
4591 
4592 	  if (output_section_statement->update_dot_tree != NULL)
4593 	    exp_fold_tree (output_section_statement->update_dot_tree,
4594 			   bfd_abs_section_ptr, &print_dot);
4595 	}
4596 
4597       print_nl ();
4598     }
4599 
4600   print_statement_list (output_section_statement->children.head,
4601 			output_section_statement);
4602 }
4603 
4604 static void
print_assignment(lang_assignment_statement_type * assignment,lang_output_section_statement_type * output_section)4605 print_assignment (lang_assignment_statement_type *assignment,
4606 		  lang_output_section_statement_type *output_section)
4607 {
4608   unsigned int i;
4609   bfd_boolean is_dot;
4610   etree_type *tree;
4611   asection *osec;
4612 
4613   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
4614     print_space ();
4615 
4616   if (assignment->exp->type.node_class == etree_assert)
4617     {
4618       is_dot = FALSE;
4619       tree = assignment->exp->assert_s.child;
4620     }
4621   else
4622     {
4623       const char *dst = assignment->exp->assign.dst;
4624 
4625       is_dot = (dst[0] == '.' && dst[1] == 0);
4626       tree = assignment->exp;
4627     }
4628 
4629   osec = output_section->bfd_section;
4630   if (osec == NULL)
4631     osec = bfd_abs_section_ptr;
4632 
4633   if (assignment->exp->type.node_class != etree_provide)
4634     exp_fold_tree (tree, osec, &print_dot);
4635   else
4636     expld.result.valid_p = FALSE;
4637 
4638   if (expld.result.valid_p)
4639     {
4640       bfd_vma value;
4641 
4642       if (assignment->exp->type.node_class == etree_assert
4643 	  || is_dot
4644 	  || expld.assign_name != NULL)
4645 	{
4646 	  value = expld.result.value;
4647 
4648 	  if (expld.result.section != NULL)
4649 	    value += expld.result.section->vma;
4650 
4651 	  minfo ("0x%V", value);
4652 	  if (is_dot)
4653 	    print_dot = value;
4654 	}
4655       else
4656 	{
4657 	  struct bfd_link_hash_entry *h;
4658 
4659 	  h = bfd_link_hash_lookup (link_info.hash, assignment->exp->assign.dst,
4660 				    FALSE, FALSE, TRUE);
4661 	  if (h != NULL
4662 	      && (h->type == bfd_link_hash_defined
4663 		  || h->type == bfd_link_hash_defweak))
4664 	    {
4665 	      value = h->u.def.value;
4666 	      value += h->u.def.section->output_section->vma;
4667 	      value += h->u.def.section->output_offset;
4668 
4669 	      minfo ("[0x%V]", value);
4670 	    }
4671 	  else
4672 	    minfo ("[unresolved]");
4673 	}
4674     }
4675   else
4676     {
4677       if (assignment->exp->type.node_class == etree_provide)
4678 	minfo ("[!provide]");
4679       else
4680 	minfo ("*undef*   ");
4681 #ifdef BFD64
4682       minfo ("        ");
4683 #endif
4684     }
4685   expld.assign_name = NULL;
4686 
4687   minfo ("                ");
4688   exp_print_tree (assignment->exp);
4689   print_nl ();
4690 }
4691 
4692 static void
print_input_statement(lang_input_statement_type * statm)4693 print_input_statement (lang_input_statement_type *statm)
4694 {
4695   if (statm->filename != NULL)
4696     fprintf (config.map_file, "LOAD %s\n", statm->filename);
4697 }
4698 
4699 /* Print all symbols defined in a particular section.  This is called
4700    via bfd_link_hash_traverse, or by print_all_symbols.  */
4701 
4702 bfd_boolean
print_one_symbol(struct bfd_link_hash_entry * hash_entry,void * ptr)4703 print_one_symbol (struct bfd_link_hash_entry *hash_entry, void *ptr)
4704 {
4705   asection *sec = (asection *) ptr;
4706 
4707   if ((hash_entry->type == bfd_link_hash_defined
4708        || hash_entry->type == bfd_link_hash_defweak)
4709       && sec == hash_entry->u.def.section)
4710     {
4711       int i;
4712 
4713       for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
4714 	print_space ();
4715       minfo ("0x%V   ",
4716 	     (hash_entry->u.def.value
4717 	      + hash_entry->u.def.section->output_offset
4718 	      + hash_entry->u.def.section->output_section->vma));
4719 
4720       minfo ("             %pT\n", hash_entry->root.string);
4721     }
4722 
4723   return TRUE;
4724 }
4725 
4726 static int
hash_entry_addr_cmp(const void * a,const void * b)4727 hash_entry_addr_cmp (const void *a, const void *b)
4728 {
4729   const struct bfd_link_hash_entry *l = *(const struct bfd_link_hash_entry **)a;
4730   const struct bfd_link_hash_entry *r = *(const struct bfd_link_hash_entry **)b;
4731 
4732   if (l->u.def.value < r->u.def.value)
4733     return -1;
4734   else if (l->u.def.value > r->u.def.value)
4735     return 1;
4736   else
4737     return 0;
4738 }
4739 
4740 static void
print_all_symbols(asection * sec)4741 print_all_symbols (asection *sec)
4742 {
4743   input_section_userdata_type *ud = bfd_section_userdata (sec);
4744   struct map_symbol_def *def;
4745   struct bfd_link_hash_entry **entries;
4746   unsigned int i;
4747 
4748   if (!ud)
4749     return;
4750 
4751   *ud->map_symbol_def_tail = 0;
4752 
4753   /* Sort the symbols by address.  */
4754   entries = (struct bfd_link_hash_entry **)
4755       obstack_alloc (&map_obstack,
4756 		     ud->map_symbol_def_count * sizeof (*entries));
4757 
4758   for (i = 0, def = ud->map_symbol_def_head; def; def = def->next, i++)
4759     entries[i] = def->entry;
4760 
4761   qsort (entries, ud->map_symbol_def_count, sizeof (*entries),
4762 	 hash_entry_addr_cmp);
4763 
4764   /* Print the symbols.  */
4765   for (i = 0; i < ud->map_symbol_def_count; i++)
4766     ldemul_print_symbol (entries[i], sec);
4767 
4768   obstack_free (&map_obstack, entries);
4769 }
4770 
4771 /* Print information about an input section to the map file.  */
4772 
4773 static void
print_input_section(asection * i,bfd_boolean is_discarded)4774 print_input_section (asection *i, bfd_boolean is_discarded)
4775 {
4776   bfd_size_type size = i->size;
4777   int len;
4778   bfd_vma addr;
4779 
4780   init_opb (i);
4781 
4782   print_space ();
4783   minfo ("%s", i->name);
4784 
4785   len = 1 + strlen (i->name);
4786   if (len >= SECTION_NAME_MAP_LENGTH - 1)
4787     {
4788       print_nl ();
4789       len = 0;
4790     }
4791   while (len < SECTION_NAME_MAP_LENGTH)
4792     {
4793       print_space ();
4794       ++len;
4795     }
4796 
4797   if (i->output_section != NULL
4798       && i->output_section->owner == link_info.output_bfd)
4799     addr = i->output_section->vma + i->output_offset;
4800   else
4801     {
4802       addr = print_dot;
4803       if (!is_discarded)
4804 	size = 0;
4805     }
4806 
4807   minfo ("0x%V %W %pB\n", addr, TO_ADDR (size), i->owner);
4808 
4809   if (size != i->rawsize && i->rawsize != 0)
4810     {
4811       len = SECTION_NAME_MAP_LENGTH + 3;
4812 #ifdef BFD64
4813       len += 16;
4814 #else
4815       len += 8;
4816 #endif
4817       while (len > 0)
4818 	{
4819 	  print_space ();
4820 	  --len;
4821 	}
4822 
4823       minfo (_("%W (size before relaxing)\n"), TO_ADDR (i->rawsize));
4824     }
4825 
4826   if (i->output_section != NULL
4827       && i->output_section->owner == link_info.output_bfd)
4828     {
4829       if (link_info.reduce_memory_overheads)
4830 	bfd_link_hash_traverse (link_info.hash, ldemul_print_symbol, i);
4831       else
4832 	print_all_symbols (i);
4833 
4834       /* Update print_dot, but make sure that we do not move it
4835 	 backwards - this could happen if we have overlays and a
4836 	 later overlay is shorter than an earier one.  */
4837       if (addr + TO_ADDR (size) > print_dot)
4838 	print_dot = addr + TO_ADDR (size);
4839     }
4840 }
4841 
4842 static void
print_fill_statement(lang_fill_statement_type * fill)4843 print_fill_statement (lang_fill_statement_type *fill)
4844 {
4845   size_t size;
4846   unsigned char *p;
4847   fputs (" FILL mask 0x", config.map_file);
4848   for (p = fill->fill->data, size = fill->fill->size; size != 0; p++, size--)
4849     fprintf (config.map_file, "%02x", *p);
4850   fputs ("\n", config.map_file);
4851 }
4852 
4853 static void
print_data_statement(lang_data_statement_type * data)4854 print_data_statement (lang_data_statement_type *data)
4855 {
4856   int i;
4857   bfd_vma addr;
4858   bfd_size_type size;
4859   const char *name;
4860 
4861   init_opb (data->output_section);
4862   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
4863     print_space ();
4864 
4865   addr = data->output_offset;
4866   if (data->output_section != NULL)
4867     addr += data->output_section->vma;
4868 
4869   switch (data->type)
4870     {
4871     default:
4872       abort ();
4873     case BYTE:
4874       size = BYTE_SIZE;
4875       name = "BYTE";
4876       break;
4877     case SHORT:
4878       size = SHORT_SIZE;
4879       name = "SHORT";
4880       break;
4881     case LONG:
4882       size = LONG_SIZE;
4883       name = "LONG";
4884       break;
4885     case QUAD:
4886       size = QUAD_SIZE;
4887       name = "QUAD";
4888       break;
4889     case SQUAD:
4890       size = QUAD_SIZE;
4891       name = "SQUAD";
4892       break;
4893     }
4894 
4895   if (size < TO_SIZE ((unsigned) 1))
4896     size = TO_SIZE ((unsigned) 1);
4897   minfo ("0x%V %W %s 0x%v", addr, TO_ADDR (size), name, data->value);
4898 
4899   if (data->exp->type.node_class != etree_value)
4900     {
4901       print_space ();
4902       exp_print_tree (data->exp);
4903     }
4904 
4905   print_nl ();
4906 
4907   print_dot = addr + TO_ADDR (size);
4908 }
4909 
4910 /* Print an address statement.  These are generated by options like
4911    -Ttext.  */
4912 
4913 static void
print_address_statement(lang_address_statement_type * address)4914 print_address_statement (lang_address_statement_type *address)
4915 {
4916   minfo (_("Address of section %s set to "), address->section_name);
4917   exp_print_tree (address->address);
4918   print_nl ();
4919 }
4920 
4921 /* Print a reloc statement.  */
4922 
4923 static void
print_reloc_statement(lang_reloc_statement_type * reloc)4924 print_reloc_statement (lang_reloc_statement_type *reloc)
4925 {
4926   int i;
4927   bfd_vma addr;
4928   bfd_size_type size;
4929 
4930   init_opb (reloc->output_section);
4931   for (i = 0; i < SECTION_NAME_MAP_LENGTH; i++)
4932     print_space ();
4933 
4934   addr = reloc->output_offset;
4935   if (reloc->output_section != NULL)
4936     addr += reloc->output_section->vma;
4937 
4938   size = bfd_get_reloc_size (reloc->howto);
4939 
4940   minfo ("0x%V %W RELOC %s ", addr, TO_ADDR (size), reloc->howto->name);
4941 
4942   if (reloc->name != NULL)
4943     minfo ("%s+", reloc->name);
4944   else
4945     minfo ("%s+", reloc->section->name);
4946 
4947   exp_print_tree (reloc->addend_exp);
4948 
4949   print_nl ();
4950 
4951   print_dot = addr + TO_ADDR (size);
4952 }
4953 
4954 static void
print_padding_statement(lang_padding_statement_type * s)4955 print_padding_statement (lang_padding_statement_type *s)
4956 {
4957   int len;
4958   bfd_vma addr;
4959 
4960   init_opb (s->output_section);
4961   minfo (" *fill*");
4962 
4963   len = sizeof " *fill*" - 1;
4964   while (len < SECTION_NAME_MAP_LENGTH)
4965     {
4966       print_space ();
4967       ++len;
4968     }
4969 
4970   addr = s->output_offset;
4971   if (s->output_section != NULL)
4972     addr += s->output_section->vma;
4973   minfo ("0x%V %W ", addr, TO_ADDR (s->size));
4974 
4975   if (s->fill->size != 0)
4976     {
4977       size_t size;
4978       unsigned char *p;
4979       for (p = s->fill->data, size = s->fill->size; size != 0; p++, size--)
4980 	fprintf (config.map_file, "%02x", *p);
4981     }
4982 
4983   print_nl ();
4984 
4985   print_dot = addr + TO_ADDR (s->size);
4986 }
4987 
4988 static void
print_wild_statement(lang_wild_statement_type * w,lang_output_section_statement_type * os)4989 print_wild_statement (lang_wild_statement_type *w,
4990 		      lang_output_section_statement_type *os)
4991 {
4992   struct wildcard_list *sec;
4993 
4994   print_space ();
4995 
4996   if (w->exclude_name_list)
4997     {
4998       name_list *tmp;
4999       minfo ("EXCLUDE_FILE(%s", w->exclude_name_list->name);
5000       for (tmp = w->exclude_name_list->next; tmp; tmp = tmp->next)
5001 	minfo (" %s", tmp->name);
5002       minfo (") ");
5003     }
5004 
5005   if (w->filenames_sorted)
5006     minfo ("SORT_BY_NAME(");
5007   if (w->filename != NULL)
5008     minfo ("%s", w->filename);
5009   else
5010     minfo ("*");
5011   if (w->filenames_sorted)
5012     minfo (")");
5013 
5014   minfo ("(");
5015   for (sec = w->section_list; sec; sec = sec->next)
5016     {
5017       int closing_paren = 0;
5018 
5019       switch (sec->spec.sorted)
5020 	{
5021 	case none:
5022 	  break;
5023 
5024 	case by_name:
5025 	  minfo ("SORT_BY_NAME(");
5026 	  closing_paren = 1;
5027 	  break;
5028 
5029 	case by_alignment:
5030 	  minfo ("SORT_BY_ALIGNMENT(");
5031 	  closing_paren = 1;
5032 	  break;
5033 
5034 	case by_name_alignment:
5035 	  minfo ("SORT_BY_NAME(SORT_BY_ALIGNMENT(");
5036 	  closing_paren = 2;
5037 	  break;
5038 
5039 	case by_alignment_name:
5040 	  minfo ("SORT_BY_ALIGNMENT(SORT_BY_NAME(");
5041 	  closing_paren = 2;
5042 	  break;
5043 
5044 	case by_none:
5045 	  minfo ("SORT_NONE(");
5046 	  closing_paren = 1;
5047 	  break;
5048 
5049 	case by_init_priority:
5050 	  minfo ("SORT_BY_INIT_PRIORITY(");
5051 	  closing_paren = 1;
5052 	  break;
5053 	}
5054 
5055       if (sec->spec.exclude_name_list != NULL)
5056 	{
5057 	  name_list *tmp;
5058 	  minfo ("EXCLUDE_FILE(%s", sec->spec.exclude_name_list->name);
5059 	  for (tmp = sec->spec.exclude_name_list->next; tmp; tmp = tmp->next)
5060 	    minfo (" %s", tmp->name);
5061 	  minfo (") ");
5062 	}
5063       if (sec->spec.name != NULL)
5064 	minfo ("%s", sec->spec.name);
5065       else
5066 	minfo ("*");
5067       for (;closing_paren > 0; closing_paren--)
5068 	minfo (")");
5069       if (sec->next)
5070 	minfo (" ");
5071     }
5072   minfo (")");
5073 
5074   print_nl ();
5075 
5076   print_statement_list (w->children.head, os);
5077 }
5078 
5079 /* Print a group statement.  */
5080 
5081 static void
print_group(lang_group_statement_type * s,lang_output_section_statement_type * os)5082 print_group (lang_group_statement_type *s,
5083 	     lang_output_section_statement_type *os)
5084 {
5085   fprintf (config.map_file, "START GROUP\n");
5086   print_statement_list (s->children.head, os);
5087   fprintf (config.map_file, "END GROUP\n");
5088 }
5089 
5090 /* Print the list of statements in S.
5091    This can be called for any statement type.  */
5092 
5093 static void
print_statement_list(lang_statement_union_type * s,lang_output_section_statement_type * os)5094 print_statement_list (lang_statement_union_type *s,
5095 		      lang_output_section_statement_type *os)
5096 {
5097   while (s != NULL)
5098     {
5099       print_statement (s, os);
5100       s = s->header.next;
5101     }
5102 }
5103 
5104 /* Print the first statement in statement list S.
5105    This can be called for any statement type.  */
5106 
5107 static void
print_statement(lang_statement_union_type * s,lang_output_section_statement_type * os)5108 print_statement (lang_statement_union_type *s,
5109 		 lang_output_section_statement_type *os)
5110 {
5111   switch (s->header.type)
5112     {
5113     default:
5114       fprintf (config.map_file, _("Fail with %d\n"), s->header.type);
5115       FAIL ();
5116       break;
5117     case lang_constructors_statement_enum:
5118       if (constructor_list.head != NULL)
5119 	{
5120 	  if (constructors_sorted)
5121 	    minfo (" SORT (CONSTRUCTORS)\n");
5122 	  else
5123 	    minfo (" CONSTRUCTORS\n");
5124 	  print_statement_list (constructor_list.head, os);
5125 	}
5126       break;
5127     case lang_wild_statement_enum:
5128       print_wild_statement (&s->wild_statement, os);
5129       break;
5130     case lang_address_statement_enum:
5131       print_address_statement (&s->address_statement);
5132       break;
5133     case lang_object_symbols_statement_enum:
5134       minfo (" CREATE_OBJECT_SYMBOLS\n");
5135       break;
5136     case lang_fill_statement_enum:
5137       print_fill_statement (&s->fill_statement);
5138       break;
5139     case lang_data_statement_enum:
5140       print_data_statement (&s->data_statement);
5141       break;
5142     case lang_reloc_statement_enum:
5143       print_reloc_statement (&s->reloc_statement);
5144       break;
5145     case lang_input_section_enum:
5146       print_input_section (s->input_section.section, FALSE);
5147       break;
5148     case lang_padding_statement_enum:
5149       print_padding_statement (&s->padding_statement);
5150       break;
5151     case lang_output_section_statement_enum:
5152       print_output_section_statement (&s->output_section_statement);
5153       break;
5154     case lang_assignment_statement_enum:
5155       print_assignment (&s->assignment_statement, os);
5156       break;
5157     case lang_target_statement_enum:
5158       fprintf (config.map_file, "TARGET(%s)\n", s->target_statement.target);
5159       break;
5160     case lang_output_statement_enum:
5161       minfo ("OUTPUT(%s", s->output_statement.name);
5162       if (output_target != NULL)
5163 	minfo (" %s", output_target);
5164       minfo (")\n");
5165       break;
5166     case lang_input_statement_enum:
5167       print_input_statement (&s->input_statement);
5168       break;
5169     case lang_group_statement_enum:
5170       print_group (&s->group_statement, os);
5171       break;
5172     case lang_insert_statement_enum:
5173       minfo ("INSERT %s %s\n",
5174 	     s->insert_statement.is_before ? "BEFORE" : "AFTER",
5175 	     s->insert_statement.where);
5176       break;
5177     }
5178 }
5179 
5180 static void
print_statements(void)5181 print_statements (void)
5182 {
5183   print_statement_list (statement_list.head, abs_output_section);
5184 }
5185 
5186 /* Print the first N statements in statement list S to STDERR.
5187    If N == 0, nothing is printed.
5188    If N < 0, the entire list is printed.
5189    Intended to be called from GDB.  */
5190 
5191 void
dprint_statement(lang_statement_union_type * s,int n)5192 dprint_statement (lang_statement_union_type *s, int n)
5193 {
5194   FILE *map_save = config.map_file;
5195 
5196   config.map_file = stderr;
5197 
5198   if (n < 0)
5199     print_statement_list (s, abs_output_section);
5200   else
5201     {
5202       while (s && --n >= 0)
5203 	{
5204 	  print_statement (s, abs_output_section);
5205 	  s = s->header.next;
5206 	}
5207     }
5208 
5209   config.map_file = map_save;
5210 }
5211 
5212 static void
insert_pad(lang_statement_union_type ** ptr,fill_type * fill,bfd_size_type alignment_needed,asection * output_section,bfd_vma dot)5213 insert_pad (lang_statement_union_type **ptr,
5214 	    fill_type *fill,
5215 	    bfd_size_type alignment_needed,
5216 	    asection *output_section,
5217 	    bfd_vma dot)
5218 {
5219   static fill_type zero_fill;
5220   lang_statement_union_type *pad = NULL;
5221 
5222   if (ptr != &statement_list.head)
5223     pad = ((lang_statement_union_type *)
5224 	   ((char *) ptr - offsetof (lang_statement_union_type, header.next)));
5225   if (pad != NULL
5226       && pad->header.type == lang_padding_statement_enum
5227       && pad->padding_statement.output_section == output_section)
5228     {
5229       /* Use the existing pad statement.  */
5230     }
5231   else if ((pad = *ptr) != NULL
5232 	   && pad->header.type == lang_padding_statement_enum
5233 	   && pad->padding_statement.output_section == output_section)
5234     {
5235       /* Use the existing pad statement.  */
5236     }
5237   else
5238     {
5239       /* Make a new padding statement, linked into existing chain.  */
5240       pad = stat_alloc (sizeof (lang_padding_statement_type));
5241       pad->header.next = *ptr;
5242       *ptr = pad;
5243       pad->header.type = lang_padding_statement_enum;
5244       pad->padding_statement.output_section = output_section;
5245       if (fill == NULL)
5246 	fill = &zero_fill;
5247       pad->padding_statement.fill = fill;
5248     }
5249   pad->padding_statement.output_offset = dot - output_section->vma;
5250   pad->padding_statement.size = alignment_needed;
5251   if (!(output_section->flags & SEC_FIXED_SIZE))
5252     output_section->size = TO_SIZE (dot + TO_ADDR (alignment_needed)
5253 				    - output_section->vma);
5254 }
5255 
5256 /* Work out how much this section will move the dot point.  */
5257 
5258 static bfd_vma
size_input_section(lang_statement_union_type ** this_ptr,lang_output_section_statement_type * output_section_statement,fill_type * fill,bfd_boolean * removed,bfd_vma dot)5259 size_input_section
5260   (lang_statement_union_type **this_ptr,
5261    lang_output_section_statement_type *output_section_statement,
5262    fill_type *fill,
5263    bfd_boolean *removed,
5264    bfd_vma dot)
5265 {
5266   lang_input_section_type *is = &((*this_ptr)->input_section);
5267   asection *i = is->section;
5268   asection *o = output_section_statement->bfd_section;
5269   *removed = 0;
5270 
5271   if (link_info.non_contiguous_regions)
5272     {
5273       /* If the input section I has already been successfully assigned
5274 	 to an output section other than O, don't bother with it and
5275 	 let the caller remove it from the list.  Keep processing in
5276 	 case we have already handled O, because the repeated passes
5277 	 have reinitialized its size.  */
5278       if (i->already_assigned && i->already_assigned != o)
5279 	{
5280 	  *removed = 1;
5281 	  return dot;
5282 	}
5283     }
5284 
5285   if (i->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
5286     i->output_offset = i->vma - o->vma;
5287   else if (((i->flags & SEC_EXCLUDE) != 0)
5288 	   || output_section_statement->ignored)
5289     i->output_offset = dot - o->vma;
5290   else
5291     {
5292       bfd_size_type alignment_needed;
5293 
5294       /* Align this section first to the input sections requirement,
5295 	 then to the output section's requirement.  If this alignment
5296 	 is greater than any seen before, then record it too.  Perform
5297 	 the alignment by inserting a magic 'padding' statement.  */
5298 
5299       if (output_section_statement->subsection_alignment != NULL)
5300 	i->alignment_power
5301 	  = exp_get_power (output_section_statement->subsection_alignment,
5302 			   "subsection alignment");
5303 
5304       if (o->alignment_power < i->alignment_power)
5305 	o->alignment_power = i->alignment_power;
5306 
5307       alignment_needed = align_power (dot, i->alignment_power) - dot;
5308 
5309       if (alignment_needed != 0)
5310 	{
5311 	  insert_pad (this_ptr, fill, TO_SIZE (alignment_needed), o, dot);
5312 	  dot += alignment_needed;
5313 	}
5314 
5315       if (link_info.non_contiguous_regions)
5316 	{
5317 	  /* If I would overflow O, let the caller remove I from the
5318 	     list.  */
5319 	  if (output_section_statement->region)
5320 	    {
5321 	      bfd_vma end = output_section_statement->region->origin
5322 		+ output_section_statement->region->length;
5323 
5324 	      if (dot + TO_ADDR (i->size) > end)
5325 		{
5326 		  if (i->flags & SEC_LINKER_CREATED)
5327 		    einfo (_("%F%P: Output section '%s' not large enough for the "
5328 			     "linker-created stubs section '%s'.\n"),
5329 			   i->output_section->name, i->name);
5330 
5331 		  if (i->rawsize && i->rawsize != i->size)
5332 		    einfo (_("%F%P: Relaxation not supported with "
5333 			     "--enable-non-contiguous-regions (section '%s' "
5334 			     "would overflow '%s' after it changed size).\n"),
5335 			   i->name, i->output_section->name);
5336 
5337 		  *removed = 1;
5338 		  dot = end;
5339 		  i->output_section = NULL;
5340 		  return dot;
5341 		}
5342 	    }
5343 	}
5344 
5345       /* Remember where in the output section this input section goes.  */
5346       i->output_offset = dot - o->vma;
5347 
5348       /* Mark how big the output section must be to contain this now.  */
5349       dot += TO_ADDR (i->size);
5350       if (!(o->flags & SEC_FIXED_SIZE))
5351 	o->size = TO_SIZE (dot - o->vma);
5352 
5353       if (link_info.non_contiguous_regions)
5354 	{
5355 	  /* Record that I was successfully assigned to O, and update
5356 	     its actual output section too.  */
5357 	  i->already_assigned = o;
5358 	  i->output_section = o;
5359 	}
5360     }
5361 
5362   return dot;
5363 }
5364 
5365 struct check_sec
5366 {
5367   asection *sec;
5368   bfd_boolean warned;
5369 };
5370 
5371 static int
sort_sections_by_lma(const void * arg1,const void * arg2)5372 sort_sections_by_lma (const void *arg1, const void *arg2)
5373 {
5374   const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5375   const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5376 
5377   if (sec1->lma < sec2->lma)
5378     return -1;
5379   else if (sec1->lma > sec2->lma)
5380     return 1;
5381   else if (sec1->id < sec2->id)
5382     return -1;
5383   else if (sec1->id > sec2->id)
5384     return 1;
5385 
5386   return 0;
5387 }
5388 
5389 static int
sort_sections_by_vma(const void * arg1,const void * arg2)5390 sort_sections_by_vma (const void *arg1, const void *arg2)
5391 {
5392   const asection *sec1 = ((const struct check_sec *) arg1)->sec;
5393   const asection *sec2 = ((const struct check_sec *) arg2)->sec;
5394 
5395   if (sec1->vma < sec2->vma)
5396     return -1;
5397   else if (sec1->vma > sec2->vma)
5398     return 1;
5399   else if (sec1->id < sec2->id)
5400     return -1;
5401   else if (sec1->id > sec2->id)
5402     return 1;
5403 
5404   return 0;
5405 }
5406 
5407 #define IS_TBSS(s) \
5408   ((s->flags & (SEC_LOAD | SEC_THREAD_LOCAL)) == SEC_THREAD_LOCAL)
5409 
5410 #define IGNORE_SECTION(s) \
5411   ((s->flags & SEC_ALLOC) == 0 || IS_TBSS (s))
5412 
5413 /* Check to see if any allocated sections overlap with other allocated
5414    sections.  This can happen if a linker script specifies the output
5415    section addresses of the two sections.  Also check whether any memory
5416    region has overflowed.  */
5417 
5418 static void
lang_check_section_addresses(void)5419 lang_check_section_addresses (void)
5420 {
5421   asection *s, *p;
5422   struct check_sec *sections;
5423   size_t i, count;
5424   bfd_vma addr_mask;
5425   bfd_vma s_start;
5426   bfd_vma s_end;
5427   bfd_vma p_start = 0;
5428   bfd_vma p_end = 0;
5429   lang_memory_region_type *m;
5430   bfd_boolean overlays;
5431 
5432   /* Detect address space overflow on allocated sections.  */
5433   addr_mask = ((bfd_vma) 1 <<
5434 	       (bfd_arch_bits_per_address (link_info.output_bfd) - 1)) - 1;
5435   addr_mask = (addr_mask << 1) + 1;
5436   for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5437     if ((s->flags & SEC_ALLOC) != 0)
5438       {
5439 	s_end = (s->vma + s->size) & addr_mask;
5440 	if (s_end != 0 && s_end < (s->vma & addr_mask))
5441 	  einfo (_("%X%P: section %s VMA wraps around address space\n"),
5442 		 s->name);
5443 	else
5444 	  {
5445 	    s_end = (s->lma + s->size) & addr_mask;
5446 	    if (s_end != 0 && s_end < (s->lma & addr_mask))
5447 	      einfo (_("%X%P: section %s LMA wraps around address space\n"),
5448 		     s->name);
5449 	  }
5450       }
5451 
5452   if (bfd_count_sections (link_info.output_bfd) <= 1)
5453     return;
5454 
5455   count = bfd_count_sections (link_info.output_bfd);
5456   sections = XNEWVEC (struct check_sec, count);
5457 
5458   /* Scan all sections in the output list.  */
5459   count = 0;
5460   for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
5461     {
5462       if (IGNORE_SECTION (s)
5463 	  || s->size == 0)
5464 	continue;
5465 
5466       sections[count].sec = s;
5467       sections[count].warned = FALSE;
5468       count++;
5469     }
5470 
5471   if (count <= 1)
5472     {
5473       free (sections);
5474       return;
5475     }
5476 
5477   qsort (sections, count, sizeof (*sections), sort_sections_by_lma);
5478 
5479   /* First check section LMAs.  There should be no overlap of LMAs on
5480      loadable sections, even with overlays.  */
5481   for (p = NULL, i = 0; i < count; i++)
5482     {
5483       s = sections[i].sec;
5484       init_opb (s);
5485       if ((s->flags & SEC_LOAD) != 0)
5486 	{
5487 	  s_start = s->lma;
5488 	  s_end = s_start + TO_ADDR (s->size) - 1;
5489 
5490 	  /* Look for an overlap.  We have sorted sections by lma, so
5491 	     we know that s_start >= p_start.  Besides the obvious
5492 	     case of overlap when the current section starts before
5493 	     the previous one ends, we also must have overlap if the
5494 	     previous section wraps around the address space.  */
5495 	  if (p != NULL
5496 	      && (s_start <= p_end
5497 		  || p_end < p_start))
5498 	    {
5499 	      einfo (_("%X%P: section %s LMA [%V,%V]"
5500 		       " overlaps section %s LMA [%V,%V]\n"),
5501 		     s->name, s_start, s_end, p->name, p_start, p_end);
5502 	      sections[i].warned = TRUE;
5503 	    }
5504 	  p = s;
5505 	  p_start = s_start;
5506 	  p_end = s_end;
5507 	}
5508     }
5509 
5510   /* If any non-zero size allocated section (excluding tbss) starts at
5511      exactly the same VMA as another such section, then we have
5512      overlays.  Overlays generated by the OVERLAY keyword will have
5513      this property.  It is possible to intentionally generate overlays
5514      that fail this test, but it would be unusual.  */
5515   qsort (sections, count, sizeof (*sections), sort_sections_by_vma);
5516   overlays = FALSE;
5517   p_start = sections[0].sec->vma;
5518   for (i = 1; i < count; i++)
5519     {
5520       s_start = sections[i].sec->vma;
5521       if (p_start == s_start)
5522 	{
5523 	  overlays = TRUE;
5524 	  break;
5525 	}
5526       p_start = s_start;
5527     }
5528 
5529   /* Now check section VMAs if no overlays were detected.  */
5530   if (!overlays)
5531     {
5532       for (p = NULL, i = 0; i < count; i++)
5533 	{
5534 	  s = sections[i].sec;
5535 	  init_opb (s);
5536 	  s_start = s->vma;
5537 	  s_end = s_start + TO_ADDR (s->size) - 1;
5538 
5539 	  if (p != NULL
5540 	      && !sections[i].warned
5541 	      && (s_start <= p_end
5542 		  || p_end < p_start))
5543 	    einfo (_("%X%P: section %s VMA [%V,%V]"
5544 		     " overlaps section %s VMA [%V,%V]\n"),
5545 		   s->name, s_start, s_end, p->name, p_start, p_end);
5546 	  p = s;
5547 	  p_start = s_start;
5548 	  p_end = s_end;
5549 	}
5550     }
5551 
5552   free (sections);
5553 
5554   /* If any memory region has overflowed, report by how much.
5555      We do not issue this diagnostic for regions that had sections
5556      explicitly placed outside their bounds; os_region_check's
5557      diagnostics are adequate for that case.
5558 
5559      FIXME: It is conceivable that m->current - (m->origin + m->length)
5560      might overflow a 32-bit integer.  There is, alas, no way to print
5561      a bfd_vma quantity in decimal.  */
5562   for (m = lang_memory_region_list; m; m = m->next)
5563     if (m->had_full_message)
5564       {
5565 	unsigned long over = m->current - (m->origin + m->length);
5566 	einfo (ngettext ("%X%P: region `%s' overflowed by %lu byte\n",
5567 			 "%X%P: region `%s' overflowed by %lu bytes\n",
5568 			 over),
5569 	       m->name_list.name, over);
5570       }
5571 }
5572 
5573 /* Make sure the new address is within the region.  We explicitly permit the
5574    current address to be at the exact end of the region when the address is
5575    non-zero, in case the region is at the end of addressable memory and the
5576    calculation wraps around.  */
5577 
5578 static void
os_region_check(lang_output_section_statement_type * os,lang_memory_region_type * region,etree_type * tree,bfd_vma rbase)5579 os_region_check (lang_output_section_statement_type *os,
5580 		 lang_memory_region_type *region,
5581 		 etree_type *tree,
5582 		 bfd_vma rbase)
5583 {
5584   if ((region->current < region->origin
5585        || (region->current - region->origin > region->length))
5586       && ((region->current != region->origin + region->length)
5587 	  || rbase == 0))
5588     {
5589       if (tree != NULL)
5590 	{
5591 	  einfo (_("%X%P: address 0x%v of %pB section `%s'"
5592 		   " is not within region `%s'\n"),
5593 		 region->current,
5594 		 os->bfd_section->owner,
5595 		 os->bfd_section->name,
5596 		 region->name_list.name);
5597 	}
5598       else if (!region->had_full_message)
5599 	{
5600 	  region->had_full_message = TRUE;
5601 
5602 	  einfo (_("%X%P: %pB section `%s' will not fit in region `%s'\n"),
5603 		 os->bfd_section->owner,
5604 		 os->bfd_section->name,
5605 		 region->name_list.name);
5606 	}
5607     }
5608 }
5609 
5610 static void
ldlang_check_relro_region(lang_statement_union_type * s,seg_align_type * seg)5611 ldlang_check_relro_region (lang_statement_union_type *s,
5612 			   seg_align_type *seg)
5613 {
5614   if (seg->relro == exp_seg_relro_start)
5615     {
5616       if (!seg->relro_start_stat)
5617 	seg->relro_start_stat = s;
5618       else
5619 	{
5620 	  ASSERT (seg->relro_start_stat == s);
5621 	}
5622     }
5623   else if (seg->relro == exp_seg_relro_end)
5624     {
5625       if (!seg->relro_end_stat)
5626 	seg->relro_end_stat = s;
5627       else
5628 	{
5629 	  ASSERT (seg->relro_end_stat == s);
5630 	}
5631     }
5632 }
5633 
5634 /* Set the sizes for all the output sections.  */
5635 
5636 static bfd_vma
lang_size_sections_1(lang_statement_union_type ** prev,lang_output_section_statement_type * output_section_statement,fill_type * fill,bfd_vma dot,bfd_boolean * relax,bfd_boolean check_regions)5637 lang_size_sections_1
5638   (lang_statement_union_type **prev,
5639    lang_output_section_statement_type *output_section_statement,
5640    fill_type *fill,
5641    bfd_vma dot,
5642    bfd_boolean *relax,
5643    bfd_boolean check_regions)
5644 {
5645   lang_statement_union_type *s;
5646   lang_statement_union_type *prev_s = NULL;
5647   bfd_boolean removed_prev_s = FALSE;
5648 
5649   /* Size up the sections from their constituent parts.  */
5650   for (s = *prev; s != NULL; prev_s = s, s = s->header.next)
5651     {
5652       bfd_boolean removed=FALSE;
5653 
5654       switch (s->header.type)
5655 	{
5656 	case lang_output_section_statement_enum:
5657 	  {
5658 	    bfd_vma newdot, after, dotdelta;
5659 	    lang_output_section_statement_type *os;
5660 	    lang_memory_region_type *r;
5661 	    int section_alignment = 0;
5662 
5663 	    os = &s->output_section_statement;
5664 	    init_opb (os->bfd_section);
5665 	    if (os->constraint == -1)
5666 	      break;
5667 
5668 	    /* FIXME: We shouldn't need to zero section vmas for ld -r
5669 	       here, in lang_insert_orphan, or in the default linker scripts.
5670 	       This is covering for coff backend linker bugs.  See PR6945.  */
5671 	    if (os->addr_tree == NULL
5672 		&& bfd_link_relocatable (&link_info)
5673 		&& (bfd_get_flavour (link_info.output_bfd)
5674 		    == bfd_target_coff_flavour))
5675 	      os->addr_tree = exp_intop (0);
5676 	    if (os->addr_tree != NULL)
5677 	      {
5678 		os->processed_vma = FALSE;
5679 		exp_fold_tree (os->addr_tree, bfd_abs_section_ptr, &dot);
5680 
5681 		if (expld.result.valid_p)
5682 		  {
5683 		    dot = expld.result.value;
5684 		    if (expld.result.section != NULL)
5685 		      dot += expld.result.section->vma;
5686 		  }
5687 		else if (expld.phase != lang_mark_phase_enum)
5688 		  einfo (_("%F%P:%pS: non constant or forward reference"
5689 			   " address expression for section %s\n"),
5690 			 os->addr_tree, os->name);
5691 	      }
5692 
5693 	    if (os->bfd_section == NULL)
5694 	      /* This section was removed or never actually created.  */
5695 	      break;
5696 
5697 	    /* If this is a COFF shared library section, use the size and
5698 	       address from the input section.  FIXME: This is COFF
5699 	       specific; it would be cleaner if there were some other way
5700 	       to do this, but nothing simple comes to mind.  */
5701 	    if (((bfd_get_flavour (link_info.output_bfd)
5702 		  == bfd_target_ecoff_flavour)
5703 		 || (bfd_get_flavour (link_info.output_bfd)
5704 		     == bfd_target_coff_flavour))
5705 		&& (os->bfd_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
5706 	      {
5707 		asection *input;
5708 
5709 		if (os->children.head == NULL
5710 		    || os->children.head->header.next != NULL
5711 		    || (os->children.head->header.type
5712 			!= lang_input_section_enum))
5713 		  einfo (_("%X%P: internal error on COFF shared library"
5714 			   " section %s\n"), os->name);
5715 
5716 		input = os->children.head->input_section.section;
5717 		bfd_set_section_vma (os->bfd_section,
5718 				     bfd_section_vma (input));
5719 		if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5720 		  os->bfd_section->size = input->size;
5721 		break;
5722 	      }
5723 
5724 	    newdot = dot;
5725 	    dotdelta = 0;
5726 	    if (bfd_is_abs_section (os->bfd_section))
5727 	      {
5728 		/* No matter what happens, an abs section starts at zero.  */
5729 		ASSERT (os->bfd_section->vma == 0);
5730 	      }
5731 	    else
5732 	      {
5733 		if (os->addr_tree == NULL)
5734 		  {
5735 		    /* No address specified for this section, get one
5736 		       from the region specification.  */
5737 		    if (os->region == NULL
5738 			|| ((os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD))
5739 			    && os->region->name_list.name[0] == '*'
5740 			    && strcmp (os->region->name_list.name,
5741 				       DEFAULT_MEMORY_REGION) == 0))
5742 		      {
5743 			os->region = lang_memory_default (os->bfd_section);
5744 		      }
5745 
5746 		    /* If a loadable section is using the default memory
5747 		       region, and some non default memory regions were
5748 		       defined, issue an error message.  */
5749 		    if (!os->ignored
5750 			&& !IGNORE_SECTION (os->bfd_section)
5751 			&& !bfd_link_relocatable (&link_info)
5752 			&& check_regions
5753 			&& strcmp (os->region->name_list.name,
5754 				   DEFAULT_MEMORY_REGION) == 0
5755 			&& lang_memory_region_list != NULL
5756 			&& (strcmp (lang_memory_region_list->name_list.name,
5757 				    DEFAULT_MEMORY_REGION) != 0
5758 			    || lang_memory_region_list->next != NULL)
5759 			&& lang_sizing_iteration == 1)
5760 		      {
5761 			/* By default this is an error rather than just a
5762 			   warning because if we allocate the section to the
5763 			   default memory region we can end up creating an
5764 			   excessively large binary, or even seg faulting when
5765 			   attempting to perform a negative seek.  See
5766 			   sources.redhat.com/ml/binutils/2003-04/msg00423.html
5767 			   for an example of this.  This behaviour can be
5768 			   overridden by the using the --no-check-sections
5769 			   switch.  */
5770 			if (command_line.check_section_addresses)
5771 			  einfo (_("%F%P: error: no memory region specified"
5772 				   " for loadable section `%s'\n"),
5773 				 bfd_section_name (os->bfd_section));
5774 			else
5775 			  einfo (_("%P: warning: no memory region specified"
5776 				   " for loadable section `%s'\n"),
5777 				 bfd_section_name (os->bfd_section));
5778 		      }
5779 
5780 		    newdot = os->region->current;
5781 		    section_alignment = os->bfd_section->alignment_power;
5782 		  }
5783 		else
5784 		  section_alignment = exp_get_power (os->section_alignment,
5785 						     "section alignment");
5786 
5787 		/* Align to what the section needs.  */
5788 		if (section_alignment > 0)
5789 		  {
5790 		    bfd_vma savedot = newdot;
5791 		    bfd_vma diff = 0;
5792 
5793 		    newdot = align_power (newdot, section_alignment);
5794 		    dotdelta = newdot - savedot;
5795 
5796 		    if (lang_sizing_iteration == 1)
5797 		      diff = dotdelta;
5798 		    else if (lang_sizing_iteration > 1)
5799 		      {
5800 			/* Only report adjustments that would change
5801 			   alignment from what we have already reported.  */
5802 			diff = newdot - os->bfd_section->vma;
5803 			if (!(diff & (((bfd_vma) 1 << section_alignment) - 1)))
5804 			  diff = 0;
5805 		      }
5806 		    if (diff != 0
5807 			&& (config.warn_section_align
5808 			    || os->addr_tree != NULL))
5809 		      einfo (_("%P: warning: "
5810 			       "start of section %s changed by %ld\n"),
5811 			     os->name, (long) diff);
5812 		  }
5813 
5814 		bfd_set_section_vma (os->bfd_section, newdot);
5815 
5816 		os->bfd_section->output_offset = 0;
5817 	      }
5818 
5819 	    lang_size_sections_1 (&os->children.head, os,
5820 				  os->fill, newdot, relax, check_regions);
5821 
5822 	    os->processed_vma = TRUE;
5823 
5824 	    if (bfd_is_abs_section (os->bfd_section) || os->ignored)
5825 	      /* Except for some special linker created sections,
5826 		 no output section should change from zero size
5827 		 after strip_excluded_output_sections.  A non-zero
5828 		 size on an ignored section indicates that some
5829 		 input section was not sized early enough.  */
5830 	      ASSERT (os->bfd_section->size == 0);
5831 	    else
5832 	      {
5833 		dot = os->bfd_section->vma;
5834 
5835 		/* Put the section within the requested block size, or
5836 		   align at the block boundary.  */
5837 		after = ((dot
5838 			  + TO_ADDR (os->bfd_section->size)
5839 			  + os->block_value - 1)
5840 			 & - (bfd_vma) os->block_value);
5841 
5842 		if (!(os->bfd_section->flags & SEC_FIXED_SIZE))
5843 		  os->bfd_section->size = TO_SIZE (after
5844 						   - os->bfd_section->vma);
5845 	      }
5846 
5847 	    /* Set section lma.  */
5848 	    r = os->region;
5849 	    if (r == NULL)
5850 	      r = lang_memory_region_lookup (DEFAULT_MEMORY_REGION, FALSE);
5851 
5852 	    if (os->load_base)
5853 	      {
5854 		bfd_vma lma = exp_get_abs_int (os->load_base, 0, "load base");
5855 		os->bfd_section->lma = lma;
5856 	      }
5857 	    else if (os->lma_region != NULL)
5858 	      {
5859 		bfd_vma lma = os->lma_region->current;
5860 
5861 		if (os->align_lma_with_input)
5862 		  lma += dotdelta;
5863 		else
5864 		  {
5865 		    /* When LMA_REGION is the same as REGION, align the LMA
5866 		       as we did for the VMA, possibly including alignment
5867 		       from the bfd section.  If a different region, then
5868 		       only align according to the value in the output
5869 		       statement.  */
5870 		    if (os->lma_region != os->region)
5871 		      section_alignment = exp_get_power (os->section_alignment,
5872 							 "section alignment");
5873 		    if (section_alignment > 0)
5874 		      lma = align_power (lma, section_alignment);
5875 		  }
5876 		os->bfd_section->lma = lma;
5877 	      }
5878 	    else if (r->last_os != NULL
5879 		     && (os->bfd_section->flags & SEC_ALLOC) != 0)
5880 	      {
5881 		bfd_vma lma;
5882 		asection *last;
5883 
5884 		last = r->last_os->output_section_statement.bfd_section;
5885 
5886 		/* A backwards move of dot should be accompanied by
5887 		   an explicit assignment to the section LMA (ie.
5888 		   os->load_base set) because backwards moves can
5889 		   create overlapping LMAs.  */
5890 		if (dot < last->vma
5891 		    && os->bfd_section->size != 0
5892 		    && dot + TO_ADDR (os->bfd_section->size) <= last->vma)
5893 		  {
5894 		    /* If dot moved backwards then leave lma equal to
5895 		       vma.  This is the old default lma, which might
5896 		       just happen to work when the backwards move is
5897 		       sufficiently large.  Nag if this changes anything,
5898 		       so people can fix their linker scripts.  */
5899 
5900 		    if (last->vma != last->lma)
5901 		      einfo (_("%P: warning: dot moved backwards "
5902 			       "before `%s'\n"), os->name);
5903 		  }
5904 		else
5905 		  {
5906 		    /* If this is an overlay, set the current lma to that
5907 		       at the end of the previous section.  */
5908 		    if (os->sectype == overlay_section)
5909 		      lma = last->lma + TO_ADDR (last->size);
5910 
5911 		    /* Otherwise, keep the same lma to vma relationship
5912 		       as the previous section.  */
5913 		    else
5914 		      lma = os->bfd_section->vma + last->lma - last->vma;
5915 
5916 		    if (section_alignment > 0)
5917 		      lma = align_power (lma, section_alignment);
5918 		    os->bfd_section->lma = lma;
5919 		  }
5920 	      }
5921 	    os->processed_lma = TRUE;
5922 
5923 	    /* Keep track of normal sections using the default
5924 	       lma region.  We use this to set the lma for
5925 	       following sections.  Overlays or other linker
5926 	       script assignment to lma might mean that the
5927 	       default lma == vma is incorrect.
5928 	       To avoid warnings about dot moving backwards when using
5929 	       -Ttext, don't start tracking sections until we find one
5930 	       of non-zero size or with lma set differently to vma.
5931 	       Do this tracking before we short-cut the loop so that we
5932 	       track changes for the case where the section size is zero,
5933 	       but the lma is set differently to the vma.  This is
5934 	       important, if an orphan section is placed after an
5935 	       otherwise empty output section that has an explicit lma
5936 	       set, we want that lma reflected in the orphans lma.  */
5937 	    if (((!IGNORE_SECTION (os->bfd_section)
5938 		  && (os->bfd_section->size != 0
5939 		      || (r->last_os == NULL
5940 			  && os->bfd_section->vma != os->bfd_section->lma)
5941 		      || (r->last_os != NULL
5942 			  && dot >= (r->last_os->output_section_statement
5943 				     .bfd_section->vma))))
5944 		 || os->sectype == first_overlay_section)
5945 		&& os->lma_region == NULL
5946 		&& !bfd_link_relocatable (&link_info))
5947 	      r->last_os = s;
5948 
5949 	    if (bfd_is_abs_section (os->bfd_section) || os->ignored)
5950 	      break;
5951 
5952 	    /* .tbss sections effectively have zero size.  */
5953 	    if (!IS_TBSS (os->bfd_section)
5954 		|| bfd_link_relocatable (&link_info))
5955 	      dotdelta = TO_ADDR (os->bfd_section->size);
5956 	    else
5957 	      dotdelta = 0;
5958 	    dot += dotdelta;
5959 
5960 	    if (os->update_dot_tree != 0)
5961 	      exp_fold_tree (os->update_dot_tree, bfd_abs_section_ptr, &dot);
5962 
5963 	    /* Update dot in the region ?
5964 	       We only do this if the section is going to be allocated,
5965 	       since unallocated sections do not contribute to the region's
5966 	       overall size in memory.  */
5967 	    if (os->region != NULL
5968 		&& (os->bfd_section->flags & (SEC_ALLOC | SEC_LOAD)))
5969 	      {
5970 		os->region->current = dot;
5971 
5972 		if (check_regions)
5973 		  /* Make sure the new address is within the region.  */
5974 		  os_region_check (os, os->region, os->addr_tree,
5975 				   os->bfd_section->vma);
5976 
5977 		if (os->lma_region != NULL && os->lma_region != os->region
5978 		    && ((os->bfd_section->flags & SEC_LOAD)
5979 			|| os->align_lma_with_input))
5980 		  {
5981 		    os->lma_region->current = os->bfd_section->lma + dotdelta;
5982 
5983 		    if (check_regions)
5984 		      os_region_check (os, os->lma_region, NULL,
5985 				       os->bfd_section->lma);
5986 		  }
5987 	      }
5988 	  }
5989 	  break;
5990 
5991 	case lang_constructors_statement_enum:
5992 	  dot = lang_size_sections_1 (&constructor_list.head,
5993 				      output_section_statement,
5994 				      fill, dot, relax, check_regions);
5995 	  break;
5996 
5997 	case lang_data_statement_enum:
5998 	  {
5999 	    unsigned int size = 0;
6000 
6001 	    s->data_statement.output_offset =
6002 	      dot - output_section_statement->bfd_section->vma;
6003 	    s->data_statement.output_section =
6004 	      output_section_statement->bfd_section;
6005 
6006 	    /* We might refer to provided symbols in the expression, and
6007 	       need to mark them as needed.  */
6008 	    exp_fold_tree (s->data_statement.exp, bfd_abs_section_ptr, &dot);
6009 
6010 	    switch (s->data_statement.type)
6011 	      {
6012 	      default:
6013 		abort ();
6014 	      case QUAD:
6015 	      case SQUAD:
6016 		size = QUAD_SIZE;
6017 		break;
6018 	      case LONG:
6019 		size = LONG_SIZE;
6020 		break;
6021 	      case SHORT:
6022 		size = SHORT_SIZE;
6023 		break;
6024 	      case BYTE:
6025 		size = BYTE_SIZE;
6026 		break;
6027 	      }
6028 	    if (size < TO_SIZE ((unsigned) 1))
6029 	      size = TO_SIZE ((unsigned) 1);
6030 	    dot += TO_ADDR (size);
6031 	    if (!(output_section_statement->bfd_section->flags
6032 		  & SEC_FIXED_SIZE))
6033 	      output_section_statement->bfd_section->size
6034 		= TO_SIZE (dot - output_section_statement->bfd_section->vma);
6035 
6036 	  }
6037 	  break;
6038 
6039 	case lang_reloc_statement_enum:
6040 	  {
6041 	    int size;
6042 
6043 	    s->reloc_statement.output_offset =
6044 	      dot - output_section_statement->bfd_section->vma;
6045 	    s->reloc_statement.output_section =
6046 	      output_section_statement->bfd_section;
6047 	    size = bfd_get_reloc_size (s->reloc_statement.howto);
6048 	    dot += TO_ADDR (size);
6049 	    if (!(output_section_statement->bfd_section->flags
6050 		  & SEC_FIXED_SIZE))
6051 	      output_section_statement->bfd_section->size
6052 		= TO_SIZE (dot - output_section_statement->bfd_section->vma);
6053 	  }
6054 	  break;
6055 
6056 	case lang_wild_statement_enum:
6057 	  dot = lang_size_sections_1 (&s->wild_statement.children.head,
6058 				      output_section_statement,
6059 				      fill, dot, relax, check_regions);
6060 	  break;
6061 
6062 	case lang_object_symbols_statement_enum:
6063 	  link_info.create_object_symbols_section
6064 	    = output_section_statement->bfd_section;
6065 	  output_section_statement->bfd_section->flags |= SEC_KEEP;
6066 	  break;
6067 
6068 	case lang_output_statement_enum:
6069 	case lang_target_statement_enum:
6070 	  break;
6071 
6072 	case lang_input_section_enum:
6073 	  {
6074 	    asection *i;
6075 
6076 	    i = s->input_section.section;
6077 	    if (relax)
6078 	      {
6079 		bfd_boolean again;
6080 
6081 		if (!bfd_relax_section (i->owner, i, &link_info, &again))
6082 		  einfo (_("%F%P: can't relax section: %E\n"));
6083 		if (again)
6084 		  *relax = TRUE;
6085 	      }
6086 	    dot = size_input_section (prev, output_section_statement,
6087 				      fill, &removed, dot);
6088 	  }
6089 	  break;
6090 
6091 	case lang_input_statement_enum:
6092 	  break;
6093 
6094 	case lang_fill_statement_enum:
6095 	  s->fill_statement.output_section =
6096 	    output_section_statement->bfd_section;
6097 
6098 	  fill = s->fill_statement.fill;
6099 	  break;
6100 
6101 	case lang_assignment_statement_enum:
6102 	  {
6103 	    bfd_vma newdot = dot;
6104 	    etree_type *tree = s->assignment_statement.exp;
6105 
6106 	    expld.dataseg.relro = exp_seg_relro_none;
6107 
6108 	    exp_fold_tree (tree,
6109 			   output_section_statement->bfd_section,
6110 			   &newdot);
6111 
6112 	    ldlang_check_relro_region (s, &expld.dataseg);
6113 
6114 	    expld.dataseg.relro = exp_seg_relro_none;
6115 
6116 	    /* This symbol may be relative to this section.  */
6117 	    if ((tree->type.node_class == etree_provided
6118 		 || tree->type.node_class == etree_assign)
6119 		&& (tree->assign.dst [0] != '.'
6120 		    || tree->assign.dst [1] != '\0'))
6121 	      output_section_statement->update_dot = 1;
6122 
6123 	    if (!output_section_statement->ignored)
6124 	      {
6125 		if (output_section_statement == abs_output_section)
6126 		  {
6127 		    /* If we don't have an output section, then just adjust
6128 		       the default memory address.  */
6129 		    lang_memory_region_lookup (DEFAULT_MEMORY_REGION,
6130 					       FALSE)->current = newdot;
6131 		  }
6132 		else if (newdot != dot)
6133 		  {
6134 		    /* Insert a pad after this statement.  We can't
6135 		       put the pad before when relaxing, in case the
6136 		       assignment references dot.  */
6137 		    insert_pad (&s->header.next, fill, TO_SIZE (newdot - dot),
6138 				output_section_statement->bfd_section, dot);
6139 
6140 		    /* Don't neuter the pad below when relaxing.  */
6141 		    s = s->header.next;
6142 
6143 		    /* If dot is advanced, this implies that the section
6144 		       should have space allocated to it, unless the
6145 		       user has explicitly stated that the section
6146 		       should not be allocated.  */
6147 		    if (output_section_statement->sectype != noalloc_section
6148 			&& (output_section_statement->sectype != noload_section
6149 			    || (bfd_get_flavour (link_info.output_bfd)
6150 				== bfd_target_elf_flavour)))
6151 		      output_section_statement->bfd_section->flags |= SEC_ALLOC;
6152 		  }
6153 		dot = newdot;
6154 	      }
6155 	  }
6156 	  break;
6157 
6158 	case lang_padding_statement_enum:
6159 	  /* If this is the first time lang_size_sections is called,
6160 	     we won't have any padding statements.  If this is the
6161 	     second or later passes when relaxing, we should allow
6162 	     padding to shrink.  If padding is needed on this pass, it
6163 	     will be added back in.  */
6164 	  s->padding_statement.size = 0;
6165 
6166 	  /* Make sure output_offset is valid.  If relaxation shrinks
6167 	     the section and this pad isn't needed, it's possible to
6168 	     have output_offset larger than the final size of the
6169 	     section.  bfd_set_section_contents will complain even for
6170 	     a pad size of zero.  */
6171 	  s->padding_statement.output_offset
6172 	    = dot - output_section_statement->bfd_section->vma;
6173 	  break;
6174 
6175 	case lang_group_statement_enum:
6176 	  dot = lang_size_sections_1 (&s->group_statement.children.head,
6177 				      output_section_statement,
6178 				      fill, dot, relax, check_regions);
6179 	  break;
6180 
6181 	case lang_insert_statement_enum:
6182 	  break;
6183 
6184 	  /* We can only get here when relaxing is turned on.  */
6185 	case lang_address_statement_enum:
6186 	  break;
6187 
6188 	default:
6189 	  FAIL ();
6190 	  break;
6191 	}
6192 
6193       /* If an input section doesn't fit in the current output
6194 	 section, remove it from the list.  Handle the case where we
6195 	 have to remove an input_section statement here: there is a
6196 	 special case to remove the first element of the list.  */
6197       if (link_info.non_contiguous_regions && removed)
6198 	{
6199 	  /* If we removed the first element during the previous
6200 	     iteration, override the loop assignment of prev_s.  */
6201 	  if (removed_prev_s)
6202 	      prev_s = NULL;
6203 
6204 	  if (prev_s)
6205 	    {
6206 	      /* If there was a real previous input section, just skip
6207 		 the current one.  */
6208 	      prev_s->header.next=s->header.next;
6209 	      s = prev_s;
6210 	      removed_prev_s = FALSE;
6211 	    }
6212 	  else
6213 	    {
6214 	      /* Remove the first input section of the list.  */
6215 	      *prev = s->header.next;
6216 	      removed_prev_s = TRUE;
6217 	    }
6218 
6219 	  /* Move to next element, unless we removed the head of the
6220 	     list.  */
6221 	  if (!removed_prev_s)
6222 	    prev = &s->header.next;
6223 	}
6224       else
6225 	{
6226 	  prev = &s->header.next;
6227 	  removed_prev_s = FALSE;
6228 	}
6229     }
6230   return dot;
6231 }
6232 
6233 /* Callback routine that is used in _bfd_elf_map_sections_to_segments.
6234    The BFD library has set NEW_SEGMENT to TRUE iff it thinks that
6235    CURRENT_SECTION and PREVIOUS_SECTION ought to be placed into different
6236    segments.  We are allowed an opportunity to override this decision.  */
6237 
6238 bfd_boolean
ldlang_override_segment_assignment(struct bfd_link_info * info ATTRIBUTE_UNUSED,bfd * abfd ATTRIBUTE_UNUSED,asection * current_section,asection * previous_section,bfd_boolean new_segment)6239 ldlang_override_segment_assignment (struct bfd_link_info *info ATTRIBUTE_UNUSED,
6240 				    bfd *abfd ATTRIBUTE_UNUSED,
6241 				    asection *current_section,
6242 				    asection *previous_section,
6243 				    bfd_boolean new_segment)
6244 {
6245   lang_output_section_statement_type *cur;
6246   lang_output_section_statement_type *prev;
6247 
6248   /* The checks below are only necessary when the BFD library has decided
6249      that the two sections ought to be placed into the same segment.  */
6250   if (new_segment)
6251     return TRUE;
6252 
6253   /* Paranoia checks.  */
6254   if (current_section == NULL || previous_section == NULL)
6255     return new_segment;
6256 
6257   /* If this flag is set, the target never wants code and non-code
6258      sections comingled in the same segment.  */
6259   if (config.separate_code
6260       && ((current_section->flags ^ previous_section->flags) & SEC_CODE))
6261     return TRUE;
6262 
6263   /* Find the memory regions associated with the two sections.
6264      We call lang_output_section_find() here rather than scanning the list
6265      of output sections looking for a matching section pointer because if
6266      we have a large number of sections then a hash lookup is faster.  */
6267   cur  = lang_output_section_find (current_section->name);
6268   prev = lang_output_section_find (previous_section->name);
6269 
6270   /* More paranoia.  */
6271   if (cur == NULL || prev == NULL)
6272     return new_segment;
6273 
6274   /* If the regions are different then force the sections to live in
6275      different segments.  See the email thread starting at the following
6276      URL for the reasons why this is necessary:
6277      http://sourceware.org/ml/binutils/2007-02/msg00216.html  */
6278   return cur->region != prev->region;
6279 }
6280 
6281 void
one_lang_size_sections_pass(bfd_boolean * relax,bfd_boolean check_regions)6282 one_lang_size_sections_pass (bfd_boolean *relax, bfd_boolean check_regions)
6283 {
6284   lang_statement_iteration++;
6285   if (expld.phase != lang_mark_phase_enum)
6286     lang_sizing_iteration++;
6287   lang_size_sections_1 (&statement_list.head, abs_output_section,
6288 			0, 0, relax, check_regions);
6289 }
6290 
6291 static bfd_boolean
lang_size_segment(seg_align_type * seg)6292 lang_size_segment (seg_align_type *seg)
6293 {
6294   /* If XXX_SEGMENT_ALIGN XXX_SEGMENT_END pair was seen, check whether
6295      a page could be saved in the data segment.  */
6296   bfd_vma first, last;
6297 
6298   first = -seg->base & (seg->pagesize - 1);
6299   last = seg->end & (seg->pagesize - 1);
6300   if (first && last
6301       && ((seg->base & ~(seg->pagesize - 1))
6302 	  != (seg->end & ~(seg->pagesize - 1)))
6303       && first + last <= seg->pagesize)
6304     {
6305       seg->phase = exp_seg_adjust;
6306       return TRUE;
6307     }
6308 
6309   seg->phase = exp_seg_done;
6310   return FALSE;
6311 }
6312 
6313 static bfd_vma
lang_size_relro_segment_1(seg_align_type * seg)6314 lang_size_relro_segment_1 (seg_align_type *seg)
6315 {
6316   bfd_vma relro_end, desired_end;
6317   asection *sec;
6318 
6319   /* Compute the expected PT_GNU_RELRO/PT_LOAD segment end.  */
6320   relro_end = ((seg->relro_end + seg->pagesize - 1)
6321 	       & ~(seg->pagesize - 1));
6322 
6323   /* Adjust by the offset arg of XXX_SEGMENT_RELRO_END.  */
6324   desired_end = relro_end - seg->relro_offset;
6325 
6326   /* For sections in the relro segment..  */
6327   for (sec = link_info.output_bfd->section_last; sec; sec = sec->prev)
6328     if ((sec->flags & SEC_ALLOC) != 0
6329 	&& sec->vma >= seg->base
6330 	&& sec->vma < seg->relro_end - seg->relro_offset)
6331       {
6332 	/* Where do we want to put this section so that it ends as
6333 	   desired?  */
6334 	bfd_vma start, end, bump;
6335 
6336 	end = start = sec->vma;
6337 	if (!IS_TBSS (sec))
6338 	  end += TO_ADDR (sec->size);
6339 	bump = desired_end - end;
6340 	/* We'd like to increase START by BUMP, but we must heed
6341 	   alignment so the increase might be less than optimum.  */
6342 	start += bump;
6343 	start &= ~(((bfd_vma) 1 << sec->alignment_power) - 1);
6344 	/* This is now the desired end for the previous section.  */
6345 	desired_end = start;
6346       }
6347 
6348   seg->phase = exp_seg_relro_adjust;
6349   ASSERT (desired_end >= seg->base);
6350   seg->base = desired_end;
6351   return relro_end;
6352 }
6353 
6354 static bfd_boolean
lang_size_relro_segment(bfd_boolean * relax,bfd_boolean check_regions)6355 lang_size_relro_segment (bfd_boolean *relax, bfd_boolean check_regions)
6356 {
6357   bfd_boolean do_reset = FALSE;
6358   bfd_boolean do_data_relro;
6359   bfd_vma data_initial_base, data_relro_end;
6360 
6361   if (link_info.relro && expld.dataseg.relro_end)
6362     {
6363       do_data_relro = TRUE;
6364       data_initial_base = expld.dataseg.base;
6365       data_relro_end = lang_size_relro_segment_1 (&expld.dataseg);
6366     }
6367   else
6368     {
6369       do_data_relro = FALSE;
6370       data_initial_base = data_relro_end = 0;
6371     }
6372 
6373   if (do_data_relro)
6374     {
6375       lang_reset_memory_regions ();
6376       one_lang_size_sections_pass (relax, check_regions);
6377 
6378       /* Assignments to dot, or to output section address in a user
6379 	 script have increased padding over the original.  Revert.  */
6380       if (do_data_relro && expld.dataseg.relro_end > data_relro_end)
6381 	{
6382 	  expld.dataseg.base = data_initial_base;;
6383 	  do_reset = TRUE;
6384 	}
6385     }
6386 
6387   if (!do_data_relro && lang_size_segment (&expld.dataseg))
6388     do_reset = TRUE;
6389 
6390   return do_reset;
6391 }
6392 
6393 void
lang_size_sections(bfd_boolean * relax,bfd_boolean check_regions)6394 lang_size_sections (bfd_boolean *relax, bfd_boolean check_regions)
6395 {
6396   expld.phase = lang_allocating_phase_enum;
6397   expld.dataseg.phase = exp_seg_none;
6398 
6399   one_lang_size_sections_pass (relax, check_regions);
6400 
6401   if (expld.dataseg.phase != exp_seg_end_seen)
6402     expld.dataseg.phase = exp_seg_done;
6403 
6404   if (expld.dataseg.phase == exp_seg_end_seen)
6405     {
6406       bfd_boolean do_reset
6407 	= lang_size_relro_segment (relax, check_regions);
6408 
6409       if (do_reset)
6410 	{
6411 	  lang_reset_memory_regions ();
6412 	  one_lang_size_sections_pass (relax, check_regions);
6413 	}
6414 
6415       if (link_info.relro && expld.dataseg.relro_end)
6416 	{
6417 	  link_info.relro_start = expld.dataseg.base;
6418 	  link_info.relro_end = expld.dataseg.relro_end;
6419 	}
6420     }
6421 }
6422 
6423 static lang_output_section_statement_type *current_section;
6424 static lang_assignment_statement_type *current_assign;
6425 static bfd_boolean prefer_next_section;
6426 
6427 /* Worker function for lang_do_assignments.  Recursiveness goes here.  */
6428 
6429 static bfd_vma
lang_do_assignments_1(lang_statement_union_type * s,lang_output_section_statement_type * current_os,fill_type * fill,bfd_vma dot,bfd_boolean * found_end)6430 lang_do_assignments_1 (lang_statement_union_type *s,
6431 		       lang_output_section_statement_type *current_os,
6432 		       fill_type *fill,
6433 		       bfd_vma dot,
6434 		       bfd_boolean *found_end)
6435 {
6436   for (; s != NULL; s = s->header.next)
6437     {
6438       switch (s->header.type)
6439 	{
6440 	case lang_constructors_statement_enum:
6441 	  dot = lang_do_assignments_1 (constructor_list.head,
6442 				       current_os, fill, dot, found_end);
6443 	  break;
6444 
6445 	case lang_output_section_statement_enum:
6446 	  {
6447 	    lang_output_section_statement_type *os;
6448 	    bfd_vma newdot;
6449 
6450 	    os = &(s->output_section_statement);
6451 	    os->after_end = *found_end;
6452 	    init_opb (os->bfd_section);
6453 	    if (os->bfd_section != NULL && !os->ignored)
6454 	      {
6455 		if ((os->bfd_section->flags & SEC_ALLOC) != 0)
6456 		  {
6457 		    current_section = os;
6458 		    prefer_next_section = FALSE;
6459 		  }
6460 		dot = os->bfd_section->vma;
6461 	      }
6462 	    newdot = lang_do_assignments_1 (os->children.head,
6463 					    os, os->fill, dot, found_end);
6464 	    if (!os->ignored)
6465 	      {
6466 		if (os->bfd_section != NULL)
6467 		  {
6468 		    /* .tbss sections effectively have zero size.  */
6469 		    if (!IS_TBSS (os->bfd_section)
6470 			|| bfd_link_relocatable (&link_info))
6471 		      dot += TO_ADDR (os->bfd_section->size);
6472 
6473 		    if (os->update_dot_tree != NULL)
6474 		      exp_fold_tree (os->update_dot_tree,
6475 				     bfd_abs_section_ptr, &dot);
6476 		  }
6477 		else
6478 		  dot = newdot;
6479 	      }
6480 	  }
6481 	  break;
6482 
6483 	case lang_wild_statement_enum:
6484 
6485 	  dot = lang_do_assignments_1 (s->wild_statement.children.head,
6486 				       current_os, fill, dot, found_end);
6487 	  break;
6488 
6489 	case lang_object_symbols_statement_enum:
6490 	case lang_output_statement_enum:
6491 	case lang_target_statement_enum:
6492 	  break;
6493 
6494 	case lang_data_statement_enum:
6495 	  exp_fold_tree (s->data_statement.exp, bfd_abs_section_ptr, &dot);
6496 	  if (expld.result.valid_p)
6497 	    {
6498 	      s->data_statement.value = expld.result.value;
6499 	      if (expld.result.section != NULL)
6500 		s->data_statement.value += expld.result.section->vma;
6501 	    }
6502 	  else if (expld.phase == lang_final_phase_enum)
6503 	    einfo (_("%F%P: invalid data statement\n"));
6504 	  {
6505 	    unsigned int size;
6506 	    switch (s->data_statement.type)
6507 	      {
6508 	      default:
6509 		abort ();
6510 	      case QUAD:
6511 	      case SQUAD:
6512 		size = QUAD_SIZE;
6513 		break;
6514 	      case LONG:
6515 		size = LONG_SIZE;
6516 		break;
6517 	      case SHORT:
6518 		size = SHORT_SIZE;
6519 		break;
6520 	      case BYTE:
6521 		size = BYTE_SIZE;
6522 		break;
6523 	      }
6524 	    if (size < TO_SIZE ((unsigned) 1))
6525 	      size = TO_SIZE ((unsigned) 1);
6526 	    dot += TO_ADDR (size);
6527 	  }
6528 	  break;
6529 
6530 	case lang_reloc_statement_enum:
6531 	  exp_fold_tree (s->reloc_statement.addend_exp,
6532 			 bfd_abs_section_ptr, &dot);
6533 	  if (expld.result.valid_p)
6534 	    s->reloc_statement.addend_value = expld.result.value;
6535 	  else if (expld.phase == lang_final_phase_enum)
6536 	    einfo (_("%F%P: invalid reloc statement\n"));
6537 	  dot += TO_ADDR (bfd_get_reloc_size (s->reloc_statement.howto));
6538 	  break;
6539 
6540 	case lang_input_section_enum:
6541 	  {
6542 	    asection *in = s->input_section.section;
6543 
6544 	    if ((in->flags & SEC_EXCLUDE) == 0)
6545 	      dot += TO_ADDR (in->size);
6546 	  }
6547 	  break;
6548 
6549 	case lang_input_statement_enum:
6550 	  break;
6551 
6552 	case lang_fill_statement_enum:
6553 	  fill = s->fill_statement.fill;
6554 	  break;
6555 
6556 	case lang_assignment_statement_enum:
6557 	  current_assign = &s->assignment_statement;
6558 	  if (current_assign->exp->type.node_class != etree_assert)
6559 	    {
6560 	      const char *p = current_assign->exp->assign.dst;
6561 
6562 	      if (current_os == abs_output_section && p[0] == '.' && p[1] == 0)
6563 		prefer_next_section = TRUE;
6564 
6565 	      while (*p == '_')
6566 		++p;
6567 	      if (strcmp (p, "end") == 0)
6568 		*found_end = TRUE;
6569 	    }
6570 	  exp_fold_tree (s->assignment_statement.exp,
6571 			 (current_os->bfd_section != NULL
6572 			  ? current_os->bfd_section : bfd_und_section_ptr),
6573 			 &dot);
6574 	  break;
6575 
6576 	case lang_padding_statement_enum:
6577 	  dot += TO_ADDR (s->padding_statement.size);
6578 	  break;
6579 
6580 	case lang_group_statement_enum:
6581 	  dot = lang_do_assignments_1 (s->group_statement.children.head,
6582 				       current_os, fill, dot, found_end);
6583 	  break;
6584 
6585 	case lang_insert_statement_enum:
6586 	  break;
6587 
6588 	case lang_address_statement_enum:
6589 	  break;
6590 
6591 	default:
6592 	  FAIL ();
6593 	  break;
6594 	}
6595     }
6596   return dot;
6597 }
6598 
6599 void
lang_do_assignments(lang_phase_type phase)6600 lang_do_assignments (lang_phase_type phase)
6601 {
6602   bfd_boolean found_end = FALSE;
6603 
6604   current_section = NULL;
6605   prefer_next_section = FALSE;
6606   expld.phase = phase;
6607   lang_statement_iteration++;
6608   lang_do_assignments_1 (statement_list.head,
6609 			 abs_output_section, NULL, 0, &found_end);
6610 }
6611 
6612 /* For an assignment statement outside of an output section statement,
6613    choose the best of neighbouring output sections to use for values
6614    of "dot".  */
6615 
6616 asection *
section_for_dot(void)6617 section_for_dot (void)
6618 {
6619   asection *s;
6620 
6621   /* Assignments belong to the previous output section, unless there
6622      has been an assignment to "dot", in which case following
6623      assignments belong to the next output section.  (The assumption
6624      is that an assignment to "dot" is setting up the address for the
6625      next output section.)  Except that past the assignment to "_end"
6626      we always associate with the previous section.  This exception is
6627      for targets like SH that define an alloc .stack or other
6628      weirdness after non-alloc sections.  */
6629   if (current_section == NULL || prefer_next_section)
6630     {
6631       lang_statement_union_type *stmt;
6632       lang_output_section_statement_type *os;
6633 
6634       for (stmt = (lang_statement_union_type *) current_assign;
6635 	   stmt != NULL;
6636 	   stmt = stmt->header.next)
6637 	if (stmt->header.type == lang_output_section_statement_enum)
6638 	  break;
6639 
6640       os = &stmt->output_section_statement;
6641       while (os != NULL
6642 	     && !os->after_end
6643 	     && (os->bfd_section == NULL
6644 		 || (os->bfd_section->flags & SEC_EXCLUDE) != 0
6645 		 || bfd_section_removed_from_list (link_info.output_bfd,
6646 						   os->bfd_section)))
6647 	os = os->next;
6648 
6649       if (current_section == NULL || os == NULL || !os->after_end)
6650 	{
6651 	  if (os != NULL)
6652 	    s = os->bfd_section;
6653 	  else
6654 	    s = link_info.output_bfd->section_last;
6655 	  while (s != NULL
6656 		 && ((s->flags & SEC_ALLOC) == 0
6657 		     || (s->flags & SEC_THREAD_LOCAL) != 0))
6658 	    s = s->prev;
6659 	  if (s != NULL)
6660 	    return s;
6661 
6662 	  return bfd_abs_section_ptr;
6663 	}
6664     }
6665 
6666   s = current_section->bfd_section;
6667 
6668   /* The section may have been stripped.  */
6669   while (s != NULL
6670 	 && ((s->flags & SEC_EXCLUDE) != 0
6671 	     || (s->flags & SEC_ALLOC) == 0
6672 	     || (s->flags & SEC_THREAD_LOCAL) != 0
6673 	     || bfd_section_removed_from_list (link_info.output_bfd, s)))
6674     s = s->prev;
6675   if (s == NULL)
6676     s = link_info.output_bfd->sections;
6677   while (s != NULL
6678 	 && ((s->flags & SEC_ALLOC) == 0
6679 	     || (s->flags & SEC_THREAD_LOCAL) != 0))
6680     s = s->next;
6681   if (s != NULL)
6682     return s;
6683 
6684   return bfd_abs_section_ptr;
6685 }
6686 
6687 /* Array of __start/__stop/.startof./.sizeof/ symbols.  */
6688 
6689 static struct bfd_link_hash_entry **start_stop_syms;
6690 static size_t start_stop_count = 0;
6691 static size_t start_stop_alloc = 0;
6692 
6693 /* Give start/stop SYMBOL for SEC a preliminary definition, and add it
6694    to start_stop_syms.  */
6695 
6696 static void
lang_define_start_stop(const char * symbol,asection * sec)6697 lang_define_start_stop (const char *symbol, asection *sec)
6698 {
6699   struct bfd_link_hash_entry *h;
6700 
6701   h = bfd_define_start_stop (link_info.output_bfd, &link_info, symbol, sec);
6702   if (h != NULL)
6703     {
6704       if (start_stop_count == start_stop_alloc)
6705 	{
6706 	  start_stop_alloc = 2 * start_stop_alloc + 10;
6707 	  start_stop_syms
6708 	    = xrealloc (start_stop_syms,
6709 			start_stop_alloc * sizeof (*start_stop_syms));
6710 	}
6711       start_stop_syms[start_stop_count++] = h;
6712     }
6713 }
6714 
6715 /* Check for input sections whose names match references to
6716    __start_SECNAME or __stop_SECNAME symbols.  Give the symbols
6717    preliminary definitions.  */
6718 
6719 static void
lang_init_start_stop(void)6720 lang_init_start_stop (void)
6721 {
6722   bfd *abfd;
6723   asection *s;
6724   char leading_char = bfd_get_symbol_leading_char (link_info.output_bfd);
6725 
6726   for (abfd = link_info.input_bfds; abfd != NULL; abfd = abfd->link.next)
6727     for (s = abfd->sections; s != NULL; s = s->next)
6728       {
6729 	const char *ps;
6730 	const char *secname = s->name;
6731 
6732 	for (ps = secname; *ps != '\0'; ps++)
6733 	  if (!ISALNUM ((unsigned char) *ps) && *ps != '_')
6734 	    break;
6735 	if (*ps == '\0')
6736 	  {
6737 	    char *symbol = (char *) xmalloc (10 + strlen (secname));
6738 
6739 	    symbol[0] = leading_char;
6740 	    sprintf (symbol + (leading_char != 0), "__start_%s", secname);
6741 	    lang_define_start_stop (symbol, s);
6742 
6743 	    symbol[1] = leading_char;
6744 	    memcpy (symbol + 1 + (leading_char != 0), "__stop", 6);
6745 	    lang_define_start_stop (symbol + 1, s);
6746 
6747 	    free (symbol);
6748 	  }
6749       }
6750 }
6751 
6752 /* Iterate over start_stop_syms.  */
6753 
6754 static void
foreach_start_stop(void (* func)(struct bfd_link_hash_entry *))6755 foreach_start_stop (void (*func) (struct bfd_link_hash_entry *))
6756 {
6757   size_t i;
6758 
6759   for (i = 0; i < start_stop_count; ++i)
6760     func (start_stop_syms[i]);
6761 }
6762 
6763 /* __start and __stop symbols are only supposed to be defined by the
6764    linker for orphan sections, but we now extend that to sections that
6765    map to an output section of the same name.  The symbols were
6766    defined early for --gc-sections, before we mapped input to output
6767    sections, so undo those that don't satisfy this rule.  */
6768 
6769 static void
undef_start_stop(struct bfd_link_hash_entry * h)6770 undef_start_stop (struct bfd_link_hash_entry *h)
6771 {
6772   if (h->ldscript_def)
6773     return;
6774 
6775   if (h->u.def.section->output_section == NULL
6776       || h->u.def.section->output_section->owner != link_info.output_bfd
6777       || strcmp (h->u.def.section->name,
6778 		 h->u.def.section->output_section->name) != 0)
6779     {
6780       asection *sec = bfd_get_section_by_name (link_info.output_bfd,
6781 					       h->u.def.section->name);
6782       if (sec != NULL)
6783 	{
6784 	  /* When there are more than one input sections with the same
6785 	     section name, SECNAME, linker picks the first one to define
6786 	     __start_SECNAME and __stop_SECNAME symbols.  When the first
6787 	     input section is removed by comdat group, we need to check
6788 	     if there is still an output section with section name
6789 	     SECNAME.  */
6790 	  asection *i;
6791 	  for (i = sec->map_head.s; i != NULL; i = i->map_head.s)
6792 	    if (strcmp (h->u.def.section->name, i->name) == 0)
6793 	      {
6794 		h->u.def.section = i;
6795 		return;
6796 	      }
6797 	}
6798       h->type = bfd_link_hash_undefined;
6799       h->u.undef.abfd = NULL;
6800     }
6801 }
6802 
6803 static void
lang_undef_start_stop(void)6804 lang_undef_start_stop (void)
6805 {
6806   foreach_start_stop (undef_start_stop);
6807 }
6808 
6809 /* Check for output sections whose names match references to
6810    .startof.SECNAME or .sizeof.SECNAME symbols.  Give the symbols
6811    preliminary definitions.  */
6812 
6813 static void
lang_init_startof_sizeof(void)6814 lang_init_startof_sizeof (void)
6815 {
6816   asection *s;
6817 
6818   for (s = link_info.output_bfd->sections; s != NULL; s = s->next)
6819     {
6820       const char *secname = s->name;
6821       char *symbol = (char *) xmalloc (10 + strlen (secname));
6822 
6823       sprintf (symbol, ".startof.%s", secname);
6824       lang_define_start_stop (symbol, s);
6825 
6826       memcpy (symbol + 1, ".size", 5);
6827       lang_define_start_stop (symbol + 1, s);
6828       free (symbol);
6829     }
6830 }
6831 
6832 /* Set .startof., .sizeof., __start and __stop symbols final values.  */
6833 
6834 static void
set_start_stop(struct bfd_link_hash_entry * h)6835 set_start_stop (struct bfd_link_hash_entry *h)
6836 {
6837   if (h->ldscript_def
6838       || h->type != bfd_link_hash_defined)
6839     return;
6840 
6841   if (h->root.string[0] == '.')
6842     {
6843       /* .startof. or .sizeof. symbol.
6844 	 .startof. already has final value.  */
6845       if (h->root.string[2] == 'i')
6846 	{
6847 	  /* .sizeof.  */
6848 	  h->u.def.value = TO_ADDR (h->u.def.section->size);
6849 	  h->u.def.section = bfd_abs_section_ptr;
6850 	}
6851     }
6852   else
6853     {
6854       /* __start or __stop symbol.  */
6855       int has_lead = bfd_get_symbol_leading_char (link_info.output_bfd) != 0;
6856 
6857       h->u.def.section = h->u.def.section->output_section;
6858       if (h->root.string[4 + has_lead] == 'o')
6859 	{
6860 	  /* __stop_ */
6861 	  h->u.def.value = TO_ADDR (h->u.def.section->size);
6862 	}
6863     }
6864 }
6865 
6866 static void
lang_finalize_start_stop(void)6867 lang_finalize_start_stop (void)
6868 {
6869   foreach_start_stop (set_start_stop);
6870 }
6871 
6872 static void
lang_end(void)6873 lang_end (void)
6874 {
6875   struct bfd_link_hash_entry *h;
6876   bfd_boolean warn;
6877 
6878   if ((bfd_link_relocatable (&link_info) && !link_info.gc_sections)
6879       || bfd_link_dll (&link_info))
6880     warn = entry_from_cmdline;
6881   else
6882     warn = TRUE;
6883 
6884   /* Force the user to specify a root when generating a relocatable with
6885      --gc-sections, unless --gc-keep-exported was also given.  */
6886   if (bfd_link_relocatable (&link_info)
6887       && link_info.gc_sections
6888       && !link_info.gc_keep_exported)
6889     {
6890       struct bfd_sym_chain *sym;
6891 
6892       for (sym = link_info.gc_sym_list; sym != NULL; sym = sym->next)
6893 	{
6894 	  h = bfd_link_hash_lookup (link_info.hash, sym->name,
6895 				    FALSE, FALSE, FALSE);
6896 	  if (h != NULL
6897 	      && (h->type == bfd_link_hash_defined
6898 		  || h->type == bfd_link_hash_defweak)
6899 	      && !bfd_is_const_section (h->u.def.section))
6900 	    break;
6901 	}
6902       if (!sym)
6903 	einfo (_("%F%P: --gc-sections requires a defined symbol root "
6904 		 "specified by -e or -u\n"));
6905     }
6906 
6907   if (entry_symbol.name == NULL)
6908     {
6909       /* No entry has been specified.  Look for the default entry, but
6910 	 don't warn if we don't find it.  */
6911       entry_symbol.name = entry_symbol_default;
6912       warn = FALSE;
6913     }
6914 
6915   h = bfd_link_hash_lookup (link_info.hash, entry_symbol.name,
6916 			    FALSE, FALSE, TRUE);
6917   if (h != NULL
6918       && (h->type == bfd_link_hash_defined
6919 	  || h->type == bfd_link_hash_defweak)
6920       && h->u.def.section->output_section != NULL)
6921     {
6922       bfd_vma val;
6923 
6924       val = (h->u.def.value
6925 	     + bfd_section_vma (h->u.def.section->output_section)
6926 	     + h->u.def.section->output_offset);
6927       if (!bfd_set_start_address (link_info.output_bfd, val))
6928 	einfo (_("%F%P: %s: can't set start address\n"), entry_symbol.name);
6929     }
6930   else
6931     {
6932       bfd_vma val;
6933       const char *send;
6934 
6935       /* We couldn't find the entry symbol.  Try parsing it as a
6936 	 number.  */
6937       val = bfd_scan_vma (entry_symbol.name, &send, 0);
6938       if (*send == '\0')
6939 	{
6940 	  if (!bfd_set_start_address (link_info.output_bfd, val))
6941 	    einfo (_("%F%P: can't set start address\n"));
6942 	}
6943       else
6944 	{
6945 	  asection *ts;
6946 
6947 	  /* Can't find the entry symbol, and it's not a number.  Use
6948 	     the first address in the text section.  */
6949 	  ts = bfd_get_section_by_name (link_info.output_bfd, entry_section);
6950 	  if (ts != NULL)
6951 	    {
6952 	      if (warn)
6953 		einfo (_("%P: warning: cannot find entry symbol %s;"
6954 			 " defaulting to %V\n"),
6955 		       entry_symbol.name,
6956 		       bfd_section_vma (ts));
6957 	      if (!bfd_set_start_address (link_info.output_bfd,
6958 					  bfd_section_vma (ts)))
6959 		einfo (_("%F%P: can't set start address\n"));
6960 	    }
6961 	  else
6962 	    {
6963 	      if (warn)
6964 		einfo (_("%P: warning: cannot find entry symbol %s;"
6965 			 " not setting start address\n"),
6966 		       entry_symbol.name);
6967 	    }
6968 	}
6969     }
6970 }
6971 
6972 /* This is a small function used when we want to ignore errors from
6973    BFD.  */
6974 
6975 static void
ignore_bfd_errors(const char * fmt ATTRIBUTE_UNUSED,va_list ap ATTRIBUTE_UNUSED)6976 ignore_bfd_errors (const char *fmt ATTRIBUTE_UNUSED,
6977 		   va_list ap ATTRIBUTE_UNUSED)
6978 {
6979   /* Don't do anything.  */
6980 }
6981 
6982 /* Check that the architecture of all the input files is compatible
6983    with the output file.  Also call the backend to let it do any
6984    other checking that is needed.  */
6985 
6986 static void
lang_check(void)6987 lang_check (void)
6988 {
6989   lang_input_statement_type *file;
6990   bfd *input_bfd;
6991   const bfd_arch_info_type *compatible;
6992 
6993   for (file = (void *) file_chain.head;
6994        file != NULL;
6995        file = file->next)
6996     {
6997 #if BFD_SUPPORTS_PLUGINS
6998       /* Don't check format of files claimed by plugin.  */
6999       if (file->flags.claimed)
7000 	continue;
7001 #endif /* BFD_SUPPORTS_PLUGINS */
7002       input_bfd = file->the_bfd;
7003       compatible
7004 	= bfd_arch_get_compatible (input_bfd, link_info.output_bfd,
7005 				   command_line.accept_unknown_input_arch);
7006 
7007       /* In general it is not possible to perform a relocatable
7008 	 link between differing object formats when the input
7009 	 file has relocations, because the relocations in the
7010 	 input format may not have equivalent representations in
7011 	 the output format (and besides BFD does not translate
7012 	 relocs for other link purposes than a final link).  */
7013       if (!file->flags.just_syms
7014 	  && (bfd_link_relocatable (&link_info)
7015 	      || link_info.emitrelocations)
7016 	  && (compatible == NULL
7017 	      || (bfd_get_flavour (input_bfd)
7018 		  != bfd_get_flavour (link_info.output_bfd)))
7019 	  && (bfd_get_file_flags (input_bfd) & HAS_RELOC) != 0)
7020 	{
7021 	  einfo (_("%F%P: relocatable linking with relocations from"
7022 		   " format %s (%pB) to format %s (%pB) is not supported\n"),
7023 		 bfd_get_target (input_bfd), input_bfd,
7024 		 bfd_get_target (link_info.output_bfd), link_info.output_bfd);
7025 	  /* einfo with %F exits.  */
7026 	}
7027 
7028       if (compatible == NULL)
7029 	{
7030 	  if (command_line.warn_mismatch)
7031 	    einfo (_("%X%P: %s architecture of input file `%pB'"
7032 		     " is incompatible with %s output\n"),
7033 		   bfd_printable_name (input_bfd), input_bfd,
7034 		   bfd_printable_name (link_info.output_bfd));
7035 	}
7036 
7037       /* If the input bfd has no contents, it shouldn't set the
7038 	 private data of the output bfd.  */
7039       else if (!file->flags.just_syms
7040 	       && ((input_bfd->flags & DYNAMIC) != 0
7041 		   || bfd_count_sections (input_bfd) != 0))
7042 	{
7043 	  bfd_error_handler_type pfn = NULL;
7044 
7045 	  /* If we aren't supposed to warn about mismatched input
7046 	     files, temporarily set the BFD error handler to a
7047 	     function which will do nothing.  We still want to call
7048 	     bfd_merge_private_bfd_data, since it may set up
7049 	     information which is needed in the output file.  */
7050 	  if (!command_line.warn_mismatch)
7051 	    pfn = bfd_set_error_handler (ignore_bfd_errors);
7052 	  if (!bfd_merge_private_bfd_data (input_bfd, &link_info))
7053 	    {
7054 	      if (command_line.warn_mismatch)
7055 		einfo (_("%X%P: failed to merge target specific data"
7056 			 " of file %pB\n"), input_bfd);
7057 	    }
7058 	  if (!command_line.warn_mismatch)
7059 	    bfd_set_error_handler (pfn);
7060 	}
7061     }
7062 }
7063 
7064 /* Look through all the global common symbols and attach them to the
7065    correct section.  The -sort-common command line switch may be used
7066    to roughly sort the entries by alignment.  */
7067 
7068 static void
lang_common(void)7069 lang_common (void)
7070 {
7071   if (link_info.inhibit_common_definition)
7072     return;
7073   if (bfd_link_relocatable (&link_info)
7074       && !command_line.force_common_definition)
7075     return;
7076 
7077   if (!config.sort_common)
7078     bfd_link_hash_traverse (link_info.hash, lang_one_common, NULL);
7079   else
7080     {
7081       unsigned int power;
7082 
7083       if (config.sort_common == sort_descending)
7084 	{
7085 	  for (power = 4; power > 0; power--)
7086 	    bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7087 
7088 	  power = 0;
7089 	  bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7090 	}
7091       else
7092 	{
7093 	  for (power = 0; power <= 4; power++)
7094 	    bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7095 
7096 	  power = (unsigned int) -1;
7097 	  bfd_link_hash_traverse (link_info.hash, lang_one_common, &power);
7098 	}
7099     }
7100 }
7101 
7102 /* Place one common symbol in the correct section.  */
7103 
7104 static bfd_boolean
lang_one_common(struct bfd_link_hash_entry * h,void * info)7105 lang_one_common (struct bfd_link_hash_entry *h, void *info)
7106 {
7107   unsigned int power_of_two;
7108   bfd_vma size;
7109   asection *section;
7110 
7111   if (h->type != bfd_link_hash_common)
7112     return TRUE;
7113 
7114   size = h->u.c.size;
7115   power_of_two = h->u.c.p->alignment_power;
7116 
7117   if (config.sort_common == sort_descending
7118       && power_of_two < *(unsigned int *) info)
7119     return TRUE;
7120   else if (config.sort_common == sort_ascending
7121 	   && power_of_two > *(unsigned int *) info)
7122     return TRUE;
7123 
7124   section = h->u.c.p->section;
7125   if (!bfd_define_common_symbol (link_info.output_bfd, &link_info, h))
7126     einfo (_("%F%P: could not define common symbol `%pT': %E\n"),
7127 	   h->root.string);
7128 
7129   if (config.map_file != NULL)
7130     {
7131       static bfd_boolean header_printed;
7132       int len;
7133       char *name;
7134       char buf[50];
7135 
7136       if (!header_printed)
7137 	{
7138 	  minfo (_("\nAllocating common symbols\n"));
7139 	  minfo (_("Common symbol       size              file\n\n"));
7140 	  header_printed = TRUE;
7141 	}
7142 
7143       name = bfd_demangle (link_info.output_bfd, h->root.string,
7144 			   DMGL_ANSI | DMGL_PARAMS);
7145       if (name == NULL)
7146 	{
7147 	  minfo ("%s", h->root.string);
7148 	  len = strlen (h->root.string);
7149 	}
7150       else
7151 	{
7152 	  minfo ("%s", name);
7153 	  len = strlen (name);
7154 	  free (name);
7155 	}
7156 
7157       if (len >= 19)
7158 	{
7159 	  print_nl ();
7160 	  len = 0;
7161 	}
7162       while (len < 20)
7163 	{
7164 	  print_space ();
7165 	  ++len;
7166 	}
7167 
7168       minfo ("0x");
7169       if (size <= 0xffffffff)
7170 	sprintf (buf, "%lx", (unsigned long) size);
7171       else
7172 	sprintf_vma (buf, size);
7173       minfo ("%s", buf);
7174       len = strlen (buf);
7175 
7176       while (len < 16)
7177 	{
7178 	  print_space ();
7179 	  ++len;
7180 	}
7181 
7182       minfo ("%pB\n", section->owner);
7183     }
7184 
7185   return TRUE;
7186 }
7187 
7188 /* Handle a single orphan section S, placing the orphan into an appropriate
7189    output section.  The effects of the --orphan-handling command line
7190    option are handled here.  */
7191 
7192 static void
ldlang_place_orphan(asection * s)7193 ldlang_place_orphan (asection *s)
7194 {
7195   if (config.orphan_handling == orphan_handling_discard)
7196     {
7197       lang_output_section_statement_type *os;
7198       os = lang_output_section_statement_lookup (DISCARD_SECTION_NAME, 0,
7199 						 TRUE);
7200       if (os->addr_tree == NULL
7201 	  && (bfd_link_relocatable (&link_info)
7202 	      || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7203 	os->addr_tree = exp_intop (0);
7204       lang_add_section (&os->children, s, NULL, os);
7205     }
7206   else
7207     {
7208       lang_output_section_statement_type *os;
7209       const char *name = s->name;
7210       int constraint = 0;
7211 
7212       if (config.orphan_handling == orphan_handling_error)
7213 	einfo (_("%X%P: error: unplaced orphan section `%pA' from `%pB'\n"),
7214 	       s, s->owner);
7215 
7216       if (config.unique_orphan_sections || unique_section_p (s, NULL))
7217 	constraint = SPECIAL;
7218 
7219       os = ldemul_place_orphan (s, name, constraint);
7220       if (os == NULL)
7221 	{
7222 	  os = lang_output_section_statement_lookup (name, constraint, TRUE);
7223 	  if (os->addr_tree == NULL
7224 	      && (bfd_link_relocatable (&link_info)
7225 		  || (s->flags & (SEC_LOAD | SEC_ALLOC)) == 0))
7226 	    os->addr_tree = exp_intop (0);
7227 	  lang_add_section (&os->children, s, NULL, os);
7228 	}
7229 
7230       if (config.orphan_handling == orphan_handling_warn)
7231 	einfo (_("%P: warning: orphan section `%pA' from `%pB' being "
7232 		 "placed in section `%s'\n"),
7233 	       s, s->owner, os->name);
7234     }
7235 }
7236 
7237 /* Run through the input files and ensure that every input section has
7238    somewhere to go.  If one is found without a destination then create
7239    an input request and place it into the statement tree.  */
7240 
7241 static void
lang_place_orphans(void)7242 lang_place_orphans (void)
7243 {
7244   LANG_FOR_EACH_INPUT_STATEMENT (file)
7245     {
7246       asection *s;
7247 
7248       for (s = file->the_bfd->sections; s != NULL; s = s->next)
7249 	{
7250 	  if (s->output_section == NULL)
7251 	    {
7252 	      /* This section of the file is not attached, root
7253 		 around for a sensible place for it to go.  */
7254 
7255 	      if (file->flags.just_syms)
7256 		bfd_link_just_syms (file->the_bfd, s, &link_info);
7257 	      else if (lang_discard_section_p (s))
7258 		s->output_section = bfd_abs_section_ptr;
7259 	      else if (strcmp (s->name, "COMMON") == 0)
7260 		{
7261 		  /* This is a lonely common section which must have
7262 		     come from an archive.  We attach to the section
7263 		     with the wildcard.  */
7264 		  if (!bfd_link_relocatable (&link_info)
7265 		      || command_line.force_common_definition)
7266 		    {
7267 		      if (default_common_section == NULL)
7268 			default_common_section
7269 			  = lang_output_section_statement_lookup (".bss", 0,
7270 								  TRUE);
7271 		      lang_add_section (&default_common_section->children, s,
7272 					NULL, default_common_section);
7273 		    }
7274 		}
7275 	      else
7276 		ldlang_place_orphan (s);
7277 	    }
7278 	}
7279     }
7280 }
7281 
7282 void
lang_set_flags(lang_memory_region_type * ptr,const char * flags,int invert)7283 lang_set_flags (lang_memory_region_type *ptr, const char *flags, int invert)
7284 {
7285   flagword *ptr_flags;
7286 
7287   ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7288 
7289   while (*flags)
7290     {
7291       switch (*flags)
7292 	{
7293 	  /* PR 17900: An exclamation mark in the attributes reverses
7294 	     the sense of any of the attributes that follow.  */
7295 	case '!':
7296 	  invert = !invert;
7297 	  ptr_flags = invert ? &ptr->not_flags : &ptr->flags;
7298 	  break;
7299 
7300 	case 'A': case 'a':
7301 	  *ptr_flags |= SEC_ALLOC;
7302 	  break;
7303 
7304 	case 'R': case 'r':
7305 	  *ptr_flags |= SEC_READONLY;
7306 	  break;
7307 
7308 	case 'W': case 'w':
7309 	  *ptr_flags |= SEC_DATA;
7310 	  break;
7311 
7312 	case 'X': case 'x':
7313 	  *ptr_flags |= SEC_CODE;
7314 	  break;
7315 
7316 	case 'L': case 'l':
7317 	case 'I': case 'i':
7318 	  *ptr_flags |= SEC_LOAD;
7319 	  break;
7320 
7321 	default:
7322 	  einfo (_("%F%P: invalid character %c (%d) in flags\n"),
7323 		 *flags, *flags);
7324 	  break;
7325 	}
7326       flags++;
7327     }
7328 }
7329 
7330 /* Call a function on each real input file.  This function will be
7331    called on an archive, but not on the elements.  */
7332 
7333 void
lang_for_each_input_file(void (* func)(lang_input_statement_type *))7334 lang_for_each_input_file (void (*func) (lang_input_statement_type *))
7335 {
7336   lang_input_statement_type *f;
7337 
7338   for (f = (void *) input_file_chain.head;
7339        f != NULL;
7340        f = f->next_real_file)
7341     if (f->flags.real)
7342       func (f);
7343 }
7344 
7345 /* Call a function on each real file.  The function will be called on
7346    all the elements of an archive which are included in the link, but
7347    will not be called on the archive file itself.  */
7348 
7349 void
lang_for_each_file(void (* func)(lang_input_statement_type *))7350 lang_for_each_file (void (*func) (lang_input_statement_type *))
7351 {
7352   LANG_FOR_EACH_INPUT_STATEMENT (f)
7353     {
7354       if (f->flags.real)
7355 	func (f);
7356     }
7357 }
7358 
7359 void
ldlang_add_file(lang_input_statement_type * entry)7360 ldlang_add_file (lang_input_statement_type *entry)
7361 {
7362   lang_statement_append (&file_chain, entry, &entry->next);
7363 
7364   /* The BFD linker needs to have a list of all input BFDs involved in
7365      a link.  */
7366   ASSERT (link_info.input_bfds_tail != &entry->the_bfd->link.next
7367 	  && entry->the_bfd->link.next == NULL);
7368   ASSERT (entry->the_bfd != link_info.output_bfd);
7369 
7370   *link_info.input_bfds_tail = entry->the_bfd;
7371   link_info.input_bfds_tail = &entry->the_bfd->link.next;
7372   bfd_set_usrdata (entry->the_bfd, entry);
7373   bfd_set_gp_size (entry->the_bfd, g_switch_value);
7374 
7375   /* Look through the sections and check for any which should not be
7376      included in the link.  We need to do this now, so that we can
7377      notice when the backend linker tries to report multiple
7378      definition errors for symbols which are in sections we aren't
7379      going to link.  FIXME: It might be better to entirely ignore
7380      symbols which are defined in sections which are going to be
7381      discarded.  This would require modifying the backend linker for
7382      each backend which might set the SEC_LINK_ONCE flag.  If we do
7383      this, we should probably handle SEC_EXCLUDE in the same way.  */
7384 
7385   bfd_map_over_sections (entry->the_bfd, section_already_linked, entry);
7386 }
7387 
7388 void
lang_add_output(const char * name,int from_script)7389 lang_add_output (const char *name, int from_script)
7390 {
7391   /* Make -o on command line override OUTPUT in script.  */
7392   if (!had_output_filename || !from_script)
7393     {
7394       output_filename = name;
7395       had_output_filename = TRUE;
7396     }
7397 }
7398 
7399 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,int align_with_input)7400 lang_enter_output_section_statement (const char *output_section_statement_name,
7401 				     etree_type *address_exp,
7402 				     enum section_type sectype,
7403 				     etree_type *align,
7404 				     etree_type *subalign,
7405 				     etree_type *ebase,
7406 				     int constraint,
7407 				     int align_with_input)
7408 {
7409   lang_output_section_statement_type *os;
7410 
7411   os = lang_output_section_statement_lookup (output_section_statement_name,
7412 					     constraint, TRUE);
7413   current_section = os;
7414 
7415   if (os->addr_tree == NULL)
7416     {
7417       os->addr_tree = address_exp;
7418     }
7419   os->sectype = sectype;
7420   if (sectype != noload_section)
7421     os->flags = SEC_NO_FLAGS;
7422   else
7423     os->flags = SEC_NEVER_LOAD;
7424   os->block_value = 1;
7425 
7426   /* Make next things chain into subchain of this.  */
7427   push_stat_ptr (&os->children);
7428 
7429   os->align_lma_with_input = align_with_input == ALIGN_WITH_INPUT;
7430   if (os->align_lma_with_input && align != NULL)
7431     einfo (_("%F%P:%pS: error: align with input and explicit align specified\n"),
7432 	   NULL);
7433 
7434   os->subsection_alignment = subalign;
7435   os->section_alignment = align;
7436 
7437   os->load_base = ebase;
7438   return os;
7439 }
7440 
7441 void
lang_final(void)7442 lang_final (void)
7443 {
7444   lang_output_statement_type *new_stmt;
7445 
7446   new_stmt = new_stat (lang_output_statement, stat_ptr);
7447   new_stmt->name = output_filename;
7448 }
7449 
7450 /* Reset the current counters in the regions.  */
7451 
7452 void
lang_reset_memory_regions(void)7453 lang_reset_memory_regions (void)
7454 {
7455   lang_memory_region_type *p = lang_memory_region_list;
7456   asection *o;
7457   lang_output_section_statement_type *os;
7458 
7459   for (p = lang_memory_region_list; p != NULL; p = p->next)
7460     {
7461       p->current = p->origin;
7462       p->last_os = NULL;
7463     }
7464 
7465   for (os = (void *) lang_os_list.head;
7466        os != NULL;
7467        os = os->next)
7468     {
7469       os->processed_vma = FALSE;
7470       os->processed_lma = FALSE;
7471     }
7472 
7473   for (o = link_info.output_bfd->sections; o != NULL; o = o->next)
7474     {
7475       /* Save the last size for possible use by bfd_relax_section.  */
7476       o->rawsize = o->size;
7477       if (!(o->flags & SEC_FIXED_SIZE))
7478 	o->size = 0;
7479     }
7480 }
7481 
7482 /* Worker for lang_gc_sections_1.  */
7483 
7484 static void
gc_section_callback(lang_wild_statement_type * ptr,struct wildcard_list * sec ATTRIBUTE_UNUSED,asection * section,struct flag_info * sflag_info ATTRIBUTE_UNUSED,lang_input_statement_type * file ATTRIBUTE_UNUSED,void * data ATTRIBUTE_UNUSED)7485 gc_section_callback (lang_wild_statement_type *ptr,
7486 		     struct wildcard_list *sec ATTRIBUTE_UNUSED,
7487 		     asection *section,
7488 		     struct flag_info *sflag_info ATTRIBUTE_UNUSED,
7489 		     lang_input_statement_type *file ATTRIBUTE_UNUSED,
7490 		     void *data ATTRIBUTE_UNUSED)
7491 {
7492   /* If the wild pattern was marked KEEP, the member sections
7493      should be as well.  */
7494   if (ptr->keep_sections)
7495     section->flags |= SEC_KEEP;
7496 }
7497 
7498 /* Iterate over sections marking them against GC.  */
7499 
7500 static void
lang_gc_sections_1(lang_statement_union_type * s)7501 lang_gc_sections_1 (lang_statement_union_type *s)
7502 {
7503   for (; s != NULL; s = s->header.next)
7504     {
7505       switch (s->header.type)
7506 	{
7507 	case lang_wild_statement_enum:
7508 	  walk_wild (&s->wild_statement, gc_section_callback, NULL);
7509 	  break;
7510 	case lang_constructors_statement_enum:
7511 	  lang_gc_sections_1 (constructor_list.head);
7512 	  break;
7513 	case lang_output_section_statement_enum:
7514 	  lang_gc_sections_1 (s->output_section_statement.children.head);
7515 	  break;
7516 	case lang_group_statement_enum:
7517 	  lang_gc_sections_1 (s->group_statement.children.head);
7518 	  break;
7519 	default:
7520 	  break;
7521 	}
7522     }
7523 }
7524 
7525 static void
lang_gc_sections(void)7526 lang_gc_sections (void)
7527 {
7528   /* Keep all sections so marked in the link script.  */
7529   lang_gc_sections_1 (statement_list.head);
7530 
7531   /* SEC_EXCLUDE is ignored when doing a relocatable link, except in
7532      the special case of debug info.  (See bfd/stabs.c)
7533      Twiddle the flag here, to simplify later linker code.  */
7534   if (bfd_link_relocatable (&link_info))
7535     {
7536       LANG_FOR_EACH_INPUT_STATEMENT (f)
7537 	{
7538 	  asection *sec;
7539 #if BFD_SUPPORTS_PLUGINS
7540 	  if (f->flags.claimed)
7541 	    continue;
7542 #endif
7543 	  for (sec = f->the_bfd->sections; sec != NULL; sec = sec->next)
7544 	    if ((sec->flags & SEC_DEBUGGING) == 0)
7545 	      sec->flags &= ~SEC_EXCLUDE;
7546 	}
7547     }
7548 
7549   if (link_info.gc_sections)
7550     bfd_gc_sections (link_info.output_bfd, &link_info);
7551 }
7552 
7553 /* Worker for lang_find_relro_sections_1.  */
7554 
7555 static void
find_relro_section_callback(lang_wild_statement_type * ptr ATTRIBUTE_UNUSED,struct wildcard_list * sec ATTRIBUTE_UNUSED,asection * section,struct flag_info * sflag_info ATTRIBUTE_UNUSED,lang_input_statement_type * file ATTRIBUTE_UNUSED,void * data)7556 find_relro_section_callback (lang_wild_statement_type *ptr ATTRIBUTE_UNUSED,
7557 			     struct wildcard_list *sec ATTRIBUTE_UNUSED,
7558 			     asection *section,
7559 			     struct flag_info *sflag_info ATTRIBUTE_UNUSED,
7560 			     lang_input_statement_type *file ATTRIBUTE_UNUSED,
7561 			     void *data)
7562 {
7563   /* Discarded, excluded and ignored sections effectively have zero
7564      size.  */
7565   if (section->output_section != NULL
7566       && section->output_section->owner == link_info.output_bfd
7567       && (section->output_section->flags & SEC_EXCLUDE) == 0
7568       && !IGNORE_SECTION (section)
7569       && section->size != 0)
7570     {
7571       bfd_boolean *has_relro_section = (bfd_boolean *) data;
7572       *has_relro_section = TRUE;
7573     }
7574 }
7575 
7576 /* Iterate over sections for relro sections.  */
7577 
7578 static void
lang_find_relro_sections_1(lang_statement_union_type * s,seg_align_type * seg,bfd_boolean * has_relro_section)7579 lang_find_relro_sections_1 (lang_statement_union_type *s,
7580 			    seg_align_type *seg,
7581 			    bfd_boolean *has_relro_section)
7582 {
7583   if (*has_relro_section)
7584     return;
7585 
7586   for (; s != NULL; s = s->header.next)
7587     {
7588       if (s == seg->relro_end_stat)
7589 	break;
7590 
7591       switch (s->header.type)
7592 	{
7593 	case lang_wild_statement_enum:
7594 	  walk_wild (&s->wild_statement,
7595 		     find_relro_section_callback,
7596 		     has_relro_section);
7597 	  break;
7598 	case lang_constructors_statement_enum:
7599 	  lang_find_relro_sections_1 (constructor_list.head,
7600 				      seg, has_relro_section);
7601 	  break;
7602 	case lang_output_section_statement_enum:
7603 	  lang_find_relro_sections_1 (s->output_section_statement.children.head,
7604 				      seg, has_relro_section);
7605 	  break;
7606 	case lang_group_statement_enum:
7607 	  lang_find_relro_sections_1 (s->group_statement.children.head,
7608 				      seg, has_relro_section);
7609 	  break;
7610 	default:
7611 	  break;
7612 	}
7613     }
7614 }
7615 
7616 static void
lang_find_relro_sections(void)7617 lang_find_relro_sections (void)
7618 {
7619   bfd_boolean has_relro_section = FALSE;
7620 
7621   /* Check all sections in the link script.  */
7622 
7623   lang_find_relro_sections_1 (expld.dataseg.relro_start_stat,
7624 			      &expld.dataseg, &has_relro_section);
7625 
7626   if (!has_relro_section)
7627     link_info.relro = FALSE;
7628 }
7629 
7630 /* Relax all sections until bfd_relax_section gives up.  */
7631 
7632 void
lang_relax_sections(bfd_boolean need_layout)7633 lang_relax_sections (bfd_boolean need_layout)
7634 {
7635   if (RELAXATION_ENABLED)
7636     {
7637       /* We may need more than one relaxation pass.  */
7638       int i = link_info.relax_pass;
7639 
7640       /* The backend can use it to determine the current pass.  */
7641       link_info.relax_pass = 0;
7642 
7643       while (i--)
7644 	{
7645 	  /* Keep relaxing until bfd_relax_section gives up.  */
7646 	  bfd_boolean relax_again;
7647 
7648 	  link_info.relax_trip = -1;
7649 	  do
7650 	    {
7651 	      link_info.relax_trip++;
7652 
7653 	      /* Note: pe-dll.c does something like this also.  If you find
7654 		 you need to change this code, you probably need to change
7655 		 pe-dll.c also.  DJ  */
7656 
7657 	      /* Do all the assignments with our current guesses as to
7658 		 section sizes.  */
7659 	      lang_do_assignments (lang_assigning_phase_enum);
7660 
7661 	      /* We must do this after lang_do_assignments, because it uses
7662 		 size.  */
7663 	      lang_reset_memory_regions ();
7664 
7665 	      /* Perform another relax pass - this time we know where the
7666 		 globals are, so can make a better guess.  */
7667 	      relax_again = FALSE;
7668 	      lang_size_sections (&relax_again, FALSE);
7669 	    }
7670 	  while (relax_again);
7671 
7672 	  link_info.relax_pass++;
7673 	}
7674       need_layout = TRUE;
7675     }
7676 
7677   if (need_layout)
7678     {
7679       /* Final extra sizing to report errors.  */
7680       lang_do_assignments (lang_assigning_phase_enum);
7681       lang_reset_memory_regions ();
7682       lang_size_sections (NULL, TRUE);
7683     }
7684 }
7685 
7686 #if BFD_SUPPORTS_PLUGINS
7687 /* Find the insert point for the plugin's replacement files.  We
7688    place them after the first claimed real object file, or if the
7689    first claimed object is an archive member, after the last real
7690    object file immediately preceding the archive.  In the event
7691    no objects have been claimed at all, we return the first dummy
7692    object file on the list as the insert point; that works, but
7693    the callee must be careful when relinking the file_chain as it
7694    is not actually on that chain, only the statement_list and the
7695    input_file list; in that case, the replacement files must be
7696    inserted at the head of the file_chain.  */
7697 
7698 static lang_input_statement_type *
find_replacements_insert_point(bfd_boolean * before)7699 find_replacements_insert_point (bfd_boolean *before)
7700 {
7701   lang_input_statement_type *claim1, *lastobject;
7702   lastobject = (void *) input_file_chain.head;
7703   for (claim1 = (void *) file_chain.head;
7704        claim1 != NULL;
7705        claim1 = claim1->next)
7706     {
7707       if (claim1->flags.claimed)
7708 	{
7709 	  *before = claim1->flags.claim_archive;
7710 	  return claim1->flags.claim_archive ? lastobject : claim1;
7711 	}
7712       /* Update lastobject if this is a real object file.  */
7713       if (claim1->the_bfd != NULL && claim1->the_bfd->my_archive == NULL)
7714 	lastobject = claim1;
7715     }
7716   /* No files were claimed by the plugin.  Choose the last object
7717      file found on the list (maybe the first, dummy entry) as the
7718      insert point.  */
7719   *before = FALSE;
7720   return lastobject;
7721 }
7722 
7723 /* Find where to insert ADD, an archive element or shared library
7724    added during a rescan.  */
7725 
7726 static lang_input_statement_type **
find_rescan_insertion(lang_input_statement_type * add)7727 find_rescan_insertion (lang_input_statement_type *add)
7728 {
7729   bfd *add_bfd = add->the_bfd;
7730   lang_input_statement_type *f;
7731   lang_input_statement_type *last_loaded = NULL;
7732   lang_input_statement_type *before = NULL;
7733   lang_input_statement_type **iter = NULL;
7734 
7735   if (add_bfd->my_archive != NULL)
7736     add_bfd = add_bfd->my_archive;
7737 
7738   /* First look through the input file chain, to find an object file
7739      before the one we've rescanned.  Normal object files always
7740      appear on both the input file chain and the file chain, so this
7741      lets us get quickly to somewhere near the correct place on the
7742      file chain if it is full of archive elements.  Archives don't
7743      appear on the file chain, but if an element has been extracted
7744      then their input_statement->next points at it.  */
7745   for (f = (void *) input_file_chain.head;
7746        f != NULL;
7747        f = f->next_real_file)
7748     {
7749       if (f->the_bfd == add_bfd)
7750 	{
7751 	  before = last_loaded;
7752 	  if (f->next != NULL)
7753 	    return &f->next->next;
7754 	}
7755       if (f->the_bfd != NULL && f->next != NULL)
7756 	last_loaded = f;
7757     }
7758 
7759   for (iter = before ? &before->next : &file_chain.head->input_statement.next;
7760        *iter != NULL;
7761        iter = &(*iter)->next)
7762     if (!(*iter)->flags.claim_archive
7763 	&& (*iter)->the_bfd->my_archive == NULL)
7764       break;
7765 
7766   return iter;
7767 }
7768 
7769 /* Insert SRCLIST into DESTLIST after given element by chaining
7770    on FIELD as the next-pointer.  (Counterintuitively does not need
7771    a pointer to the actual after-node itself, just its chain field.)  */
7772 
7773 static void
lang_list_insert_after(lang_statement_list_type * destlist,lang_statement_list_type * srclist,lang_statement_union_type ** field)7774 lang_list_insert_after (lang_statement_list_type *destlist,
7775 			lang_statement_list_type *srclist,
7776 			lang_statement_union_type **field)
7777 {
7778   *(srclist->tail) = *field;
7779   *field = srclist->head;
7780   if (destlist->tail == field)
7781     destlist->tail = srclist->tail;
7782 }
7783 
7784 /* Detach new nodes added to DESTLIST since the time ORIGLIST
7785    was taken as a copy of it and leave them in ORIGLIST.  */
7786 
7787 static void
lang_list_remove_tail(lang_statement_list_type * destlist,lang_statement_list_type * origlist)7788 lang_list_remove_tail (lang_statement_list_type *destlist,
7789 		       lang_statement_list_type *origlist)
7790 {
7791   union lang_statement_union **savetail;
7792   /* Check that ORIGLIST really is an earlier state of DESTLIST.  */
7793   ASSERT (origlist->head == destlist->head);
7794   savetail = origlist->tail;
7795   origlist->head = *(savetail);
7796   origlist->tail = destlist->tail;
7797   destlist->tail = savetail;
7798   *savetail = NULL;
7799 }
7800 
7801 static lang_statement_union_type **
find_next_input_statement(lang_statement_union_type ** s)7802 find_next_input_statement (lang_statement_union_type **s)
7803 {
7804   for ( ; *s; s = &(*s)->header.next)
7805     {
7806       lang_statement_union_type **t;
7807       switch ((*s)->header.type)
7808 	{
7809 	case lang_input_statement_enum:
7810 	  return s;
7811 	case lang_wild_statement_enum:
7812 	  t = &(*s)->wild_statement.children.head;
7813 	  break;
7814 	case lang_group_statement_enum:
7815 	  t = &(*s)->group_statement.children.head;
7816 	  break;
7817 	case lang_output_section_statement_enum:
7818 	  t = &(*s)->output_section_statement.children.head;
7819 	  break;
7820 	default:
7821 	  continue;
7822 	}
7823       t = find_next_input_statement (t);
7824       if (*t)
7825 	return t;
7826     }
7827   return s;
7828 }
7829 #endif /* BFD_SUPPORTS_PLUGINS */
7830 
7831 /* Add NAME to the list of garbage collection entry points.  */
7832 
7833 void
lang_add_gc_name(const char * name)7834 lang_add_gc_name (const char *name)
7835 {
7836   struct bfd_sym_chain *sym;
7837 
7838   if (name == NULL)
7839     return;
7840 
7841   sym = stat_alloc (sizeof (*sym));
7842 
7843   sym->next = link_info.gc_sym_list;
7844   sym->name = name;
7845   link_info.gc_sym_list = sym;
7846 }
7847 
7848 /* Check relocations.  */
7849 
7850 static void
lang_check_relocs(void)7851 lang_check_relocs (void)
7852 {
7853   if (link_info.check_relocs_after_open_input)
7854     {
7855       bfd *abfd;
7856 
7857       for (abfd = link_info.input_bfds;
7858 	   abfd != (bfd *) NULL; abfd = abfd->link.next)
7859 	if (!bfd_link_check_relocs (abfd, &link_info))
7860 	  {
7861 	    /* No object output, fail return.  */
7862 	    config.make_executable = FALSE;
7863 	    /* Note: we do not abort the loop, but rather
7864 	       continue the scan in case there are other
7865 	       bad relocations to report.  */
7866 	  }
7867     }
7868 }
7869 
7870 /* Look through all output sections looking for places where we can
7871    propagate forward the lma region.  */
7872 
7873 static void
lang_propagate_lma_regions(void)7874 lang_propagate_lma_regions (void)
7875 {
7876   lang_output_section_statement_type *os;
7877 
7878   for (os = (void *) lang_os_list.head;
7879        os != NULL;
7880        os = os->next)
7881     {
7882       if (os->prev != NULL
7883 	  && os->lma_region == NULL
7884 	  && os->load_base == NULL
7885 	  && os->addr_tree == NULL
7886 	  && os->region == os->prev->region)
7887 	os->lma_region = os->prev->lma_region;
7888     }
7889 }
7890 
7891 void
lang_process(void)7892 lang_process (void)
7893 {
7894   /* Finalize dynamic list.  */
7895   if (link_info.dynamic_list)
7896     lang_finalize_version_expr_head (&link_info.dynamic_list->head);
7897 
7898   current_target = default_target;
7899 
7900   /* Open the output file.  */
7901   lang_for_each_statement (ldlang_open_output);
7902   init_opb (NULL);
7903 
7904   ldemul_create_output_section_statements ();
7905 
7906   /* Add to the hash table all undefineds on the command line.  */
7907   lang_place_undefineds ();
7908 
7909   if (!bfd_section_already_linked_table_init ())
7910     einfo (_("%F%P: can not create hash table: %E\n"));
7911 
7912   /* Create a bfd for each input file.  */
7913   current_target = default_target;
7914   lang_statement_iteration++;
7915   open_input_bfds (statement_list.head, OPEN_BFD_NORMAL);
7916   /* open_input_bfds also handles assignments, so we can give values
7917      to symbolic origin/length now.  */
7918   lang_do_memory_regions ();
7919 
7920 #if BFD_SUPPORTS_PLUGINS
7921   if (link_info.lto_plugin_active)
7922     {
7923       lang_statement_list_type added;
7924       lang_statement_list_type files, inputfiles;
7925 
7926       /* Now all files are read, let the plugin(s) decide if there
7927 	 are any more to be added to the link before we call the
7928 	 emulation's after_open hook.  We create a private list of
7929 	 input statements for this purpose, which we will eventually
7930 	 insert into the global statement list after the first claimed
7931 	 file.  */
7932       added = *stat_ptr;
7933       /* We need to manipulate all three chains in synchrony.  */
7934       files = file_chain;
7935       inputfiles = input_file_chain;
7936       if (plugin_call_all_symbols_read ())
7937 	einfo (_("%F%P: %s: plugin reported error after all symbols read\n"),
7938 	       plugin_error_plugin ());
7939       link_info.lto_all_symbols_read = TRUE;
7940       /* Open any newly added files, updating the file chains.  */
7941       plugin_undefs = link_info.hash->undefs_tail;
7942       open_input_bfds (*added.tail, OPEN_BFD_NORMAL);
7943       if (plugin_undefs == link_info.hash->undefs_tail)
7944 	plugin_undefs = NULL;
7945       /* Restore the global list pointer now they have all been added.  */
7946       lang_list_remove_tail (stat_ptr, &added);
7947       /* And detach the fresh ends of the file lists.  */
7948       lang_list_remove_tail (&file_chain, &files);
7949       lang_list_remove_tail (&input_file_chain, &inputfiles);
7950       /* Were any new files added?  */
7951       if (added.head != NULL)
7952 	{
7953 	  /* If so, we will insert them into the statement list immediately
7954 	     after the first input file that was claimed by the plugin,
7955 	     unless that file was an archive in which case it is inserted
7956 	     immediately before.  */
7957 	  bfd_boolean before;
7958 	  lang_statement_union_type **prev;
7959 	  plugin_insert = find_replacements_insert_point (&before);
7960 	  /* If a plugin adds input files without having claimed any, we
7961 	     don't really have a good idea where to place them.  Just putting
7962 	     them at the start or end of the list is liable to leave them
7963 	     outside the crtbegin...crtend range.  */
7964 	  ASSERT (plugin_insert != NULL);
7965 	  /* Splice the new statement list into the old one.  */
7966 	  prev = &plugin_insert->header.next;
7967 	  if (before)
7968 	    {
7969 	      prev = find_next_input_statement (prev);
7970 	      if (*prev != (void *) plugin_insert->next_real_file)
7971 		{
7972 		  /* We didn't find the expected input statement.
7973 		     Fall back to adding after plugin_insert.  */
7974 		  prev = &plugin_insert->header.next;
7975 		}
7976 	    }
7977 	  lang_list_insert_after (stat_ptr, &added, prev);
7978 	  /* Likewise for the file chains.  */
7979 	  lang_list_insert_after (&input_file_chain, &inputfiles,
7980 				  (void *) &plugin_insert->next_real_file);
7981 	  /* We must be careful when relinking file_chain; we may need to
7982 	     insert the new files at the head of the list if the insert
7983 	     point chosen is the dummy first input file.  */
7984 	  if (plugin_insert->filename)
7985 	    lang_list_insert_after (&file_chain, &files,
7986 				    (void *) &plugin_insert->next);
7987 	  else
7988 	    lang_list_insert_after (&file_chain, &files, &file_chain.head);
7989 
7990 	  /* Rescan archives in case new undefined symbols have appeared.  */
7991 	  files = file_chain;
7992 	  lang_statement_iteration++;
7993 	  open_input_bfds (statement_list.head, OPEN_BFD_RESCAN);
7994 	  lang_list_remove_tail (&file_chain, &files);
7995 	  while (files.head != NULL)
7996 	    {
7997 	      lang_input_statement_type **insert;
7998 	      lang_input_statement_type **iter, *temp;
7999 	      bfd *my_arch;
8000 
8001 	      insert = find_rescan_insertion (&files.head->input_statement);
8002 	      /* All elements from an archive can be added at once.  */
8003 	      iter = &files.head->input_statement.next;
8004 	      my_arch = files.head->input_statement.the_bfd->my_archive;
8005 	      if (my_arch != NULL)
8006 		for (; *iter != NULL; iter = &(*iter)->next)
8007 		  if ((*iter)->the_bfd->my_archive != my_arch)
8008 		    break;
8009 	      temp = *insert;
8010 	      *insert = &files.head->input_statement;
8011 	      files.head = (lang_statement_union_type *) *iter;
8012 	      *iter = temp;
8013 	      if (my_arch != NULL)
8014 		{
8015 		  lang_input_statement_type *parent = bfd_usrdata (my_arch);
8016 		  if (parent != NULL)
8017 		    parent->next = (lang_input_statement_type *)
8018 		      ((char *) iter
8019 		       - offsetof (lang_input_statement_type, next));
8020 		}
8021 	    }
8022 	}
8023     }
8024 #endif /* BFD_SUPPORTS_PLUGINS */
8025 
8026   /* Make sure that nobody has tried to add a symbol to this list
8027      before now.  */
8028   ASSERT (link_info.gc_sym_list == NULL);
8029 
8030   link_info.gc_sym_list = &entry_symbol;
8031 
8032   if (entry_symbol.name == NULL)
8033     {
8034       link_info.gc_sym_list = ldlang_undef_chain_list_head;
8035 
8036       /* entry_symbol is normally initialied by a ENTRY definition in the
8037 	 linker script or the -e command line option.  But if neither of
8038 	 these have been used, the target specific backend may still have
8039 	 provided an entry symbol via a call to lang_default_entry().
8040 	 Unfortunately this value will not be processed until lang_end()
8041 	 is called, long after this function has finished.  So detect this
8042 	 case here and add the target's entry symbol to the list of starting
8043 	 points for garbage collection resolution.  */
8044       lang_add_gc_name (entry_symbol_default);
8045     }
8046 
8047   lang_add_gc_name (link_info.init_function);
8048   lang_add_gc_name (link_info.fini_function);
8049 
8050   ldemul_after_open ();
8051   if (config.map_file != NULL)
8052     lang_print_asneeded ();
8053 
8054   ldlang_open_ctf ();
8055 
8056   bfd_section_already_linked_table_free ();
8057 
8058   /* Make sure that we're not mixing architectures.  We call this
8059      after all the input files have been opened, but before we do any
8060      other processing, so that any operations merge_private_bfd_data
8061      does on the output file will be known during the rest of the
8062      link.  */
8063   lang_check ();
8064 
8065   /* Handle .exports instead of a version script if we're told to do so.  */
8066   if (command_line.version_exports_section)
8067     lang_do_version_exports_section ();
8068 
8069   /* Build all sets based on the information gathered from the input
8070      files.  */
8071   ldctor_build_sets ();
8072 
8073   /* Give initial values for __start and __stop symbols, so that  ELF
8074      gc_sections will keep sections referenced by these symbols.  Must
8075      be done before lang_do_assignments below.  */
8076   if (config.build_constructors)
8077     lang_init_start_stop ();
8078 
8079   /* PR 13683: We must rerun the assignments prior to running garbage
8080      collection in order to make sure that all symbol aliases are resolved.  */
8081   lang_do_assignments (lang_mark_phase_enum);
8082   expld.phase = lang_first_phase_enum;
8083 
8084   /* Size up the common data.  */
8085   lang_common ();
8086 
8087   /* Remove unreferenced sections if asked to.  */
8088   lang_gc_sections ();
8089 
8090   /* Check relocations.  */
8091   lang_check_relocs ();
8092 
8093   ldemul_after_check_relocs ();
8094 
8095   /* Update wild statements.  */
8096   update_wild_statements (statement_list.head);
8097 
8098   /* Run through the contours of the script and attach input sections
8099      to the correct output sections.  */
8100   lang_statement_iteration++;
8101   map_input_to_output_sections (statement_list.head, NULL, NULL);
8102 
8103   /* Start at the statement immediately after the special abs_section
8104      output statement, so that it isn't reordered.  */
8105   process_insert_statements (&lang_os_list.head->header.next);
8106 
8107   ldemul_before_place_orphans ();
8108 
8109   /* Find any sections not attached explicitly and handle them.  */
8110   lang_place_orphans ();
8111 
8112   if (!bfd_link_relocatable (&link_info))
8113     {
8114       asection *found;
8115 
8116       /* Merge SEC_MERGE sections.  This has to be done after GC of
8117 	 sections, so that GCed sections are not merged, but before
8118 	 assigning dynamic symbols, since removing whole input sections
8119 	 is hard then.  */
8120       bfd_merge_sections (link_info.output_bfd, &link_info);
8121 
8122       /* Look for a text section and set the readonly attribute in it.  */
8123       found = bfd_get_section_by_name (link_info.output_bfd, ".text");
8124 
8125       if (found != NULL)
8126 	{
8127 	  if (config.text_read_only)
8128 	    found->flags |= SEC_READONLY;
8129 	  else
8130 	    found->flags &= ~SEC_READONLY;
8131 	}
8132     }
8133 
8134   /* Merge together CTF sections.  After this, only the symtab-dependent
8135      function and data object sections need adjustment.  */
8136   lang_merge_ctf ();
8137 
8138   /* Emit the CTF, iff the emulation doesn't need to do late emission after
8139      examining things laid out late, like the strtab.  */
8140   lang_write_ctf (0);
8141 
8142   /* Copy forward lma regions for output sections in same lma region.  */
8143   lang_propagate_lma_regions ();
8144 
8145   /* Defining __start/__stop symbols early for --gc-sections to work
8146      around a glibc build problem can result in these symbols being
8147      defined when they should not be.  Fix them now.  */
8148   if (config.build_constructors)
8149     lang_undef_start_stop ();
8150 
8151   /* Define .startof./.sizeof. symbols with preliminary values before
8152      dynamic symbols are created.  */
8153   if (!bfd_link_relocatable (&link_info))
8154     lang_init_startof_sizeof ();
8155 
8156   /* Do anything special before sizing sections.  This is where ELF
8157      and other back-ends size dynamic sections.  */
8158   ldemul_before_allocation ();
8159 
8160   /* We must record the program headers before we try to fix the
8161      section positions, since they will affect SIZEOF_HEADERS.  */
8162   lang_record_phdrs ();
8163 
8164   /* Check relro sections.  */
8165   if (link_info.relro && !bfd_link_relocatable (&link_info))
8166     lang_find_relro_sections ();
8167 
8168   /* Size up the sections.  */
8169   lang_size_sections (NULL, !RELAXATION_ENABLED);
8170 
8171   /* See if anything special should be done now we know how big
8172      everything is.  This is where relaxation is done.  */
8173   ldemul_after_allocation ();
8174 
8175   /* Fix any __start, __stop, .startof. or .sizeof. symbols.  */
8176   lang_finalize_start_stop ();
8177 
8178   /* Do all the assignments again, to report errors.  Assignment
8179      statements are processed multiple times, updating symbols; In
8180      open_input_bfds, lang_do_assignments, and lang_size_sections.
8181      Since lang_relax_sections calls lang_do_assignments, symbols are
8182      also updated in ldemul_after_allocation.  */
8183   lang_do_assignments (lang_final_phase_enum);
8184 
8185   ldemul_finish ();
8186 
8187   /* Convert absolute symbols to section relative.  */
8188   ldexp_finalize_syms ();
8189 
8190   /* Make sure that the section addresses make sense.  */
8191   if (command_line.check_section_addresses)
8192     lang_check_section_addresses ();
8193 
8194   /* Check any required symbols are known.  */
8195   ldlang_check_require_defined_symbols ();
8196 
8197   lang_end ();
8198 }
8199 
8200 /* EXPORTED TO YACC */
8201 
8202 void
lang_add_wild(struct wildcard_spec * filespec,struct wildcard_list * section_list,bfd_boolean keep_sections)8203 lang_add_wild (struct wildcard_spec *filespec,
8204 	       struct wildcard_list *section_list,
8205 	       bfd_boolean keep_sections)
8206 {
8207   struct wildcard_list *curr, *next;
8208   lang_wild_statement_type *new_stmt;
8209 
8210   /* Reverse the list as the parser puts it back to front.  */
8211   for (curr = section_list, section_list = NULL;
8212        curr != NULL;
8213        section_list = curr, curr = next)
8214     {
8215       next = curr->next;
8216       curr->next = section_list;
8217     }
8218 
8219   if (filespec != NULL && filespec->name != NULL)
8220     {
8221       if (strcmp (filespec->name, "*") == 0)
8222 	filespec->name = NULL;
8223       else if (!wildcardp (filespec->name))
8224 	lang_has_input_file = TRUE;
8225     }
8226 
8227   new_stmt = new_stat (lang_wild_statement, stat_ptr);
8228   new_stmt->filename = NULL;
8229   new_stmt->filenames_sorted = FALSE;
8230   new_stmt->section_flag_list = NULL;
8231   new_stmt->exclude_name_list = NULL;
8232   if (filespec != NULL)
8233     {
8234       new_stmt->filename = filespec->name;
8235       new_stmt->filenames_sorted = filespec->sorted == by_name;
8236       new_stmt->section_flag_list = filespec->section_flag_list;
8237       new_stmt->exclude_name_list = filespec->exclude_name_list;
8238     }
8239   new_stmt->section_list = section_list;
8240   new_stmt->keep_sections = keep_sections;
8241   lang_list_init (&new_stmt->children);
8242   analyze_walk_wild_section_handler (new_stmt);
8243 }
8244 
8245 void
lang_section_start(const char * name,etree_type * address,const segment_type * segment)8246 lang_section_start (const char *name, etree_type *address,
8247 		    const segment_type *segment)
8248 {
8249   lang_address_statement_type *ad;
8250 
8251   ad = new_stat (lang_address_statement, stat_ptr);
8252   ad->section_name = name;
8253   ad->address = address;
8254   ad->segment = segment;
8255 }
8256 
8257 /* Set the start symbol to NAME.  CMDLINE is nonzero if this is called
8258    because of a -e argument on the command line, or zero if this is
8259    called by ENTRY in a linker script.  Command line arguments take
8260    precedence.  */
8261 
8262 void
lang_add_entry(const char * name,bfd_boolean cmdline)8263 lang_add_entry (const char *name, bfd_boolean cmdline)
8264 {
8265   if (entry_symbol.name == NULL
8266       || cmdline
8267       || !entry_from_cmdline)
8268     {
8269       entry_symbol.name = name;
8270       entry_from_cmdline = cmdline;
8271     }
8272 }
8273 
8274 /* Set the default start symbol to NAME.  .em files should use this,
8275    not lang_add_entry, to override the use of "start" if neither the
8276    linker script nor the command line specifies an entry point.  NAME
8277    must be permanently allocated.  */
8278 void
lang_default_entry(const char * name)8279 lang_default_entry (const char *name)
8280 {
8281   entry_symbol_default = name;
8282 }
8283 
8284 void
lang_add_target(const char * name)8285 lang_add_target (const char *name)
8286 {
8287   lang_target_statement_type *new_stmt;
8288 
8289   new_stmt = new_stat (lang_target_statement, stat_ptr);
8290   new_stmt->target = name;
8291 }
8292 
8293 void
lang_add_map(const char * name)8294 lang_add_map (const char *name)
8295 {
8296   while (*name)
8297     {
8298       switch (*name)
8299 	{
8300 	case 'F':
8301 	  map_option_f = TRUE;
8302 	  break;
8303 	}
8304       name++;
8305     }
8306 }
8307 
8308 void
lang_add_fill(fill_type * fill)8309 lang_add_fill (fill_type *fill)
8310 {
8311   lang_fill_statement_type *new_stmt;
8312 
8313   new_stmt = new_stat (lang_fill_statement, stat_ptr);
8314   new_stmt->fill = fill;
8315 }
8316 
8317 void
lang_add_data(int type,union etree_union * exp)8318 lang_add_data (int type, union etree_union *exp)
8319 {
8320   lang_data_statement_type *new_stmt;
8321 
8322   new_stmt = new_stat (lang_data_statement, stat_ptr);
8323   new_stmt->exp = exp;
8324   new_stmt->type = type;
8325 }
8326 
8327 /* Create a new reloc statement.  RELOC is the BFD relocation type to
8328    generate.  HOWTO is the corresponding howto structure (we could
8329    look this up, but the caller has already done so).  SECTION is the
8330    section to generate a reloc against, or NAME is the name of the
8331    symbol to generate a reloc against.  Exactly one of SECTION and
8332    NAME must be NULL.  ADDEND is an expression for the addend.  */
8333 
8334 void
lang_add_reloc(bfd_reloc_code_real_type reloc,reloc_howto_type * howto,asection * section,const char * name,union etree_union * addend)8335 lang_add_reloc (bfd_reloc_code_real_type reloc,
8336 		reloc_howto_type *howto,
8337 		asection *section,
8338 		const char *name,
8339 		union etree_union *addend)
8340 {
8341   lang_reloc_statement_type *p = new_stat (lang_reloc_statement, stat_ptr);
8342 
8343   p->reloc = reloc;
8344   p->howto = howto;
8345   p->section = section;
8346   p->name = name;
8347   p->addend_exp = addend;
8348 
8349   p->addend_value = 0;
8350   p->output_section = NULL;
8351   p->output_offset = 0;
8352 }
8353 
8354 lang_assignment_statement_type *
lang_add_assignment(etree_type * exp)8355 lang_add_assignment (etree_type *exp)
8356 {
8357   lang_assignment_statement_type *new_stmt;
8358 
8359   new_stmt = new_stat (lang_assignment_statement, stat_ptr);
8360   new_stmt->exp = exp;
8361   return new_stmt;
8362 }
8363 
8364 void
lang_add_attribute(enum statement_enum attribute)8365 lang_add_attribute (enum statement_enum attribute)
8366 {
8367   new_statement (attribute, sizeof (lang_statement_header_type), stat_ptr);
8368 }
8369 
8370 void
lang_startup(const char * name)8371 lang_startup (const char *name)
8372 {
8373   if (first_file->filename != NULL)
8374     {
8375       einfo (_("%F%P: multiple STARTUP files\n"));
8376     }
8377   first_file->filename = name;
8378   first_file->local_sym_name = name;
8379   first_file->flags.real = TRUE;
8380 }
8381 
8382 void
lang_float(bfd_boolean maybe)8383 lang_float (bfd_boolean maybe)
8384 {
8385   lang_float_flag = maybe;
8386 }
8387 
8388 
8389 /* Work out the load- and run-time regions from a script statement, and
8390    store them in *LMA_REGION and *REGION respectively.
8391 
8392    MEMSPEC is the name of the run-time region, or the value of
8393    DEFAULT_MEMORY_REGION if the statement didn't specify one.
8394    LMA_MEMSPEC is the name of the load-time region, or null if the
8395    statement didn't specify one.HAVE_LMA_P is TRUE if the statement
8396    had an explicit load address.
8397 
8398    It is an error to specify both a load region and a load address.  */
8399 
8400 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)8401 lang_get_regions (lang_memory_region_type **region,
8402 		  lang_memory_region_type **lma_region,
8403 		  const char *memspec,
8404 		  const char *lma_memspec,
8405 		  bfd_boolean have_lma,
8406 		  bfd_boolean have_vma)
8407 {
8408   *lma_region = lang_memory_region_lookup (lma_memspec, FALSE);
8409 
8410   /* If no runtime region or VMA has been specified, but the load region
8411      has been specified, then use the load region for the runtime region
8412      as well.  */
8413   if (lma_memspec != NULL
8414       && !have_vma
8415       && strcmp (memspec, DEFAULT_MEMORY_REGION) == 0)
8416     *region = *lma_region;
8417   else
8418     *region = lang_memory_region_lookup (memspec, FALSE);
8419 
8420   if (have_lma && lma_memspec != 0)
8421     einfo (_("%X%P:%pS: section has both a load address and a load region\n"),
8422 	   NULL);
8423 }
8424 
8425 void
lang_leave_output_section_statement(fill_type * fill,const char * memspec,lang_output_section_phdr_list * phdrs,const char * lma_memspec)8426 lang_leave_output_section_statement (fill_type *fill, const char *memspec,
8427 				     lang_output_section_phdr_list *phdrs,
8428 				     const char *lma_memspec)
8429 {
8430   lang_get_regions (&current_section->region,
8431 		    &current_section->lma_region,
8432 		    memspec, lma_memspec,
8433 		    current_section->load_base != NULL,
8434 		    current_section->addr_tree != NULL);
8435 
8436   current_section->fill = fill;
8437   current_section->phdrs = phdrs;
8438   pop_stat_ptr ();
8439 }
8440 
8441 /* Set the output format type.  -oformat overrides scripts.  */
8442 
8443 void
lang_add_output_format(const char * format,const char * big,const char * little,int from_script)8444 lang_add_output_format (const char *format,
8445 			const char *big,
8446 			const char *little,
8447 			int from_script)
8448 {
8449   if (output_target == NULL || !from_script)
8450     {
8451       if (command_line.endian == ENDIAN_BIG
8452 	  && big != NULL)
8453 	format = big;
8454       else if (command_line.endian == ENDIAN_LITTLE
8455 	       && little != NULL)
8456 	format = little;
8457 
8458       output_target = format;
8459     }
8460 }
8461 
8462 void
lang_add_insert(const char * where,int is_before)8463 lang_add_insert (const char *where, int is_before)
8464 {
8465   lang_insert_statement_type *new_stmt;
8466 
8467   new_stmt = new_stat (lang_insert_statement, stat_ptr);
8468   new_stmt->where = where;
8469   new_stmt->is_before = is_before;
8470   saved_script_handle = previous_script_handle;
8471 }
8472 
8473 /* Enter a group.  This creates a new lang_group_statement, and sets
8474    stat_ptr to build new statements within the group.  */
8475 
8476 void
lang_enter_group(void)8477 lang_enter_group (void)
8478 {
8479   lang_group_statement_type *g;
8480 
8481   g = new_stat (lang_group_statement, stat_ptr);
8482   lang_list_init (&g->children);
8483   push_stat_ptr (&g->children);
8484 }
8485 
8486 /* Leave a group.  This just resets stat_ptr to start writing to the
8487    regular list of statements again.  Note that this will not work if
8488    groups can occur inside anything else which can adjust stat_ptr,
8489    but currently they can't.  */
8490 
8491 void
lang_leave_group(void)8492 lang_leave_group (void)
8493 {
8494   pop_stat_ptr ();
8495 }
8496 
8497 /* Add a new program header.  This is called for each entry in a PHDRS
8498    command in a linker script.  */
8499 
8500 void
lang_new_phdr(const char * name,etree_type * type,bfd_boolean filehdr,bfd_boolean phdrs,etree_type * at,etree_type * flags)8501 lang_new_phdr (const char *name,
8502 	       etree_type *type,
8503 	       bfd_boolean filehdr,
8504 	       bfd_boolean phdrs,
8505 	       etree_type *at,
8506 	       etree_type *flags)
8507 {
8508   struct lang_phdr *n, **pp;
8509   bfd_boolean hdrs;
8510 
8511   n = stat_alloc (sizeof (struct lang_phdr));
8512   n->next = NULL;
8513   n->name = name;
8514   n->type = exp_get_vma (type, 0, "program header type");
8515   n->filehdr = filehdr;
8516   n->phdrs = phdrs;
8517   n->at = at;
8518   n->flags = flags;
8519 
8520   hdrs = n->type == 1 && (phdrs || filehdr);
8521 
8522   for (pp = &lang_phdr_list; *pp != NULL; pp = &(*pp)->next)
8523     if (hdrs
8524 	&& (*pp)->type == 1
8525 	&& !((*pp)->filehdr || (*pp)->phdrs))
8526       {
8527 	einfo (_("%X%P:%pS: PHDRS and FILEHDR are not supported"
8528 		 " when prior PT_LOAD headers lack them\n"), NULL);
8529 	hdrs = FALSE;
8530       }
8531 
8532   *pp = n;
8533 }
8534 
8535 /* Record the program header information in the output BFD.  FIXME: We
8536    should not be calling an ELF specific function here.  */
8537 
8538 static void
lang_record_phdrs(void)8539 lang_record_phdrs (void)
8540 {
8541   unsigned int alc;
8542   asection **secs;
8543   lang_output_section_phdr_list *last;
8544   struct lang_phdr *l;
8545   lang_output_section_statement_type *os;
8546 
8547   alc = 10;
8548   secs = (asection **) xmalloc (alc * sizeof (asection *));
8549   last = NULL;
8550 
8551   for (l = lang_phdr_list; l != NULL; l = l->next)
8552     {
8553       unsigned int c;
8554       flagword flags;
8555       bfd_vma at;
8556 
8557       c = 0;
8558       for (os = (void *) lang_os_list.head;
8559 	   os != NULL;
8560 	   os = os->next)
8561 	{
8562 	  lang_output_section_phdr_list *pl;
8563 
8564 	  if (os->constraint < 0)
8565 	    continue;
8566 
8567 	  pl = os->phdrs;
8568 	  if (pl != NULL)
8569 	    last = pl;
8570 	  else
8571 	    {
8572 	      if (os->sectype == noload_section
8573 		  || os->bfd_section == NULL
8574 		  || (os->bfd_section->flags & SEC_ALLOC) == 0)
8575 		continue;
8576 
8577 	      /* Don't add orphans to PT_INTERP header.  */
8578 	      if (l->type == 3)
8579 		continue;
8580 
8581 	      if (last == NULL)
8582 		{
8583 		  lang_output_section_statement_type *tmp_os;
8584 
8585 		  /* If we have not run across a section with a program
8586 		     header assigned to it yet, then scan forwards to find
8587 		     one.  This prevents inconsistencies in the linker's
8588 		     behaviour when a script has specified just a single
8589 		     header and there are sections in that script which are
8590 		     not assigned to it, and which occur before the first
8591 		     use of that header. See here for more details:
8592 		     http://sourceware.org/ml/binutils/2007-02/msg00291.html  */
8593 		  for (tmp_os = os; tmp_os; tmp_os = tmp_os->next)
8594 		    if (tmp_os->phdrs)
8595 		      {
8596 			last = tmp_os->phdrs;
8597 			break;
8598 		      }
8599 		  if (last == NULL)
8600 		    einfo (_("%F%P: no sections assigned to phdrs\n"));
8601 		}
8602 	      pl = last;
8603 	    }
8604 
8605 	  if (os->bfd_section == NULL)
8606 	    continue;
8607 
8608 	  for (; pl != NULL; pl = pl->next)
8609 	    {
8610 	      if (strcmp (pl->name, l->name) == 0)
8611 		{
8612 		  if (c >= alc)
8613 		    {
8614 		      alc *= 2;
8615 		      secs = (asection **) xrealloc (secs,
8616 						     alc * sizeof (asection *));
8617 		    }
8618 		  secs[c] = os->bfd_section;
8619 		  ++c;
8620 		  pl->used = TRUE;
8621 		}
8622 	    }
8623 	}
8624 
8625       if (l->flags == NULL)
8626 	flags = 0;
8627       else
8628 	flags = exp_get_vma (l->flags, 0, "phdr flags");
8629 
8630       if (l->at == NULL)
8631 	at = 0;
8632       else
8633 	at = exp_get_vma (l->at, 0, "phdr load address");
8634 
8635       if (!bfd_record_phdr (link_info.output_bfd, l->type,
8636 			    l->flags != NULL, flags, l->at != NULL,
8637 			    at, l->filehdr, l->phdrs, c, secs))
8638 	einfo (_("%F%P: bfd_record_phdr failed: %E\n"));
8639     }
8640 
8641   free (secs);
8642 
8643   /* Make sure all the phdr assignments succeeded.  */
8644   for (os = (void *) lang_os_list.head;
8645        os != NULL;
8646        os = os->next)
8647     {
8648       lang_output_section_phdr_list *pl;
8649 
8650       if (os->constraint < 0
8651 	  || os->bfd_section == NULL)
8652 	continue;
8653 
8654       for (pl = os->phdrs;
8655 	   pl != NULL;
8656 	   pl = pl->next)
8657 	if (!pl->used && strcmp (pl->name, "NONE") != 0)
8658 	  einfo (_("%X%P: section `%s' assigned to non-existent phdr `%s'\n"),
8659 		 os->name, pl->name);
8660     }
8661 }
8662 
8663 /* Record a list of sections which may not be cross referenced.  */
8664 
8665 void
lang_add_nocrossref(lang_nocrossref_type * l)8666 lang_add_nocrossref (lang_nocrossref_type *l)
8667 {
8668   struct lang_nocrossrefs *n;
8669 
8670   n = (struct lang_nocrossrefs *) xmalloc (sizeof *n);
8671   n->next = nocrossref_list;
8672   n->list = l;
8673   n->onlyfirst = FALSE;
8674   nocrossref_list = n;
8675 
8676   /* Set notice_all so that we get informed about all symbols.  */
8677   link_info.notice_all = TRUE;
8678 }
8679 
8680 /* Record a section that cannot be referenced from a list of sections.  */
8681 
8682 void
lang_add_nocrossref_to(lang_nocrossref_type * l)8683 lang_add_nocrossref_to (lang_nocrossref_type *l)
8684 {
8685   lang_add_nocrossref (l);
8686   nocrossref_list->onlyfirst = TRUE;
8687 }
8688 
8689 /* Overlay handling.  We handle overlays with some static variables.  */
8690 
8691 /* The overlay virtual address.  */
8692 static etree_type *overlay_vma;
8693 /* And subsection alignment.  */
8694 static etree_type *overlay_subalign;
8695 
8696 /* An expression for the maximum section size seen so far.  */
8697 static etree_type *overlay_max;
8698 
8699 /* A list of all the sections in this overlay.  */
8700 
8701 struct overlay_list {
8702   struct overlay_list *next;
8703   lang_output_section_statement_type *os;
8704 };
8705 
8706 static struct overlay_list *overlay_list;
8707 
8708 /* Start handling an overlay.  */
8709 
8710 void
lang_enter_overlay(etree_type * vma_expr,etree_type * subalign)8711 lang_enter_overlay (etree_type *vma_expr, etree_type *subalign)
8712 {
8713   /* The grammar should prevent nested overlays from occurring.  */
8714   ASSERT (overlay_vma == NULL
8715 	  && overlay_subalign == NULL
8716 	  && overlay_max == NULL);
8717 
8718   overlay_vma = vma_expr;
8719   overlay_subalign = subalign;
8720 }
8721 
8722 /* Start a section in an overlay.  We handle this by calling
8723    lang_enter_output_section_statement with the correct VMA.
8724    lang_leave_overlay sets up the LMA and memory regions.  */
8725 
8726 void
lang_enter_overlay_section(const char * name)8727 lang_enter_overlay_section (const char *name)
8728 {
8729   struct overlay_list *n;
8730   etree_type *size;
8731 
8732   lang_enter_output_section_statement (name, overlay_vma, overlay_section,
8733 				       0, overlay_subalign, 0, 0, 0);
8734 
8735   /* If this is the first section, then base the VMA of future
8736      sections on this one.  This will work correctly even if `.' is
8737      used in the addresses.  */
8738   if (overlay_list == NULL)
8739     overlay_vma = exp_nameop (ADDR, name);
8740 
8741   /* Remember the section.  */
8742   n = (struct overlay_list *) xmalloc (sizeof *n);
8743   n->os = current_section;
8744   n->next = overlay_list;
8745   overlay_list = n;
8746 
8747   size = exp_nameop (SIZEOF, name);
8748 
8749   /* Arrange to work out the maximum section end address.  */
8750   if (overlay_max == NULL)
8751     overlay_max = size;
8752   else
8753     overlay_max = exp_binop (MAX_K, overlay_max, size);
8754 }
8755 
8756 /* Finish a section in an overlay.  There isn't any special to do
8757    here.  */
8758 
8759 void
lang_leave_overlay_section(fill_type * fill,lang_output_section_phdr_list * phdrs)8760 lang_leave_overlay_section (fill_type *fill,
8761 			    lang_output_section_phdr_list *phdrs)
8762 {
8763   const char *name;
8764   char *clean, *s2;
8765   const char *s1;
8766   char *buf;
8767 
8768   name = current_section->name;
8769 
8770   /* For now, assume that DEFAULT_MEMORY_REGION is the run-time memory
8771      region and that no load-time region has been specified.  It doesn't
8772      really matter what we say here, since lang_leave_overlay will
8773      override it.  */
8774   lang_leave_output_section_statement (fill, DEFAULT_MEMORY_REGION, phdrs, 0);
8775 
8776   /* Define the magic symbols.  */
8777 
8778   clean = (char *) xmalloc (strlen (name) + 1);
8779   s2 = clean;
8780   for (s1 = name; *s1 != '\0'; s1++)
8781     if (ISALNUM (*s1) || *s1 == '_')
8782       *s2++ = *s1;
8783   *s2 = '\0';
8784 
8785   buf = (char *) xmalloc (strlen (clean) + sizeof "__load_start_");
8786   sprintf (buf, "__load_start_%s", clean);
8787   lang_add_assignment (exp_provide (buf,
8788 				    exp_nameop (LOADADDR, name),
8789 				    FALSE));
8790 
8791   buf = (char *) xmalloc (strlen (clean) + sizeof "__load_stop_");
8792   sprintf (buf, "__load_stop_%s", clean);
8793   lang_add_assignment (exp_provide (buf,
8794 				    exp_binop ('+',
8795 					       exp_nameop (LOADADDR, name),
8796 					       exp_nameop (SIZEOF, name)),
8797 				    FALSE));
8798 
8799   free (clean);
8800 }
8801 
8802 /* Finish an overlay.  If there are any overlay wide settings, this
8803    looks through all the sections in the overlay and sets them.  */
8804 
8805 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)8806 lang_leave_overlay (etree_type *lma_expr,
8807 		    int nocrossrefs,
8808 		    fill_type *fill,
8809 		    const char *memspec,
8810 		    lang_output_section_phdr_list *phdrs,
8811 		    const char *lma_memspec)
8812 {
8813   lang_memory_region_type *region;
8814   lang_memory_region_type *lma_region;
8815   struct overlay_list *l;
8816   lang_nocrossref_type *nocrossref;
8817 
8818   lang_get_regions (&region, &lma_region,
8819 		    memspec, lma_memspec,
8820 		    lma_expr != NULL, FALSE);
8821 
8822   nocrossref = NULL;
8823 
8824   /* After setting the size of the last section, set '.' to end of the
8825      overlay region.  */
8826   if (overlay_list != NULL)
8827     {
8828       overlay_list->os->update_dot = 1;
8829       overlay_list->os->update_dot_tree
8830 	= exp_assign (".", exp_binop ('+', overlay_vma, overlay_max), FALSE);
8831     }
8832 
8833   l = overlay_list;
8834   while (l != NULL)
8835     {
8836       struct overlay_list *next;
8837 
8838       if (fill != NULL && l->os->fill == NULL)
8839 	l->os->fill = fill;
8840 
8841       l->os->region = region;
8842       l->os->lma_region = lma_region;
8843 
8844       /* The first section has the load address specified in the
8845 	 OVERLAY statement.  The rest are worked out from that.
8846 	 The base address is not needed (and should be null) if
8847 	 an LMA region was specified.  */
8848       if (l->next == 0)
8849 	{
8850 	  l->os->load_base = lma_expr;
8851 	  l->os->sectype = first_overlay_section;
8852 	}
8853       if (phdrs != NULL && l->os->phdrs == NULL)
8854 	l->os->phdrs = phdrs;
8855 
8856       if (nocrossrefs)
8857 	{
8858 	  lang_nocrossref_type *nc;
8859 
8860 	  nc = (lang_nocrossref_type *) xmalloc (sizeof *nc);
8861 	  nc->name = l->os->name;
8862 	  nc->next = nocrossref;
8863 	  nocrossref = nc;
8864 	}
8865 
8866       next = l->next;
8867       free (l);
8868       l = next;
8869     }
8870 
8871   if (nocrossref != NULL)
8872     lang_add_nocrossref (nocrossref);
8873 
8874   overlay_vma = NULL;
8875   overlay_list = NULL;
8876   overlay_max = NULL;
8877   overlay_subalign = NULL;
8878 }
8879 
8880 /* Version handling.  This is only useful for ELF.  */
8881 
8882 /* If PREV is NULL, return first version pattern matching particular symbol.
8883    If PREV is non-NULL, return first version pattern matching particular
8884    symbol after PREV (previously returned by lang_vers_match).  */
8885 
8886 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)8887 lang_vers_match (struct bfd_elf_version_expr_head *head,
8888 		 struct bfd_elf_version_expr *prev,
8889 		 const char *sym)
8890 {
8891   const char *c_sym;
8892   const char *cxx_sym = sym;
8893   const char *java_sym = sym;
8894   struct bfd_elf_version_expr *expr = NULL;
8895   enum demangling_styles curr_style;
8896 
8897   curr_style = CURRENT_DEMANGLING_STYLE;
8898   cplus_demangle_set_style (no_demangling);
8899   c_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_NO_OPTS);
8900   if (!c_sym)
8901     c_sym = sym;
8902   cplus_demangle_set_style (curr_style);
8903 
8904   if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
8905     {
8906       cxx_sym = bfd_demangle (link_info.output_bfd, sym,
8907 			      DMGL_PARAMS | DMGL_ANSI);
8908       if (!cxx_sym)
8909 	cxx_sym = sym;
8910     }
8911   if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
8912     {
8913       java_sym = bfd_demangle (link_info.output_bfd, sym, DMGL_JAVA);
8914       if (!java_sym)
8915 	java_sym = sym;
8916     }
8917 
8918   if (head->htab && (prev == NULL || prev->literal))
8919     {
8920       struct bfd_elf_version_expr e;
8921 
8922       switch (prev ? prev->mask : 0)
8923 	{
8924 	case 0:
8925 	  if (head->mask & BFD_ELF_VERSION_C_TYPE)
8926 	    {
8927 	      e.pattern = c_sym;
8928 	      expr = (struct bfd_elf_version_expr *)
8929 		  htab_find ((htab_t) head->htab, &e);
8930 	      while (expr && strcmp (expr->pattern, c_sym) == 0)
8931 		if (expr->mask == BFD_ELF_VERSION_C_TYPE)
8932 		  goto out_ret;
8933 		else
8934 		  expr = expr->next;
8935 	    }
8936 	  /* Fallthrough */
8937 	case BFD_ELF_VERSION_C_TYPE:
8938 	  if (head->mask & BFD_ELF_VERSION_CXX_TYPE)
8939 	    {
8940 	      e.pattern = cxx_sym;
8941 	      expr = (struct bfd_elf_version_expr *)
8942 		  htab_find ((htab_t) head->htab, &e);
8943 	      while (expr && strcmp (expr->pattern, cxx_sym) == 0)
8944 		if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
8945 		  goto out_ret;
8946 		else
8947 		  expr = expr->next;
8948 	    }
8949 	  /* Fallthrough */
8950 	case BFD_ELF_VERSION_CXX_TYPE:
8951 	  if (head->mask & BFD_ELF_VERSION_JAVA_TYPE)
8952 	    {
8953 	      e.pattern = java_sym;
8954 	      expr = (struct bfd_elf_version_expr *)
8955 		  htab_find ((htab_t) head->htab, &e);
8956 	      while (expr && strcmp (expr->pattern, java_sym) == 0)
8957 		if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
8958 		  goto out_ret;
8959 		else
8960 		  expr = expr->next;
8961 	    }
8962 	  /* Fallthrough */
8963 	default:
8964 	  break;
8965 	}
8966     }
8967 
8968   /* Finally, try the wildcards.  */
8969   if (prev == NULL || prev->literal)
8970     expr = head->remaining;
8971   else
8972     expr = prev->next;
8973   for (; expr; expr = expr->next)
8974     {
8975       const char *s;
8976 
8977       if (!expr->pattern)
8978 	continue;
8979 
8980       if (expr->pattern[0] == '*' && expr->pattern[1] == '\0')
8981 	break;
8982 
8983       if (expr->mask == BFD_ELF_VERSION_JAVA_TYPE)
8984 	s = java_sym;
8985       else if (expr->mask == BFD_ELF_VERSION_CXX_TYPE)
8986 	s = cxx_sym;
8987       else
8988 	s = c_sym;
8989       if (fnmatch (expr->pattern, s, 0) == 0)
8990 	break;
8991     }
8992 
8993  out_ret:
8994   if (c_sym != sym)
8995     free ((char *) c_sym);
8996   if (cxx_sym != sym)
8997     free ((char *) cxx_sym);
8998   if (java_sym != sym)
8999     free ((char *) java_sym);
9000   return expr;
9001 }
9002 
9003 /* Return NULL if the PATTERN argument is a glob pattern, otherwise,
9004    return a pointer to the symbol name with any backslash quotes removed.  */
9005 
9006 static const char *
realsymbol(const char * pattern)9007 realsymbol (const char *pattern)
9008 {
9009   const char *p;
9010   bfd_boolean changed = FALSE, backslash = FALSE;
9011   char *s, *symbol = (char *) xmalloc (strlen (pattern) + 1);
9012 
9013   for (p = pattern, s = symbol; *p != '\0'; ++p)
9014     {
9015       /* It is a glob pattern only if there is no preceding
9016 	 backslash.  */
9017       if (backslash)
9018 	{
9019 	  /* Remove the preceding backslash.  */
9020 	  *(s - 1) = *p;
9021 	  backslash = FALSE;
9022 	  changed = TRUE;
9023 	}
9024       else
9025 	{
9026 	  if (*p == '?' || *p == '*' || *p == '[')
9027 	    {
9028 	      free (symbol);
9029 	      return NULL;
9030 	    }
9031 
9032 	  *s++ = *p;
9033 	  backslash = *p == '\\';
9034 	}
9035     }
9036 
9037   if (changed)
9038     {
9039       *s = '\0';
9040       return symbol;
9041     }
9042   else
9043     {
9044       free (symbol);
9045       return pattern;
9046     }
9047 }
9048 
9049 /* This is called for each variable name or match expression.  NEW_NAME is
9050    the name of the symbol to match, or, if LITERAL_P is FALSE, a glob
9051    pattern to be matched against symbol names.  */
9052 
9053 struct bfd_elf_version_expr *
lang_new_vers_pattern(struct bfd_elf_version_expr * orig,const char * new_name,const char * lang,bfd_boolean literal_p)9054 lang_new_vers_pattern (struct bfd_elf_version_expr *orig,
9055 		       const char *new_name,
9056 		       const char *lang,
9057 		       bfd_boolean literal_p)
9058 {
9059   struct bfd_elf_version_expr *ret;
9060 
9061   ret = (struct bfd_elf_version_expr *) xmalloc (sizeof *ret);
9062   ret->next = orig;
9063   ret->symver = 0;
9064   ret->script = 0;
9065   ret->literal = TRUE;
9066   ret->pattern = literal_p ? new_name : realsymbol (new_name);
9067   if (ret->pattern == NULL)
9068     {
9069       ret->pattern = new_name;
9070       ret->literal = FALSE;
9071     }
9072 
9073   if (lang == NULL || strcasecmp (lang, "C") == 0)
9074     ret->mask = BFD_ELF_VERSION_C_TYPE;
9075   else if (strcasecmp (lang, "C++") == 0)
9076     ret->mask = BFD_ELF_VERSION_CXX_TYPE;
9077   else if (strcasecmp (lang, "Java") == 0)
9078     ret->mask = BFD_ELF_VERSION_JAVA_TYPE;
9079   else
9080     {
9081       einfo (_("%X%P: unknown language `%s' in version information\n"),
9082 	     lang);
9083       ret->mask = BFD_ELF_VERSION_C_TYPE;
9084     }
9085 
9086   return ldemul_new_vers_pattern (ret);
9087 }
9088 
9089 /* This is called for each set of variable names and match
9090    expressions.  */
9091 
9092 struct bfd_elf_version_tree *
lang_new_vers_node(struct bfd_elf_version_expr * globals,struct bfd_elf_version_expr * locals)9093 lang_new_vers_node (struct bfd_elf_version_expr *globals,
9094 		    struct bfd_elf_version_expr *locals)
9095 {
9096   struct bfd_elf_version_tree *ret;
9097 
9098   ret = (struct bfd_elf_version_tree *) xcalloc (1, sizeof *ret);
9099   ret->globals.list = globals;
9100   ret->locals.list = locals;
9101   ret->match = lang_vers_match;
9102   ret->name_indx = (unsigned int) -1;
9103   return ret;
9104 }
9105 
9106 /* This static variable keeps track of version indices.  */
9107 
9108 static int version_index;
9109 
9110 static hashval_t
version_expr_head_hash(const void * p)9111 version_expr_head_hash (const void *p)
9112 {
9113   const struct bfd_elf_version_expr *e =
9114       (const struct bfd_elf_version_expr *) p;
9115 
9116   return htab_hash_string (e->pattern);
9117 }
9118 
9119 static int
version_expr_head_eq(const void * p1,const void * p2)9120 version_expr_head_eq (const void *p1, const void *p2)
9121 {
9122   const struct bfd_elf_version_expr *e1 =
9123       (const struct bfd_elf_version_expr *) p1;
9124   const struct bfd_elf_version_expr *e2 =
9125       (const struct bfd_elf_version_expr *) p2;
9126 
9127   return strcmp (e1->pattern, e2->pattern) == 0;
9128 }
9129 
9130 static void
lang_finalize_version_expr_head(struct bfd_elf_version_expr_head * head)9131 lang_finalize_version_expr_head (struct bfd_elf_version_expr_head *head)
9132 {
9133   size_t count = 0;
9134   struct bfd_elf_version_expr *e, *next;
9135   struct bfd_elf_version_expr **list_loc, **remaining_loc;
9136 
9137   for (e = head->list; e; e = e->next)
9138     {
9139       if (e->literal)
9140 	count++;
9141       head->mask |= e->mask;
9142     }
9143 
9144   if (count)
9145     {
9146       head->htab = htab_create (count * 2, version_expr_head_hash,
9147 				version_expr_head_eq, NULL);
9148       list_loc = &head->list;
9149       remaining_loc = &head->remaining;
9150       for (e = head->list; e; e = next)
9151 	{
9152 	  next = e->next;
9153 	  if (!e->literal)
9154 	    {
9155 	      *remaining_loc = e;
9156 	      remaining_loc = &e->next;
9157 	    }
9158 	  else
9159 	    {
9160 	      void **loc = htab_find_slot ((htab_t) head->htab, e, INSERT);
9161 
9162 	      if (*loc)
9163 		{
9164 		  struct bfd_elf_version_expr *e1, *last;
9165 
9166 		  e1 = (struct bfd_elf_version_expr *) *loc;
9167 		  last = NULL;
9168 		  do
9169 		    {
9170 		      if (e1->mask == e->mask)
9171 			{
9172 			  last = NULL;
9173 			  break;
9174 			}
9175 		      last = e1;
9176 		      e1 = e1->next;
9177 		    }
9178 		  while (e1 && strcmp (e1->pattern, e->pattern) == 0);
9179 
9180 		  if (last == NULL)
9181 		    {
9182 		      /* This is a duplicate.  */
9183 		      /* FIXME: Memory leak.  Sometimes pattern is not
9184 			 xmalloced alone, but in larger chunk of memory.  */
9185 		      /* free (e->pattern); */
9186 		      free (e);
9187 		    }
9188 		  else
9189 		    {
9190 		      e->next = last->next;
9191 		      last->next = e;
9192 		    }
9193 		}
9194 	      else
9195 		{
9196 		  *loc = e;
9197 		  *list_loc = e;
9198 		  list_loc = &e->next;
9199 		}
9200 	    }
9201 	}
9202       *remaining_loc = NULL;
9203       *list_loc = head->remaining;
9204     }
9205   else
9206     head->remaining = head->list;
9207 }
9208 
9209 /* This is called when we know the name and dependencies of the
9210    version.  */
9211 
9212 void
lang_register_vers_node(const char * name,struct bfd_elf_version_tree * version,struct bfd_elf_version_deps * deps)9213 lang_register_vers_node (const char *name,
9214 			 struct bfd_elf_version_tree *version,
9215 			 struct bfd_elf_version_deps *deps)
9216 {
9217   struct bfd_elf_version_tree *t, **pp;
9218   struct bfd_elf_version_expr *e1;
9219 
9220   if (name == NULL)
9221     name = "";
9222 
9223   if (link_info.version_info != NULL
9224       && (name[0] == '\0' || link_info.version_info->name[0] == '\0'))
9225     {
9226       einfo (_("%X%P: anonymous version tag cannot be combined"
9227 	       " with other version tags\n"));
9228       free (version);
9229       return;
9230     }
9231 
9232   /* Make sure this node has a unique name.  */
9233   for (t = link_info.version_info; t != NULL; t = t->next)
9234     if (strcmp (t->name, name) == 0)
9235       einfo (_("%X%P: duplicate version tag `%s'\n"), name);
9236 
9237   lang_finalize_version_expr_head (&version->globals);
9238   lang_finalize_version_expr_head (&version->locals);
9239 
9240   /* Check the global and local match names, and make sure there
9241      aren't any duplicates.  */
9242 
9243   for (e1 = version->globals.list; e1 != NULL; e1 = e1->next)
9244     {
9245       for (t = link_info.version_info; t != NULL; t = t->next)
9246 	{
9247 	  struct bfd_elf_version_expr *e2;
9248 
9249 	  if (t->locals.htab && e1->literal)
9250 	    {
9251 	      e2 = (struct bfd_elf_version_expr *)
9252 		  htab_find ((htab_t) t->locals.htab, e1);
9253 	      while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9254 		{
9255 		  if (e1->mask == e2->mask)
9256 		    einfo (_("%X%P: duplicate expression `%s'"
9257 			     " in version information\n"), e1->pattern);
9258 		  e2 = e2->next;
9259 		}
9260 	    }
9261 	  else if (!e1->literal)
9262 	    for (e2 = t->locals.remaining; e2 != NULL; e2 = e2->next)
9263 	      if (strcmp (e1->pattern, e2->pattern) == 0
9264 		  && e1->mask == e2->mask)
9265 		einfo (_("%X%P: duplicate expression `%s'"
9266 			 " in version information\n"), e1->pattern);
9267 	}
9268     }
9269 
9270   for (e1 = version->locals.list; e1 != NULL; e1 = e1->next)
9271     {
9272       for (t = link_info.version_info; t != NULL; t = t->next)
9273 	{
9274 	  struct bfd_elf_version_expr *e2;
9275 
9276 	  if (t->globals.htab && e1->literal)
9277 	    {
9278 	      e2 = (struct bfd_elf_version_expr *)
9279 		  htab_find ((htab_t) t->globals.htab, e1);
9280 	      while (e2 && strcmp (e1->pattern, e2->pattern) == 0)
9281 		{
9282 		  if (e1->mask == e2->mask)
9283 		    einfo (_("%X%P: duplicate expression `%s'"
9284 			     " in version information\n"),
9285 			   e1->pattern);
9286 		  e2 = e2->next;
9287 		}
9288 	    }
9289 	  else if (!e1->literal)
9290 	    for (e2 = t->globals.remaining; e2 != NULL; e2 = e2->next)
9291 	      if (strcmp (e1->pattern, e2->pattern) == 0
9292 		  && e1->mask == e2->mask)
9293 		einfo (_("%X%P: duplicate expression `%s'"
9294 			 " in version information\n"), e1->pattern);
9295 	}
9296     }
9297 
9298   version->deps = deps;
9299   version->name = name;
9300   if (name[0] != '\0')
9301     {
9302       ++version_index;
9303       version->vernum = version_index;
9304     }
9305   else
9306     version->vernum = 0;
9307 
9308   for (pp = &link_info.version_info; *pp != NULL; pp = &(*pp)->next)
9309     ;
9310   *pp = version;
9311 }
9312 
9313 /* This is called when we see a version dependency.  */
9314 
9315 struct bfd_elf_version_deps *
lang_add_vers_depend(struct bfd_elf_version_deps * list,const char * name)9316 lang_add_vers_depend (struct bfd_elf_version_deps *list, const char *name)
9317 {
9318   struct bfd_elf_version_deps *ret;
9319   struct bfd_elf_version_tree *t;
9320 
9321   ret = (struct bfd_elf_version_deps *) xmalloc (sizeof *ret);
9322   ret->next = list;
9323 
9324   for (t = link_info.version_info; t != NULL; t = t->next)
9325     {
9326       if (strcmp (t->name, name) == 0)
9327 	{
9328 	  ret->version_needed = t;
9329 	  return ret;
9330 	}
9331     }
9332 
9333   einfo (_("%X%P: unable to find version dependency `%s'\n"), name);
9334 
9335   ret->version_needed = NULL;
9336   return ret;
9337 }
9338 
9339 static void
lang_do_version_exports_section(void)9340 lang_do_version_exports_section (void)
9341 {
9342   struct bfd_elf_version_expr *greg = NULL, *lreg;
9343 
9344   LANG_FOR_EACH_INPUT_STATEMENT (is)
9345     {
9346       asection *sec = bfd_get_section_by_name (is->the_bfd, ".exports");
9347       char *contents, *p;
9348       bfd_size_type len;
9349 
9350       if (sec == NULL)
9351 	continue;
9352 
9353       len = sec->size;
9354       contents = (char *) xmalloc (len);
9355       if (!bfd_get_section_contents (is->the_bfd, sec, contents, 0, len))
9356 	einfo (_("%X%P: unable to read .exports section contents\n"), sec);
9357 
9358       p = contents;
9359       while (p < contents + len)
9360 	{
9361 	  greg = lang_new_vers_pattern (greg, p, NULL, FALSE);
9362 	  p = strchr (p, '\0') + 1;
9363 	}
9364 
9365       /* Do not free the contents, as we used them creating the regex.  */
9366 
9367       /* Do not include this section in the link.  */
9368       sec->flags |= SEC_EXCLUDE | SEC_KEEP;
9369     }
9370 
9371   lreg = lang_new_vers_pattern (NULL, "*", NULL, FALSE);
9372   lang_register_vers_node (command_line.version_exports_section,
9373 			   lang_new_vers_node (greg, lreg), NULL);
9374 }
9375 
9376 /* Evaluate LENGTH and ORIGIN parts of MEMORY spec */
9377 
9378 static void
lang_do_memory_regions(void)9379 lang_do_memory_regions (void)
9380 {
9381   lang_memory_region_type *r = lang_memory_region_list;
9382 
9383   for (; r != NULL; r = r->next)
9384     {
9385       if (r->origin_exp)
9386 	{
9387 	  exp_fold_tree_no_dot (r->origin_exp);
9388 	  if (expld.result.valid_p)
9389 	    {
9390 	      r->origin = expld.result.value;
9391 	      r->current = r->origin;
9392 	    }
9393 	  else
9394 	    einfo (_("%F%P: invalid origin for memory region %s\n"),
9395 		   r->name_list.name);
9396 	}
9397       if (r->length_exp)
9398 	{
9399 	  exp_fold_tree_no_dot (r->length_exp);
9400 	  if (expld.result.valid_p)
9401 	    r->length = expld.result.value;
9402 	  else
9403 	    einfo (_("%F%P: invalid length for memory region %s\n"),
9404 		   r->name_list.name);
9405 	}
9406     }
9407 }
9408 
9409 void
lang_add_unique(const char * name)9410 lang_add_unique (const char *name)
9411 {
9412   struct unique_sections *ent;
9413 
9414   for (ent = unique_section_list; ent; ent = ent->next)
9415     if (strcmp (ent->name, name) == 0)
9416       return;
9417 
9418   ent = (struct unique_sections *) xmalloc (sizeof *ent);
9419   ent->name = xstrdup (name);
9420   ent->next = unique_section_list;
9421   unique_section_list = ent;
9422 }
9423 
9424 /* Append the list of dynamic symbols to the existing one.  */
9425 
9426 void
lang_append_dynamic_list(struct bfd_elf_dynamic_list ** list_p,struct bfd_elf_version_expr * dynamic)9427 lang_append_dynamic_list (struct bfd_elf_dynamic_list **list_p,
9428 			  struct bfd_elf_version_expr *dynamic)
9429 {
9430   if (*list_p)
9431     {
9432       struct bfd_elf_version_expr *tail;
9433       for (tail = dynamic; tail->next != NULL; tail = tail->next)
9434 	;
9435       tail->next = (*list_p)->head.list;
9436       (*list_p)->head.list = dynamic;
9437     }
9438   else
9439     {
9440       struct bfd_elf_dynamic_list *d;
9441 
9442       d = (struct bfd_elf_dynamic_list *) xcalloc (1, sizeof *d);
9443       d->head.list = dynamic;
9444       d->match = lang_vers_match;
9445       *list_p = d;
9446     }
9447 }
9448 
9449 /* Append the list of C++ typeinfo dynamic symbols to the existing
9450    one.  */
9451 
9452 void
lang_append_dynamic_list_cpp_typeinfo(void)9453 lang_append_dynamic_list_cpp_typeinfo (void)
9454 {
9455   const char *symbols[] =
9456     {
9457       "typeinfo name for*",
9458       "typeinfo for*"
9459     };
9460   struct bfd_elf_version_expr *dynamic = NULL;
9461   unsigned int i;
9462 
9463   for (i = 0; i < ARRAY_SIZE (symbols); i++)
9464     dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9465 				     FALSE);
9466 
9467   lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9468 }
9469 
9470 /* Append the list of C++ operator new and delete dynamic symbols to the
9471    existing one.  */
9472 
9473 void
lang_append_dynamic_list_cpp_new(void)9474 lang_append_dynamic_list_cpp_new (void)
9475 {
9476   const char *symbols[] =
9477     {
9478       "operator new*",
9479       "operator delete*"
9480     };
9481   struct bfd_elf_version_expr *dynamic = NULL;
9482   unsigned int i;
9483 
9484   for (i = 0; i < ARRAY_SIZE (symbols); i++)
9485     dynamic = lang_new_vers_pattern (dynamic, symbols [i], "C++",
9486 				     FALSE);
9487 
9488   lang_append_dynamic_list (&link_info.dynamic_list, dynamic);
9489 }
9490 
9491 /* Scan a space and/or comma separated string of features.  */
9492 
9493 void
lang_ld_feature(char * str)9494 lang_ld_feature (char *str)
9495 {
9496   char *p, *q;
9497 
9498   p = str;
9499   while (*p)
9500     {
9501       char sep;
9502       while (*p == ',' || ISSPACE (*p))
9503 	++p;
9504       if (!*p)
9505 	break;
9506       q = p + 1;
9507       while (*q && *q != ',' && !ISSPACE (*q))
9508 	++q;
9509       sep = *q;
9510       *q = 0;
9511       if (strcasecmp (p, "SANE_EXPR") == 0)
9512 	config.sane_expr = TRUE;
9513       else
9514 	einfo (_("%X%P: unknown feature `%s'\n"), p);
9515       *q = sep;
9516       p = q;
9517     }
9518 }
9519 
9520 /* Pretty print memory amount.  */
9521 
9522 static void
lang_print_memory_size(bfd_vma sz)9523 lang_print_memory_size (bfd_vma sz)
9524 {
9525   if ((sz & 0x3fffffff) == 0)
9526     printf ("%10" BFD_VMA_FMT "u GB", sz >> 30);
9527   else if ((sz & 0xfffff) == 0)
9528     printf ("%10" BFD_VMA_FMT "u MB", sz >> 20);
9529   else if ((sz & 0x3ff) == 0)
9530     printf ("%10" BFD_VMA_FMT "u KB", sz >> 10);
9531   else
9532     printf (" %10" BFD_VMA_FMT "u B", sz);
9533 }
9534 
9535 /* Implement --print-memory-usage: disply per region memory usage.  */
9536 
9537 void
lang_print_memory_usage(void)9538 lang_print_memory_usage (void)
9539 {
9540   lang_memory_region_type *r;
9541 
9542   printf ("Memory region         Used Size  Region Size  %%age Used\n");
9543   for (r = lang_memory_region_list; r->next != NULL; r = r->next)
9544     {
9545       bfd_vma used_length = r->current - r->origin;
9546 
9547       printf ("%16s: ",r->name_list.name);
9548       lang_print_memory_size (used_length);
9549       lang_print_memory_size ((bfd_vma) r->length);
9550 
9551       if (r->length != 0)
9552 	{
9553 	  double percent = used_length * 100.0 / r->length;
9554 	  printf ("    %6.2f%%", percent);
9555 	}
9556       printf ("\n");
9557     }
9558 }
9559