bfd/
[external/binutils.git] / ld / emultempl / spuelf.em
1 # This shell script emits a C file. -*- C -*-
2 #   Copyright 2006, 2007, 2008 Free Software Foundation, Inc.
3 #
4 # This file is part of the GNU Binutils.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19 # MA 02110-1301, USA.
20 #
21
22 # This file is sourced from elf32.em, and defines extra spu specific
23 # features.
24 #
25 fragment <<EOF
26 #include "ldctor.h"
27 #include "elf32-spu.h"
28
29 /* Non-zero if no overlay processing should be done.  */
30 static int no_overlays = 0;
31
32 /* Non-zero if we want stubs on all calls out of overlay regions.  */
33 static int non_overlay_stubs = 0;
34
35 /* Whether to emit symbols for stubs.  */
36 static int emit_stub_syms = 0;
37
38 /* Non-zero to perform stack space analysis.  */
39 static int stack_analysis = 0;
40
41 /* Whether to emit symbols with stack requirements for each function.  */
42 static int emit_stack_syms = 0;
43
44 /* Range of valid addresses for loadable sections.  */
45 static bfd_vma local_store_lo = 0;
46 static bfd_vma local_store_hi = 0x3ffff;
47
48 /* Control --auto-overlay feature.  */
49 static int auto_overlay = 0;
50 static char *auto_overlay_file = 0;
51 static unsigned int auto_overlay_fixed = 0;
52 static unsigned int auto_overlay_reserved = 0;
53 static int extra_stack_space = 2000;
54 int my_argc;
55 char **my_argv;
56
57 static const char ovl_mgr[] = {
58 EOF
59
60 ../binutils/bin2c < ${srcdir}/emultempl/spu_ovl.o >> e${EMULATION_NAME}.c
61
62 fragment <<EOF
63 };
64
65 static const struct _ovl_stream ovl_mgr_stream = {
66   ovl_mgr,
67   ovl_mgr + sizeof (ovl_mgr)
68 };
69
70
71 static int
72 is_spu_target (void)
73 {
74   extern const bfd_target bfd_elf32_spu_vec;
75
76   return link_info.output_bfd->xvec == &bfd_elf32_spu_vec;
77 }
78
79 /* Create our note section.  */
80
81 static void
82 spu_after_open (void)
83 {
84   if (is_spu_target ()
85       && !link_info.relocatable
86       && link_info.input_bfds != NULL
87       && !spu_elf_create_sections (&link_info,
88                                    stack_analysis, emit_stack_syms))
89     einfo ("%X%P: can not create note section: %E\n");
90
91   gld${EMULATION_NAME}_after_open ();
92 }
93
94 /* If O is NULL, add section S at the end of output section OUTPUT_NAME.
95    If O is not NULL, add section S at the beginning of output section O.
96
97    Really, we should be duplicating ldlang.c map_input_to_output_sections
98    logic here, ie. using the linker script to find where the section
99    goes.  That's rather a lot of code, and we don't want to run
100    map_input_to_output_sections again because most sections are already
101    mapped.  So cheat, and put the section in a fixed place, ignoring any
102    attempt via a linker script to put .stub, .ovtab, and built-in
103    overlay manager code somewhere else.  */
104
105 static void
106 spu_place_special_section (asection *s, asection *o, const char *output_name)
107 {
108   lang_output_section_statement_type *os;
109
110   os = lang_output_section_find (o != NULL ? o->name : output_name);
111   if (os == NULL)
112     {
113       const char *save = s->name;
114       s->name = output_name;
115       gld${EMULATION_NAME}_place_orphan (s);
116       s->name = save;
117     }
118   else if (o != NULL && os->children.head != NULL)
119     {
120       lang_statement_list_type add;
121
122       lang_list_init (&add);
123       lang_add_section (&add, s, os);
124       *add.tail = os->children.head;
125       os->children.head = add.head;
126     }
127   else
128     lang_add_section (&os->children, s, os);
129
130   s->output_section->size += s->size;
131 }
132
133 /* Load built-in overlay manager, and tweak overlay section alignment.  */
134
135 static void
136 spu_elf_load_ovl_mgr (void)
137 {
138   lang_output_section_statement_type *os;
139   struct elf_link_hash_entry *h;
140
141   h = elf_link_hash_lookup (elf_hash_table (&link_info),
142                             "__ovly_load", FALSE, FALSE, FALSE);
143
144   if (h != NULL
145       && (h->root.type == bfd_link_hash_defined
146           || h->root.type == bfd_link_hash_defweak)
147       && h->def_regular)
148     {
149       /* User supplied __ovly_load.  */
150     }
151   else if (ovl_mgr_stream.start == ovl_mgr_stream.end)
152     einfo ("%F%P: no built-in overlay manager\n");
153   else
154     {
155       lang_input_statement_type *ovl_is;
156
157       ovl_is = lang_add_input_file ("builtin ovl_mgr",
158                                     lang_input_file_is_file_enum,
159                                     NULL);
160
161       if (!spu_elf_open_builtin_lib (&ovl_is->the_bfd, &ovl_mgr_stream))
162         einfo ("%X%P: can not open built-in overlay manager: %E\n");
163       else
164         {
165           asection *in;
166
167           if (!load_symbols (ovl_is, NULL))
168             einfo ("%X%P: can not load built-in overlay manager: %E\n");
169
170           /* Map overlay manager sections to output sections.  */
171           for (in = ovl_is->the_bfd->sections; in != NULL; in = in->next)
172             if ((in->flags & (SEC_ALLOC | SEC_LOAD))
173                 == (SEC_ALLOC | SEC_LOAD))
174               spu_place_special_section (in, NULL, ".text");
175         }
176     }
177
178   /* Ensure alignment of overlay sections is sufficient.  */
179   for (os = &lang_output_section_statement.head->output_section_statement;
180        os != NULL;
181        os = os->next)
182     if (os->bfd_section != NULL
183         && spu_elf_section_data (os->bfd_section) != NULL
184         && spu_elf_section_data (os->bfd_section)->u.o.ovl_index != 0)
185       {
186         if (os->bfd_section->alignment_power < 4)
187           os->bfd_section->alignment_power = 4;
188
189         /* Also ensure size rounds up.  */
190         os->block_value = 16;
191       }
192 }
193
194 /* Go find if we need to do anything special for overlays.  */
195
196 static void
197 spu_before_allocation (void)
198 {
199   if (is_spu_target ()
200       && !link_info.relocatable
201       && !no_overlays)
202     {
203       /* Size the sections.  This is premature, but we need to know the
204          rough layout so that overlays can be found.  */
205       expld.phase = lang_mark_phase_enum;
206       expld.dataseg.phase = exp_dataseg_none;
207       one_lang_size_sections_pass (NULL, TRUE);
208
209       /* Find overlays by inspecting section vmas.  */
210       if (spu_elf_find_overlays (&link_info))
211         {
212           int ret;
213
214           if (auto_overlay != 0)
215             {
216               einfo ("%P: --auto-overlay ignored with user overlay script\n");
217               auto_overlay = 0;
218             }
219
220           ret = spu_elf_size_stubs (&link_info,
221                                     spu_place_special_section,
222                                     non_overlay_stubs);
223           if (ret == 0)
224             einfo ("%X%P: can not size overlay stubs: %E\n");
225           else if (ret == 2)
226             spu_elf_load_ovl_mgr ();
227         }
228
229       /* We must not cache anything from the preliminary sizing.  */
230       lang_reset_memory_regions ();
231     }
232
233   gld${EMULATION_NAME}_before_allocation ();
234 }
235
236 struct tflist {
237   struct tflist *next;
238   char name[9];
239 };
240
241 static struct tflist *tmp_file_list;
242
243 static void clean_tmp (void)
244 {
245   for (; tmp_file_list != NULL; tmp_file_list = tmp_file_list->next)
246     unlink (tmp_file_list->name);
247 }
248
249 static int
250 new_tmp_file (char **fname)
251 {
252   struct tflist *tf;
253   int fd;
254
255   if (tmp_file_list == NULL)
256     atexit (clean_tmp);
257   tf = xmalloc (sizeof (*tf));
258   tf->next = tmp_file_list;
259   tmp_file_list = tf;
260   memcpy (tf->name, "ldXXXXXX", sizeof (tf->name));
261   *fname = tf->name;
262 #ifdef HAVE_MKSTEMP
263   fd = mkstemp (*fname);
264 #else
265   *fname = mktemp (*fname);
266   if (*fname == NULL)
267     return -1;
268   fd = open (fname, O_RDWR | O_CREAT | O_EXCL, 0600);
269 #endif
270   return fd;
271 }
272
273 static FILE *
274 spu_elf_open_overlay_script (void)
275 {
276   FILE *script = NULL;
277
278   if (auto_overlay_file == NULL)
279     {
280       int fd = new_tmp_file (&auto_overlay_file);
281       if (fd == -1)
282         goto file_err;
283       script = fdopen (fd, "w");
284     }
285   else
286     script = fopen (auto_overlay_file, "w");
287
288   if (script == NULL)
289     {
290     file_err:
291       einfo ("%F%P: can not open script: %E\n");
292     }
293   return script;
294 }
295
296 static void
297 spu_elf_relink (void)
298 {
299   char **argv = xmalloc ((my_argc + 4) * sizeof (*argv));
300
301   memcpy (argv, my_argv, my_argc * sizeof (*argv));
302   argv[my_argc++] = "--no-auto-overlay";
303   if (tmp_file_list->name == auto_overlay_file)
304     argv[my_argc - 1] = concat (argv[my_argc - 1], "=",
305                                 auto_overlay_file, (const char *) NULL);
306   argv[my_argc++] = "-T";
307   argv[my_argc++] = auto_overlay_file;
308   argv[my_argc] = 0;
309   execvp (argv[0], (char *const *) argv);
310   perror (argv[0]);
311   _exit (127);
312 }
313
314 /* Final emulation specific call.  */
315
316 static void
317 gld${EMULATION_NAME}_finish (void)
318 {
319   int need_laying_out;
320
321   need_laying_out = bfd_elf_discard_info (link_info.output_bfd, &link_info);
322
323   gld${EMULATION_NAME}_map_segments (need_laying_out);
324
325   if (is_spu_target ())
326     {
327       if (local_store_lo < local_store_hi)
328         {
329           asection *s;
330
331           s = spu_elf_check_vma (&link_info, auto_overlay,
332                                  local_store_lo, local_store_hi,
333                                  auto_overlay_fixed, auto_overlay_reserved,
334                                  extra_stack_space,
335                                  spu_elf_load_ovl_mgr,
336                                  spu_elf_open_overlay_script,
337                                  spu_elf_relink);
338           if (s != NULL && !auto_overlay)
339             einfo ("%X%P: %A exceeds local store range\n", s);
340         }
341       else if (auto_overlay)
342         einfo ("%P: --auto-overlay ignored with zero local store range\n");
343
344       if (!spu_elf_build_stubs (&link_info,
345                                 emit_stub_syms || link_info.emitrelocations))
346         einfo ("%X%P: can not build overlay stubs: %E\n");
347     }
348
349   finish_default ();
350 }
351
352 static char *
353 gld${EMULATION_NAME}_choose_target (int argc, char *argv[])
354 {
355   my_argc = argc;
356   my_argv = argv;
357   return ldemul_default_target (argc, argv);
358 }
359
360 EOF
361
362 if grep -q 'ld_elf.*ppc.*_emulation' ldemul-list.h; then
363   fragment <<EOF
364 #include "filenames.h"
365 #include <fcntl.h>
366 #include <sys/wait.h>
367
368 static const char *
369 base_name (const char *path)
370 {
371   const char *file = strrchr (path, '/');
372 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
373   {
374     char *bslash = strrchr (path, '\\\\');
375
376     if (file == NULL || (bslash != NULL && bslash > file))
377       file = bslash;
378     if (file == NULL
379         && path[0] != '\0'
380         && path[1] == ':')
381       file = path + 1;
382   }
383 #endif
384   if (file == NULL)
385     file = path;
386   else
387     ++file;
388   return file;
389 }
390
391 /* This function is called when building a ppc32 or ppc64 executable
392    to handle embedded spu images.  */
393 extern bfd_boolean embedded_spu_file (lang_input_statement_type *, const char *);
394
395 bfd_boolean
396 embedded_spu_file (lang_input_statement_type *entry, const char *flags)
397 {
398   const char *cmd[6];
399   const char *sym;
400   char *handle, *p;
401   char *oname;
402   int fd;
403   pid_t pid;
404   int status;
405   union lang_statement_union **old_stat_tail;
406   union lang_statement_union **old_file_tail;
407   union lang_statement_union *new_ent;
408   lang_input_statement_type *search;
409
410   if (entry->the_bfd->format != bfd_object
411       || strcmp (entry->the_bfd->xvec->name, "elf32-spu") != 0
412       || (entry->the_bfd->tdata.elf_obj_data->elf_header->e_type != ET_EXEC
413           && entry->the_bfd->tdata.elf_obj_data->elf_header->e_type != ET_DYN))
414     return FALSE;
415
416   /* Use the filename as the symbol marking the program handle struct.  */
417   sym = base_name (entry->the_bfd->filename);
418
419   handle = xstrdup (sym);
420   for (p = handle; *p; ++p)
421     if (!(ISALNUM (*p) || *p == '$' || *p == '.'))
422       *p = '_';
423
424   fd = new_tmp_file (&oname);
425   if (fd == -1)
426     return FALSE;
427   close (fd);
428
429   for (search = (lang_input_statement_type *) input_file_chain.head;
430        search != NULL;
431        search = (lang_input_statement_type *) search->next_real_file)
432     if (search->filename != NULL)
433       {
434         const char *infile = base_name (search->filename);
435
436         if (strncmp (infile, "crtbegin", 8) == 0)
437           {
438             if (infile[8] == 'S')
439               flags = concat (flags, " -fPIC", (const char *) NULL);
440             else if (infile[8] == 'T')
441               flags = concat (flags, " -fpie", (const char *) NULL);
442             break;
443           }
444       }
445
446   /* Use fork() and exec() rather than system() so that we don't
447      need to worry about quoting args.  */
448   cmd[0] = EMBEDSPU;
449   cmd[1] = flags;
450   cmd[2] = handle;
451   cmd[3] = entry->the_bfd->filename;
452   cmd[4] = oname;
453   cmd[5] = NULL;
454   if (trace_file_tries)
455     {
456       info_msg (_("running: %s \"%s\" \"%s\" \"%s\" \"%s\"\n"),
457                 cmd[0], cmd[1], cmd[2], cmd[3], cmd[4]);
458       fflush (stdout);
459     }
460
461   pid = fork ();
462   if (pid == -1)
463     return FALSE;
464   if (pid == 0)
465     {
466       execvp (cmd[0], (char *const *) cmd);
467       if (strcmp ("embedspu", EMBEDSPU) != 0)
468         {
469           cmd[0] = "embedspu";
470           execvp (cmd[0], (char *const *) cmd);
471         }
472       perror (cmd[0]);
473       _exit (127);
474     }
475 #ifdef HAVE_WAITPID
476 #define WAITFOR(PID, STAT) waitpid (PID, STAT, 0)
477 #else
478 #define WAITFOR(PID, STAT) wait (STAT)
479 #endif
480   if (WAITFOR (pid, &status) != pid
481       || !WIFEXITED (status)
482       || WEXITSTATUS (status) != 0)
483     return FALSE;
484 #undef WAITFOR
485
486   old_stat_tail = stat_ptr->tail;
487   old_file_tail = input_file_chain.tail;
488   if (lang_add_input_file (oname, lang_input_file_is_file_enum, NULL) == NULL)
489     return FALSE;
490
491   /* lang_add_input_file put the new list entry at the end of the statement
492      and input file lists.  Move it to just after the current entry.  */
493   new_ent = *old_stat_tail;
494   *old_stat_tail = NULL;
495   stat_ptr->tail = old_stat_tail;
496   *old_file_tail = NULL;
497   input_file_chain.tail = old_file_tail;
498   new_ent->header.next = entry->header.next;
499   entry->header.next = new_ent;
500   new_ent->input_statement.next_real_file = entry->next_real_file;
501   entry->next_real_file = new_ent;
502
503   /* Ensure bfd sections are excluded from the output.  */
504   bfd_section_list_clear (entry->the_bfd);
505   entry->loaded = TRUE;
506   return TRUE;
507 }
508
509 EOF
510 fi
511
512 # Define some shell vars to insert bits of code into the standard elf
513 # parse_args and list_options functions.
514 #
515 PARSE_AND_LIST_PROLOGUE='
516 #define OPTION_SPU_PLUGIN               301
517 #define OPTION_SPU_NO_OVERLAYS          (OPTION_SPU_PLUGIN + 1)
518 #define OPTION_SPU_STUB_SYMS            (OPTION_SPU_NO_OVERLAYS + 1)
519 #define OPTION_SPU_NON_OVERLAY_STUBS    (OPTION_SPU_STUB_SYMS + 1)
520 #define OPTION_SPU_LOCAL_STORE          (OPTION_SPU_NON_OVERLAY_STUBS + 1)
521 #define OPTION_SPU_STACK_ANALYSIS       (OPTION_SPU_LOCAL_STORE + 1)
522 #define OPTION_SPU_STACK_SYMS           (OPTION_SPU_STACK_ANALYSIS + 1)
523 #define OPTION_SPU_AUTO_OVERLAY         (OPTION_SPU_STACK_SYMS + 1)
524 #define OPTION_SPU_AUTO_RELINK          (OPTION_SPU_AUTO_OVERLAY + 1)
525 #define OPTION_SPU_OVERLAY_RODATA       (OPTION_SPU_AUTO_RELINK + 1)
526 #define OPTION_SPU_FIXED_SPACE          (OPTION_SPU_OVERLAY_RODATA + 1)
527 #define OPTION_SPU_RESERVED_SPACE       (OPTION_SPU_FIXED_SPACE + 1)
528 #define OPTION_SPU_EXTRA_STACK          (OPTION_SPU_RESERVED_SPACE + 1)
529 #define OPTION_SPU_NO_AUTO_OVERLAY      (OPTION_SPU_EXTRA_STACK + 1)
530 '
531
532 PARSE_AND_LIST_LONGOPTS='
533   { "plugin", no_argument, NULL, OPTION_SPU_PLUGIN },
534   { "no-overlays", no_argument, NULL, OPTION_SPU_NO_OVERLAYS },
535   { "emit-stub-syms", no_argument, NULL, OPTION_SPU_STUB_SYMS },
536   { "extra-overlay-stubs", no_argument, NULL, OPTION_SPU_NON_OVERLAY_STUBS },
537   { "local-store", required_argument, NULL, OPTION_SPU_LOCAL_STORE },
538   { "stack-analysis", no_argument, NULL, OPTION_SPU_STACK_ANALYSIS },
539   { "emit-stack-syms", no_argument, NULL, OPTION_SPU_STACK_SYMS },
540   { "auto-overlay", optional_argument, NULL, OPTION_SPU_AUTO_OVERLAY },
541   { "auto-relink", no_argument, NULL, OPTION_SPU_AUTO_RELINK },
542   { "overlay-rodata", no_argument, NULL, OPTION_SPU_OVERLAY_RODATA },
543   { "fixed-space", required_argument, NULL, OPTION_SPU_FIXED_SPACE },
544   { "reserved-space", required_argument, NULL, OPTION_SPU_RESERVED_SPACE },
545   { "extra-stack-space", required_argument, NULL, OPTION_SPU_EXTRA_STACK },
546   { "no-auto-overlay", optional_argument, NULL, OPTION_SPU_NO_AUTO_OVERLAY },
547 '
548
549 PARSE_AND_LIST_OPTIONS='
550   fprintf (file, _("\
551   --plugin                    Make SPU plugin.\n\
552   --no-overlays               No overlay handling.\n\
553   --emit-stub-syms            Add symbols on overlay call stubs.\n\
554   --extra-overlay-stubs       Add stubs on all calls out of overlay regions.\n\
555   --local-store=lo:hi         Valid address range.\n\
556   --stack-analysis            Estimate maximum stack requirement.\n\
557   --emit-stack-syms           Add sym giving stack needed for each func.\n\
558   --auto-overlay [=filename]  Create an overlay script in filename if\n\
559                               executable does not fit in local store.\n\
560   --auto-relink               Rerun linker using auto-overlay script.\n\
561   --overlay-rodata            Place read-only data with associated function\n\
562                               code in overlays.\n\
563   --fixed-space=bytes         Local store for non-overlay code and data.\n\
564   --reserved-space=bytes      Local store for stack and heap.  If not specified\n\
565                               ld will estimate stack size and assume no heap.\n\
566   --extra-stack-space=bytes   Space for negative sp access (default 2000) if\n\
567                               --reserved-space not given.\n"
568                    ));
569 '
570
571 PARSE_AND_LIST_ARGS_CASES='
572     case OPTION_SPU_PLUGIN:
573       spu_elf_plugin (1);
574       break;
575
576     case OPTION_SPU_NO_OVERLAYS:
577       no_overlays = 1;
578       break;
579
580     case OPTION_SPU_STUB_SYMS:
581       emit_stub_syms = 1;
582       break;
583
584     case OPTION_SPU_NON_OVERLAY_STUBS:
585       non_overlay_stubs = 1;
586       break;
587
588     case OPTION_SPU_LOCAL_STORE:
589       {
590         char *end;
591         local_store_lo = strtoul (optarg, &end, 0);
592         if (*end == '\'':'\'')
593           {
594             local_store_hi = strtoul (end + 1, &end, 0);
595             if (*end == 0)
596               break;
597           }
598         einfo (_("%P%F: invalid --local-store address range `%s'\''\n"), optarg);
599       }
600       break;
601
602     case OPTION_SPU_STACK_ANALYSIS:
603       stack_analysis = 1;
604       break;
605
606     case OPTION_SPU_STACK_SYMS:
607       emit_stack_syms = 1;
608       break;
609
610     case OPTION_SPU_AUTO_OVERLAY:
611       auto_overlay |= 1;
612       if (optarg != NULL)
613         {
614           auto_overlay_file = optarg;
615           break;
616         }
617       /* Fall thru */
618
619     case OPTION_SPU_AUTO_RELINK:
620       auto_overlay |= 2;
621       break;
622
623     case OPTION_SPU_OVERLAY_RODATA:
624       auto_overlay |= 4;
625       break;
626
627     case OPTION_SPU_FIXED_SPACE:
628       {
629         char *end;
630         auto_overlay_fixed = strtoul (optarg, &end, 0);
631         if (*end != 0)
632           einfo (_("%P%F: invalid --fixed-space value `%s'\''\n"), optarg);
633       }
634       break;
635
636     case OPTION_SPU_RESERVED_SPACE:
637       {
638         char *end;
639         auto_overlay_reserved = strtoul (optarg, &end, 0);
640         if (*end != 0)
641           einfo (_("%P%F: invalid --reserved-space value `%s'\''\n"), optarg);
642       }
643       break;
644
645     case OPTION_SPU_EXTRA_STACK:
646       {
647         char *end;
648         extra_stack_space = strtol (optarg, &end, 0);
649         if (*end != 0)
650           einfo (_("%P%F: invalid --extra-stack-space value `%s'\''\n"), optarg);
651       }
652       break;
653
654     case OPTION_SPU_NO_AUTO_OVERLAY:
655       auto_overlay = 0;
656       if (optarg != NULL)
657         {
658           struct tflist *tf;
659           size_t len;
660
661           if (tmp_file_list == NULL)
662             atexit (clean_tmp);
663
664           len = strlen (optarg) + 1;
665           tf = xmalloc (sizeof (*tf) - sizeof (tf->name) + len);
666           memcpy (tf->name, optarg, len);
667           tf->next = tmp_file_list;
668           tmp_file_list = tf;
669           break;
670         }
671       break;
672 '
673
674 LDEMUL_AFTER_OPEN=spu_after_open
675 LDEMUL_BEFORE_ALLOCATION=spu_before_allocation
676 LDEMUL_FINISH=gld${EMULATION_NAME}_finish
677 LDEMUL_CHOOSE_TARGET=gld${EMULATION_NAME}_choose_target