OSDN Git Service

2010-02-11 Richard Guenther <rguenther@suse.de>
[pf3gnuchains/gcc-fork.git] / gcc / lto / lto-elf.c
1 /* LTO routines for ELF object files.
2    Copyright 2009 Free Software Foundation, Inc.
3    Contributed by CodeSourcery, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "toplev.h"
25 #include <gelf.h>
26 #include "lto.h"
27 #include "tm.h"
28 #include "libiberty.h"
29 #include "ggc.h"
30 #include "lto-streamer.h"
31
32 /* Handle opening elf files on hosts, such as Windows, that may use 
33    text file handling that will break binary access.  */
34
35 #ifndef O_BINARY
36 # define O_BINARY 0
37 #endif
38
39
40 /* Initialize FILE, an LTO file object for FILENAME.  */
41 static void
42 lto_file_init (lto_file *file, const char *filename, off_t offset)
43 {
44   file->filename = filename;
45   file->offset = offset;
46 }
47
48 /* An ELF file.  */
49 struct lto_elf_file 
50 {
51   /* The base information.  */
52   lto_file base;
53
54   /* The system file descriptor for the file.  */
55   int fd;
56
57   /* The libelf descriptor for the file.  */
58   Elf *elf;
59
60   /* Section number of string table used for section names.  */
61   size_t sec_strtab;
62
63   /* Writable file members.  */
64
65   /* The currently active section.  */
66   Elf_Scn *scn;
67
68   /* The output stream for section header names.  */
69   struct lto_output_stream *shstrtab_stream;
70
71   /* Linked list of data which must be freed *after* the file has been
72      closed.  This is an annoying limitation of libelf.  */
73   struct lto_char_ptr_base *data;
74 };
75 typedef struct lto_elf_file lto_elf_file;
76
77 /* Stores executable header attributes which must be shared by all ELF files.
78    This is used for validating input files and populating output files.  */
79 static struct {
80   bool initialized;
81   /* 32 or 64 bits?  */
82   size_t bits;
83   unsigned char elf_ident[EI_NIDENT];
84   Elf64_Half elf_machine;
85 } cached_file_attrs;
86
87
88 /* Return the section header for SECTION.  The return value is never
89    NULL.  Call lto_elf_free_shdr to release the memory allocated.  */
90
91 static Elf64_Shdr *
92 lto_elf_get_shdr (Elf_Scn *section)
93 {
94   Elf64_Shdr *shdr;
95
96   switch (cached_file_attrs.bits)
97     {
98     case 32:
99       {
100         Elf32_Shdr *shdr32;
101
102         /* Read the 32-bit section header.  */
103         shdr32 = elf32_getshdr (section);
104         if (!shdr32)
105           fatal_error ("could not read section header: %s", elf_errmsg (0));
106
107         /* Transform it into a 64-bit section header.  */
108         shdr = XNEW (Elf64_Shdr);
109         shdr->sh_name = shdr32->sh_name;
110         shdr->sh_type = shdr32->sh_type;
111         shdr->sh_flags = shdr32->sh_flags;
112         shdr->sh_addr = shdr32->sh_addr;
113         shdr->sh_offset = shdr32->sh_offset;
114         shdr->sh_size = shdr32->sh_size;
115         shdr->sh_link = shdr32->sh_link;
116         shdr->sh_info = shdr32->sh_info;
117         shdr->sh_addralign = shdr32->sh_addralign;
118         shdr->sh_entsize  = shdr32->sh_entsize;
119         break;
120       }
121       break;
122
123     case 64:
124       shdr = elf64_getshdr (section);
125       if (!shdr)
126         fatal_error ("could not read section header: %s", elf_errmsg (0));
127       break;
128
129     default:
130       gcc_unreachable ();
131     }
132
133   return shdr;
134 }
135
136 /* Free SHDR, previously allocated by lto_elf_get_shdr.  */
137 static void
138 lto_elf_free_shdr (Elf64_Shdr *shdr)
139 {
140   if (cached_file_attrs.bits != 64)
141     free (shdr);
142 }
143
144
145 /* Returns a hash code for P.  */
146
147 static hashval_t
148 hash_name (const void *p)
149 {
150   const struct lto_section_slot *ds = (const struct lto_section_slot *) p;
151   return (hashval_t) htab_hash_string (ds->name);
152 }
153
154
155 /* Returns nonzero if P1 and P2 are equal.  */
156
157 static int
158 eq_name (const void *p1, const void *p2)
159 {
160   const struct lto_section_slot *s1 =
161     (const struct lto_section_slot *) p1;
162   const struct lto_section_slot *s2 =
163     (const struct lto_section_slot *) p2;
164
165   return strcmp (s1->name, s2->name) == 0;
166 }
167
168
169 /* Build a hash table whose key is the section names and whose data is
170    the start and size of each section in the .o file.  */
171
172 htab_t
173 lto_elf_build_section_table (lto_file *lto_file) 
174 {
175   lto_elf_file *elf_file = (lto_elf_file *)lto_file;
176   htab_t section_hash_table;
177   Elf_Scn *section;
178   size_t base_offset;
179
180   section_hash_table = htab_create (37, hash_name, eq_name, free);
181
182   base_offset = elf_getbase (elf_file->elf);
183   for (section = elf_getscn (elf_file->elf, 0);
184        section;
185        section = elf_nextscn (elf_file->elf, section)) 
186     {
187       Elf64_Shdr *shdr;
188       const char *name;
189       size_t offset;
190       char *new_name;
191       void **slot;
192       struct lto_section_slot s_slot;
193
194       /* Get the name of this section.  */
195       shdr = lto_elf_get_shdr (section);
196       offset = shdr->sh_name;
197       name = elf_strptr (elf_file->elf, 
198                          elf_file->sec_strtab,
199                          offset);
200
201       /* Only put lto stuff into the symtab.  */
202       if (strncmp (name, LTO_SECTION_NAME_PREFIX, 
203                    strlen (LTO_SECTION_NAME_PREFIX)) != 0)
204         {
205           lto_elf_free_shdr (shdr);
206           continue;
207         }
208
209       new_name = XNEWVEC (char, strlen (name) + 1);
210       strcpy (new_name, name);
211       s_slot.name = new_name;
212       slot = htab_find_slot (section_hash_table, &s_slot, INSERT);
213       if (*slot == NULL)
214         {
215           struct lto_section_slot *new_slot = XNEW (struct lto_section_slot);
216
217           new_slot->name = new_name;
218           /* The offset into the file for this section.  */
219           new_slot->start = base_offset + shdr->sh_offset;
220           new_slot->len = shdr->sh_size;
221           *slot = new_slot;
222         }
223       else
224         {
225           error ("two or more sections for %s:", new_name);
226           return NULL;
227         }
228
229       lto_elf_free_shdr (shdr);
230     }
231
232   return section_hash_table;
233 }
234
235
236 /* Initialize the section header of section SCN.  SH_NAME is the section name
237    as an index into the section header string table.  SH_TYPE is the section
238    type, an SHT_* macro from libelf headers.  */
239
240 #define DEFINE_INIT_SHDR(BITS)                                        \
241 static void                                                           \
242 init_shdr##BITS (Elf_Scn *scn, size_t sh_name, size_t sh_type)        \
243 {                                                                     \
244   Elf##BITS##_Shdr *shdr;                                             \
245                                                                       \
246   shdr = elf##BITS##_getshdr (scn);                                   \
247   if (!shdr)                                                          \
248     {                                                                 \
249       if (BITS == 32)                                                 \
250         fatal_error ("elf32_getshdr() failed: %s", elf_errmsg (-1));  \
251       else                                                            \
252         fatal_error ("elf64_getshdr() failed: %s", elf_errmsg (-1));  \
253     }                                                                 \
254                                                                       \
255   shdr->sh_name = sh_name;                                            \
256   shdr->sh_type = sh_type;                                            \
257   shdr->sh_addralign = POINTER_SIZE / BITS_PER_UNIT;                  \
258   shdr->sh_flags = 0;                                                 \
259   shdr->sh_entsize = 0;                                               \
260 }
261
262 DEFINE_INIT_SHDR (32)
263 DEFINE_INIT_SHDR (64)
264
265 static bool first_data_block;
266
267 /* Begin a new ELF section named NAME with type TYPE in the current output
268    file.  TYPE is an SHT_* macro from the libelf headers.  */
269
270 static void
271 lto_elf_begin_section_with_type (const char *name, size_t type)
272 {
273   lto_elf_file *file;
274   Elf_Scn *scn;
275   size_t sh_name;
276
277   /* Grab the current output file and do some basic assertion checking.  */
278   file = (lto_elf_file *) lto_get_current_out_file (),
279   gcc_assert (file);
280   gcc_assert (file->elf);
281   gcc_assert (!file->scn);
282
283   /* Create a new section.  */
284   scn = elf_newscn (file->elf);
285   if (!scn)
286     fatal_error ("could not create a new ELF section: %s", elf_errmsg (-1));
287   file->scn = scn;
288
289   /* Add a string table entry and record the offset.  */
290   gcc_assert (file->shstrtab_stream);
291   sh_name = file->shstrtab_stream->total_size;
292   lto_output_data_stream (file->shstrtab_stream, name, strlen (name) + 1);
293
294   /* Initialize the section header.  */
295   switch (cached_file_attrs.bits)
296     {
297     case 32:
298       init_shdr32 (scn, sh_name, type);
299       break;
300
301     case 64:
302       init_shdr64 (scn, sh_name, type);
303       break;
304
305     default:
306       gcc_unreachable ();
307     }
308
309   first_data_block = true;
310 }
311
312
313 /* Begin a new ELF section named NAME in the current output file.  */
314
315 void
316 lto_elf_begin_section (const char *name)
317 {
318   lto_elf_begin_section_with_type (name, SHT_PROGBITS);
319 }
320
321
322 /* Append DATA of length LEN to the current output section.  BASE is a pointer
323    to the output page containing DATA.  It is freed once the output file has
324    been written.  */
325
326 void
327 lto_elf_append_data (const void *data, size_t len, void *block)
328 {
329   lto_elf_file *file;
330   Elf_Data *elf_data;
331   struct lto_char_ptr_base *base = (struct lto_char_ptr_base *) block;
332
333   /* Grab the current output file and do some basic assertion checking.  */
334   file = (lto_elf_file *) lto_get_current_out_file ();
335   gcc_assert (file);
336   gcc_assert (file->scn);
337
338   elf_data = elf_newdata (file->scn);
339   if (!elf_data)
340     fatal_error ("could not append data to ELF section: %s", elf_errmsg (-1));
341
342   if (first_data_block)
343     {
344       elf_data->d_align = POINTER_SIZE / BITS_PER_UNIT;
345       first_data_block = false;
346     }
347   else
348     elf_data->d_align = 1;
349   elf_data->d_buf = CONST_CAST (void *, data);
350   elf_data->d_off = 0LL;
351   elf_data->d_size = len;
352   elf_data->d_type = ELF_T_BYTE;
353   elf_data->d_version = EV_CURRENT;
354
355   base->ptr = (char *)file->data;
356   file->data = base;
357 }
358
359
360 /* End the current output section.  This just does some assertion checking
361    and sets the current output file's scn member to NULL.  */
362
363 void
364 lto_elf_end_section (void)
365 {
366   lto_elf_file *file;
367
368   /* Grab the current output file and validate some basic assertions.  */
369   file = (lto_elf_file *) lto_get_current_out_file ();
370   gcc_assert (file);
371   gcc_assert (file->scn);
372
373   file->scn = NULL;
374 }
375
376
377 /* Validate's ELF_FILE's executable header and, if cached_file_attrs is
378    uninitialized, caches the architecture.  */
379
380 #define DEFINE_VALIDATE_EHDR(BITS)                              \
381 static bool                                                     \
382 validate_ehdr##BITS (lto_elf_file *elf_file)                    \
383 {                                                               \
384   Elf##BITS##_Ehdr *elf_header;                                 \
385                                                                 \
386   elf_header = elf##BITS##_getehdr (elf_file->elf);             \
387   if (!elf_header)                                              \
388     {                                                           \
389       error ("could not read ELF header: %s", elf_errmsg (0));  \
390       return false;                                             \
391     }                                                           \
392                                                                 \
393   if (elf_header->e_type != ET_REL)                             \
394     {                                                           \
395       error ("not a relocatable ELF object file");              \
396       return false;                                             \
397     }                                                           \
398                                                                 \
399   if (!cached_file_attrs.initialized)                           \
400     cached_file_attrs.elf_machine = elf_header->e_machine;      \
401                                                                 \
402   if (cached_file_attrs.elf_machine != elf_header->e_machine)   \
403     {                                                           \
404       error ("inconsistent file architecture detected");        \
405       return false;                                             \
406     }                                                           \
407                                                                 \
408   return true;                                                  \
409 }
410
411 DEFINE_VALIDATE_EHDR (32)
412 DEFINE_VALIDATE_EHDR (64)
413
414
415 /* Validate's ELF_FILE's executable header and, if cached_file_attrs is
416    uninitialized, caches the results.  Also records the section header string
417    table's section index.  Returns true on success or false on failure.  */
418
419 static bool
420 validate_file (lto_elf_file *elf_file)
421 {
422   const char *elf_ident;
423
424   /* Some aspects of the libelf API are dependent on whether the
425      object file is a 32-bit or 64-bit file.  Determine which kind of
426      file this is now.  */
427   elf_ident = elf_getident (elf_file->elf, NULL);
428   if (!elf_ident)
429     {
430       error ("could not read ELF identification information: %s",
431               elf_errmsg (0));
432       return false;
433              
434     }
435
436   if (!cached_file_attrs.initialized)
437     {
438       switch (elf_ident[EI_CLASS])
439         {
440         case ELFCLASS32:
441           cached_file_attrs.bits = 32;
442           break;
443
444         case ELFCLASS64:
445           cached_file_attrs.bits = 64;
446           break;
447
448         default:
449           error ("unsupported ELF file class");
450           return false;
451         }
452
453       memcpy (cached_file_attrs.elf_ident, elf_ident,
454               sizeof cached_file_attrs.elf_ident);
455     }
456
457   if (memcmp (elf_ident, cached_file_attrs.elf_ident,
458               sizeof cached_file_attrs.elf_ident))
459     return false;
460
461   /* Check that the input file is a relocatable object file with the correct
462      architecture.  */
463   switch (cached_file_attrs.bits)
464     {
465     case 32:
466       if (!validate_ehdr32 (elf_file))
467         return false;
468       break;
469
470     case 64:
471       if (!validate_ehdr64 (elf_file))
472         return false;
473       break;
474
475     default:
476       gcc_unreachable ();
477     }
478
479   /* Read the string table used for section header names.  */
480   if (elf_getshdrstrndx (elf_file->elf, &elf_file->sec_strtab) == -1)
481     {
482       error ("could not locate ELF string table: %s", elf_errmsg (0));
483       return false;
484     }
485
486   cached_file_attrs.initialized = true;
487   return true;
488 }
489
490
491 /* Helper functions used by init_ehdr.  Initialize ELF_FILE's executable
492    header using cached data from previously read files.  */
493
494 #define DEFINE_INIT_EHDR(BITS)                                        \
495 static void                                                           \
496 init_ehdr##BITS (lto_elf_file *elf_file)                              \
497 {                                                                     \
498   Elf##BITS##_Ehdr *ehdr;                                             \
499                                                                       \
500   gcc_assert (cached_file_attrs.bits);                                \
501                                                                       \
502   ehdr = elf##BITS##_newehdr (elf_file->elf);                         \
503   if (!ehdr)                                                          \
504     {                                                                 \
505       if (BITS == 32)                                                 \
506         fatal_error ("elf32_newehdr() failed: %s", elf_errmsg (-1));  \
507       else                                                            \
508         fatal_error ("elf64_newehdr() failed: %s", elf_errmsg (-1));  \
509     }                                                                 \
510                                                                       \
511   memcpy (ehdr->e_ident, cached_file_attrs.elf_ident,                 \
512           sizeof cached_file_attrs.elf_ident);                        \
513   ehdr->e_type = ET_REL;                                              \
514   ehdr->e_version = EV_CURRENT;                                       \
515   ehdr->e_machine = cached_file_attrs.elf_machine;                    \
516 }
517
518 DEFINE_INIT_EHDR (32)
519 DEFINE_INIT_EHDR (64)
520
521
522 /* Initialize ELF_FILE's executable header using cached data from previously
523    read files.  */
524
525 static void
526 init_ehdr (lto_elf_file *elf_file)
527 {
528   switch (cached_file_attrs.bits)
529     {
530     case 32:
531       init_ehdr32 (elf_file);
532       break;
533
534     case 64:
535       init_ehdr64 (elf_file);
536       break;
537
538     default:
539       gcc_unreachable ();
540     }
541 }
542
543 /* Open ELF file FILENAME.  If WRITABLE is true, the file is opened for write
544    and, if necessary, created.  Otherwise, the file is opened for reading.
545    Returns the opened file.  */
546
547 lto_file *
548 lto_elf_file_open (const char *filename, bool writable)
549 {
550   lto_elf_file *elf_file;
551   lto_file *result = NULL;
552   off_t offset;
553   long loffset;
554   off_t header_offset;
555   const char *offset_p;
556   char *fname;
557   int consumed;
558
559   offset_p = strrchr (filename, '@');
560   if (offset_p
561       && offset_p != filename
562       && sscanf (offset_p, "@%li%n", &loffset, &consumed) >= 1
563       && strlen (offset_p) == (unsigned int)consumed)
564     {
565       fname = (char *) xmalloc (offset_p - filename + 1);
566       memcpy (fname, filename, offset_p - filename);
567       fname[offset_p - filename] = '\0';
568       offset = (off_t)loffset;
569       /* elf_rand expects the offset to point to the ar header, not the
570          object itself. Subtract the size of the ar header (60 bytes).
571          We don't uses sizeof (struct ar_hd) to avoid including ar.h */
572       header_offset = offset - 60;
573     }
574   else
575     {
576       fname = xstrdup (filename);
577       offset = 0;
578       header_offset = 0;
579     }
580
581   /* Set up.  */
582   elf_file = XCNEW (lto_elf_file);
583   result = (lto_file *) elf_file;
584   lto_file_init (result, fname, offset);
585   elf_file->fd = -1;
586
587   /* Open the file.  */
588   elf_file->fd = open (fname, writable ? O_WRONLY|O_CREAT|O_BINARY 
589                                        : O_RDONLY|O_BINARY, 0666);
590   if (elf_file->fd == -1)
591     {
592       error ("could not open file %s", fname);
593       goto fail;
594     }
595
596   /* Initialize the ELF library.  */
597   if (elf_version (EV_CURRENT) == EV_NONE)
598     {
599       error ("ELF library is older than that used when building GCC");
600       goto fail;
601     }
602
603   /* Open the ELF file descriptor.  */
604   elf_file->elf = elf_begin (elf_file->fd, writable ? ELF_C_WRITE : ELF_C_READ,
605                              NULL);
606   if (!elf_file->elf)
607     {
608       error ("could not open ELF file: %s", elf_errmsg (0));
609       goto fail;
610     }
611
612   if (offset != 0)
613     {
614       Elf *e;
615       off_t t = elf_rand (elf_file->elf, header_offset);
616       if (t != header_offset)
617         {
618           error ("could not seek in archive");
619           goto fail;
620         }
621
622       e = elf_begin (elf_file->fd, ELF_C_READ, elf_file->elf);
623       if (e == NULL)
624         {
625           error("could not find archive member");
626           goto fail;
627         }
628       elf_end (elf_file->elf);
629       elf_file->elf = e;
630     }
631
632   if (writable)
633     {
634       init_ehdr (elf_file);
635       elf_file->shstrtab_stream = XCNEW (struct lto_output_stream);
636       /* Output an empty string to the section header table.  This becomes the
637          name of the initial NULL section.  */
638       lto_output_1_stream (elf_file->shstrtab_stream, '\0');
639     }
640   else
641     if (!validate_file (elf_file))
642       goto fail;
643
644   return result;
645
646  fail:
647   if (result)
648     lto_elf_file_close (result);
649   return NULL;
650 }
651
652
653 /* Close ELF file FILE and clean up any associated data structures.  If FILE
654    was opened for writing, the file's ELF data is written at this time, and
655    any cached data buffers are freed.  */
656
657 void
658 lto_elf_file_close (lto_file *file)
659 {
660   lto_elf_file *elf_file = (lto_elf_file *) file;
661   struct lto_char_ptr_base *cur, *tmp;
662
663   /* Write the ELF section header string table.  */
664   if (elf_file->shstrtab_stream)
665     {
666       size_t strtab;
667       GElf_Ehdr *ehdr_p, ehdr_buf;
668       lto_file *old_file = lto_set_current_out_file (file);
669
670       lto_elf_begin_section_with_type (".shstrtab", SHT_STRTAB);
671       ehdr_p = gelf_getehdr (elf_file->elf, &ehdr_buf);
672       if (ehdr_p == NULL)
673         fatal_error ("gelf_getehdr() failed: %s", elf_errmsg (-1));
674       strtab = elf_ndxscn (elf_file->scn);
675       if (strtab < SHN_LORESERVE)
676         ehdr_p->e_shstrndx = strtab;
677       else
678         {
679           GElf_Shdr *shdr_p, shdr_buf;
680           Elf_Scn *scn_p = elf_getscn (elf_file->elf, 0);
681           if (scn_p == NULL)
682             fatal_error ("elf_getscn() failed: %s", elf_errmsg (-1));
683           shdr_p = gelf_getshdr (scn_p, &shdr_buf);
684           if (shdr_p == NULL)
685             fatal_error ("gelf_getshdr() failed: %s", elf_errmsg (-1));
686           shdr_p->sh_link = strtab;
687           if (gelf_update_shdr (scn_p, shdr_p) == 0)
688             fatal_error ("gelf_update_shdr() failed: %s", elf_errmsg (-1));
689           ehdr_p->e_shstrndx = SHN_XINDEX;
690         }
691       if (gelf_update_ehdr (elf_file->elf, ehdr_p) == 0)
692         fatal_error ("gelf_update_ehdr() failed: %s", elf_errmsg (-1));
693       lto_write_stream (elf_file->shstrtab_stream);
694       lto_elf_end_section ();
695
696       lto_set_current_out_file (old_file);
697       free (elf_file->shstrtab_stream);
698
699       if (elf_update (elf_file->elf, ELF_C_WRITE) < 0)
700         fatal_error ("elf_update() failed: %s", elf_errmsg (-1));
701     }
702
703   if (elf_file->elf)
704     elf_end (elf_file->elf);
705   if (elf_file->fd != -1)
706     close (elf_file->fd);
707
708   /* Free any ELF data buffers.  */
709   cur = elf_file->data;
710   while (cur)
711     {
712       tmp = cur;
713       cur = (struct lto_char_ptr_base *) cur->ptr;
714       free (tmp);
715     }
716
717   free (file);
718 }
719
720
721 /* The current output file.  */
722 static lto_file *current_out_file;
723
724
725 /* Sets the current output file to FILE.  Returns the old output file or
726    NULL.  */
727
728 lto_file *
729 lto_set_current_out_file (lto_file *file)
730 {
731   lto_file *old_file = current_out_file;
732   current_out_file = file;
733   return old_file;
734 }
735
736
737 /* Returns the current output file.  */
738
739 lto_file *
740 lto_get_current_out_file (void)
741 {
742   return current_out_file;
743 }