simple-object-elf.c revision 1.6
1/* simple-object-elf.c -- routines to manipulate ELF object files.
2   Copyright (C) 2010-2018 Free Software Foundation, Inc.
3   Written by Ian Lance Taylor, Google.
4
5This program is free software; you can redistribute it and/or modify it
6under the terms of the GNU General Public License as published by the
7Free Software Foundation; either version 2, or (at your option) any
8later version.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program; if not, write to the Free Software
17Foundation, 51 Franklin Street - Fifth Floor,
18Boston, MA 02110-1301, USA.  */
19
20#include "config.h"
21#include "libiberty.h"
22#include "simple-object.h"
23
24#include <errno.h>
25#include <stddef.h>
26
27#ifdef HAVE_STDLIB_H
28#include <stdlib.h>
29#endif
30
31#ifdef HAVE_STDINT_H
32#include <stdint.h>
33#endif
34
35#ifdef HAVE_STRING_H
36#include <string.h>
37#endif
38
39#ifdef HAVE_INTTYPES_H
40#include <inttypes.h>
41#endif
42
43#include "simple-object-common.h"
44
45/* ELF structures and constants.  */
46
47/* 32-bit ELF file header.  */
48
49typedef struct {
50  unsigned char	e_ident[16];		/* ELF "magic number" */
51  unsigned char	e_type[2];		/* Identifies object file type */
52  unsigned char	e_machine[2];		/* Specifies required architecture */
53  unsigned char	e_version[4];		/* Identifies object file version */
54  unsigned char	e_entry[4];		/* Entry point virtual address */
55  unsigned char	e_phoff[4];		/* Program header table file offset */
56  unsigned char	e_shoff[4];		/* Section header table file offset */
57  unsigned char	e_flags[4];		/* Processor-specific flags */
58  unsigned char	e_ehsize[2];		/* ELF header size in bytes */
59  unsigned char	e_phentsize[2];		/* Program header table entry size */
60  unsigned char	e_phnum[2];		/* Program header table entry count */
61  unsigned char	e_shentsize[2];		/* Section header table entry size */
62  unsigned char	e_shnum[2];		/* Section header table entry count */
63  unsigned char	e_shstrndx[2];		/* Section header string table index */
64} Elf32_External_Ehdr;
65
66/* 64-bit ELF file header.  */
67
68typedef struct {
69  unsigned char	e_ident[16];		/* ELF "magic number" */
70  unsigned char	e_type[2];		/* Identifies object file type */
71  unsigned char	e_machine[2];		/* Specifies required architecture */
72  unsigned char	e_version[4];		/* Identifies object file version */
73  unsigned char	e_entry[8];		/* Entry point virtual address */
74  unsigned char	e_phoff[8];		/* Program header table file offset */
75  unsigned char	e_shoff[8];		/* Section header table file offset */
76  unsigned char	e_flags[4];		/* Processor-specific flags */
77  unsigned char	e_ehsize[2];		/* ELF header size in bytes */
78  unsigned char	e_phentsize[2];		/* Program header table entry size */
79  unsigned char	e_phnum[2];		/* Program header table entry count */
80  unsigned char	e_shentsize[2];		/* Section header table entry size */
81  unsigned char	e_shnum[2];		/* Section header table entry count */
82  unsigned char	e_shstrndx[2];		/* Section header string table index */
83} Elf64_External_Ehdr;
84
85/* Indexes and values in e_ident field of Ehdr.  */
86
87#define EI_MAG0		0	/* File identification byte 0 index */
88#define ELFMAG0		   0x7F	/* Magic number byte 0 */
89
90#define EI_MAG1		1	/* File identification byte 1 index */
91#define ELFMAG1		    'E'	/* Magic number byte 1 */
92
93#define EI_MAG2		2	/* File identification byte 2 index */
94#define ELFMAG2		    'L'	/* Magic number byte 2 */
95
96#define EI_MAG3		3	/* File identification byte 3 index */
97#define ELFMAG3		    'F'	/* Magic number byte 3 */
98
99#define EI_CLASS	4	/* File class */
100#define ELFCLASSNONE	      0	/* Invalid class */
101#define ELFCLASS32	      1	/* 32-bit objects */
102#define ELFCLASS64	      2	/* 64-bit objects */
103
104#define EI_DATA		5	/* Data encoding */
105#define ELFDATANONE	      0	/* Invalid data encoding */
106#define ELFDATA2LSB	      1	/* 2's complement, little endian */
107#define ELFDATA2MSB	      2	/* 2's complement, big endian */
108
109#define EI_VERSION	6	/* File version */
110#define EV_CURRENT	1		/* Current version */
111
112#define EI_OSABI	7	/* Operating System/ABI indication */
113
114/* Values for e_type field of Ehdr.  */
115
116#define ET_REL		1	/* Relocatable file */
117
118/* Values for e_machine field of Ehdr.  */
119
120#define EM_SPARC	  2	/* SUN SPARC */
121#define EM_SPARC32PLUS	 18	/* Sun's "v8plus" */
122
123/* Special section index values.  */
124
125#define SHN_UNDEF	0		/* Undefined section */
126#define SHN_LORESERVE	0xFF00		/* Begin range of reserved indices */
127#define SHN_COMMON	0xFFF2	/* Associated symbol is in common */
128#define SHN_XINDEX	0xFFFF		/* Section index is held elsewhere */
129#define SHN_HIRESERVE	0xffff		/* End of reserved indices */
130
131
132/* 32-bit ELF program header.  */
133
134typedef struct {
135  unsigned char	p_type[4];		/* Identifies program segment type */
136  unsigned char	p_offset[4];		/* Segment file offset */
137  unsigned char	p_vaddr[4];		/* Segment virtual address */
138  unsigned char	p_paddr[4];		/* Segment physical address */
139  unsigned char	p_filesz[4];		/* Segment size in file */
140  unsigned char	p_memsz[4];		/* Segment size in memory */
141  unsigned char	p_flags[4];		/* Segment flags */
142  unsigned char	p_align[4];		/* Segment alignment, file & memory */
143} Elf32_External_Phdr;
144
145/* 64-bit ELF program header.  */
146
147typedef struct {
148  unsigned char	p_type[4];		/* Identifies program segment type */
149  unsigned char	p_flags[4];		/* Segment flags */
150  unsigned char	p_offset[8];		/* Segment file offset */
151  unsigned char	p_vaddr[8];		/* Segment virtual address */
152  unsigned char	p_paddr[8];		/* Segment physical address */
153  unsigned char	p_filesz[8];		/* Segment size in file */
154  unsigned char	p_memsz[8];		/* Segment size in memory */
155  unsigned char	p_align[8];		/* Segment alignment, file & memory */
156} Elf64_External_Phdr;
157
158/* 32-bit ELF section header */
159
160typedef struct {
161  unsigned char	sh_name[4];		/* Section name, index in string tbl */
162  unsigned char	sh_type[4];		/* Type of section */
163  unsigned char	sh_flags[4];		/* Miscellaneous section attributes */
164  unsigned char	sh_addr[4];		/* Section virtual addr at execution */
165  unsigned char	sh_offset[4];		/* Section file offset */
166  unsigned char	sh_size[4];		/* Size of section in bytes */
167  unsigned char	sh_link[4];		/* Index of another section */
168  unsigned char	sh_info[4];		/* Additional section information */
169  unsigned char	sh_addralign[4];	/* Section alignment */
170  unsigned char	sh_entsize[4];		/* Entry size if section holds table */
171} Elf32_External_Shdr;
172
173/* 64-bit ELF section header.  */
174
175typedef struct {
176  unsigned char	sh_name[4];		/* Section name, index in string tbl */
177  unsigned char	sh_type[4];		/* Type of section */
178  unsigned char	sh_flags[8];		/* Miscellaneous section attributes */
179  unsigned char	sh_addr[8];		/* Section virtual addr at execution */
180  unsigned char	sh_offset[8];		/* Section file offset */
181  unsigned char	sh_size[8];		/* Size of section in bytes */
182  unsigned char	sh_link[4];		/* Index of another section */
183  unsigned char	sh_info[4];		/* Additional section information */
184  unsigned char	sh_addralign[8];	/* Section alignment */
185  unsigned char	sh_entsize[8];		/* Entry size if section holds table */
186} Elf64_External_Shdr;
187
188/* Values for sh_type field.  */
189
190#define SHT_NULL	0		/* Section header table entry unused */
191#define SHT_PROGBITS	1		/* Program data */
192#define SHT_SYMTAB	2		/* Link editing symbol table */
193#define SHT_STRTAB	3		/* A string table */
194#define SHT_RELA	4		/* Relocation entries with addends */
195#define SHT_REL		9		/* Relocation entries, no addends */
196#define SHT_GROUP	17		/* Section contains a section group */
197#define SHT_SYMTAB_SHNDX 18		/* Extended section indeces */
198
199/* Values for sh_flags field.  */
200
201#define SHF_INFO_LINK	0x00000040	/* `sh_info' contains SHT index */
202#define SHF_EXECINSTR	0x00000004	/* Executable section.  */
203#define SHF_EXCLUDE	0x80000000	/* Link editor is to exclude this
204					   section from executable and
205					   shared library that it builds
206					   when those objects are not to be
207					   further relocated.  */
208/* Symbol table entry.  */
209
210typedef struct
211{
212  unsigned char st_name[4];                /* Symbol name (string tbl index) */
213  unsigned char st_value[4];               /* Symbol value */
214  unsigned char st_size[4];                /* Symbol size */
215  unsigned char st_info;                /* Symbol type and binding */
216  unsigned char st_other;               /* Symbol visibility */
217  unsigned char st_shndx[2];               /* Section index */
218} Elf32_External_Sym;
219
220typedef struct
221{
222  unsigned char st_name[4];                /* Symbol name (string tbl index) */
223  unsigned char st_info;                /* Symbol type and binding */
224  unsigned char st_other;               /* Symbol visibility */
225  unsigned char st_shndx[2];               /* Section index */
226  unsigned char st_value[8];               /* Symbol value */
227  unsigned char st_size[8];                /* Symbol size */
228} Elf64_External_Sym;
229
230#define ELF_ST_BIND(val)              (((unsigned char) (val)) >> 4)
231#define ELF_ST_TYPE(val)              ((val) & 0xf)
232#define ELF_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
233
234#define STT_NOTYPE	0	/* Symbol type is unspecified */
235#define STT_OBJECT	1	/* Symbol is a data object */
236#define STT_FUNC	2	/* Symbol is a code object */
237#define STT_TLS		6	/* Thread local data object */
238#define STT_GNU_IFUNC	10	/* Symbol is an indirect code object */
239
240#define STB_LOCAL	0	/* Local symbol */
241#define STB_GLOBAL	1	/* Global symbol */
242#define STB_WEAK	2	/* Weak global */
243
244#define STV_DEFAULT	0	/* Visibility is specified by binding type */
245#define STV_HIDDEN	2	/* Can only be seen inside currect component */
246
247/* Functions to fetch and store different ELF types, depending on the
248   endianness and size.  */
249
250struct elf_type_functions
251{
252  unsigned short (*fetch_Elf_Half) (const unsigned char *);
253  unsigned int (*fetch_Elf_Word) (const unsigned char *);
254  ulong_type (*fetch_Elf_Addr) (const unsigned char *);
255  void (*set_Elf_Half) (unsigned char *, unsigned short);
256  void (*set_Elf_Word) (unsigned char *, unsigned int);
257  void (*set_Elf_Addr) (unsigned char *, ulong_type);
258};
259
260static const struct elf_type_functions elf_big_32_functions =
261{
262  simple_object_fetch_big_16,
263  simple_object_fetch_big_32,
264  simple_object_fetch_big_32_ulong,
265  simple_object_set_big_16,
266  simple_object_set_big_32,
267  simple_object_set_big_32_ulong
268};
269
270static const struct elf_type_functions elf_little_32_functions =
271{
272  simple_object_fetch_little_16,
273  simple_object_fetch_little_32,
274  simple_object_fetch_little_32_ulong,
275  simple_object_set_little_16,
276  simple_object_set_little_32,
277  simple_object_set_little_32_ulong
278};
279
280#ifdef UNSIGNED_64BIT_TYPE
281
282static const struct elf_type_functions elf_big_64_functions =
283{
284  simple_object_fetch_big_16,
285  simple_object_fetch_big_32,
286  simple_object_fetch_big_64,
287  simple_object_set_big_16,
288  simple_object_set_big_32,
289  simple_object_set_big_64
290};
291
292static const struct elf_type_functions elf_little_64_functions =
293{
294  simple_object_fetch_little_16,
295  simple_object_fetch_little_32,
296  simple_object_fetch_little_64,
297  simple_object_set_little_16,
298  simple_object_set_little_32,
299  simple_object_set_little_64
300};
301
302#endif
303
304/* Hideous macro to fetch the value of a field from an external ELF
305   struct of some sort.  TYPEFUNCS is the set of type functions.
306   BUFFER points to the external data.  STRUCTTYPE is the appropriate
307   struct type.  FIELD is a field within the struct.  TYPE is the type
308   of the field in the struct: Elf_Half, Elf_Word, or Elf_Addr.  */
309
310#define ELF_FETCH_STRUCT_FIELD(TYPEFUNCS, STRUCTTYPE, FIELD, BUFFER, TYPE) \
311  ((TYPEFUNCS)->fetch_ ## TYPE ((BUFFER) + offsetof (STRUCTTYPE, FIELD)))
312
313/* Even more hideous macro to fetch the value of FIELD from BUFFER.
314   SIZE is 32 or 64.  STRUCTTYPE is the name of the struct from
315   elf/external.h: Ehdr, Shdr, etc.  FIELD is the name of a field in
316   the struct.  TYPE is the type of the field in the struct: Elf_Half,
317   Elf_Word, or Elf_Addr.  */
318
319#define ELF_FETCH_SIZED_FIELD(TYPEFUNCS, SIZE, STRUCTTYPE, BUFFER,	\
320			      FIELD, TYPE)				\
321  ELF_FETCH_STRUCT_FIELD (TYPEFUNCS,					\
322			  Elf ## SIZE ## _External_ ## STRUCTTYPE,	\
323			  FIELD, BUFFER, TYPE)
324
325/* Like ELF_FETCH_SIZED_FIELD but taking an ELFCLASS value.  */
326
327#define ELF_FETCH_FIELD(TYPEFUNCS, CLASS, STRUCTTYPE, BUFFER,		\
328			FIELD, TYPE)					\
329  ((CLASS) == ELFCLASS32						\
330    ? ELF_FETCH_SIZED_FIELD (TYPEFUNCS, 32, STRUCTTYPE, BUFFER, FIELD,	\
331			     TYPE)					\
332    : ELF_FETCH_SIZED_FIELD (TYPEFUNCS, 64, STRUCTTYPE, BUFFER, FIELD,	\
333			     TYPE))
334
335/* Hideous macro to set the value of a field in an external ELF
336   structure to VAL.  TYPEFUNCS is the set of type functions.  BUFFER
337   points to the external data.  STRUCTTYPE is the appropriate
338   structure type.  FIELD is a field within the struct.  TYPE is the
339   type of the field in the struct: Elf_Half, Elf_Word, or
340   Elf_Addr.  */
341
342#define ELF_SET_STRUCT_FIELD(TYPEFUNCS, STRUCTTYPE, FIELD, BUFFER, TYPE, VAL) \
343  (TYPEFUNCS)->set_ ## TYPE ((BUFFER) + offsetof (STRUCTTYPE, FIELD), (VAL))
344
345/* Even more hideous macro to set the value of FIELD in BUFFER to VAL.
346   SIZE is 32 or 64.  STRUCTTYPE is the name of the struct from
347   elf/external.h: Ehdr, Shdr, etc.  FIELD is the name of a field in
348   the struct.  TYPE is the type of the field in the struct: Elf_Half,
349   Elf_Word, or Elf_Addr.  */
350
351#define ELF_SET_SIZED_FIELD(TYPEFUNCS, SIZE, STRUCTTYPE, BUFFER, FIELD, \
352			    TYPE, VAL)					\
353  ELF_SET_STRUCT_FIELD (TYPEFUNCS,					\
354			Elf ## SIZE ## _External_ ## STRUCTTYPE,	\
355			FIELD, BUFFER, TYPE, VAL)
356
357/* Like ELF_SET_SIZED_FIELD but taking an ELFCLASS value.  */
358
359#define ELF_SET_FIELD(TYPEFUNCS, CLASS, STRUCTTYPE, BUFFER, FIELD,	\
360		      TYPE, VAL)					\
361  ((CLASS) == ELFCLASS32						\
362    ? ELF_SET_SIZED_FIELD (TYPEFUNCS, 32, STRUCTTYPE, BUFFER, FIELD,	\
363			   TYPE, VAL)					\
364    : ELF_SET_SIZED_FIELD (TYPEFUNCS, 64, STRUCTTYPE, BUFFER, FIELD,	\
365			   TYPE, VAL))
366
367/* Private data for an simple_object_read.  */
368
369struct simple_object_elf_read
370{
371  /* Type functions.  */
372  const struct elf_type_functions* type_functions;
373  /* Elf data.  */
374  unsigned char ei_data;
375  /* Elf class.  */
376  unsigned char ei_class;
377  /* ELF OS ABI.  */
378  unsigned char ei_osabi;
379  /* Elf machine number.  */
380  unsigned short machine;
381  /* Processor specific flags.  */
382  unsigned int flags;
383  /* File offset of section headers.  */
384  ulong_type shoff;
385  /* Number of sections.  */
386  unsigned int shnum;
387  /* Index of string table section header.  */
388  unsigned int shstrndx;
389};
390
391/* Private data for an simple_object_attributes.  */
392
393struct simple_object_elf_attributes
394{
395  /* Type functions.  */
396  const struct elf_type_functions* type_functions;
397  /* Elf data.  */
398  unsigned char ei_data;
399  /* Elf class.  */
400  unsigned char ei_class;
401  /* ELF OS ABI.  */
402  unsigned char ei_osabi;
403  /* Elf machine number.  */
404  unsigned short machine;
405  /* Processor specific flags.  */
406  unsigned int flags;
407};
408
409/* Private data for an simple_object_write.  */
410
411struct simple_object_elf_write
412{
413  struct simple_object_elf_attributes attrs;
414  unsigned char *shdrs;
415};
416
417/* See if we have an ELF file.  */
418
419static void *
420simple_object_elf_match (unsigned char header[SIMPLE_OBJECT_MATCH_HEADER_LEN],
421			 int descriptor, off_t offset,
422			 const char *segment_name ATTRIBUTE_UNUSED,
423			 const char **errmsg, int *err)
424{
425  unsigned char ei_data;
426  unsigned char ei_class;
427  const struct elf_type_functions *type_functions;
428  unsigned char ehdr[sizeof (Elf64_External_Ehdr)];
429  struct simple_object_elf_read *eor;
430
431  if (header[EI_MAG0] != ELFMAG0
432      || header[EI_MAG1] != ELFMAG1
433      || header[EI_MAG2] != ELFMAG2
434      || header[EI_MAG3] != ELFMAG3
435      || header[EI_VERSION] != EV_CURRENT)
436    {
437      *errmsg = NULL;
438      *err = 0;
439      return NULL;
440    }
441
442  ei_data = header[EI_DATA];
443  if (ei_data != ELFDATA2LSB && ei_data != ELFDATA2MSB)
444    {
445      *errmsg = "unknown ELF endianness";
446      *err = 0;
447      return NULL;
448    }
449
450  ei_class = header[EI_CLASS];
451  switch (ei_class)
452    {
453    case ELFCLASS32:
454      type_functions = (ei_data == ELFDATA2LSB
455			? &elf_little_32_functions
456			: &elf_big_32_functions);
457      break;
458
459    case ELFCLASS64:
460#ifndef UNSIGNED_64BIT_TYPE
461      *errmsg = "64-bit ELF objects not supported";
462      *err = 0;
463      return NULL;
464#else
465      type_functions = (ei_data == ELFDATA2LSB
466			? &elf_little_64_functions
467			: &elf_big_64_functions);
468      break;
469#endif
470
471    default:
472      *errmsg = "unrecognized ELF size";
473      *err = 0;
474      return NULL;
475    }
476
477  if (!simple_object_internal_read (descriptor, offset, ehdr, sizeof ehdr,
478				    errmsg, err))
479    return NULL;
480
481  eor = XNEW (struct simple_object_elf_read);
482  eor->type_functions = type_functions;
483  eor->ei_data = ei_data;
484  eor->ei_class = ei_class;
485  eor->ei_osabi = header[EI_OSABI];
486  eor->machine = ELF_FETCH_FIELD (type_functions, ei_class, Ehdr, ehdr,
487				  e_machine, Elf_Half);
488  eor->flags = ELF_FETCH_FIELD (type_functions, ei_class, Ehdr, ehdr,
489				e_flags, Elf_Word);
490  eor->shoff = ELF_FETCH_FIELD (type_functions, ei_class, Ehdr, ehdr,
491				e_shoff, Elf_Addr);
492  eor->shnum = ELF_FETCH_FIELD (type_functions, ei_class, Ehdr, ehdr,
493				e_shnum, Elf_Half);
494  eor->shstrndx = ELF_FETCH_FIELD (type_functions, ei_class, Ehdr, ehdr,
495				   e_shstrndx, Elf_Half);
496
497  if ((eor->shnum == 0 || eor->shstrndx == SHN_XINDEX)
498      && eor->shoff != 0)
499    {
500      unsigned char shdr[sizeof (Elf64_External_Shdr)];
501
502      /* Object file has more than 0xffff sections.  */
503
504      if (!simple_object_internal_read (descriptor, offset + eor->shoff, shdr,
505					(ei_class == ELFCLASS32
506					 ? sizeof (Elf32_External_Shdr)
507					 : sizeof (Elf64_External_Shdr)),
508					errmsg, err))
509	{
510	  XDELETE (eor);
511	  return NULL;
512	}
513
514      if (eor->shnum == 0)
515	eor->shnum = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
516				      shdr, sh_size, Elf_Addr);
517
518      if (eor->shstrndx == SHN_XINDEX)
519	{
520	  eor->shstrndx = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
521					   shdr, sh_link, Elf_Word);
522
523	  /* Versions of the GNU binutils between 2.12 and 2.18 did
524	     not handle objects with more than SHN_LORESERVE sections
525	     correctly.  All large section indexes were offset by
526	     0x100.  There is more information at
527	     http://sourceware.org/bugzilla/show_bug.cgi?id-5900 .
528	     Fortunately these object files are easy to detect, as the
529	     GNU binutils always put the section header string table
530	     near the end of the list of sections.  Thus if the
531	     section header string table index is larger than the
532	     number of sections, then we know we have to subtract
533	     0x100 to get the real section index.  */
534	  if (eor->shstrndx >= eor->shnum
535	      && eor->shstrndx >= SHN_LORESERVE + 0x100)
536	    eor->shstrndx -= 0x100;
537	}
538    }
539
540  if (eor->shstrndx >= eor->shnum)
541    {
542      *errmsg = "invalid ELF shstrndx >= shnum";
543      *err = 0;
544      XDELETE (eor);
545      return NULL;
546    }
547
548  return (void *) eor;
549}
550
551/* Find all sections in an ELF file.  */
552
553static const char *
554simple_object_elf_find_sections (simple_object_read *sobj,
555				 int (*pfn) (void *, const char *,
556					     off_t offset, off_t length),
557				 void *data,
558				 int *err)
559{
560  struct simple_object_elf_read *eor =
561    (struct simple_object_elf_read *) sobj->data;
562  const struct elf_type_functions *type_functions = eor->type_functions;
563  unsigned char ei_class = eor->ei_class;
564  size_t shdr_size;
565  unsigned int shnum;
566  unsigned char *shdrs;
567  const char *errmsg;
568  unsigned char *shstrhdr;
569  size_t name_size;
570  off_t shstroff;
571  unsigned char *names;
572  unsigned int i;
573
574  shdr_size = (ei_class == ELFCLASS32
575	       ? sizeof (Elf32_External_Shdr)
576	       : sizeof (Elf64_External_Shdr));
577
578  /* Read the section headers.  We skip section 0, which is not a
579     useful section.  */
580
581  shnum = eor->shnum;
582  shdrs = XNEWVEC (unsigned char, shdr_size * (shnum - 1));
583
584  if (!simple_object_internal_read (sobj->descriptor,
585				    sobj->offset + eor->shoff + shdr_size,
586				    shdrs,
587				    shdr_size * (shnum - 1),
588				    &errmsg, err))
589    {
590      XDELETEVEC (shdrs);
591      return errmsg;
592    }
593
594  /* Read the section names.  */
595
596  shstrhdr = shdrs + (eor->shstrndx - 1) * shdr_size;
597  name_size = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
598			       shstrhdr, sh_size, Elf_Addr);
599  shstroff = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
600			      shstrhdr, sh_offset, Elf_Addr);
601  names = XNEWVEC (unsigned char, name_size);
602  if (!simple_object_internal_read (sobj->descriptor,
603				    sobj->offset + shstroff,
604				    names, name_size, &errmsg, err))
605    {
606      XDELETEVEC (names);
607      XDELETEVEC (shdrs);
608      return errmsg;
609    }
610
611  for (i = 1; i < shnum; ++i)
612    {
613      unsigned char *shdr;
614      unsigned int sh_name;
615      const char *name;
616      off_t offset;
617      off_t length;
618
619      shdr = shdrs + (i - 1) * shdr_size;
620      sh_name = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
621				 shdr, sh_name, Elf_Word);
622      if (sh_name >= name_size)
623	{
624	  *err = 0;
625	  XDELETEVEC (names);
626	  XDELETEVEC (shdrs);
627	  return "ELF section name out of range";
628	}
629
630      name = (const char *) names + sh_name;
631      offset = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
632				shdr, sh_offset, Elf_Addr);
633      length = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
634				shdr, sh_size, Elf_Addr);
635
636      if (!(*pfn) (data, name, offset, length))
637	break;
638    }
639
640  XDELETEVEC (names);
641  XDELETEVEC (shdrs);
642
643  return NULL;
644}
645
646/* Fetch the attributes for an simple_object_read.  */
647
648static void *
649simple_object_elf_fetch_attributes (simple_object_read *sobj,
650				    const char **errmsg ATTRIBUTE_UNUSED,
651				    int *err ATTRIBUTE_UNUSED)
652{
653  struct simple_object_elf_read *eor =
654    (struct simple_object_elf_read *) sobj->data;
655  struct simple_object_elf_attributes *ret;
656
657  ret = XNEW (struct simple_object_elf_attributes);
658  ret->type_functions = eor->type_functions;
659  ret->ei_data = eor->ei_data;
660  ret->ei_class = eor->ei_class;
661  ret->ei_osabi = eor->ei_osabi;
662  ret->machine = eor->machine;
663  ret->flags = eor->flags;
664  return ret;
665}
666
667/* Release the privata data for an simple_object_read.  */
668
669static void
670simple_object_elf_release_read (void *data)
671{
672  XDELETE (data);
673}
674
675/* Compare two attributes structures.  */
676
677static const char *
678simple_object_elf_attributes_merge (void *todata, void *fromdata, int *err)
679{
680  struct simple_object_elf_attributes *to =
681    (struct simple_object_elf_attributes *) todata;
682  struct simple_object_elf_attributes *from =
683    (struct simple_object_elf_attributes *) fromdata;
684
685  if (to->ei_data != from->ei_data || to->ei_class != from->ei_class)
686    {
687      *err = 0;
688      return "ELF object format mismatch";
689    }
690
691  if (to->machine != from->machine)
692    {
693      int ok;
694
695      /* EM_SPARC and EM_SPARC32PLUS are compatible and force an
696	 output of EM_SPARC32PLUS.  */
697      ok = 0;
698      switch (to->machine)
699	{
700	case EM_SPARC:
701	  if (from->machine == EM_SPARC32PLUS)
702	    {
703	      to->machine = from->machine;
704	      ok = 1;
705	    }
706	  break;
707
708	case EM_SPARC32PLUS:
709	  if (from->machine == EM_SPARC)
710	    ok = 1;
711	  break;
712
713	default:
714	  break;
715	}
716
717      if (!ok)
718	{
719	  *err = 0;
720	  return "ELF machine number mismatch";
721	}
722    }
723
724  return NULL;
725}
726
727/* Release the private data for an attributes structure.  */
728
729static void
730simple_object_elf_release_attributes (void *data)
731{
732  XDELETE (data);
733}
734
735/* Prepare to write out a file.  */
736
737static void *
738simple_object_elf_start_write (void *attributes_data,
739			       const char **errmsg ATTRIBUTE_UNUSED,
740			       int *err ATTRIBUTE_UNUSED)
741{
742  struct simple_object_elf_attributes *attrs =
743    (struct simple_object_elf_attributes *) attributes_data;
744  struct simple_object_elf_write *ret;
745
746  /* We're just going to record the attributes, but we need to make a
747     copy because the user may delete them.  */
748  ret = XNEW (struct simple_object_elf_write);
749  ret->attrs = *attrs;
750  ret->shdrs = NULL;
751  return ret;
752}
753
754/* Write out an ELF ehdr.  */
755
756static int
757simple_object_elf_write_ehdr (simple_object_write *sobj, int descriptor,
758			      const char **errmsg, int *err)
759{
760  struct simple_object_elf_attributes *attrs =
761    (struct simple_object_elf_attributes *) sobj->data;
762  const struct elf_type_functions* fns;
763  unsigned char cl;
764  size_t ehdr_size;
765  unsigned char buf[sizeof (Elf64_External_Ehdr)];
766  simple_object_write_section *section;
767  unsigned int shnum;
768  unsigned int shstrndx;
769
770  fns = attrs->type_functions;
771  cl = attrs->ei_class;
772
773  shnum = 0;
774  for (section = sobj->sections; section != NULL; section = section->next)
775    ++shnum;
776  if (shnum > 0)
777    {
778      /* Add a section header for the dummy section and one for
779	 .shstrtab.  */
780      shnum += 2;
781    }
782
783  ehdr_size = (cl == ELFCLASS32
784	       ? sizeof (Elf32_External_Ehdr)
785	       : sizeof (Elf64_External_Ehdr));
786  memset (buf, 0, sizeof (Elf64_External_Ehdr));
787
788  buf[EI_MAG0] = ELFMAG0;
789  buf[EI_MAG1] = ELFMAG1;
790  buf[EI_MAG2] = ELFMAG2;
791  buf[EI_MAG3] = ELFMAG3;
792  buf[EI_CLASS] = cl;
793  buf[EI_DATA] = attrs->ei_data;
794  buf[EI_VERSION] = EV_CURRENT;
795  buf[EI_OSABI] = attrs->ei_osabi;
796
797  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_type, Elf_Half, ET_REL);
798  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_machine, Elf_Half, attrs->machine);
799  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_version, Elf_Word, EV_CURRENT);
800  /* e_entry left as zero.  */
801  /* e_phoff left as zero.  */
802  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_shoff, Elf_Addr, ehdr_size);
803  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_flags, Elf_Word, attrs->flags);
804  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_ehsize, Elf_Half, ehdr_size);
805  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_phentsize, Elf_Half,
806		 (cl == ELFCLASS32
807		  ? sizeof (Elf32_External_Phdr)
808		  : sizeof (Elf64_External_Phdr)));
809  /* e_phnum left as zero.  */
810  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_shentsize, Elf_Half,
811		 (cl == ELFCLASS32
812		  ? sizeof (Elf32_External_Shdr)
813		  : sizeof (Elf64_External_Shdr)));
814  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_shnum, Elf_Half,
815		 shnum >= SHN_LORESERVE ? 0 : shnum);
816  if (shnum == 0)
817    shstrndx = 0;
818  else
819    {
820      shstrndx = shnum - 1;
821      if (shstrndx >= SHN_LORESERVE)
822	shstrndx = SHN_XINDEX;
823    }
824  ELF_SET_FIELD (fns, cl, Ehdr, buf, e_shstrndx, Elf_Half, shstrndx);
825
826  return simple_object_internal_write (descriptor, 0, buf, ehdr_size,
827				       errmsg, err);
828}
829
830/* Write out an ELF shdr.  */
831
832static int
833simple_object_elf_write_shdr (simple_object_write *sobj, int descriptor,
834			      off_t offset, unsigned int sh_name,
835			      unsigned int sh_type, unsigned int sh_flags,
836			      off_t sh_addr,
837			      unsigned int sh_offset, unsigned int sh_size,
838			      unsigned int sh_link, unsigned int sh_info,
839			      size_t sh_addralign,
840			      size_t sh_entsize,
841			      const char **errmsg, int *err)
842{
843  struct simple_object_elf_attributes *attrs =
844    (struct simple_object_elf_attributes *) sobj->data;
845  const struct elf_type_functions* fns;
846  unsigned char cl;
847  size_t shdr_size;
848  unsigned char buf[sizeof (Elf64_External_Shdr)];
849
850  fns = attrs->type_functions;
851  cl = attrs->ei_class;
852
853  shdr_size = (cl == ELFCLASS32
854	       ? sizeof (Elf32_External_Shdr)
855	       : sizeof (Elf64_External_Shdr));
856  memset (buf, 0, sizeof (Elf64_External_Shdr));
857
858  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_name, Elf_Word, sh_name);
859  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_type, Elf_Word, sh_type);
860  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_flags, Elf_Addr, sh_flags);
861  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_addr, Elf_Addr, sh_addr);
862  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_offset, Elf_Addr, sh_offset);
863  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_size, Elf_Addr, sh_size);
864  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_link, Elf_Word, sh_link);
865  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_info, Elf_Word, sh_info);
866  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_addralign, Elf_Addr, sh_addralign);
867  ELF_SET_FIELD (fns, cl, Shdr, buf, sh_entsize, Elf_Addr, sh_entsize);
868
869  return simple_object_internal_write (descriptor, offset, buf, shdr_size,
870				       errmsg, err);
871}
872
873/* Write out a complete ELF file.
874   Ehdr
875   initial dummy Shdr
876   user-created Shdrs
877   .shstrtab Shdr
878   user-created section data
879   .shstrtab data  */
880
881static const char *
882simple_object_elf_write_to_file (simple_object_write *sobj, int descriptor,
883				 int *err)
884{
885  struct simple_object_elf_write *eow =
886    (struct simple_object_elf_write *) sobj->data;
887  struct simple_object_elf_attributes *attrs = &eow->attrs;
888  unsigned char cl;
889  size_t ehdr_size;
890  size_t shdr_size;
891  const char *errmsg;
892  simple_object_write_section *section;
893  unsigned int shnum;
894  size_t shdr_offset;
895  size_t sh_offset;
896  unsigned int first_sh_size;
897  unsigned int first_sh_link;
898  size_t sh_name;
899  unsigned char zero;
900  unsigned secnum;
901
902  if (!simple_object_elf_write_ehdr (sobj, descriptor, &errmsg, err))
903    return errmsg;
904
905  cl = attrs->ei_class;
906  if (cl == ELFCLASS32)
907    {
908      ehdr_size = sizeof (Elf32_External_Ehdr);
909      shdr_size = sizeof (Elf32_External_Shdr);
910    }
911  else
912    {
913      ehdr_size = sizeof (Elf64_External_Ehdr);
914      shdr_size = sizeof (Elf64_External_Shdr);
915    }
916
917  shnum = 0;
918  for (section = sobj->sections; section != NULL; section = section->next)
919    ++shnum;
920  if (shnum == 0)
921    return NULL;
922
923  /* Add initial dummy Shdr and .shstrtab.  */
924  shnum += 2;
925
926  shdr_offset = ehdr_size;
927  sh_offset = shdr_offset + shnum * shdr_size;
928
929  if (shnum < SHN_LORESERVE)
930    first_sh_size = 0;
931  else
932    first_sh_size = shnum;
933  if (shnum - 1 < SHN_LORESERVE)
934    first_sh_link = 0;
935  else
936    first_sh_link = shnum - 1;
937  if (!simple_object_elf_write_shdr (sobj, descriptor, shdr_offset,
938				     0, 0, 0, 0, 0, first_sh_size, first_sh_link,
939				     0, 0, 0, &errmsg, err))
940    return errmsg;
941
942  shdr_offset += shdr_size;
943
944  sh_name = 1;
945  secnum = 0;
946  for (section = sobj->sections; section != NULL; section = section->next)
947    {
948      size_t mask;
949      size_t new_sh_offset;
950      size_t sh_size;
951      struct simple_object_write_section_buffer *buffer;
952      unsigned int sh_type = SHT_PROGBITS;
953      unsigned int sh_flags = 0;
954      off_t sh_addr = 0;
955      unsigned int sh_link = 0;
956      unsigned int sh_info = 0;
957      size_t sh_addralign = 1U << section->align;
958      size_t sh_entsize = 0;
959      if (eow->shdrs)
960	{
961	  sh_type = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
962				     eow->shdrs + secnum * shdr_size,
963				     sh_type, Elf_Word);
964	  sh_flags = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
965				      eow->shdrs + secnum * shdr_size,
966				      sh_flags, Elf_Addr);
967	  sh_addr = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
968				     eow->shdrs + secnum * shdr_size,
969				     sh_addr, Elf_Addr);
970	  sh_link = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
971				     eow->shdrs + secnum * shdr_size,
972				     sh_link, Elf_Word);
973	  sh_info = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
974				     eow->shdrs + secnum * shdr_size,
975				     sh_info, Elf_Word);
976	  sh_addralign = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
977					  eow->shdrs + secnum * shdr_size,
978					  sh_addralign, Elf_Addr);
979	  sh_entsize = ELF_FETCH_FIELD (attrs->type_functions, attrs->ei_class, Shdr,
980					eow->shdrs + secnum * shdr_size,
981					sh_entsize, Elf_Addr);
982	  secnum++;
983	}
984
985      mask = sh_addralign - 1;
986      new_sh_offset = sh_offset + mask;
987      new_sh_offset &= ~ mask;
988      while (new_sh_offset > sh_offset)
989	{
990	  unsigned char zeroes[16];
991	  size_t write;
992
993	  memset (zeroes, 0, sizeof zeroes);
994	  write = new_sh_offset - sh_offset;
995	  if (write > sizeof zeroes)
996	    write = sizeof zeroes;
997	  if (!simple_object_internal_write (descriptor, sh_offset, zeroes,
998					     write, &errmsg, err))
999	    return errmsg;
1000	  sh_offset += write;
1001	}
1002
1003      sh_size = 0;
1004      for (buffer = section->buffers; buffer != NULL; buffer = buffer->next)
1005	{
1006	  if (!simple_object_internal_write (descriptor, sh_offset + sh_size,
1007					     ((const unsigned char *)
1008					      buffer->buffer),
1009					     buffer->size, &errmsg, err))
1010	    return errmsg;
1011	  sh_size += buffer->size;
1012	}
1013
1014      if (!simple_object_elf_write_shdr (sobj, descriptor, shdr_offset,
1015					 sh_name, sh_type, sh_flags,
1016					 sh_addr, sh_offset,
1017					 sh_size, sh_link, sh_info,
1018					 sh_addralign, sh_entsize,
1019					 &errmsg, err))
1020	return errmsg;
1021
1022      shdr_offset += shdr_size;
1023      sh_name += strlen (section->name) + 1;
1024      sh_offset += sh_size;
1025    }
1026
1027  if (!simple_object_elf_write_shdr (sobj, descriptor, shdr_offset,
1028				     sh_name, SHT_STRTAB, 0, 0, sh_offset,
1029				     sh_name + strlen (".shstrtab") + 1, 0, 0,
1030				     1, 0, &errmsg, err))
1031    return errmsg;
1032
1033  /* .shstrtab has a leading zero byte.  */
1034  zero = 0;
1035  if (!simple_object_internal_write (descriptor, sh_offset, &zero, 1,
1036				     &errmsg, err))
1037    return errmsg;
1038  ++sh_offset;
1039
1040  for (section = sobj->sections; section != NULL; section = section->next)
1041    {
1042      size_t len;
1043
1044      len = strlen (section->name) + 1;
1045      if (!simple_object_internal_write (descriptor, sh_offset,
1046					 (const unsigned char *) section->name,
1047					 len, &errmsg, err))
1048	return errmsg;
1049      sh_offset += len;
1050    }
1051
1052  if (!simple_object_internal_write (descriptor, sh_offset,
1053				     (const unsigned char *) ".shstrtab",
1054				     strlen (".shstrtab") + 1, &errmsg, err))
1055    return errmsg;
1056
1057  return NULL;
1058}
1059
1060/* Release the private data for an simple_object_write structure.  */
1061
1062static void
1063simple_object_elf_release_write (void *data)
1064{
1065  struct simple_object_elf_write *eow = (struct simple_object_elf_write *) data;
1066  if (eow->shdrs)
1067    XDELETE (eow->shdrs);
1068  XDELETE (data);
1069}
1070
1071/* Copy all sections in an ELF file.  */
1072
1073static const char *
1074simple_object_elf_copy_lto_debug_sections (simple_object_read *sobj,
1075					   simple_object_write *dobj,
1076					   char *(*pfn) (const char *),
1077					   int *err)
1078{
1079  struct simple_object_elf_read *eor =
1080    (struct simple_object_elf_read *) sobj->data;
1081  const struct elf_type_functions *type_functions = eor->type_functions;
1082  struct simple_object_elf_write *eow =
1083    (struct simple_object_elf_write *) dobj->data;
1084  unsigned char ei_class = eor->ei_class;
1085  size_t shdr_size;
1086  unsigned int shnum;
1087  unsigned char *shdrs;
1088  const char *errmsg;
1089  unsigned char *shstrhdr;
1090  size_t name_size;
1091  off_t shstroff;
1092  unsigned char *names;
1093  unsigned int i;
1094  int changed;
1095  int *pfnret;
1096  const char **pfnname;
1097  unsigned new_i;
1098  unsigned *sh_map;
1099  unsigned first_shndx = 0;
1100  unsigned int *symtab_indices_shndx;
1101
1102  shdr_size = (ei_class == ELFCLASS32
1103	       ? sizeof (Elf32_External_Shdr)
1104	       : sizeof (Elf64_External_Shdr));
1105
1106  /* Read the section headers.  We skip section 0, which is not a
1107     useful section.  */
1108
1109  shnum = eor->shnum;
1110  shdrs = XNEWVEC (unsigned char, shdr_size * (shnum - 1));
1111
1112  if (!simple_object_internal_read (sobj->descriptor,
1113				    sobj->offset + eor->shoff + shdr_size,
1114				    shdrs,
1115				    shdr_size * (shnum - 1),
1116				    &errmsg, err))
1117    {
1118      XDELETEVEC (shdrs);
1119      return errmsg;
1120    }
1121
1122  /* Read the section names.  */
1123
1124  shstrhdr = shdrs + (eor->shstrndx - 1) * shdr_size;
1125  name_size = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1126			       shstrhdr, sh_size, Elf_Addr);
1127  shstroff = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1128			      shstrhdr, sh_offset, Elf_Addr);
1129  names = XNEWVEC (unsigned char, name_size);
1130  if (!simple_object_internal_read (sobj->descriptor,
1131				    sobj->offset + shstroff,
1132				    names, name_size, &errmsg, err))
1133    {
1134      XDELETEVEC (names);
1135      XDELETEVEC (shdrs);
1136      return errmsg;
1137    }
1138
1139  pfnret = XNEWVEC (int, shnum);
1140  pfnname = XNEWVEC (const char *, shnum);
1141
1142  /* Map of symtab to index section.  */
1143  symtab_indices_shndx = XCNEWVEC (unsigned int, shnum - 1);
1144
1145  /* First perform the callbacks to know which sections to preserve and
1146     what name to use for those.  */
1147  for (i = 1; i < shnum; ++i)
1148    {
1149      unsigned char *shdr;
1150      unsigned int sh_name, sh_type;
1151      const char *name;
1152      char *ret;
1153
1154      shdr = shdrs + (i - 1) * shdr_size;
1155      sh_name = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1156				 shdr, sh_name, Elf_Word);
1157      if (sh_name >= name_size)
1158	{
1159	  *err = 0;
1160	  XDELETEVEC (names);
1161	  XDELETEVEC (shdrs);
1162	  return "ELF section name out of range";
1163	}
1164
1165      name = (const char *) names + sh_name;
1166
1167      ret = (*pfn) (name);
1168      pfnret[i - 1] = ret == NULL ? -1 : 0;
1169      pfnname[i - 1] = ret == NULL ? name : ret;
1170      if (first_shndx == 0
1171	  && pfnret[i - 1] == 0)
1172	first_shndx = i;
1173
1174      /* Remember the indexes of existing SHT_SYMTAB_SHNDX sections.  */
1175      sh_type = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1176				 shdr, sh_type, Elf_Word);
1177      if (sh_type == SHT_SYMTAB_SHNDX)
1178	{
1179	  unsigned int sh_link;
1180	  sh_link = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1181				     shdr, sh_link, Elf_Word);
1182	  symtab_indices_shndx[sh_link - 1] = i;
1183	  /* Always discard the extended index sections, after
1184	     copying it will not be needed.  This way we don't need to
1185	     update it and deal with the ordering constraints of
1186	     processing the existing symtab and changing the index.  */
1187	  pfnret[i - 1] = -1;
1188	}
1189    }
1190
1191  /* Mark sections as preserved that are required by to be preserved
1192     sections.  */
1193  do
1194    {
1195      changed = 0;
1196      for (i = 1; i < shnum; ++i)
1197	{
1198	  unsigned char *shdr;
1199	  unsigned int sh_type, sh_info, sh_link;
1200	  off_t offset;
1201	  off_t length;
1202
1203	  shdr = shdrs + (i - 1) * shdr_size;
1204	  sh_type = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1205				     shdr, sh_type, Elf_Word);
1206	  sh_info = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1207				     shdr, sh_info, Elf_Word);
1208	  sh_link = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1209				     shdr, sh_link, Elf_Word);
1210	  if (sh_type == SHT_GROUP)
1211	    {
1212	      /* Mark groups containing copied sections.  */
1213	      unsigned entsize = ELF_FETCH_FIELD (type_functions, ei_class,
1214						  Shdr, shdr, sh_entsize,
1215						  Elf_Addr);
1216	      unsigned char *ent, *buf;
1217	      int keep = 0;
1218	      offset = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1219					shdr, sh_offset, Elf_Addr);
1220	      length = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1221					shdr, sh_size, Elf_Addr);
1222	      buf = XNEWVEC (unsigned char, length);
1223	      if (!simple_object_internal_read (sobj->descriptor,
1224						sobj->offset + offset, buf,
1225						(size_t) length, &errmsg, err))
1226		{
1227		  XDELETEVEC (buf);
1228		  XDELETEVEC (names);
1229		  XDELETEVEC (shdrs);
1230		  return errmsg;
1231		}
1232	      for (ent = buf + entsize; ent < buf + length; ent += entsize)
1233		{
1234		  unsigned sec = type_functions->fetch_Elf_Word (ent);
1235		  if (pfnret[sec - 1] == 0)
1236		    keep = 1;
1237		}
1238	      if (keep)
1239		{
1240		  changed |= (pfnret[sh_link - 1] == -1
1241			      || pfnret[i - 1] == -1);
1242		  pfnret[sh_link - 1] = 0;
1243		  pfnret[i - 1] = 0;
1244		}
1245	    }
1246	  if (sh_type == SHT_RELA
1247	      || sh_type == SHT_REL)
1248	    {
1249	      /* Mark relocation sections and symtab of copied sections.  */
1250	      if (pfnret[sh_info - 1] == 0)
1251		{
1252		  changed |= (pfnret[sh_link - 1] == -1
1253			      || pfnret[i - 1] == -1);
1254		  pfnret[sh_link - 1] = 0;
1255		  pfnret[i - 1] = 0;
1256		}
1257	    }
1258	  if (sh_type == SHT_SYMTAB)
1259	    {
1260	      /* Mark strings sections of copied symtabs.  */
1261	      if (pfnret[i - 1] == 0)
1262		{
1263		  changed |= pfnret[sh_link - 1] == -1;
1264		  pfnret[sh_link - 1] = 0;
1265		}
1266	    }
1267	}
1268    }
1269  while (changed);
1270
1271  /* Compute a mapping of old -> new section numbers.  */
1272  sh_map = XNEWVEC (unsigned, shnum);
1273  sh_map[0] = 0;
1274  new_i = 1;
1275  for (i = 1; i < shnum; ++i)
1276    {
1277      if (pfnret[i - 1] == -1)
1278	sh_map[i] = 0;
1279      else
1280	sh_map[i] = new_i++;
1281    }
1282  if (new_i - 1 >= SHN_LORESERVE)
1283    {
1284      *err = ENOTSUP;
1285      return "Too many copied sections";
1286    }
1287  eow->shdrs = XNEWVEC (unsigned char, shdr_size * (new_i - 1));
1288
1289  /* Then perform the actual copying.  */
1290  new_i = 0;
1291  for (i = 1; i < shnum; ++i)
1292    {
1293      unsigned char *shdr;
1294      unsigned int sh_name, sh_type;
1295      const char *name;
1296      off_t offset;
1297      off_t length;
1298      simple_object_write_section *dest;
1299      off_t flags;
1300      unsigned char *buf;
1301
1302      if (pfnret[i - 1])
1303	continue;
1304
1305      new_i++;
1306      shdr = shdrs + (i - 1) * shdr_size;
1307      sh_name = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1308				 shdr, sh_name, Elf_Word);
1309      if (sh_name >= name_size)
1310	{
1311	  *err = 0;
1312	  XDELETEVEC (names);
1313	  XDELETEVEC (shdrs);
1314	  XDELETEVEC (symtab_indices_shndx);
1315	  return "ELF section name out of range";
1316	}
1317
1318      name = pfnname[i - 1];
1319      offset = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1320				shdr, sh_offset, Elf_Addr);
1321      length = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1322				shdr, sh_size, Elf_Addr);
1323      sh_type = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1324				 shdr, sh_type, Elf_Word);
1325
1326      dest = simple_object_write_create_section (dobj, pfnname[i - 1],
1327						 0, &errmsg, err);
1328      if (dest == NULL)
1329	{
1330	  XDELETEVEC (names);
1331	  XDELETEVEC (shdrs);
1332	  XDELETEVEC (symtab_indices_shndx);
1333	  return errmsg;
1334	}
1335
1336      /* Record the SHDR of the source.  */
1337      memcpy (eow->shdrs + (new_i - 1) * shdr_size, shdr, shdr_size);
1338      shdr = eow->shdrs + (new_i - 1) * shdr_size;
1339
1340      /* Copy the data.
1341	 ???  This is quite wasteful and ideally would be delayed until
1342	 write_to_file ().  Thus it questions the interfacing
1343	 which eventually should contain destination creation plus
1344	 writing.  */
1345      buf = XNEWVEC (unsigned char, length);
1346      if (!simple_object_internal_read (sobj->descriptor,
1347					sobj->offset + offset, buf,
1348					(size_t) length, &errmsg, err))
1349	{
1350	  XDELETEVEC (buf);
1351	  XDELETEVEC (names);
1352	  XDELETEVEC (shdrs);
1353	  XDELETEVEC (symtab_indices_shndx);
1354	  return errmsg;
1355	}
1356
1357      /* If we are processing .symtab purge __gnu_lto_v1 and
1358	 __gnu_lto_slim symbols from it and any symbols in discarded
1359	 sections.  */
1360      if (sh_type == SHT_SYMTAB)
1361	{
1362	  unsigned entsize = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1363					      shdr, sh_entsize, Elf_Addr);
1364	  unsigned strtab = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1365					     shdr, sh_link, Elf_Word);
1366	  unsigned char *strshdr = shdrs + (strtab - 1) * shdr_size;
1367	  off_t stroff = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1368					  strshdr, sh_offset, Elf_Addr);
1369	  size_t strsz = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1370					  strshdr, sh_size, Elf_Addr);
1371	  char *strings = XNEWVEC (char, strsz);
1372	  char *gnu_lto = strings;
1373	  unsigned char *ent;
1374	  unsigned *shndx_table = NULL;
1375	  simple_object_internal_read (sobj->descriptor,
1376				       sobj->offset + stroff,
1377				       (unsigned char *)strings,
1378				       strsz, &errmsg, err);
1379	  /* Find gnu_lto_ in strings.  */
1380	  while ((gnu_lto = (char *) memchr (gnu_lto, 'g',
1381					     strings + strsz - gnu_lto)))
1382	    if (strncmp (gnu_lto, "gnu_lto_v1",
1383			 strings + strsz - gnu_lto) == 0)
1384	      break;
1385	    else
1386	      gnu_lto++;
1387	  /* Read the section index table if present.  */
1388	  if (symtab_indices_shndx[i - 1] != 0)
1389	    {
1390	      unsigned char *sidxhdr = shdrs + (strtab - 1) * shdr_size;
1391	      off_t sidxoff = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1392					       sidxhdr, sh_offset, Elf_Addr);
1393	      size_t sidxsz = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1394					       sidxhdr, sh_size, Elf_Addr);
1395	      shndx_table = (unsigned *)XNEWVEC (char, sidxsz);
1396	      simple_object_internal_read (sobj->descriptor,
1397					   sobj->offset + sidxoff,
1398					   (unsigned char *)shndx_table,
1399					   sidxsz, &errmsg, err);
1400	    }
1401	  for (ent = buf; ent < buf + length; ent += entsize)
1402	    {
1403	      unsigned st_shndx = ELF_FETCH_FIELD (type_functions, ei_class,
1404						   Sym, ent,
1405						   st_shndx, Elf_Half);
1406	      unsigned raw_st_shndx = st_shndx;
1407	      unsigned char *st_info;
1408	      unsigned char *st_other;
1409	      int discard = 0;
1410	      if (ei_class == ELFCLASS32)
1411		{
1412		  st_info = &((Elf32_External_Sym *)ent)->st_info;
1413		  st_other = &((Elf32_External_Sym *)ent)->st_other;
1414		}
1415	      else
1416		{
1417		  st_info = &((Elf64_External_Sym *)ent)->st_info;
1418		  st_other = &((Elf64_External_Sym *)ent)->st_other;
1419		}
1420	      if (st_shndx == SHN_XINDEX)
1421		st_shndx = type_functions->fetch_Elf_Word
1422		    ((unsigned char *)(shndx_table + (ent - buf) / entsize));
1423	      /* Eliminate all COMMONs - this includes __gnu_lto_v1
1424		 and __gnu_lto_slim which otherwise cause endless
1425		 LTO plugin invocation.  */
1426	      if (st_shndx == SHN_COMMON)
1427		discard = 1;
1428	      /* We also need to remove symbols refering to sections
1429		 we'll eventually remove as with fat LTO objects
1430		 we otherwise get duplicate symbols at final link
1431		 (with GNU ld, gold is fine and ignores symbols in
1432		 sections marked as EXCLUDE).  ld/20513  */
1433	      else if (st_shndx != SHN_UNDEF
1434		       && st_shndx < shnum
1435		       && pfnret[st_shndx - 1] == -1)
1436		discard = 1;
1437
1438	      if (discard)
1439		{
1440		  /* Make discarded symbols undefined and unnamed
1441		     in case it is local.  */
1442		  int bind = ELF_ST_BIND (*st_info);
1443		  int other = STV_DEFAULT;
1444		  if (bind == STB_LOCAL)
1445		    {
1446		      /* Make discarded local symbols unnamed and
1447			 defined in the first prevailing section.  */
1448		      ELF_SET_FIELD (type_functions, ei_class, Sym,
1449				     ent, st_name, Elf_Word, 0);
1450		      ELF_SET_FIELD (type_functions, ei_class, Sym,
1451				     ent, st_shndx, Elf_Half,
1452				     sh_map[first_shndx]);
1453		    }
1454		  else
1455		    {
1456		      /* Make discarded global symbols hidden weak
1457			 undefined and sharing the gnu_lto_ name.  */
1458		      bind = STB_WEAK;
1459		      other = STV_HIDDEN;
1460		      if (gnu_lto)
1461			ELF_SET_FIELD (type_functions, ei_class, Sym,
1462				       ent, st_name, Elf_Word,
1463				       gnu_lto - strings);
1464		      ELF_SET_FIELD (type_functions, ei_class, Sym,
1465				     ent, st_shndx, Elf_Half, SHN_UNDEF);
1466		    }
1467		  *st_other = other;
1468		  *st_info = ELF_ST_INFO (bind, STT_NOTYPE);
1469		  ELF_SET_FIELD (type_functions, ei_class, Sym,
1470				 ent, st_value, Elf_Addr, 0);
1471		  ELF_SET_FIELD (type_functions, ei_class, Sym,
1472				 ent, st_size, Elf_Word, 0);
1473		}
1474	      else if (raw_st_shndx < SHN_LORESERVE
1475		       || raw_st_shndx == SHN_XINDEX)
1476		/* Remap the section reference.  */
1477		ELF_SET_FIELD (type_functions, ei_class, Sym,
1478			       ent, st_shndx, Elf_Half, sh_map[st_shndx]);
1479	    }
1480	  XDELETEVEC (strings);
1481	  XDELETEVEC (shndx_table);
1482	}
1483      else if (sh_type == SHT_GROUP)
1484	{
1485	  /* Remap section indices in groups and remove removed members.  */
1486	  unsigned char *ent, *dst;
1487	  for (dst = ent = buf + 4; ent < buf + length; ent += 4)
1488	    {
1489	      unsigned shndx = type_functions->fetch_Elf_Word (ent);
1490	      if (pfnret[shndx - 1] == -1)
1491		;
1492	      else
1493		{
1494		  type_functions->set_Elf_Word (dst, sh_map[shndx]);
1495		  dst += 4;
1496		}
1497	    }
1498	  /* Adjust the length.  */
1499	  length = dst - buf;
1500	}
1501
1502      errmsg = simple_object_write_add_data (dobj, dest,
1503					     buf, length, 1, err);
1504      XDELETEVEC (buf);
1505      if (errmsg)
1506	{
1507	  XDELETEVEC (names);
1508	  XDELETEVEC (shdrs);
1509	  XDELETEVEC (symtab_indices_shndx);
1510	  return errmsg;
1511	}
1512
1513      flags = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1514			       shdr, sh_flags, Elf_Addr);
1515      /* Remap the section references.  */
1516      {
1517	unsigned int sh_info, sh_link;
1518	if (flags & SHF_INFO_LINK || sh_type == SHT_REL || sh_type == SHT_RELA)
1519	  {
1520	    sh_info = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1521				       shdr, sh_info, Elf_Word);
1522	    if (sh_info < SHN_LORESERVE
1523		|| sh_info > SHN_HIRESERVE)
1524	      sh_info = sh_map[sh_info];
1525	    ELF_SET_FIELD (type_functions, ei_class, Shdr,
1526			   shdr, sh_info, Elf_Word, sh_info);
1527	  }
1528	sh_link = ELF_FETCH_FIELD (type_functions, ei_class, Shdr,
1529				   shdr, sh_link, Elf_Word);
1530	if (sh_link < SHN_LORESERVE
1531	    || sh_link > SHN_HIRESERVE)
1532	  sh_link = sh_map[sh_link];
1533	ELF_SET_FIELD (type_functions, ei_class, Shdr,
1534		       shdr, sh_link, Elf_Word, sh_link);
1535      }
1536      /* The debugobj doesn't contain any code, thus no trampolines.
1537	 Even when the original object needs trampolines, debugobj
1538	 doesn't.  */
1539      if (strcmp (name, ".note.GNU-stack") == 0)
1540	flags &= ~SHF_EXECINSTR;
1541      /* Clear SHF_EXCLUDE on to be preserved sections.  */
1542      flags &= ~SHF_EXCLUDE;
1543      ELF_SET_FIELD (type_functions, ei_class, Shdr,
1544		     shdr, sh_flags, Elf_Addr, flags);
1545    }
1546
1547  XDELETEVEC (names);
1548  XDELETEVEC (shdrs);
1549  XDELETEVEC (pfnret);
1550  XDELETEVEC (pfnname);
1551  XDELETEVEC (symtab_indices_shndx);
1552  XDELETEVEC (sh_map);
1553
1554  return NULL;
1555}
1556
1557
1558/* The ELF functions.  */
1559
1560const struct simple_object_functions simple_object_elf_functions =
1561{
1562  simple_object_elf_match,
1563  simple_object_elf_find_sections,
1564  simple_object_elf_fetch_attributes,
1565  simple_object_elf_release_read,
1566  simple_object_elf_attributes_merge,
1567  simple_object_elf_release_attributes,
1568  simple_object_elf_start_write,
1569  simple_object_elf_write_to_file,
1570  simple_object_elf_release_write,
1571  simple_object_elf_copy_lto_debug_sections
1572};
1573