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