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