* emultempl/armelf.em: Watch EMULATION_LIBPATH instead of
[platform/upstream/binutils.git] / ld / emultempl / armelf.em
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 ELFSIZE=32
4 cat >e${EMULATION_NAME}.c <<EOF
5 /* This file is is generated by a shell script.  DO NOT EDIT! */
6
7 /* emulate the original gld for the given ${EMULATION_NAME}
8    Copyright (C) 1991, 93, 96, 97, 98, 1999 Free Software Foundation, Inc.
9    Written by Steve Chamberlain steve@cygnus.com
10
11 This file is part of GLD, the Gnu Linker.
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
26
27 #define TARGET_IS_${EMULATION_NAME}
28
29 #include "bfd.h"
30 #include "sysdep.h"
31 #include "bfdlink.h"
32 #include "getopt.h"
33
34 #include "ld.h"
35 #include "ldmain.h"
36 #include "ldemul.h"
37 #include "ldfile.h"
38 #include "ldmisc.h"
39
40 #include "ldexp.h"
41 #include "ldlang.h"
42 #include "ldgram.h"
43
44 static boolean gld${EMULATION_NAME}_open_dynamic_archive
45   PARAMS ((const char *, search_dirs_type *, lang_input_statement_type *));
46 static void gld${EMULATION_NAME}_after_open PARAMS ((void));
47 static void gld${EMULATION_NAME}_check_needed
48   PARAMS ((lang_input_statement_type *));
49 static void gld${EMULATION_NAME}_stat_needed
50   PARAMS ((lang_input_statement_type *));
51 static boolean gld${EMULATION_NAME}_search_needed
52   PARAMS ((const char *, const char *, int));
53 static boolean gld${EMULATION_NAME}_try_needed PARAMS ((const char *, int));
54 static void gld${EMULATION_NAME}_vercheck
55   PARAMS ((lang_input_statement_type *));
56 static void gld${EMULATION_NAME}_find_statement_assignment
57   PARAMS ((lang_statement_union_type *));
58 static void gld${EMULATION_NAME}_find_exp_assignment PARAMS ((etree_type *));
59 static boolean gld${EMULATION_NAME}_place_orphan
60   PARAMS ((lang_input_statement_type *, asection *));
61 static void gld${EMULATION_NAME}_place_section
62   PARAMS ((lang_statement_union_type *));
63 static void gld${EMULATION_NAME}_before_parse PARAMS ((void));
64 static void gld${EMULATION_NAME}_before_allocation PARAMS ((void));
65 static char *gld${EMULATION_NAME}_get_script PARAMS ((int *isfile));
66 static int  gld${EMULATION_NAME}_parse_args PARAMS((int, char **));
67 static void gld${EMULATION_NAME}_list_options PARAMS ((FILE *));
68
69 \f
70 static int no_pipeline_knowledge = 0;
71
72 static struct option longopts[] =
73 {
74   { "no-pipeline-knowledge", no_argument, NULL, 'p'},
75   { NULL, no_argument, NULL, 0 }
76 };
77
78 static void
79 gld${EMULATION_NAME}_list_options (file)
80      FILE * file;
81 {
82   fprintf (file, _("  -p --no-pipeline-knowledge  Stop the linker knowing about the pipeline length\n"));
83 }
84
85 static int
86 gld${EMULATION_NAME}_parse_args (argc, argv)
87      int     argc;
88      char ** argv;
89 {
90   int        longind;
91   int        optc;
92   int        prevoptind = optind;
93   int        prevopterr = opterr;
94   int        wanterror;
95   static int lastoptind = -1;
96
97   if (lastoptind != optind)
98     opterr = 0;
99   
100   wanterror  = opterr;
101   lastoptind = optind;
102
103   optc   = getopt_long_only (argc, argv, "-p", longopts, & longind);
104   opterr = prevopterr;
105
106   switch (optc)
107     {
108     default:
109       if (wanterror)
110         xexit (1);
111       optind =  prevoptind;
112       return 0;
113
114     case 'p':
115       no_pipeline_knowledge = 1;
116       break;
117     }
118   
119   return 1;
120 }
121 \f
122
123 static void
124 gld${EMULATION_NAME}_before_parse ()
125 {
126 #ifndef TARGET_                 /* I.e., if not generic.  */
127   ldfile_set_output_arch ("`echo ${ARCH}`");
128 #endif /* not TARGET_ */
129   config.dynamic_link = ${DYNAMIC_LINK-true};
130   config.has_shared = `if test -n "$GENERATE_SHLIB_SCRIPT" ; then echo true ; else echo false ; fi`;
131 }
132
133 /* Try to open a dynamic archive.  This is where we know that ELF
134    dynamic libraries have an extension of .so.  */
135
136 static boolean
137 gld${EMULATION_NAME}_open_dynamic_archive (arch, search, entry)
138      const char *arch;
139      search_dirs_type *search;
140      lang_input_statement_type *entry;
141 {
142   const char *filename;
143   char *string;
144
145   if (! entry->is_archive)
146     return false;
147
148   filename = entry->filename;
149
150   string = (char *) xmalloc (strlen (search->name)
151                              + strlen (filename)
152                              + strlen (arch)
153                              + sizeof "/lib.so");
154
155   sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
156
157   if (! ldfile_try_open_bfd (string, entry))
158     {
159       free (string);
160       return false;
161     }
162
163   entry->filename = string;
164
165   /* We have found a dynamic object to include in the link.  The ELF
166      backend linker will create a DT_NEEDED entry in the .dynamic
167      section naming this file.  If this file includes a DT_SONAME
168      entry, it will be used.  Otherwise, the ELF linker will just use
169      the name of the file.  For an archive found by searching, like
170      this one, the DT_NEEDED entry should consist of just the name of
171      the file, without the path information used to find it.  Note
172      that we only need to do this if we have a dynamic object; an
173      archive will never be referenced by a DT_NEEDED entry.
174
175      FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
176      very pretty.  I haven't been able to think of anything that is
177      pretty, though.  */
178   if (bfd_check_format (entry->the_bfd, bfd_object)
179       && (entry->the_bfd->flags & DYNAMIC) != 0)
180     {
181       char *needed_name;
182
183       ASSERT (entry->is_archive && entry->search_dirs_flag);
184       needed_name = (char *) xmalloc (strlen (filename)
185                                       + strlen (arch)
186                                       + sizeof "lib.so");
187       sprintf (needed_name, "lib%s%s.so", filename, arch);
188       bfd_elf_set_dt_needed_name (entry->the_bfd, needed_name);
189     }
190
191   return true;
192 }
193
194 EOF
195 if [ "x${host}" = "x${target}" ] ; then
196   case " ${EMULATION_LIBPATH} " in
197   *" ${EMULATION_NAME} "*)
198 cat >>e${EMULATION_NAME}.c <<EOF
199
200 /* For a native linker, check the file /etc/ld.so.conf for directories
201    in which we may find shared libraries.  /etc/ld.so.conf is really
202    only meaningful on Linux, but we check it on other systems anyhow.  */
203
204 static boolean gld${EMULATION_NAME}_check_ld_so_conf
205   PARAMS ((const char *, int));
206
207 static boolean
208 gld${EMULATION_NAME}_check_ld_so_conf (name, force)
209      const char *name;
210      int force;
211 {
212   static boolean initialized;
213   static char *ld_so_conf;
214
215   if (! initialized)
216     {
217       FILE *f;
218
219       f = fopen ("/etc/ld.so.conf", FOPEN_RT);
220       if (f != NULL)
221         {
222           char *b;
223           size_t len, alloc;
224           int c;
225
226           len = 0;
227           alloc = 100;
228           b = (char *) xmalloc (alloc);
229
230           while ((c = getc (f)) != EOF)
231             {
232               if (len + 1 >= alloc)
233                 {
234                   alloc *= 2;
235                   b = (char *) xrealloc (b, alloc);
236                 }
237               if (c != ':'
238                   && c != ' '
239                   && c != '\t'
240                   && c != '\n'
241                   && c != ',')
242                 {
243                   b[len] = c;
244                   ++len;
245                 }
246               else
247                 {
248                   if (len > 0 && b[len - 1] != ':')
249                     {
250                       b[len] = ':';
251                       ++len;
252                     }
253                 }
254             }
255
256           if (len > 0 && b[len - 1] == ':')
257             --len;
258
259           if (len > 0)
260             b[len] = '\0';
261           else
262             {
263               free (b);
264               b = NULL;
265             }
266
267           fclose (f);
268
269           ld_so_conf = b;
270         }
271
272       initialized = true;
273     }
274
275   if (ld_so_conf == NULL)
276     return false;
277
278   return gld${EMULATION_NAME}_search_needed (ld_so_conf, name, force);
279 }
280
281 EOF
282   ;;
283   esac
284 fi
285 cat >>e${EMULATION_NAME}.c <<EOF
286
287 /* These variables are required to pass information back and forth
288    between after_open and check_needed and stat_needed and vercheck.  */
289
290 static struct bfd_link_needed_list *global_needed;
291 static struct stat global_stat;
292 static boolean global_found;
293 static struct bfd_link_needed_list *global_vercheck_needed;
294 static boolean global_vercheck_failed;
295
296 static void
297 gld${EMULATION_NAME}_after_open ()
298 {
299   struct bfd_link_needed_list *needed, *l;
300
301   LANG_FOR_EACH_INPUT_STATEMENT (is)
302     {
303       /* The interworking bfd must be the last one to be processed */
304       if (!is->next)
305          bfd_elf32_arm_get_bfd_for_interworking (is->the_bfd, & link_info);
306     }
307
308   /* We only need to worry about this when doing a final link.  */
309   if (link_info.relocateable || link_info.shared)
310     return;
311
312   /* Get the list of files which appear in DT_NEEDED entries in
313      dynamic objects included in the link (often there will be none).
314      For each such file, we want to track down the corresponding
315      library, and include the symbol table in the link.  This is what
316      the runtime dynamic linker will do.  Tracking the files down here
317      permits one dynamic object to include another without requiring
318      special action by the person doing the link.  Note that the
319      needed list can actually grow while we are stepping through this
320      loop.  */
321   needed = bfd_elf_get_needed_list (output_bfd, &link_info);
322   for (l = needed; l != NULL; l = l->next)
323     {
324       struct bfd_link_needed_list *ll;
325       int force;
326
327       /* If we've already seen this file, skip it.  */
328       for (ll = needed; ll != l; ll = ll->next)
329         if (strcmp (ll->name, l->name) == 0)
330           break;
331       if (ll != l)
332         continue;
333
334       /* See if this file was included in the link explicitly.  */
335       global_needed = l;
336       global_found = false;
337       lang_for_each_input_file (gld${EMULATION_NAME}_check_needed);
338       if (global_found)
339         continue;
340
341       /* We need to find this file and include the symbol table.  We
342          want to search for the file in the same way that the dynamic
343          linker will search.  That means that we want to use
344          rpath_link, rpath, then the environment variable
345          LD_LIBRARY_PATH (native only), then the linker script
346          LIB_SEARCH_DIRS.  We do not search using the -L arguments.
347
348          We search twice.  The first time, we skip objects which may
349          introduce version mismatches.  The second time, we force
350          their use.  See gld${EMULATION_NAME}_vercheck comment.  */
351       for (force = 0; force < 2; force++)
352         {
353           const char *lib_path;
354           size_t len;
355           search_dirs_type *search;
356
357           if (gld${EMULATION_NAME}_search_needed (command_line.rpath_link,
358                                                   l->name, force))
359             break;
360           if (gld${EMULATION_NAME}_search_needed (command_line.rpath,
361                                                   l->name, force))
362             break;
363           if (command_line.rpath_link == NULL
364               && command_line.rpath == NULL)
365             {
366               lib_path = (const char *) getenv ("LD_RUN_PATH");
367               if (gld${EMULATION_NAME}_search_needed (lib_path, l->name,
368                                                       force))
369                 break;
370             }
371 EOF
372 if [ "x${host}" = "x${target}" ] ; then
373   case " ${EMULATION_LIBPATH} " in
374   *" ${EMULATION_NAME} "*)
375 cat >>e${EMULATION_NAME}.c <<EOF
376           lib_path = (const char *) getenv ("LD_LIBRARY_PATH");
377           if (gld${EMULATION_NAME}_search_needed (lib_path, l->name, force))
378             break;
379 EOF
380   ;;
381   esac
382 fi
383 cat >>e${EMULATION_NAME}.c <<EOF
384           len = strlen (l->name);
385           for (search = search_head; search != NULL; search = search->next)
386             {
387               char *filename;
388
389               if (search->cmdline)
390                 continue;
391               filename = (char *) xmalloc (strlen (search->name) + len + 2);
392               sprintf (filename, "%s/%s", search->name, l->name);
393               if (gld${EMULATION_NAME}_try_needed (filename, force))
394                 break;
395               free (filename);
396             }
397           if (search != NULL)
398             break;
399 EOF
400 if [ "x${host}" = "x${target}" ] ; then
401   case " ${EMULATION_LIBPATH} " in
402   *" ${EMULATION_NAME} "*)
403 cat >>e${EMULATION_NAME}.c <<EOF
404           if (gld${EMULATION_NAME}_check_ld_so_conf (l->name, force))
405             break;
406 EOF
407   ;;
408   esac
409 fi
410 cat >>e${EMULATION_NAME}.c <<EOF
411         }
412
413       if (force < 2)
414         continue;
415
416       einfo ("%P: warning: %s, needed by %B, not found (try using --rpath)\n",
417              l->name, l->by);
418     }
419 }
420
421 /* Search for a needed file in a path.  */
422
423 static boolean
424 gld${EMULATION_NAME}_search_needed (path, name, force)
425      const char *path;
426      const char *name;
427      int force;
428 {
429   const char *s;
430   size_t len;
431
432   if (path == NULL || *path == '\0')
433     return false;
434   len = strlen (name);
435   while (1)
436     {
437       char *filename, *sset;
438
439       s = strchr (path, ':');
440       if (s == NULL)
441         s = path + strlen (path);
442
443       filename = (char *) xmalloc (s - path + len + 2);
444       if (s == path)
445         sset = filename;
446       else
447         {
448           memcpy (filename, path, s - path);
449           filename[s - path] = '/';
450           sset = filename + (s - path) + 1;
451         }
452       strcpy (sset, name);
453
454       if (gld${EMULATION_NAME}_try_needed (filename, force))
455         return true;
456
457       free (filename);
458
459       if (*s == '\0')
460         break;
461       path = s + 1;
462     }
463
464   return false;   
465 }
466
467 /* This function is called for each possible name for a dynamic object
468    named by a DT_NEEDED entry.  The FORCE parameter indicates whether
469    to skip the check for a conflicting version.  */
470
471 static boolean
472 gld${EMULATION_NAME}_try_needed (name, force)
473      const char *name;
474      int force;
475 {
476   bfd *abfd;
477
478   abfd = bfd_openr (name, bfd_get_target (output_bfd));
479   if (abfd == NULL)
480     return false;
481   if (! bfd_check_format (abfd, bfd_object))
482     {
483       (void) bfd_close (abfd);
484       return false;
485     }
486   if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
487     {
488       (void) bfd_close (abfd);
489       return false;
490     }
491
492   /* Check whether this object would include any conflicting library
493      versions.  If FORCE is set, then we skip this check; we use this
494      the second time around, if we couldn't find any compatible
495      instance of the shared library.  */
496
497   if (! force)
498     {
499       struct bfd_link_needed_list *needed;
500
501       if (! bfd_elf_get_bfd_needed_list (abfd, &needed))
502         einfo ("%F%P:%B: bfd_elf_get_bfd_needed_list failed: %E\n", abfd);
503
504       if (needed != NULL)
505         {
506           global_vercheck_needed = needed;
507           global_vercheck_failed = false;
508           lang_for_each_input_file (gld${EMULATION_NAME}_vercheck);
509           if (global_vercheck_failed)
510             {
511               (void) bfd_close (abfd);
512               /* Return false to force the caller to move on to try
513                  another file on the search path.  */
514               return false;
515             }
516
517           /* But wait!  It gets much worse.  On Linux, if a shared
518              library does not use libc at all, we are supposed to skip
519              it the first time around in case we encounter a shared
520              library later on with the same name which does use the
521              version of libc that we want.  This is much too horrible
522              to use on any system other than Linux.  */
523
524 EOF
525 case ${target} in
526   *-*-linux-gnu*)
527     cat >>e${EMULATION_NAME}.c <<EOF
528           {
529             struct bfd_link_needed_list *l;
530
531             for (l = needed; l != NULL; l = l->next)
532               if (strncmp (l->name, "libc.so", 7) == 0)
533                 break;
534             if (l == NULL)
535               {
536                 (void) bfd_close (abfd);
537                 return false;
538               }
539           }
540
541 EOF
542     ;;
543 esac
544 cat >>e${EMULATION_NAME}.c <<EOF
545         }
546     }
547
548   /* We've found a dynamic object matching the DT_NEEDED entry.  */
549
550   /* We have already checked that there is no other input file of the
551      same name.  We must now check again that we are not including the
552      same file twice.  We need to do this because on many systems
553      libc.so is a symlink to, e.g., libc.so.1.  The SONAME entry will
554      reference libc.so.1.  If we have already included libc.so, we
555      don't want to include libc.so.1 if they are the same file, and we
556      can only check that using stat.  */
557
558   if (bfd_stat (abfd, &global_stat) != 0)
559     einfo ("%F%P:%B: bfd_stat failed: %E\n", abfd);
560   global_found = false;
561   lang_for_each_input_file (gld${EMULATION_NAME}_stat_needed);
562   if (global_found)
563     {
564       /* Return true to indicate that we found the file, even though
565          we aren't going to do anything with it.  */
566       return true;
567     }
568
569   /* Tell the ELF backend that don't want the output file to have a
570      DT_NEEDED entry for this file.  */
571   bfd_elf_set_dt_needed_name (abfd, "");
572
573   /* Add this file into the symbol table.  */
574   if (! bfd_link_add_symbols (abfd, &link_info))
575     einfo ("%F%B: could not read symbols: %E\n", abfd);
576
577   return true;
578 }
579
580 /* See if an input file matches a DT_NEEDED entry by name.  */
581
582 static void
583 gld${EMULATION_NAME}_check_needed (s)
584      lang_input_statement_type *s;
585 {
586   if (global_found)
587     return;
588
589   if (s->filename != NULL
590       && strcmp (s->filename, global_needed->name) == 0)
591     {
592       global_found = true;
593       return;
594     }
595
596   if (s->the_bfd != NULL)
597     {
598       const char *soname;
599
600       soname = bfd_elf_get_dt_soname (s->the_bfd);
601       if (soname != NULL
602           && strcmp (soname, global_needed->name) == 0)
603         {
604           global_found = true;
605           return;
606         }
607     }
608           
609   if (s->search_dirs_flag
610       && s->filename != NULL
611       && strchr (global_needed->name, '/') == NULL)
612     {
613       const char *f;
614
615       f = strrchr (s->filename, '/');
616       if (f != NULL
617           && strcmp (f + 1, global_needed->name) == 0)
618         {
619           global_found = true;
620           return;
621         }
622     }
623 }
624
625 /* See if an input file matches a DT_NEEDED entry by running stat on
626    the file.  */
627
628 static void
629 gld${EMULATION_NAME}_stat_needed (s)
630      lang_input_statement_type *s;
631 {
632   struct stat st;
633   const char *suffix;
634   const char *soname;
635   const char *f;
636
637   if (global_found)
638     return;
639   if (s->the_bfd == NULL)
640     return;
641
642   if (bfd_stat (s->the_bfd, &st) != 0)
643     {
644       einfo ("%P:%B: bfd_stat failed: %E\n", s->the_bfd);
645       return;
646     }
647
648   if (st.st_dev == global_stat.st_dev
649       && st.st_ino == global_stat.st_ino)
650     {
651       global_found = true;
652       return;
653     }
654
655   /* We issue a warning if it looks like we are including two
656      different versions of the same shared library.  For example,
657      there may be a problem if -lc picks up libc.so.6 but some other
658      shared library has a DT_NEEDED entry of libc.so.5.  This is a
659      hueristic test, and it will only work if the name looks like
660      NAME.so.VERSION.  FIXME: Depending on file names is error-prone.
661      If we really want to issue warnings about mixing version numbers
662      of shared libraries, we need to find a better way.  */
663
664   if (strchr (global_needed->name, '/') != NULL)
665     return;
666   suffix = strstr (global_needed->name, ".so.");
667   if (suffix == NULL)
668     return;
669   suffix += sizeof ".so." - 1;
670
671   soname = bfd_elf_get_dt_soname (s->the_bfd);
672   if (soname == NULL)
673     soname = s->filename;
674
675   f = strrchr (soname, '/');
676   if (f != NULL)
677     ++f;
678   else
679     f = soname;
680
681   if (strncmp (f, global_needed->name, suffix - global_needed->name) == 0)
682     einfo ("%P: warning: %s, needed by %B, may conflict with %s\n",
683            global_needed->name, global_needed->by, f);
684 }
685
686 /* On Linux, it's possible to have different versions of the same
687    shared library linked against different versions of libc.  The
688    dynamic linker somehow tags which libc version to use in
689    /etc/ld.so.cache, and, based on the libc that it sees in the
690    executable, chooses which version of the shared library to use.
691
692    We try to do a similar check here by checking whether this shared
693    library needs any other shared libraries which may conflict with
694    libraries we have already included in the link.  If it does, we
695    skip it, and try to find another shared library farther on down the
696    link path.
697
698    This is called via lang_for_each_input_file.
699    GLOBAL_VERCHECK_NEEDED is the list of objects needed by the object
700    which we ar checking.  This sets GLOBAL_VERCHECK_FAILED if we find
701    a conflicting version.  */
702
703 static void
704 gld${EMULATION_NAME}_vercheck (s)
705      lang_input_statement_type *s;
706 {
707   const char *soname, *f;
708   struct bfd_link_needed_list *l;
709
710   if (global_vercheck_failed)
711     return;
712   if (s->the_bfd == NULL
713       || (bfd_get_file_flags (s->the_bfd) & DYNAMIC) == 0)
714     return;
715
716   soname = bfd_elf_get_dt_soname (s->the_bfd);
717   if (soname == NULL)
718     soname = bfd_get_filename (s->the_bfd);
719
720   f = strrchr (soname, '/');
721   if (f != NULL)
722     ++f;
723   else
724     f = soname;
725
726   for (l = global_vercheck_needed; l != NULL; l = l->next)
727     {
728       const char *suffix;
729
730       if (strcmp (f, l->name) == 0)
731         {
732           /* Probably can't happen, but it's an easy check.  */
733           continue;
734         }
735
736       if (strchr (l->name, '/') != NULL)
737         continue;
738
739       suffix = strstr (l->name, ".so.");
740       if (suffix == NULL)
741         continue;
742
743       suffix += sizeof ".so." - 1;
744
745       if (strncmp (f, l->name, suffix - l->name) == 0)
746         {
747           /* Here we know that S is a dynamic object FOO.SO.VER1, and
748              the object we are considering needs a dynamic object
749              FOO.SO.VER2, and VER1 and VER2 are different.  This
750              appears to be a version mismatch, so we tell the caller
751              to try a different version of this library.  */
752           global_vercheck_failed = true;
753           return;
754         }
755     }
756 }
757
758 /* Place an orphan section.  We use this to put random SHF_ALLOC
759    sections in the right segment.  */
760
761 static asection *hold_section;
762 static lang_output_section_statement_type *hold_use;
763 static lang_output_section_statement_type *hold_text;
764 static lang_output_section_statement_type *hold_rodata;
765 static lang_output_section_statement_type *hold_data;
766 static lang_output_section_statement_type *hold_bss;
767 static lang_output_section_statement_type *hold_rel;
768 static lang_output_section_statement_type *hold_interp;
769
770 /*ARGSUSED*/
771 static boolean
772 gld${EMULATION_NAME}_place_orphan (file, s)
773      lang_input_statement_type *file;
774      asection *s;
775 {
776   lang_output_section_statement_type *place;
777   asection *snew, **pps;
778   lang_statement_list_type *old;
779   lang_statement_list_type add;
780   etree_type *address;
781   const char *secname, *ps;
782   const char *outsecname;
783   lang_output_section_statement_type *os;
784
785   if ((s->flags & SEC_ALLOC) == 0)
786     return false;
787
788   /* Look through the script to see where to place this section.  */
789   hold_section = s;
790   hold_use = NULL;
791   lang_for_each_statement (gld${EMULATION_NAME}_place_section);
792
793   if (hold_use != NULL)
794     {
795       /* We have already placed a section with this name.  */
796       wild_doit (&hold_use->children, s, hold_use, file);
797       return true;
798     }
799
800   secname = bfd_get_section_name (s->owner, s);
801
802   /* If this is a final link, then always put .gnu.warning.SYMBOL
803      sections into the .text section to get them out of the way.  */
804   if (! link_info.shared
805       && ! link_info.relocateable
806       && strncmp (secname, ".gnu.warning.", sizeof ".gnu.warning." - 1) == 0
807       && hold_text != NULL)
808     {
809       wild_doit (&hold_text->children, s, hold_text, file);
810       return true;
811     }
812
813   /* Decide which segment the section should go in based on the
814      section name and section flags.  We put loadable .note sections
815      right after the .interp section, so that the PT_NOTE segment is
816      stored right after the program headers where the OS can read it
817      in the first page.  */
818   place = NULL;
819   if (s->flags & SEC_EXCLUDE)
820     return false;
821   else if ((s->flags & SEC_LOAD) != 0
822       && strncmp (secname, ".note", 4) == 0
823       && hold_interp != NULL)
824     place = hold_interp;
825   else if ((s->flags & SEC_HAS_CONTENTS) == 0
826            && hold_bss != NULL)
827     place = hold_bss;
828   else if ((s->flags & SEC_READONLY) == 0
829            && hold_data != NULL)
830     place = hold_data;
831   else if (strncmp (secname, ".rel", 4) == 0
832            && hold_rel != NULL)
833     place = hold_rel;
834   else if ((s->flags & SEC_CODE) == 0
835            && (s->flags & SEC_READONLY) != 0
836            && hold_rodata != NULL)
837     place = hold_rodata;
838   else if ((s->flags & SEC_READONLY) != 0
839            && hold_text != NULL)
840     place = hold_text;
841   if (place == NULL)
842     return false;
843
844   /* Choose a unique name for the section.  This will be needed if the
845      same section name appears in the input file with different
846      loadable or allocateable characteristics.  */
847   outsecname = secname;
848   if (bfd_get_section_by_name (output_bfd, outsecname) != NULL)
849     {
850       unsigned int len;
851       char *newname;
852       unsigned int i;
853
854       len = strlen (outsecname);
855       newname = xmalloc (len + 5);
856       strcpy (newname, outsecname);
857       i = 0;
858       do
859         {
860           sprintf (newname + len, "%d", i);
861           ++i;
862         }
863       while (bfd_get_section_by_name (output_bfd, newname) != NULL);
864
865       outsecname = newname;
866     }
867
868   /* Create the section in the output file, and put it in the right
869      place.  This shuffling is to make the output file look neater.  */
870   snew = bfd_make_section (output_bfd, outsecname);
871   if (snew == NULL)
872       einfo ("%P%F: output format %s cannot represent section called %s\n",
873              output_bfd->xvec->name, outsecname);
874   if (place->bfd_section != NULL)
875     {
876       for (pps = &output_bfd->sections; *pps != snew; pps = &(*pps)->next)
877         ;
878       *pps = snew->next;
879       snew->next = place->bfd_section->next;
880       place->bfd_section->next = snew;
881     }
882
883   /* Start building a list of statements for this section.  */
884   old = stat_ptr;
885   stat_ptr = &add;
886   lang_list_init (stat_ptr);
887
888   /* If the name of the section is representable in C, then create
889      symbols to mark the start and the end of the section.  */
890   for (ps = outsecname; *ps != '\0'; ps++)
891     if (! isalnum ((unsigned char) *ps) && *ps != '_')
892       break;
893   if (*ps == '\0' && config.build_constructors)
894     {
895       char *symname;
896
897       symname = (char *) xmalloc (ps - outsecname + sizeof "__start_");
898       sprintf (symname, "__start_%s", outsecname);
899       lang_add_assignment (exp_assop ('=', symname,
900                                       exp_unop (ALIGN_K,
901                                                 exp_intop ((bfd_vma) 1
902                                                            << s->alignment_power))));
903     }
904
905   if (! link_info.relocateable)
906     address = NULL;
907   else
908     address = exp_intop ((bfd_vma) 0);
909
910   lang_enter_output_section_statement (outsecname, address, 0,
911                                        (bfd_vma) 0,
912                                        (etree_type *) NULL,
913                                        (etree_type *) NULL,
914                                        (etree_type *) NULL);
915
916   os = lang_output_section_statement_lookup (outsecname);
917   wild_doit (&os->children, s, os, file);
918
919   lang_leave_output_section_statement
920     ((bfd_vma) 0, "*default*", (struct lang_output_section_phdr_list *) NULL);
921   stat_ptr = &add;
922
923   if (*ps == '\0' && config.build_constructors)
924     {
925       char *symname;
926
927       symname = (char *) xmalloc (ps - outsecname + sizeof "__stop_");
928       sprintf (symname, "__stop_%s", outsecname);
929       lang_add_assignment (exp_assop ('=', symname,
930                                       exp_nameop (NAME, ".")));
931     }
932
933   /* Now stick the new statement list right after PLACE.  */
934   *add.tail = place->header.next;
935   place->header.next = add.head;
936
937   stat_ptr = old;
938
939   return true;
940 }
941
942 static void
943 gld${EMULATION_NAME}_place_section (s)
944      lang_statement_union_type *s;
945 {
946   lang_output_section_statement_type *os;
947
948   if (s->header.type != lang_output_section_statement_enum)
949     return;
950
951   os = &s->output_section_statement;
952
953   if (strcmp (os->name, hold_section->name) == 0
954       && os->bfd_section != NULL
955       && ((hold_section->flags & (SEC_LOAD | SEC_ALLOC))
956           == (os->bfd_section->flags & (SEC_LOAD | SEC_ALLOC))))
957     hold_use = os;
958
959   if (strcmp (os->name, ".text") == 0)
960     hold_text = os;
961   else if (strcmp (os->name, ".rodata") == 0)
962     hold_rodata = os;
963   else if (strcmp (os->name, ".data") == 0)
964     hold_data = os;
965   else if (strcmp (os->name, ".bss") == 0)
966     hold_bss = os;
967   else if (hold_rel == NULL
968            && os->bfd_section != NULL
969            && (os->bfd_section->flags & SEC_ALLOC) != 0
970            && strncmp (os->name, ".rel", 4) == 0)
971     hold_rel = os;
972   else if (strcmp (os->name, ".interp") == 0)
973     hold_interp = os;
974 }
975
976 /* Look through an expression for an assignment statement.  */
977
978 static void
979 gld${EMULATION_NAME}_find_exp_assignment (exp)
980      etree_type *exp;
981 {
982   struct bfd_link_hash_entry *h;
983
984   switch (exp->type.node_class)
985     {
986     case etree_provide:
987       h = bfd_link_hash_lookup (link_info.hash, exp->assign.dst,
988                                 false, false, false);
989       if (h == NULL)
990         break;
991
992       /* We call record_link_assignment even if the symbol is defined.
993          This is because if it is defined by a dynamic object, we
994          actually want to use the value defined by the linker script,
995          not the value from the dynamic object (because we are setting
996          symbols like etext).  If the symbol is defined by a regular
997          object, then, as it happens, calling record_link_assignment
998          will do no harm.  */
999
1000       /* Fall through.  */
1001     case etree_assign:
1002       if (strcmp (exp->assign.dst, ".") != 0)
1003         {
1004           if (! (bfd_elf${ELFSIZE}_record_link_assignment
1005                  (output_bfd, &link_info, exp->assign.dst,
1006                   exp->type.node_class == etree_provide ? true : false)))
1007             einfo ("%P%F: failed to record assignment to %s: %E\n",
1008                    exp->assign.dst);
1009         }
1010       gld${EMULATION_NAME}_find_exp_assignment (exp->assign.src);
1011       break;
1012
1013     case etree_binary:
1014       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.lhs);
1015       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.rhs);
1016       break;
1017
1018     case etree_trinary:
1019       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.cond);
1020       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.lhs);
1021       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.rhs);
1022       break;
1023
1024     case etree_unary:
1025       gld${EMULATION_NAME}_find_exp_assignment (exp->unary.child);
1026       break;
1027
1028     default:
1029       break;
1030     }
1031 }
1032
1033 /* This is called by the before_allocation routine via
1034    lang_for_each_statement.  It locates any assignment statements, and
1035    tells the ELF backend about them, in case they are assignments to
1036    symbols which are referred to by dynamic objects.  */
1037
1038 static void
1039 gld${EMULATION_NAME}_find_statement_assignment (s)
1040      lang_statement_union_type *s;
1041 {
1042   if (s->header.type == lang_assignment_statement_enum)
1043     gld${EMULATION_NAME}_find_exp_assignment (s->assignment_statement.exp);
1044 }
1045
1046 /* This is called after the sections have been attached to output
1047    sections, but before any sizes or addresses have been set.  */
1048
1049 static void
1050 gld${EMULATION_NAME}_before_allocation ()
1051 {
1052   const char *rpath;
1053   asection *sinterp;
1054
1055   /* If we are going to make any variable assignments, we need to let
1056      the ELF backend know about them in case the variables are
1057      referred to by dynamic objects.  */
1058   lang_for_each_statement (gld${EMULATION_NAME}_find_statement_assignment);
1059
1060   /* Let the ELF backend work out the sizes of any sections required
1061      by dynamic linking.  */
1062   rpath = command_line.rpath;
1063   if (rpath == NULL)
1064     rpath = (const char *) getenv ("LD_RUN_PATH");
1065   if (! (bfd_elf${ELFSIZE}_size_dynamic_sections
1066          (output_bfd, command_line.soname, rpath,
1067           command_line.export_dynamic, command_line.filter_shlib,
1068           (const char * const *) command_line.auxiliary_filters,
1069           &link_info, &sinterp, lang_elf_version_info)))
1070     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
1071
1072   /* Let the user override the dynamic linker we are using.  */
1073   if (command_line.interpreter != NULL
1074       && sinterp != NULL)
1075     {
1076       sinterp->contents = (bfd_byte *) command_line.interpreter;
1077       sinterp->_raw_size = strlen (command_line.interpreter) + 1;
1078     }
1079
1080   /* Look for any sections named .gnu.warning.  As a GNU extensions,
1081      we treat such sections as containing warning messages.  We print
1082      out the warning message, and then zero out the section size so
1083      that it does not get copied into the output file.  */
1084
1085   {
1086     LANG_FOR_EACH_INPUT_STATEMENT (is)
1087       {
1088         asection *s;
1089         bfd_size_type sz;
1090         char *msg;
1091         boolean ret;
1092
1093         if (is->just_syms_flag)
1094           continue;
1095
1096         s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1097         if (s == NULL)
1098           continue;
1099
1100         sz = bfd_section_size (is->the_bfd, s);
1101         msg = xmalloc ((size_t) sz + 1);
1102         if (! bfd_get_section_contents (is->the_bfd, s, msg, (file_ptr) 0, sz))
1103           einfo ("%F%B: Can't read contents of section .gnu.warning: %E\n",
1104                  is->the_bfd);
1105         msg[sz] = '\0';
1106         ret = link_info.callbacks->warning (&link_info, msg,
1107                                             (const char *) NULL,
1108                                             is->the_bfd, (asection *) NULL,
1109                                             (bfd_vma) 0);
1110         ASSERT (ret);
1111         free (msg);
1112
1113         /* Clobber the section size, so that we don't waste copying the
1114            warning into the output file.  */
1115         s->_raw_size = 0;
1116       }
1117   }
1118
1119   /* we should be able to set the size of the interworking stub section */
1120
1121   /* Here we rummage through the found bfds to collect glue information */
1122   /* FIXME: should this be based on a command line option? krk@cygnus.com */
1123   {
1124     LANG_FOR_EACH_INPUT_STATEMENT (is)
1125       {
1126         if (!bfd_elf32_arm_process_before_allocation (is->the_bfd, & link_info,
1127                                                       no_pipeline_knowledge))
1128           {
1129             /* xgettext:c-format */
1130             einfo (_("Errors encountered processing file %s"), is->filename);
1131           }
1132       }
1133   }
1134
1135   /* We have seen it all. Allocate it, and carry on */
1136   bfd_elf32_arm_allocate_interworking_sections (& link_info);
1137 }
1138
1139 static char *
1140 gld${EMULATION_NAME}_get_script (isfile)
1141      int *isfile;
1142 EOF
1143
1144 if test -n "$COMPILE_IN"
1145 then
1146 # Scripts compiled in.
1147
1148 # sed commands to quote an ld script as a C string.
1149 sc="-f ${srcdir}/emultempl/stringify.sed"
1150
1151 cat >>e${EMULATION_NAME}.c <<EOF
1152 {                            
1153   *isfile = 0;
1154
1155   if (link_info.relocateable == true && config.build_constructors == true)
1156     return
1157 EOF
1158 sed $sc ldscripts/${EMULATION_NAME}.xu                     >> e${EMULATION_NAME}.c
1159 echo '  ; else if (link_info.relocateable == true) return' >> e${EMULATION_NAME}.c
1160 sed $sc ldscripts/${EMULATION_NAME}.xr                     >> e${EMULATION_NAME}.c
1161 echo '  ; else if (!config.text_read_only) return'         >> e${EMULATION_NAME}.c
1162 sed $sc ldscripts/${EMULATION_NAME}.xbn                    >> e${EMULATION_NAME}.c
1163 echo '  ; else if (!config.magic_demand_paged) return'     >> e${EMULATION_NAME}.c
1164 sed $sc ldscripts/${EMULATION_NAME}.xn                     >> e${EMULATION_NAME}.c
1165 echo '  ; else return'                                     >> e${EMULATION_NAME}.c
1166 sed $sc ldscripts/${EMULATION_NAME}.x                      >> e${EMULATION_NAME}.c
1167 echo '; }'                                                 >> e${EMULATION_NAME}.c
1168
1169 else
1170 # Scripts read from the filesystem.
1171
1172 cat >>e${EMULATION_NAME}.c <<EOF
1173 {                            
1174   *isfile = 1;
1175
1176   if (link_info.relocateable == true && config.build_constructors == true)
1177     return "ldscripts/${EMULATION_NAME}.xu";
1178   else if (link_info.relocateable == true)
1179     return "ldscripts/${EMULATION_NAME}.xr";
1180   else if (!config.text_read_only)
1181     return "ldscripts/${EMULATION_NAME}.xbn";
1182   else if (!config.magic_demand_paged)
1183     return "ldscripts/${EMULATION_NAME}.xn";
1184   else
1185     return "ldscripts/${EMULATION_NAME}.x";
1186 }
1187 EOF
1188
1189 fi
1190
1191 cat >>e${EMULATION_NAME}.c <<EOF
1192
1193 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation = 
1194 {
1195   gld${EMULATION_NAME}_before_parse,
1196   syslib_default,
1197   hll_default,
1198   after_parse_default,
1199   gld${EMULATION_NAME}_after_open,
1200   after_allocation_default,
1201   set_output_arch_default,
1202   ldemul_default_target,
1203   gld${EMULATION_NAME}_before_allocation,
1204   gld${EMULATION_NAME}_get_script,
1205   "${EMULATION_NAME}",
1206   "${OUTPUT_FORMAT}",
1207   NULL, /* finish */
1208   NULL, /* create output section statements */
1209   gld${EMULATION_NAME}_open_dynamic_archive,
1210   gld${EMULATION_NAME}_place_orphan,
1211   NULL, /* set_symbols */
1212   gld${EMULATION_NAME}_parse_args,
1213   NULL, /* unrecognised file */
1214   gld${EMULATION_NAME}_list_options,
1215   NULL /* recognized file */
1216 };
1217 EOF