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