• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Pedantic checking of ELF files compliance with gABI/psABI spec.
2    Copyright (C) 2001-2015, 2017, 2018 Red Hat, Inc.
3    This file is part of elfutils.
4    Written by Ulrich Drepper <drepper@redhat.com>, 2001.
5 
6    This file is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    elfutils is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18 
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22 
23 #include <argp.h>
24 #include <assert.h>
25 #include <byteswap.h>
26 #include <endian.h>
27 #include <fcntl.h>
28 #include <gelf.h>
29 #include <inttypes.h>
30 #include <libintl.h>
31 #include <locale.h>
32 #include <stdbool.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <sys/stat.h>
37 
38 #include <elf-knowledge.h>
39 #include <libeu.h>
40 #include <system.h>
41 #include <printversion.h>
42 #include "../libelf/libelfP.h"
43 #include "../libelf/common.h"
44 #include "../libebl/libeblP.h"
45 #include "../libdw/libdwP.h"
46 #include "../libdwfl/libdwflP.h"
47 #include "../libdw/memory-access.h"
48 
49 
50 /* Name and version of program.  */
51 ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
52 
53 /* Bug report address.  */
54 ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
55 
56 #define ARGP_strict	300
57 #define ARGP_gnuld	301
58 
59 /* Definitions of arguments for argp functions.  */
60 static const struct argp_option options[] =
61 {
62   { "strict", ARGP_strict, NULL, 0,
63     N_("Be extremely strict, flag level 2 features."), 0 },
64   { "quiet", 'q', NULL, 0, N_("Do not print anything if successful"), 0 },
65   { "debuginfo", 'd', NULL, 0, N_("Binary is a separate debuginfo file"), 0 },
66   { "gnu-ld", ARGP_gnuld, NULL, 0,
67     N_("Binary has been created with GNU ld and is therefore known to be \
68 broken in certain ways"), 0 },
69   { NULL, 0, NULL, 0, NULL, 0 }
70 };
71 
72 /* Short description of program.  */
73 static const char doc[] = N_("\
74 Pedantic checking of ELF files compliance with gABI/psABI spec.");
75 
76 /* Strings for arguments in help texts.  */
77 static const char args_doc[] = N_("FILE...");
78 
79 /* Prototype for option handler.  */
80 static error_t parse_opt (int key, char *arg, struct argp_state *state);
81 
82 /* Data structure to communicate with argp functions.  */
83 static struct argp argp =
84 {
85   options, parse_opt, args_doc, doc, NULL, NULL, NULL
86 };
87 
88 
89 /* Declarations of local functions.  */
90 static void process_file (int fd, Elf *elf, const char *prefix,
91 			  const char *suffix, const char *fname, size_t size,
92 			  bool only_one);
93 static void process_elf_file (Elf *elf, const char *prefix, const char *suffix,
94 			      const char *fname, size_t size, bool only_one);
95 static void check_note_section (Ebl *ebl, GElf_Ehdr *ehdr,
96 				GElf_Shdr *shdr, int idx);
97 
98 
99 /* Report an error.  */
100 #define ERROR(str, args...) \
101   do {									      \
102     printf (str, ##args);						      \
103     ++error_count;							      \
104   } while (0)
105 static unsigned int error_count;
106 
107 /* True if we should perform very strict testing.  */
108 static bool be_strict;
109 
110 /* True if no message is to be printed if the run is successful.  */
111 static bool be_quiet;
112 
113 /* True if binary is from strip -f, not a normal ELF file.  */
114 static bool is_debuginfo;
115 
116 /* True if binary is assumed to be generated with GNU ld.  */
117 static bool gnuld;
118 
119 /* Index of section header string table.  */
120 static uint32_t shstrndx;
121 
122 /* Array to count references in section groups.  */
123 static int *scnref;
124 
125 /* Numbers of sections and program headers.  */
126 static unsigned int shnum;
127 static unsigned int phnum;
128 
129 
130 int
main(int argc,char * argv[])131 main (int argc, char *argv[])
132 {
133   /* Set locale.  */
134   setlocale (LC_ALL, "");
135 
136   /* Initialize the message catalog.  */
137   textdomain (PACKAGE_TARNAME);
138 
139   /* Parse and process arguments.  */
140   int remaining;
141   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
142 
143   /* Before we start tell the ELF library which version we are using.  */
144   elf_version (EV_CURRENT);
145 
146   /* Now process all the files given at the command line.  */
147   bool only_one = remaining + 1 == argc;
148   do
149     {
150       /* Open the file.  */
151       int fd = open (argv[remaining], O_RDONLY);
152       if (fd == -1)
153 	{
154 	  error (0, errno, _("cannot open input file '%s'"), argv[remaining]);
155 	  continue;
156 	}
157 
158       /* Create an `Elf' descriptor.  */
159       Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
160       if (elf == NULL)
161 	ERROR (_("cannot generate Elf descriptor for '%s': %s\n"),
162 	       argv[remaining], elf_errmsg (-1));
163       else
164 	{
165 	  unsigned int prev_error_count = error_count;
166 	  struct stat st;
167 
168 	  if (fstat (fd, &st) != 0)
169 	    {
170 	      printf ("cannot stat '%s': %m\n", argv[remaining]);
171 	      close (fd);
172 	      continue;
173 	    }
174 
175 	  process_file (fd, elf, NULL, NULL, argv[remaining], st.st_size,
176 			only_one);
177 
178 	  /* Now we can close the descriptor.  */
179 	  if (elf_end (elf) != 0)
180 	    ERROR (_("error while closing Elf descriptor: %s\n"),
181 		   elf_errmsg (-1));
182 
183 	  if (prev_error_count == error_count && !be_quiet)
184 	    puts (_("No errors"));
185 	}
186 
187       close (fd);
188     }
189   while (++remaining < argc);
190 
191   return error_count != 0;
192 }
193 
194 
195 /* Handle program arguments.  */
196 static error_t
parse_opt(int key,char * arg,struct argp_state * state)197 parse_opt (int key, char *arg __attribute__ ((unused)),
198 	   struct argp_state *state __attribute__ ((unused)))
199 {
200   switch (key)
201     {
202     case ARGP_strict:
203       be_strict = true;
204       break;
205 
206     case 'q':
207       be_quiet = true;
208       break;
209 
210     case 'd':
211       is_debuginfo = true;
212       break;
213 
214     case ARGP_gnuld:
215       gnuld = true;
216       break;
217 
218     case ARGP_KEY_NO_ARGS:
219       fputs (_("Missing file name.\n"), stderr);
220       argp_help (&argp, stderr, ARGP_HELP_SEE, program_invocation_short_name);
221       exit (EXIT_FAILURE);
222 
223     default:
224       return ARGP_ERR_UNKNOWN;
225     }
226   return 0;
227 }
228 
229 
230 /* Process one file.  */
231 static void
process_file(int fd,Elf * elf,const char * prefix,const char * suffix,const char * fname,size_t size,bool only_one)232 process_file (int fd, Elf *elf, const char *prefix, const char *suffix,
233 	      const char *fname, size_t size, bool only_one)
234 {
235   /* We can handle two types of files: ELF files and archives.  */
236   Elf_Kind kind = elf_kind (elf);
237 
238   switch (kind)
239     {
240     case ELF_K_ELF:
241       /* Yes!  It's an ELF file.  */
242       process_elf_file (elf, prefix, suffix, fname, size, only_one);
243       break;
244 
245     case ELF_K_AR:
246       {
247 	Elf *subelf;
248 	Elf_Cmd cmd = ELF_C_READ_MMAP;
249 	size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
250 	size_t fname_len = strlen (fname) + 1;
251 	char new_prefix[prefix_len + 1 + fname_len];
252 	char new_suffix[(suffix == NULL ? 0 : strlen (suffix)) + 2];
253 	char *cp = new_prefix;
254 
255 	/* Create the full name of the file.  */
256 	if (prefix != NULL)
257 	  {
258 	    cp = mempcpy (cp, prefix, prefix_len);
259 	    *cp++ = '(';
260 	    strcpy (stpcpy (new_suffix, suffix), ")");
261 	  }
262 	else
263 	  new_suffix[0] = '\0';
264 	memcpy (cp, fname, fname_len);
265 
266 	/* It's an archive.  We process each file in it.  */
267 	while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
268 	  {
269 	    kind = elf_kind (subelf);
270 
271 	    /* Call this function recursively.  */
272 	    if (kind == ELF_K_ELF || kind == ELF_K_AR)
273 	      {
274 		Elf_Arhdr *arhdr = elf_getarhdr (subelf);
275 		assert (arhdr != NULL);
276 
277 		process_file (fd, subelf, new_prefix, new_suffix,
278 			      arhdr->ar_name, arhdr->ar_size, false);
279 	      }
280 
281 	    /* Get next archive element.  */
282 	    cmd = elf_next (subelf);
283 	    if (elf_end (subelf) != 0)
284 	      ERROR (_(" error while freeing sub-ELF descriptor: %s\n"),
285 		     elf_errmsg (-1));
286 	  }
287       }
288       break;
289 
290     default:
291       /* We cannot do anything.  */
292       ERROR (_("\
293 Not an ELF file - it has the wrong magic bytes at the start\n"));
294       break;
295     }
296 }
297 
298 
299 static const char *
section_name(Ebl * ebl,int idx)300 section_name (Ebl *ebl, int idx)
301 {
302   GElf_Shdr shdr_mem;
303   GElf_Shdr *shdr;
304   const char *ret;
305 
306   if ((unsigned int) idx > shnum)
307     return "<invalid>";
308 
309   shdr = gelf_getshdr (elf_getscn (ebl->elf, idx), &shdr_mem);
310   if (shdr == NULL)
311     return "<invalid>";
312 
313   ret = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
314   if (ret == NULL)
315     return "<invalid>";
316   return ret;
317 }
318 
319 
320 static const int valid_e_machine[] =
321   {
322     EM_M32, EM_SPARC, EM_386, EM_68K, EM_88K, EM_860, EM_MIPS, EM_S370,
323     EM_MIPS_RS3_LE, EM_PARISC, EM_VPP500, EM_SPARC32PLUS, EM_960, EM_PPC,
324     EM_PPC64, EM_S390, EM_V800, EM_FR20, EM_RH32, EM_RCE, EM_ARM,
325     EM_FAKE_ALPHA, EM_SH, EM_SPARCV9, EM_TRICORE, EM_ARC, EM_H8_300,
326     EM_H8_300H, EM_H8S, EM_H8_500, EM_IA_64, EM_MIPS_X, EM_COLDFIRE,
327     EM_68HC12, EM_MMA, EM_PCP, EM_NCPU, EM_NDR1, EM_STARCORE, EM_ME16,
328     EM_ST100, EM_TINYJ, EM_X86_64, EM_PDSP, EM_FX66, EM_ST9PLUS, EM_ST7,
329     EM_68HC16, EM_68HC11, EM_68HC08, EM_68HC05, EM_SVX, EM_ST19, EM_VAX,
330     EM_CRIS, EM_JAVELIN, EM_FIREPATH, EM_ZSP, EM_MMIX, EM_HUANY, EM_PRISM,
331     EM_AVR, EM_FR30, EM_D10V, EM_D30V, EM_V850, EM_M32R, EM_MN10300,
332     EM_MN10200, EM_PJ, EM_OPENRISC, EM_ARC_A5, EM_XTENSA, EM_ALPHA,
333     EM_TILEGX, EM_TILEPRO, EM_AARCH64, EM_BPF, EM_RISCV, EM_CSKY
334   };
335 #define nvalid_e_machine \
336   (sizeof (valid_e_machine) / sizeof (valid_e_machine[0]))
337 
338 
339 static void
check_elf_header(Ebl * ebl,GElf_Ehdr * ehdr,size_t size)340 check_elf_header (Ebl *ebl, GElf_Ehdr *ehdr, size_t size)
341 {
342   char buf[512];
343   size_t cnt;
344 
345   /* Check e_ident field.  */
346   if (ehdr->e_ident[EI_MAG0] != ELFMAG0)
347     ERROR ("e_ident[%d] != '%c'\n", EI_MAG0, ELFMAG0);
348   if (ehdr->e_ident[EI_MAG1] != ELFMAG1)
349     ERROR ("e_ident[%d] != '%c'\n", EI_MAG1, ELFMAG1);
350   if (ehdr->e_ident[EI_MAG2] != ELFMAG2)
351     ERROR ("e_ident[%d] != '%c'\n", EI_MAG2, ELFMAG2);
352   if (ehdr->e_ident[EI_MAG3] != ELFMAG3)
353     ERROR ("e_ident[%d] != '%c'\n", EI_MAG3, ELFMAG3);
354 
355   if (ehdr->e_ident[EI_CLASS] != ELFCLASS32
356       && ehdr->e_ident[EI_CLASS] != ELFCLASS64)
357     ERROR (_("e_ident[%d] == %d is no known class\n"),
358 	   EI_CLASS, ehdr->e_ident[EI_CLASS]);
359 
360   if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB
361       && ehdr->e_ident[EI_DATA] != ELFDATA2MSB)
362     ERROR (_("e_ident[%d] == %d is no known data encoding\n"),
363 	   EI_DATA, ehdr->e_ident[EI_DATA]);
364 
365   if (ehdr->e_ident[EI_VERSION] != EV_CURRENT)
366     ERROR (_("unknown ELF header version number e_ident[%d] == %d\n"),
367 	   EI_VERSION, ehdr->e_ident[EI_VERSION]);
368 
369   /* We currently don't handle any OS ABIs other than Linux and the
370      kFreeBSD variant of Debian.  */
371   if (ehdr->e_ident[EI_OSABI] != ELFOSABI_NONE
372       && ehdr->e_ident[EI_OSABI] != ELFOSABI_LINUX
373       && ehdr->e_ident[EI_OSABI] != ELFOSABI_FREEBSD)
374     ERROR (_("unsupported OS ABI e_ident[%d] == '%s'\n"),
375 	   EI_OSABI,
376 	   ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
377 
378   /* No ABI versions other than zero are supported either.  */
379   if (ehdr->e_ident[EI_ABIVERSION] != 0)
380     ERROR (_("unsupported ABI version e_ident[%d] == %d\n"),
381 	   EI_ABIVERSION, ehdr->e_ident[EI_ABIVERSION]);
382 
383   for (cnt = EI_PAD; cnt < EI_NIDENT; ++cnt)
384     if (ehdr->e_ident[cnt] != 0)
385       ERROR (_("e_ident[%zu] is not zero\n"), cnt);
386 
387   /* Check the e_type field.  */
388   if (ehdr->e_type != ET_REL && ehdr->e_type != ET_EXEC
389       && ehdr->e_type != ET_DYN && ehdr->e_type != ET_CORE)
390     ERROR (_("unknown object file type %d\n"), ehdr->e_type);
391 
392   /* Check the e_machine field.  */
393   for (cnt = 0; cnt < nvalid_e_machine; ++cnt)
394     if (valid_e_machine[cnt] == ehdr->e_machine)
395       break;
396   if (cnt == nvalid_e_machine)
397     ERROR (_("unknown machine type %d\n"), ehdr->e_machine);
398 
399   /* Check the e_version field.  */
400   if (ehdr->e_version != EV_CURRENT)
401     ERROR (_("unknown object file version\n"));
402 
403   /* Check the e_phoff and e_phnum fields.  */
404   if (ehdr->e_phoff == 0)
405     {
406       if (ehdr->e_phnum != 0)
407 	ERROR (_("invalid program header offset\n"));
408       else if (ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN)
409 	ERROR (_("\
410 executables and DSOs cannot have zero program header offset\n"));
411     }
412   else if (ehdr->e_phnum == 0)
413     ERROR (_("invalid number of program header entries\n"));
414 
415   /* Check the e_shoff field.  */
416   shnum = ehdr->e_shnum;
417   shstrndx = ehdr->e_shstrndx;
418   if (ehdr->e_shoff == 0)
419     {
420       if (ehdr->e_shnum != 0)
421 	ERROR (_("invalid section header table offset\n"));
422       else if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN
423 	       && ehdr->e_type != ET_CORE)
424 	ERROR (_("section header table must be present\n"));
425     }
426   else
427     {
428       if (ehdr->e_shnum == 0)
429 	{
430 	  /* Get the header of the zeroth section.  The sh_size field
431 	     might contain the section number.  */
432 	  GElf_Shdr shdr_mem;
433 	  GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
434 	  if (shdr != NULL)
435 	    {
436 	      /* The error will be reported later.  */
437 	      if (shdr->sh_size == 0)
438 		ERROR (_("\
439 invalid number of section header table entries\n"));
440 	      else
441 		shnum = shdr->sh_size;
442 	    }
443 	}
444 
445       if (ehdr->e_shstrndx == SHN_XINDEX)
446 	{
447 	  /* Get the header of the zeroth section.  The sh_size field
448 	     might contain the section number.  */
449 	  GElf_Shdr shdr_mem;
450 	  GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
451 	  if (shdr != NULL && shdr->sh_link < shnum)
452 	    shstrndx = shdr->sh_link;
453 	}
454       else if (shstrndx >= shnum)
455 	ERROR (_("invalid section header index\n"));
456     }
457 
458   /* Check the shdrs actually exist.  And uncompress them before
459      further checking.  Indexes between sections reference the
460      uncompressed data.  */
461   unsigned int scnt;
462   Elf_Scn *scn = NULL;
463   for (scnt = 1; scnt < shnum; ++scnt)
464      {
465 	scn = elf_nextscn (ebl->elf, scn);
466 	if (scn == NULL)
467 	  break;
468 	/* If the section wasn't compressed this does nothing, but
469 	   returns an error.  We don't care.  */
470 	if (elf_compress (scn, 0, 0) < 0) { ; }
471      }
472   if (scnt < shnum)
473     ERROR (_("Can only check %u headers, shnum was %u\n"), scnt, shnum);
474   shnum = scnt;
475 
476   phnum = ehdr->e_phnum;
477   if (ehdr->e_phnum == PN_XNUM)
478     {
479       /* Get the header of the zeroth section.  The sh_info field
480 	 might contain the phnum count.  */
481       GElf_Shdr shdr_mem;
482       GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
483       if (shdr != NULL)
484 	{
485 	  /* The error will be reported later.  */
486 	  if (shdr->sh_info < PN_XNUM)
487 	    ERROR (_("\
488 invalid number of program header table entries\n"));
489 	  else
490 	    phnum = shdr->sh_info;
491 	}
492     }
493 
494   /* Check the phdrs actually exist. */
495   unsigned int pcnt;
496   for (pcnt = 0; pcnt < phnum; ++pcnt)
497      {
498 	GElf_Phdr phdr_mem;
499 	GElf_Phdr *phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
500 	if (phdr == NULL)
501 	  break;
502      }
503   if (pcnt < phnum)
504     ERROR (_("Can only check %u headers, phnum was %u\n"), pcnt, phnum);
505   phnum = pcnt;
506 
507   /* Check the e_flags field.  */
508   if (!ebl_machine_flag_check (ebl, ehdr->e_flags))
509     ERROR (_("invalid machine flags: %s\n"),
510 	   ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
511 
512   /* Check e_ehsize, e_phentsize, and e_shentsize fields.  */
513   if (gelf_getclass (ebl->elf) == ELFCLASS32)
514     {
515       if (ehdr->e_ehsize != 0 && ehdr->e_ehsize != sizeof (Elf32_Ehdr))
516 	ERROR (_("invalid ELF header size: %hd\n"), ehdr->e_ehsize);
517 
518       if (ehdr->e_phentsize != 0 && ehdr->e_phentsize != sizeof (Elf32_Phdr))
519 	ERROR (_("invalid program header size: %hd\n"),
520 	       ehdr->e_phentsize);
521       else if (ehdr->e_phoff + phnum * ehdr->e_phentsize > size)
522 	ERROR (_("invalid program header position or size\n"));
523 
524       if (ehdr->e_shentsize != 0 && ehdr->e_shentsize != sizeof (Elf32_Shdr))
525 	ERROR (_("invalid section header size: %hd\n"),
526 	       ehdr->e_shentsize);
527       else if (ehdr->e_shoff + shnum * ehdr->e_shentsize > size)
528 	ERROR (_("invalid section header position or size\n"));
529     }
530   else if (gelf_getclass (ebl->elf) == ELFCLASS64)
531     {
532       if (ehdr->e_ehsize != 0 && ehdr->e_ehsize != sizeof (Elf64_Ehdr))
533 	ERROR (_("invalid ELF header size: %hd\n"), ehdr->e_ehsize);
534 
535       if (ehdr->e_phentsize != 0 && ehdr->e_phentsize != sizeof (Elf64_Phdr))
536 	ERROR (_("invalid program header size: %hd\n"),
537 	       ehdr->e_phentsize);
538       else if (ehdr->e_phoff + phnum * ehdr->e_phentsize > size)
539 	ERROR (_("invalid program header position or size\n"));
540 
541       if (ehdr->e_shentsize != 0 && ehdr->e_shentsize != sizeof (Elf64_Shdr))
542 	ERROR (_("invalid section header size: %hd\n"),
543 	       ehdr->e_shentsize);
544       else if (ehdr->e_shoff + shnum * ehdr->e_shentsize > size)
545 	ERROR (_("invalid section header position or size\n"));
546     }
547 }
548 
549 
550 /* Check that there is a section group section with index < IDX which
551    contains section IDX and that there is exactly one.  */
552 static void
check_scn_group(Ebl * ebl,int idx)553 check_scn_group (Ebl *ebl, int idx)
554 {
555   if (scnref[idx] == 0)
556     {
557       /* No reference so far.  Search following sections, maybe the
558 	 order is wrong.  */
559       size_t cnt;
560 
561       for (cnt = idx + 1; cnt < shnum; ++cnt)
562 	{
563 	  Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
564 	  GElf_Shdr shdr_mem;
565 	  GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
566 	  if (shdr == NULL)
567 	    /* We cannot get the section header so we cannot check it.
568 	       The error to get the section header will be shown
569 	       somewhere else.  */
570 	    continue;
571 
572 	  if (shdr->sh_type != SHT_GROUP)
573 	    continue;
574 
575 	  Elf_Data *data = elf_getdata (scn, NULL);
576 	  if (data == NULL || data->d_buf == NULL
577 	      || data->d_size < sizeof (Elf32_Word))
578 	    /* Cannot check the section.  */
579 	    continue;
580 
581 	  Elf32_Word *grpdata = (Elf32_Word *) data->d_buf;
582 	  for (size_t inner = 1; inner < data->d_size / sizeof (Elf32_Word);
583 	       ++inner)
584 	    if (grpdata[inner] == (Elf32_Word) idx)
585 	      goto out;
586 	}
587 
588     out:
589       if (cnt == shnum)
590 	ERROR (_("\
591 section [%2d] '%s': section with SHF_GROUP flag set not part of a section group\n"),
592 	       idx, section_name (ebl, idx));
593       else
594 	ERROR (_("\
595 section [%2d] '%s': section group [%2zu] '%s' does not precede group member\n"),
596 	       idx, section_name (ebl, idx),
597 	       cnt, section_name (ebl, cnt));
598     }
599 }
600 
601 
602 static void
check_symtab(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)603 check_symtab (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
604 {
605   bool no_xndx_warned = false;
606   int no_pt_tls = 0;
607   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
608   if (data == NULL)
609     {
610       ERROR (_("section [%2d] '%s': cannot get section data\n"),
611 	     idx, section_name (ebl, idx));
612       return;
613     }
614 
615   GElf_Shdr strshdr_mem;
616   GElf_Shdr *strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
617 				     &strshdr_mem);
618   if (strshdr == NULL)
619     return;
620 
621   if (strshdr->sh_type != SHT_STRTAB)
622     {
623       ERROR (_("section [%2d] '%s': referenced as string table for section [%2d] '%s' but type is not SHT_STRTAB\n"),
624 	     shdr->sh_link, section_name (ebl, shdr->sh_link),
625 	     idx, section_name (ebl, idx));
626       strshdr = NULL;
627     }
628 
629   /* Search for an extended section index table section.  */
630   Elf_Data *xndxdata = NULL;
631   Elf32_Word xndxscnidx = 0;
632   bool found_xndx = false;
633   for (size_t cnt = 1; cnt < shnum; ++cnt)
634     if (cnt != (size_t) idx)
635       {
636 	Elf_Scn *xndxscn = elf_getscn (ebl->elf, cnt);
637 	GElf_Shdr xndxshdr_mem;
638 	GElf_Shdr *xndxshdr = gelf_getshdr (xndxscn, &xndxshdr_mem);
639 	if (xndxshdr == NULL)
640 	  continue;
641 
642 	if (xndxshdr->sh_type == SHT_SYMTAB_SHNDX
643 	    && xndxshdr->sh_link == (GElf_Word) idx)
644 	  {
645 	    if (found_xndx)
646 	      ERROR (_("\
647 section [%2d] '%s': symbol table cannot have more than one extended index section\n"),
648 		     idx, section_name (ebl, idx));
649 
650 	    xndxdata = elf_getdata (xndxscn, NULL);
651 	    xndxscnidx = elf_ndxscn (xndxscn);
652 	    found_xndx = true;
653 	  }
654       }
655 
656   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_SYM, 1, EV_CURRENT);
657   if (shdr->sh_entsize != sh_entsize)
658     ERROR (_("\
659 section [%2u] '%s': entry size is does not match ElfXX_Sym\n"),
660 	   idx, section_name (ebl, idx));
661   else if (shdr->sh_info > shdr->sh_size / sh_entsize)
662     ERROR (_("\
663 section [%2u] '%s': number of local entries in 'st_info' larger than table size\n"),
664 	   idx, section_name (ebl, idx));
665 
666   /* Test the zeroth entry.  */
667   GElf_Sym sym_mem;
668   Elf32_Word xndx;
669   GElf_Sym *sym = gelf_getsymshndx (data, xndxdata, 0, &sym_mem, &xndx);
670   if (sym == NULL)
671       ERROR (_("section [%2d] '%s': cannot get symbol %d: %s\n"),
672 	     idx, section_name (ebl, idx), 0, elf_errmsg (-1));
673   else
674     {
675       if (sym->st_name != 0)
676 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
677 	       idx, section_name (ebl, idx), "st_name");
678       if (sym->st_value != 0)
679 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
680 	       idx, section_name (ebl, idx), "st_value");
681       if (sym->st_size != 0)
682 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
683 	       idx, section_name (ebl, idx), "st_size");
684       if (sym->st_info != 0)
685 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
686 	       idx, section_name (ebl, idx), "st_info");
687       if (sym->st_other != 0)
688 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
689 	       idx, section_name (ebl, idx), "st_other");
690       if (sym->st_shndx != 0)
691 	ERROR (_("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
692 	       idx, section_name (ebl, idx), "st_shndx");
693       if (xndxdata != NULL && xndx != 0)
694 	ERROR (_("\
695 section [%2d] '%s': XINDEX for zeroth entry not zero\n"),
696 	       xndxscnidx, section_name (ebl, xndxscnidx));
697     }
698 
699   for (size_t cnt = 1; cnt < shdr->sh_size / sh_entsize; ++cnt)
700     {
701       sym = gelf_getsymshndx (data, xndxdata, cnt, &sym_mem, &xndx);
702       if (sym == NULL)
703 	{
704 	  ERROR (_("section [%2d] '%s': cannot get symbol %zu: %s\n"),
705 		 idx, section_name (ebl, idx), cnt, elf_errmsg (-1));
706 	  continue;
707 	}
708 
709       const char *name = "<invalid>";
710       if (strshdr == NULL)
711 	name = "";
712       else if (sym->st_name >= strshdr->sh_size)
713 	ERROR (_("\
714 section [%2d] '%s': symbol %zu: invalid name value\n"),
715 	       idx, section_name (ebl, idx), cnt);
716       else
717 	{
718 	  name = elf_strptr (ebl->elf, shdr->sh_link, sym->st_name);
719 	  if (name == NULL)
720 	    name = "";
721 	}
722 
723       if (sym->st_shndx == SHN_XINDEX)
724 	{
725 	  if (xndxdata == NULL)
726 	    {
727 	      if (!no_xndx_warned)
728 		ERROR (_("\
729 section [%2d] '%s': symbol %zu (%s): too large section index but no extended section index section\n"),
730 		       idx, section_name (ebl, idx), cnt, name);
731 	      no_xndx_warned = true;
732 	    }
733 	  else if (xndx < SHN_LORESERVE)
734 	    ERROR (_("\
735 section [%2d] '%s': symbol %zu (%s): XINDEX used for index which would fit in st_shndx (%" PRIu32 ")\n"),
736 		   xndxscnidx, section_name (ebl, xndxscnidx), cnt, name,
737 		   xndx);
738 	}
739       else if ((sym->st_shndx >= SHN_LORESERVE
740 		// && sym->st_shndx <= SHN_HIRESERVE    always true
741 		&& sym->st_shndx != SHN_ABS
742 		&& sym->st_shndx != SHN_COMMON)
743 	       || (sym->st_shndx >= shnum
744 		   && (sym->st_shndx < SHN_LORESERVE
745 		       /* || sym->st_shndx > SHN_HIRESERVE  always false */)))
746 	ERROR (_("\
747 section [%2d] '%s': symbol %zu (%s): invalid section index\n"),
748 	       idx, section_name (ebl, idx), cnt, name);
749       else
750 	xndx = sym->st_shndx;
751 
752       if (GELF_ST_TYPE (sym->st_info) >= STT_NUM
753 	  && !ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info), NULL, 0))
754 	ERROR (_("section [%2d] '%s': symbol %zu (%s): unknown type\n"),
755 	       idx, section_name (ebl, idx), cnt, name);
756 
757       if (GELF_ST_BIND (sym->st_info) >= STB_NUM
758 	  && !ebl_symbol_binding_name (ebl, GELF_ST_BIND (sym->st_info), NULL,
759 				       0))
760 	ERROR (_("\
761 section [%2d] '%s': symbol %zu (%s): unknown symbol binding\n"),
762 	       idx, section_name (ebl, idx), cnt, name);
763       if (GELF_ST_BIND (sym->st_info) == STB_GNU_UNIQUE
764 	  && GELF_ST_TYPE (sym->st_info) != STT_OBJECT)
765 	ERROR (_("\
766 section [%2d] '%s': symbol %zu (%s): unique symbol not of object type\n"),
767 	       idx, section_name (ebl, idx), cnt, name);
768 
769       if (xndx == SHN_COMMON)
770 	{
771 	  /* Common symbols can only appear in relocatable files.  */
772 	  if (ehdr->e_type != ET_REL)
773 	    ERROR (_("\
774 section [%2d] '%s': symbol %zu (%s): COMMON only allowed in relocatable files\n"),
775 		   idx, section_name (ebl, idx), cnt, name);
776 	  if (cnt < shdr->sh_info)
777 	    ERROR (_("\
778 section [%2d] '%s': symbol %zu (%s): local COMMON symbols are nonsense\n"),
779 		   idx, section_name (ebl, idx), cnt, name);
780 	  if (GELF_R_TYPE (sym->st_info) == STT_FUNC)
781 	    ERROR (_("\
782 section [%2d] '%s': symbol %zu (%s): function in COMMON section is nonsense\n"),
783 		   idx, section_name (ebl, idx), cnt, name);
784 	}
785       else if (xndx > 0 && xndx < shnum)
786 	{
787 	  GElf_Shdr destshdr_mem;
788 	  GElf_Shdr *destshdr;
789 
790 	  destshdr = gelf_getshdr (elf_getscn (ebl->elf, xndx), &destshdr_mem);
791 	  if (destshdr != NULL)
792 	    {
793 	      GElf_Addr sh_addr = (ehdr->e_type == ET_REL ? 0
794 				   : destshdr->sh_addr);
795 	      GElf_Addr st_value;
796 	      if (GELF_ST_TYPE (sym->st_info) == STT_FUNC
797 		  || (GELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC))
798 		st_value = sym->st_value & ebl_func_addr_mask (ebl);
799 	      else
800 		st_value = sym->st_value;
801 	      if (GELF_ST_TYPE (sym->st_info) != STT_TLS)
802 		{
803 		  if (! ebl_check_special_symbol (ebl, sym, name,
804 						  destshdr))
805 		    {
806 		      if (st_value - sh_addr > destshdr->sh_size)
807 			{
808 			  /* GNU ld has severe bugs.  When it decides to remove
809 			     empty sections it leaves symbols referencing them
810 			     behind.  These are symbols in .symtab or .dynsym
811 			     and for the named symbols have zero size.  See
812 			     sourceware PR13621.  */
813 			  if (!gnuld
814 			      || (strcmp (section_name (ebl, idx), ".symtab")
815 			          && strcmp (section_name (ebl, idx),
816 					     ".dynsym"))
817 			      || sym->st_size != 0
818 			      || (strcmp (name, "__preinit_array_start") != 0
819 				  && strcmp (name, "__preinit_array_end") != 0
820 				  && strcmp (name, "__init_array_start") != 0
821 				  && strcmp (name, "__init_array_end") != 0
822 				  && strcmp (name, "__fini_array_start") != 0
823 				  && strcmp (name, "__fini_array_end") != 0
824 				  && strcmp (name, "__bss_start") != 0
825 				  && strcmp (name, "__bss_start__") != 0
826 				  && strcmp (name, "__TMC_END__") != 0
827 				  && strcmp (name, ".TOC.") != 0
828 				  && strcmp (name, "_edata") != 0
829 				  && strcmp (name, "__edata") != 0
830 				  && strcmp (name, "_end") != 0
831 				  && strcmp (name, "__end") != 0))
832 			    ERROR (_("\
833 section [%2d] '%s': symbol %zu (%s): st_value out of bounds\n"),
834 				   idx, section_name (ebl, idx), cnt, name);
835 			}
836 		      else if ((st_value - sh_addr
837 				+ sym->st_size) > destshdr->sh_size)
838 			ERROR (_("\
839 section [%2d] '%s': symbol %zu (%s) does not fit completely in referenced section [%2d] '%s'\n"),
840 			       idx, section_name (ebl, idx), cnt, name,
841 			       (int) xndx, section_name (ebl, xndx));
842 		    }
843 		}
844 	      else
845 		{
846 		  if ((destshdr->sh_flags & SHF_TLS) == 0)
847 		    ERROR (_("\
848 section [%2d] '%s': symbol %zu (%s): referenced section [%2d] '%s' does not have SHF_TLS flag set\n"),
849 			   idx, section_name (ebl, idx), cnt, name,
850 			   (int) xndx, section_name (ebl, xndx));
851 
852 		  if (ehdr->e_type == ET_REL)
853 		    {
854 		      /* For object files the symbol value must fall
855 			 into the section.  */
856 		      if (st_value > destshdr->sh_size)
857 			ERROR (_("\
858 section [%2d] '%s': symbol %zu (%s): st_value out of bounds of referenced section [%2d] '%s'\n"),
859 			       idx, section_name (ebl, idx), cnt, name,
860 			       (int) xndx, section_name (ebl, xndx));
861 		      else if (st_value + sym->st_size
862 			       > destshdr->sh_size)
863 			ERROR (_("\
864 section [%2d] '%s': symbol %zu (%s) does not fit completely in referenced section [%2d] '%s'\n"),
865 			       idx, section_name (ebl, idx), cnt, name,
866 			       (int) xndx, section_name (ebl, xndx));
867 		    }
868 		  else
869 		    {
870 		      GElf_Phdr phdr_mem;
871 		      GElf_Phdr *phdr = NULL;
872 		      unsigned int pcnt;
873 
874 		      for (pcnt = 0; pcnt < phnum; ++pcnt)
875 			{
876 			  phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
877 			  if (phdr != NULL && phdr->p_type == PT_TLS)
878 			    break;
879 			}
880 
881 		      if (pcnt == phnum)
882 			{
883 			  if (no_pt_tls++ == 0)
884 			    ERROR (_("\
885 section [%2d] '%s': symbol %zu (%s): TLS symbol but no TLS program header entry\n"),
886 				   idx, section_name (ebl, idx), cnt, name);
887 			}
888 		      else if (phdr == NULL)
889 			{
890 			    ERROR (_("\
891 section [%2d] '%s': symbol %zu (%s): TLS symbol but couldn't get TLS program header entry\n"),
892 				   idx, section_name (ebl, idx), cnt, name);
893 			}
894 		      else if (!is_debuginfo)
895 			{
896 			  if (st_value
897 			      < destshdr->sh_offset - phdr->p_offset)
898 			    ERROR (_("\
899 section [%2d] '%s': symbol %zu (%s): st_value short of referenced section [%2d] '%s'\n"),
900 				   idx, section_name (ebl, idx), cnt, name,
901 				   (int) xndx, section_name (ebl, xndx));
902 			  else if (st_value
903 				   > (destshdr->sh_offset - phdr->p_offset
904 				      + destshdr->sh_size))
905 			    ERROR (_("\
906 section [%2d] '%s': symbol %zu (%s): st_value out of bounds of referenced section [%2d] '%s'\n"),
907 				   idx, section_name (ebl, idx), cnt, name,
908 				   (int) xndx, section_name (ebl, xndx));
909 			  else if (st_value + sym->st_size
910 				   > (destshdr->sh_offset - phdr->p_offset
911 				      + destshdr->sh_size))
912 			    ERROR (_("\
913 section [%2d] '%s': symbol %zu (%s) does not fit completely in referenced section [%2d] '%s'\n"),
914 				   idx, section_name (ebl, idx), cnt, name,
915 				   (int) xndx, section_name (ebl, xndx));
916 			}
917 		    }
918 		}
919 	    }
920 	}
921 
922       if (GELF_ST_BIND (sym->st_info) == STB_LOCAL)
923 	{
924 	  if (cnt >= shdr->sh_info)
925 	    ERROR (_("\
926 section [%2d] '%s': symbol %zu (%s): local symbol outside range described in sh_info\n"),
927 		   idx, section_name (ebl, idx), cnt, name);
928 	}
929       else
930 	{
931 	  if (cnt < shdr->sh_info)
932 	    ERROR (_("\
933 section [%2d] '%s': symbol %zu (%s): non-local symbol outside range described in sh_info\n"),
934 		   idx, section_name (ebl, idx), cnt, name);
935 	}
936 
937       if (GELF_ST_TYPE (sym->st_info) == STT_SECTION
938 	  && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
939 	ERROR (_("\
940 section [%2d] '%s': symbol %zu (%s): non-local section symbol\n"),
941 	       idx, section_name (ebl, idx), cnt, name);
942 
943       if (name != NULL)
944 	{
945 	  if (strcmp (name, "_GLOBAL_OFFSET_TABLE_") == 0)
946 	    {
947 	      /* Check that address and size match the global offset table.  */
948 
949 	      GElf_Shdr destshdr_mem;
950 	      GElf_Shdr *destshdr = gelf_getshdr (elf_getscn (ebl->elf, xndx),
951 						  &destshdr_mem);
952 
953 	      if (destshdr == NULL && xndx == SHN_ABS)
954 		{
955 		  /* In a DSO, we have to find the GOT section by name.  */
956 		  Elf_Scn *gotscn = NULL;
957 		  Elf_Scn *gscn = NULL;
958 		  while ((gscn = elf_nextscn (ebl->elf, gscn)) != NULL)
959 		    {
960 		      destshdr = gelf_getshdr (gscn, &destshdr_mem);
961 		      assert (destshdr != NULL);
962 		      const char *sname = elf_strptr (ebl->elf,
963 						      shstrndx,
964 						      destshdr->sh_name);
965 		      if (sname != NULL)
966 			{
967 			  if (strcmp (sname, ".got.plt") == 0)
968 			    break;
969 			  if (strcmp (sname, ".got") == 0)
970 			    /* Do not stop looking.
971 			       There might be a .got.plt section.  */
972 			    gotscn = gscn;
973 			}
974 
975 		      destshdr = NULL;
976 		    }
977 
978 		  if (destshdr == NULL && gotscn != NULL)
979 		    destshdr = gelf_getshdr (gotscn, &destshdr_mem);
980 		}
981 
982 	      const char *sname = ((destshdr == NULL || xndx == SHN_UNDEF)
983 				   ? NULL
984 				   : elf_strptr (ebl->elf, shstrndx,
985 						 destshdr->sh_name));
986 	      if (sname == NULL)
987 		{
988 		  if (xndx != SHN_UNDEF || ehdr->e_type != ET_REL)
989 		    ERROR (_("\
990 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol refers to \
991 bad section [%2d]\n"),
992 			   idx, section_name (ebl, idx), xndx);
993 		}
994 	      else if (strcmp (sname, ".got.plt") != 0
995 		       && strcmp (sname, ".got") != 0)
996 		ERROR (_("\
997 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol refers to \
998 section [%2d] '%s'\n"),
999 		       idx, section_name (ebl, idx), xndx, sname);
1000 
1001 	      if (destshdr != NULL)
1002 		{
1003 		  /* Found it.  */
1004 		  if (!ebl_check_special_symbol (ebl, sym, name,
1005 						 destshdr))
1006 		    {
1007 		      if (ehdr->e_type != ET_REL
1008 			  && sym->st_value != destshdr->sh_addr)
1009 			/* This test is more strict than the psABIs which
1010 			   usually allow the symbol to be in the middle of
1011 			   the .got section, allowing negative offsets.  */
1012 			ERROR (_("\
1013 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol value %#" PRIx64 " does not match %s section address %#" PRIx64 "\n"),
1014 			       idx, section_name (ebl, idx),
1015 			       (uint64_t) sym->st_value,
1016 			       sname, (uint64_t) destshdr->sh_addr);
1017 
1018 		      if (!gnuld && sym->st_size != destshdr->sh_size)
1019 			ERROR (_("\
1020 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol size %" PRIu64 " does not match %s section size %" PRIu64 "\n"),
1021 			       idx, section_name (ebl, idx),
1022 			       (uint64_t) sym->st_size,
1023 			       sname, (uint64_t) destshdr->sh_size);
1024 		    }
1025 		}
1026 	      else
1027 		ERROR (_("\
1028 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol present, but no .got section\n"),
1029 		       idx, section_name (ebl, idx));
1030 	    }
1031 	  else if (strcmp (name, "_DYNAMIC") == 0)
1032 	    /* Check that address and size match the dynamic section.
1033 	       We locate the dynamic section via the program header
1034 	       entry.  */
1035 	    for (unsigned int pcnt = 0; pcnt < phnum; ++pcnt)
1036 	      {
1037 		GElf_Phdr phdr_mem;
1038 		GElf_Phdr *phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
1039 
1040 		if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
1041 		  {
1042 		    if (sym->st_value != phdr->p_vaddr)
1043 		      ERROR (_("\
1044 section [%2d] '%s': _DYNAMIC_ symbol value %#" PRIx64 " does not match dynamic segment address %#" PRIx64 "\n"),
1045 			     idx, section_name (ebl, idx),
1046 			     (uint64_t) sym->st_value,
1047 			     (uint64_t) phdr->p_vaddr);
1048 
1049 		    if (!gnuld && sym->st_size != phdr->p_memsz)
1050 		      ERROR (_("\
1051 section [%2d] '%s': _DYNAMIC symbol size %" PRIu64 " does not match dynamic segment size %" PRIu64 "\n"),
1052 			     idx, section_name (ebl, idx),
1053 			     (uint64_t) sym->st_size,
1054 			     (uint64_t) phdr->p_memsz);
1055 
1056 		    break;
1057 		  }
1058 	    }
1059 	}
1060 
1061       if (GELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1062 	  && shdr->sh_type == SHT_DYNSYM)
1063 	ERROR (_("\
1064 section [%2d] '%s': symbol %zu (%s): symbol in dynamic symbol table with non-default visibility\n"),
1065 	       idx, section_name (ebl, idx), cnt, name);
1066       if (! ebl_check_st_other_bits (ebl, sym->st_other))
1067 	ERROR (_("\
1068 section [%2d] '%s': symbol %zu (%s): unknown bit set in st_other\n"),
1069 	       idx, section_name (ebl, idx), cnt, name);
1070 
1071     }
1072 }
1073 
1074 
1075 static bool
is_rel_dyn(Ebl * ebl,const GElf_Ehdr * ehdr,int idx,const GElf_Shdr * shdr,bool is_rela)1076 is_rel_dyn (Ebl *ebl, const GElf_Ehdr *ehdr, int idx, const GElf_Shdr *shdr,
1077 	    bool is_rela)
1078 {
1079   /* If this is no executable or DSO it cannot be a .rel.dyn section.  */
1080   if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
1081     return false;
1082 
1083   /* Check the section name.  Unfortunately necessary.  */
1084   if (strcmp (section_name (ebl, idx), is_rela ? ".rela.dyn" : ".rel.dyn"))
1085     return false;
1086 
1087   /* When a .rel.dyn section is used a DT_RELCOUNT dynamic section
1088      entry can be present as well.  */
1089   Elf_Scn *scn = NULL;
1090   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
1091     {
1092       GElf_Shdr rcshdr_mem;
1093       const GElf_Shdr *rcshdr = gelf_getshdr (scn, &rcshdr_mem);
1094 
1095       if (rcshdr == NULL)
1096 	break;
1097 
1098       if (rcshdr->sh_type == SHT_DYNAMIC && rcshdr->sh_entsize != 0)
1099 	{
1100 	  /* Found the dynamic section.  Look through it.  */
1101 	  Elf_Data *d = elf_getdata (scn, NULL);
1102 	  size_t cnt;
1103 
1104 	  if (d == NULL)
1105 	    ERROR (_("\
1106 section [%2d] '%s': cannot get section data.\n"),
1107 		   idx, section_name (ebl, idx));
1108 
1109 	  for (cnt = 1; cnt < rcshdr->sh_size / rcshdr->sh_entsize; ++cnt)
1110 	    {
1111 	      GElf_Dyn dyn_mem;
1112 	      GElf_Dyn *dyn = gelf_getdyn (d, cnt, &dyn_mem);
1113 
1114 	      if (dyn == NULL)
1115 		break;
1116 
1117 	      if (dyn->d_tag == DT_RELCOUNT)
1118 		{
1119 		  /* Found it.  Does the type match.  */
1120 		  if (is_rela)
1121 		    ERROR (_("\
1122 section [%2d] '%s': DT_RELCOUNT used for this RELA section\n"),
1123 			   idx, section_name (ebl, idx));
1124 		  else
1125 		    {
1126 		      /* Does the number specified number of relative
1127 			 relocations exceed the total number of
1128 			 relocations?  */
1129 		      if (shdr->sh_entsize != 0
1130 			  && dyn->d_un.d_val > (shdr->sh_size
1131 						/ shdr->sh_entsize))
1132 			ERROR (_("\
1133 section [%2d] '%s': DT_RELCOUNT value %d too high for this section\n"),
1134 			       idx, section_name (ebl, idx),
1135 			       (int) dyn->d_un.d_val);
1136 
1137 		      /* Make sure the specified number of relocations are
1138 			 relative.  */
1139 		      Elf_Data *reldata = elf_getdata (elf_getscn (ebl->elf,
1140 								   idx), NULL);
1141 		      if (reldata != NULL && shdr->sh_entsize != 0)
1142 			for (size_t inner = 0;
1143 			     inner < shdr->sh_size / shdr->sh_entsize;
1144 			     ++inner)
1145 			  {
1146 			    GElf_Rel rel_mem;
1147 			    GElf_Rel *rel = gelf_getrel (reldata, inner,
1148 							 &rel_mem);
1149 			    if (rel == NULL)
1150 			      /* The problem will be reported elsewhere.  */
1151 			      break;
1152 
1153 			    if (ebl_relative_reloc_p (ebl,
1154 						      GELF_R_TYPE (rel->r_info)))
1155 			      {
1156 				if (inner >= dyn->d_un.d_val)
1157 				  ERROR (_("\
1158 section [%2d] '%s': relative relocations after index %d as specified by DT_RELCOUNT\n"),
1159 					 idx, section_name (ebl, idx),
1160 					 (int) dyn->d_un.d_val);
1161 			      }
1162 			    else if (inner < dyn->d_un.d_val)
1163 			      ERROR (_("\
1164 section [%2d] '%s': non-relative relocation at index %zu; DT_RELCOUNT specified %d relative relocations\n"),
1165 				     idx, section_name (ebl, idx),
1166 				     inner, (int) dyn->d_un.d_val);
1167 			  }
1168 		    }
1169 		}
1170 
1171 	      if (dyn->d_tag == DT_RELACOUNT)
1172 		{
1173 		  /* Found it.  Does the type match.  */
1174 		  if (!is_rela)
1175 		    ERROR (_("\
1176 section [%2d] '%s': DT_RELACOUNT used for this REL section\n"),
1177 			   idx, section_name (ebl, idx));
1178 		  else
1179 		    {
1180 		      /* Does the number specified number of relative
1181 			 relocations exceed the total number of
1182 			 relocations?  */
1183 		      if (shdr->sh_entsize != 0
1184 			  && dyn->d_un.d_val > shdr->sh_size / shdr->sh_entsize)
1185 			ERROR (_("\
1186 section [%2d] '%s': DT_RELCOUNT value %d too high for this section\n"),
1187 			       idx, section_name (ebl, idx),
1188 			       (int) dyn->d_un.d_val);
1189 
1190 		      /* Make sure the specified number of relocations are
1191 			 relative.  */
1192 		      Elf_Data *reldata = elf_getdata (elf_getscn (ebl->elf,
1193 								   idx), NULL);
1194 		      if (reldata != NULL && shdr->sh_entsize != 0)
1195 			for (size_t inner = 0;
1196 			     inner < shdr->sh_size / shdr->sh_entsize;
1197 			     ++inner)
1198 			  {
1199 			    GElf_Rela rela_mem;
1200 			    GElf_Rela *rela = gelf_getrela (reldata, inner,
1201 							    &rela_mem);
1202 			    if (rela == NULL)
1203 			      /* The problem will be reported elsewhere.  */
1204 			      break;
1205 
1206 			    if (ebl_relative_reloc_p (ebl,
1207 						      GELF_R_TYPE (rela->r_info)))
1208 			      {
1209 				if (inner >= dyn->d_un.d_val)
1210 				  ERROR (_("\
1211 section [%2d] '%s': relative relocations after index %d as specified by DT_RELCOUNT\n"),
1212 					 idx, section_name (ebl, idx),
1213 					 (int) dyn->d_un.d_val);
1214 			      }
1215 			    else if (inner < dyn->d_un.d_val)
1216 			      ERROR (_("\
1217 section [%2d] '%s': non-relative relocation at index %zu; DT_RELCOUNT specified %d relative relocations\n"),
1218 				     idx, section_name (ebl, idx),
1219 				     inner, (int) dyn->d_un.d_val);
1220 			  }
1221 		    }
1222 		}
1223 	    }
1224 
1225 	  break;
1226 	}
1227     }
1228 
1229   return true;
1230 }
1231 
1232 
1233 struct loaded_segment
1234 {
1235   GElf_Addr from;
1236   GElf_Addr to;
1237   bool read_only;
1238   struct loaded_segment *next;
1239 };
1240 
1241 
1242 /* Check whether binary has text relocation flag set.  */
1243 static bool textrel;
1244 
1245 /* Keep track of whether text relocation flag is needed.  */
1246 static bool needed_textrel;
1247 
1248 
1249 static bool
check_reloc_shdr(Ebl * ebl,const GElf_Ehdr * ehdr,const GElf_Shdr * shdr,int idx,int reltype,GElf_Shdr ** destshdrp,GElf_Shdr * destshdr_memp,struct loaded_segment ** loadedp)1250 check_reloc_shdr (Ebl *ebl, const GElf_Ehdr *ehdr, const GElf_Shdr *shdr,
1251 		  int idx, int reltype, GElf_Shdr **destshdrp,
1252 		  GElf_Shdr *destshdr_memp, struct loaded_segment **loadedp)
1253 {
1254   bool reldyn = false;
1255 
1256   /* Check whether the link to the section we relocate is reasonable.  */
1257   if (shdr->sh_info >= shnum)
1258     ERROR (_("section [%2d] '%s': invalid destination section index\n"),
1259 	   idx, section_name (ebl, idx));
1260   else if (shdr->sh_info != 0)
1261     {
1262       *destshdrp = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1263 				 destshdr_memp);
1264       if (*destshdrp != NULL)
1265 	{
1266 	  if(! ebl_check_reloc_target_type (ebl, (*destshdrp)->sh_type))
1267 	    {
1268 	      reldyn = is_rel_dyn (ebl, ehdr, idx, shdr, true);
1269 	      if (!reldyn)
1270 		ERROR (_("\
1271 section [%2d] '%s': invalid destination section type\n"),
1272 		       idx, section_name (ebl, idx));
1273 	      else
1274 		{
1275 		  /* There is no standard, but we require that .rel{,a}.dyn
1276 		     sections have a sh_info value of zero.  */
1277 		  if (shdr->sh_info != 0)
1278 		    ERROR (_("\
1279 section [%2d] '%s': sh_info should be zero\n"),
1280 			   idx, section_name (ebl, idx));
1281 		}
1282 	    }
1283 
1284 	  if ((((*destshdrp)->sh_flags & SHF_MERGE) != 0)
1285 	      && ((*destshdrp)->sh_flags & SHF_STRINGS) != 0)
1286 	    ERROR (_("\
1287 section [%2d] '%s': no relocations for merge-able string sections possible\n"),
1288 		   idx, section_name (ebl, idx));
1289 	}
1290     }
1291 
1292   size_t sh_entsize = gelf_fsize (ebl->elf, reltype, 1, EV_CURRENT);
1293   if (shdr->sh_entsize != sh_entsize)
1294     ERROR (_(reltype == ELF_T_RELA ? "\
1295 section [%2d] '%s': section entry size does not match ElfXX_Rela\n" : "\
1296 section [%2d] '%s': section entry size does not match ElfXX_Rel\n"),
1297 	   idx, section_name (ebl, idx));
1298 
1299   /* In preparation of checking whether relocations are text
1300      relocations or not we need to determine whether the file is
1301      flagged to have text relocation and we need to determine a) what
1302      the loaded segments are and b) which are read-only.  This will
1303      also allow us to determine whether the same reloc section is
1304      modifying loaded and not loaded segments.  */
1305   for (unsigned int i = 0; i < phnum; ++i)
1306     {
1307       GElf_Phdr phdr_mem;
1308       GElf_Phdr *phdr = gelf_getphdr (ebl->elf, i, &phdr_mem);
1309       if (phdr == NULL)
1310 	continue;
1311 
1312       if (phdr->p_type == PT_LOAD)
1313 	{
1314 	  struct loaded_segment *newp = xmalloc (sizeof (*newp));
1315 	  newp->from = phdr->p_vaddr;
1316 	  newp->to = phdr->p_vaddr + phdr->p_memsz;
1317 	  newp->read_only = (phdr->p_flags & PF_W) == 0;
1318 	  newp->next = *loadedp;
1319 	  *loadedp = newp;
1320 	}
1321       else if (phdr->p_type == PT_DYNAMIC)
1322 	{
1323 	  Elf_Scn *dynscn = gelf_offscn (ebl->elf, phdr->p_offset);
1324 	  GElf_Shdr dynshdr_mem;
1325 	  GElf_Shdr *dynshdr = gelf_getshdr (dynscn, &dynshdr_mem);
1326 	  Elf_Data *dyndata = elf_getdata (dynscn, NULL);
1327 	  if (dynshdr != NULL && dynshdr->sh_type == SHT_DYNAMIC
1328 	      && dyndata != NULL && dynshdr->sh_entsize != 0)
1329 	    for (size_t j = 0; j < dynshdr->sh_size / dynshdr->sh_entsize; ++j)
1330 	      {
1331 		GElf_Dyn dyn_mem;
1332 		GElf_Dyn *dyn = gelf_getdyn (dyndata, j, &dyn_mem);
1333 		if (dyn != NULL
1334 		    && (dyn->d_tag == DT_TEXTREL
1335 			|| (dyn->d_tag == DT_FLAGS
1336 			    && (dyn->d_un.d_val & DF_TEXTREL) != 0)))
1337 		  {
1338 		    textrel = true;
1339 		    break;
1340 		  }
1341 	      }
1342 	}
1343     }
1344 
1345   /* A quick test which can be easily done here (although it is a bit
1346      out of place): the text relocation flag makes only sense if there
1347      is a segment which is not writable.  */
1348   if (textrel)
1349     {
1350       struct loaded_segment *seg = *loadedp;
1351       while (seg != NULL && !seg->read_only)
1352 	seg = seg->next;
1353       if (seg == NULL)
1354 	ERROR (_("\
1355 text relocation flag set but there is no read-only segment\n"));
1356     }
1357 
1358   return reldyn;
1359 }
1360 
1361 
1362 enum load_state
1363   {
1364     state_undecided,
1365     state_loaded,
1366     state_unloaded,
1367     state_error
1368   };
1369 
1370 
1371 static void
check_one_reloc(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * relshdr,int idx,size_t cnt,const GElf_Shdr * symshdr,Elf_Data * symdata,GElf_Addr r_offset,GElf_Xword r_info,const GElf_Shdr * destshdr,bool reldyn,struct loaded_segment * loaded,enum load_state * statep)1372 check_one_reloc (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *relshdr, int idx,
1373 		 size_t cnt, const GElf_Shdr *symshdr, Elf_Data *symdata,
1374 		 GElf_Addr r_offset, GElf_Xword r_info,
1375 		 const GElf_Shdr *destshdr, bool reldyn,
1376 		 struct loaded_segment *loaded, enum load_state *statep)
1377 {
1378   bool known_broken = gnuld;
1379 
1380   if (!ebl_reloc_type_check (ebl, GELF_R_TYPE (r_info)))
1381     ERROR (_("section [%2d] '%s': relocation %zu: invalid type\n"),
1382 	   idx, section_name (ebl, idx), cnt);
1383   else if (((ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
1384 	    /* The executable/DSO can contain relocation sections with
1385 	       all the relocations the linker has applied.  Those sections
1386 	       are marked non-loaded, though.  */
1387 	    || (relshdr->sh_flags & SHF_ALLOC) != 0)
1388 	   && !ebl_reloc_valid_use (ebl, GELF_R_TYPE (r_info)))
1389     ERROR (_("\
1390 section [%2d] '%s': relocation %zu: relocation type invalid for the file type\n"),
1391 	   idx, section_name (ebl, idx), cnt);
1392 
1393   if (symshdr != NULL
1394       && ((GELF_R_SYM (r_info) + 1)
1395 	  * gelf_fsize (ebl->elf, ELF_T_SYM, 1, EV_CURRENT)
1396 	  > symshdr->sh_size))
1397     ERROR (_("\
1398 section [%2d] '%s': relocation %zu: invalid symbol index\n"),
1399 	   idx, section_name (ebl, idx), cnt);
1400 
1401   /* No more tests if this is a no-op relocation.  */
1402   if (ebl_none_reloc_p (ebl, GELF_R_TYPE (r_info)))
1403     return;
1404 
1405   if (ebl_gotpc_reloc_check (ebl, GELF_R_TYPE (r_info)))
1406     {
1407       const char *name;
1408       char buf[64];
1409       GElf_Sym sym_mem;
1410       GElf_Sym *sym = gelf_getsym (symdata, GELF_R_SYM (r_info), &sym_mem);
1411       if (sym != NULL
1412 	  /* Get the name for the symbol.  */
1413 	  && (name = elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1414 	  && strcmp (name, "_GLOBAL_OFFSET_TABLE_") !=0 )
1415 	ERROR (_("\
1416 section [%2d] '%s': relocation %zu: only symbol '_GLOBAL_OFFSET_TABLE_' can be used with %s\n"),
1417 	       idx, section_name (ebl, idx), cnt,
1418 	       ebl_reloc_type_name (ebl, GELF_R_SYM (r_info),
1419 				    buf, sizeof (buf)));
1420     }
1421 
1422   if (reldyn)
1423     {
1424       // XXX TODO Check .rel.dyn section addresses.
1425     }
1426   else if (!known_broken)
1427     {
1428       if (destshdr != NULL
1429 	  && GELF_R_TYPE (r_info) != 0
1430 	  && (r_offset - (ehdr->e_type == ET_REL ? 0
1431 			  : destshdr->sh_addr)) >= destshdr->sh_size)
1432 	ERROR (_("\
1433 section [%2d] '%s': relocation %zu: offset out of bounds\n"),
1434 	       idx, section_name (ebl, idx), cnt);
1435     }
1436 
1437   GElf_Sym sym_mem;
1438   GElf_Sym *sym = gelf_getsym (symdata, GELF_R_SYM (r_info), &sym_mem);
1439 
1440   if (ebl_copy_reloc_p (ebl, GELF_R_TYPE (r_info))
1441       /* Make sure the referenced symbol is an object or unspecified.  */
1442       && sym != NULL
1443       && GELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1444       && GELF_ST_TYPE (sym->st_info) != STT_OBJECT)
1445     {
1446       char buf[64];
1447       ERROR (_("section [%2d] '%s': relocation %zu: copy relocation against symbol of type %s\n"),
1448 	     idx, section_name (ebl, idx), cnt,
1449 	     ebl_symbol_type_name (ebl, GELF_ST_TYPE (sym->st_info),
1450 				   buf, sizeof (buf)));
1451     }
1452 
1453   if ((ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
1454       || (relshdr->sh_flags & SHF_ALLOC) != 0)
1455     {
1456       bool in_loaded_seg = false;
1457       while (loaded != NULL)
1458 	{
1459 	  if (r_offset < loaded->to
1460 	      && r_offset + (sym == NULL ? 0 : sym->st_size) >= loaded->from)
1461 	    {
1462 	      /* The symbol is in this segment.  */
1463 	      if  (loaded->read_only)
1464 		{
1465 		  if (textrel)
1466 		    needed_textrel = true;
1467 		  else
1468 		    ERROR (_("section [%2d] '%s': relocation %zu: read-only section modified but text relocation flag not set\n"),
1469 			   idx, section_name (ebl, idx), cnt);
1470 		}
1471 
1472 	      in_loaded_seg = true;
1473 	    }
1474 
1475 	  loaded = loaded->next;
1476 	}
1477 
1478       if (*statep == state_undecided)
1479 	*statep = in_loaded_seg ? state_loaded : state_unloaded;
1480       else if ((*statep == state_unloaded && in_loaded_seg)
1481 	       || (*statep == state_loaded && !in_loaded_seg))
1482 	{
1483 	  ERROR (_("\
1484 section [%2d] '%s': relocations are against loaded and unloaded data\n"),
1485 		 idx, section_name (ebl, idx));
1486 	  *statep = state_error;
1487 	}
1488     }
1489 }
1490 
1491 
1492 static void
check_rela(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1493 check_rela (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1494 {
1495   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
1496   if (data == NULL)
1497     {
1498       ERROR (_("section [%2d] '%s': cannot get section data\n"),
1499 	     idx, section_name (ebl, idx));
1500       return;
1501     }
1502 
1503   /* Check the fields of the section header.  */
1504   GElf_Shdr destshdr_mem;
1505   GElf_Shdr *destshdr = NULL;
1506   struct loaded_segment *loaded = NULL;
1507   bool reldyn = check_reloc_shdr (ebl, ehdr, shdr, idx, ELF_T_RELA, &destshdr,
1508 				  &destshdr_mem, &loaded);
1509 
1510   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1511   GElf_Shdr symshdr_mem;
1512   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1513   Elf_Data *symdata = elf_getdata (symscn, NULL);
1514   enum load_state state = state_undecided;
1515 
1516   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT);
1517   for (size_t cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
1518     {
1519       GElf_Rela rela_mem;
1520       GElf_Rela *rela = gelf_getrela (data, cnt, &rela_mem);
1521       if (rela == NULL)
1522 	{
1523 	  ERROR (_("\
1524 section [%2d] '%s': cannot get relocation %zu: %s\n"),
1525 		 idx, section_name (ebl, idx), cnt, elf_errmsg (-1));
1526 	  continue;
1527 	}
1528 
1529       check_one_reloc (ebl, ehdr, shdr, idx, cnt, symshdr, symdata,
1530 		       rela->r_offset, rela->r_info, destshdr, reldyn, loaded,
1531 		       &state);
1532     }
1533 
1534   while (loaded != NULL)
1535     {
1536       struct loaded_segment *old = loaded;
1537       loaded = loaded->next;
1538       free (old);
1539     }
1540 }
1541 
1542 
1543 static void
check_rel(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1544 check_rel (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1545 {
1546   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
1547   if (data == NULL)
1548     {
1549       ERROR (_("section [%2d] '%s': cannot get section data\n"),
1550 	     idx, section_name (ebl, idx));
1551       return;
1552     }
1553 
1554   /* Check the fields of the section header.  */
1555   GElf_Shdr destshdr_mem;
1556   GElf_Shdr *destshdr = NULL;
1557   struct loaded_segment *loaded = NULL;
1558   bool reldyn = check_reloc_shdr (ebl, ehdr, shdr, idx, ELF_T_REL, &destshdr,
1559 				  &destshdr_mem, &loaded);
1560 
1561   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1562   GElf_Shdr symshdr_mem;
1563   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1564   Elf_Data *symdata = elf_getdata (symscn, NULL);
1565   enum load_state state = state_undecided;
1566 
1567   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT);
1568   for (size_t cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
1569     {
1570       GElf_Rel rel_mem;
1571       GElf_Rel *rel = gelf_getrel (data, cnt, &rel_mem);
1572       if (rel == NULL)
1573 	{
1574 	  ERROR (_("\
1575 section [%2d] '%s': cannot get relocation %zu: %s\n"),
1576 		 idx, section_name (ebl, idx), cnt, elf_errmsg (-1));
1577 	  continue;
1578 	}
1579 
1580       check_one_reloc (ebl, ehdr, shdr, idx, cnt, symshdr, symdata,
1581 		       rel->r_offset, rel->r_info, destshdr, reldyn, loaded,
1582 		       &state);
1583     }
1584 
1585   while (loaded != NULL)
1586     {
1587       struct loaded_segment *old = loaded;
1588       loaded = loaded->next;
1589       free (old);
1590     }
1591 }
1592 
1593 
1594 /* Number of dynamic sections.  */
1595 static int ndynamic;
1596 
1597 
1598 static void
check_dynamic(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1599 check_dynamic (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1600 {
1601   Elf_Data *data;
1602   GElf_Shdr strshdr_mem;
1603   GElf_Shdr *strshdr;
1604   size_t cnt;
1605   static const bool dependencies[DT_NUM][DT_NUM] =
1606     {
1607       [DT_NEEDED] = { [DT_STRTAB] = true },
1608       [DT_PLTRELSZ] = { [DT_JMPREL] = true },
1609       [DT_HASH] = { [DT_SYMTAB] = true },
1610       [DT_STRTAB] = { [DT_STRSZ] = true },
1611       [DT_SYMTAB] = { [DT_STRTAB] = true, [DT_SYMENT] = true },
1612       [DT_RELA] = { [DT_RELASZ] = true, [DT_RELAENT] = true },
1613       [DT_RELASZ] = { [DT_RELA] = true },
1614       [DT_RELAENT] = { [DT_RELA] = true },
1615       [DT_STRSZ] = { [DT_STRTAB] = true },
1616       [DT_SYMENT] = { [DT_SYMTAB] = true },
1617       [DT_SONAME] = { [DT_STRTAB] = true },
1618       [DT_RPATH] = { [DT_STRTAB] = true },
1619       [DT_REL] = { [DT_RELSZ] = true, [DT_RELENT] = true },
1620       [DT_RELSZ] = { [DT_REL] = true },
1621       [DT_RELENT] = { [DT_REL] = true },
1622       [DT_JMPREL] = { [DT_PLTRELSZ] = true, [DT_PLTREL] = true },
1623       [DT_RUNPATH] = { [DT_STRTAB] = true },
1624       [DT_PLTREL] = { [DT_JMPREL] = true },
1625     };
1626   bool has_dt[DT_NUM];
1627   bool has_val_dt[DT_VALNUM];
1628   bool has_addr_dt[DT_ADDRNUM];
1629   static const bool level2[DT_NUM] =
1630     {
1631       [DT_RPATH] = true,
1632       [DT_SYMBOLIC] = true,
1633       [DT_TEXTREL] = true,
1634       [DT_BIND_NOW] = true
1635     };
1636   static const bool mandatory[DT_NUM] =
1637     {
1638       [DT_NULL] = true,
1639       [DT_STRTAB] = true,
1640       [DT_SYMTAB] = true,
1641       [DT_STRSZ] = true,
1642       [DT_SYMENT] = true
1643     };
1644 
1645   memset (has_dt, '\0', sizeof (has_dt));
1646   memset (has_val_dt, '\0', sizeof (has_val_dt));
1647   memset (has_addr_dt, '\0', sizeof (has_addr_dt));
1648 
1649   if (++ndynamic == 2)
1650     ERROR (_("more than one dynamic section present\n"));
1651 
1652   data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
1653   if (data == NULL)
1654     {
1655       ERROR (_("section [%2d] '%s': cannot get section data\n"),
1656 	     idx, section_name (ebl, idx));
1657       return;
1658     }
1659 
1660   strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &strshdr_mem);
1661   if (strshdr != NULL && strshdr->sh_type != SHT_STRTAB)
1662     ERROR (_("\
1663 section [%2d] '%s': referenced as string table for section [%2d] '%s' but type is not SHT_STRTAB\n"),
1664 	   shdr->sh_link, section_name (ebl, shdr->sh_link),
1665 	   idx, section_name (ebl, idx));
1666   else if (strshdr == NULL)
1667     {
1668       ERROR (_("\
1669 section [%2d]: referenced as string table for section [%2d] '%s' but section link value is invalid\n"),
1670 	   shdr->sh_link, idx, section_name (ebl, idx));
1671       return;
1672     }
1673 
1674   size_t sh_entsize = gelf_fsize (ebl->elf, ELF_T_DYN, 1, EV_CURRENT);
1675   if (shdr->sh_entsize != sh_entsize)
1676     ERROR (_("\
1677 section [%2d] '%s': section entry size does not match ElfXX_Dyn\n"),
1678 	   idx, section_name (ebl, idx));
1679 
1680   if (shdr->sh_info != 0)
1681     ERROR (_("section [%2d] '%s': sh_info not zero\n"),
1682 	   idx, section_name (ebl, idx));
1683 
1684   bool non_null_warned = false;
1685   for (cnt = 0; cnt < shdr->sh_size / sh_entsize; ++cnt)
1686     {
1687       GElf_Dyn dyn_mem;
1688       GElf_Dyn *dyn = gelf_getdyn (data, cnt, &dyn_mem);
1689       if (dyn == NULL)
1690 	{
1691 	  ERROR (_("\
1692 section [%2d] '%s': cannot get dynamic section entry %zu: %s\n"),
1693 		 idx, section_name (ebl, idx), cnt, elf_errmsg (-1));
1694 	  continue;
1695 	}
1696 
1697       if (has_dt[DT_NULL] && dyn->d_tag != DT_NULL && ! non_null_warned)
1698 	{
1699 	  ERROR (_("\
1700 section [%2d] '%s': non-DT_NULL entries follow DT_NULL entry\n"),
1701 		 idx, section_name (ebl, idx));
1702 	  non_null_warned = true;
1703 	}
1704 
1705       if (!ebl_dynamic_tag_check (ebl, dyn->d_tag))
1706 	ERROR (_("section [%2d] '%s': entry %zu: unknown tag\n"),
1707 	       idx, section_name (ebl, idx), cnt);
1708 
1709       if (dyn->d_tag >= 0 && dyn->d_tag < DT_NUM)
1710 	{
1711 	  if (has_dt[dyn->d_tag]
1712 	      && dyn->d_tag != DT_NEEDED
1713 	      && dyn->d_tag != DT_NULL
1714 	      && dyn->d_tag != DT_POSFLAG_1)
1715 	    {
1716 	      char buf[50];
1717 	      ERROR (_("\
1718 section [%2d] '%s': entry %zu: more than one entry with tag %s\n"),
1719 		     idx, section_name (ebl, idx), cnt,
1720 		     ebl_dynamic_tag_name (ebl, dyn->d_tag,
1721 					   buf, sizeof (buf)));
1722 	    }
1723 
1724 	  if (be_strict && level2[dyn->d_tag])
1725 	    {
1726 	      char buf[50];
1727 	      ERROR (_("\
1728 section [%2d] '%s': entry %zu: level 2 tag %s used\n"),
1729 		     idx, section_name (ebl, idx), cnt,
1730 		     ebl_dynamic_tag_name (ebl, dyn->d_tag,
1731 					   buf, sizeof (buf)));
1732 	    }
1733 
1734 	  has_dt[dyn->d_tag] = true;
1735 	}
1736       else if (dyn->d_tag >= 0 && dyn->d_tag <= DT_VALRNGHI
1737 	       && DT_VALTAGIDX (dyn->d_tag) < DT_VALNUM)
1738 	has_val_dt[DT_VALTAGIDX (dyn->d_tag)] = true;
1739       else if (dyn->d_tag >= 0 && dyn->d_tag <= DT_ADDRRNGHI
1740 	       && DT_ADDRTAGIDX (dyn->d_tag) < DT_ADDRNUM)
1741 	has_addr_dt[DT_ADDRTAGIDX (dyn->d_tag)] = true;
1742 
1743       if (dyn->d_tag == DT_PLTREL && dyn->d_un.d_val != DT_REL
1744 	  && dyn->d_un.d_val != DT_RELA)
1745 	ERROR (_("\
1746 section [%2d] '%s': entry %zu: DT_PLTREL value must be DT_REL or DT_RELA\n"),
1747 	       idx, section_name (ebl, idx), cnt);
1748 
1749       /* Check that addresses for entries are in loaded segments.  */
1750       switch (dyn->d_tag)
1751 	{
1752 	  size_t n;
1753 	case DT_STRTAB:
1754 	  /* We require the referenced section is the same as the one
1755 	     specified in sh_link.  */
1756 	  if (strshdr->sh_addr != dyn->d_un.d_val)
1757 	    {
1758 	      ERROR (_("\
1759 section [%2d] '%s': entry %zu: pointer does not match address of section [%2d] '%s' referenced by sh_link\n"),
1760 		     idx, section_name (ebl, idx), cnt,
1761 		     shdr->sh_link, section_name (ebl, shdr->sh_link));
1762 	      break;
1763 	    }
1764 	  goto check_addr;
1765 
1766 	default:
1767 	  if (dyn->d_tag < DT_ADDRRNGLO || dyn->d_tag > DT_ADDRRNGHI)
1768 	    /* Value is no pointer.  */
1769 	    break;
1770 	  FALLTHROUGH;
1771 
1772 	case DT_AUXILIARY:
1773 	case DT_FILTER:
1774 	case DT_FINI:
1775 	case DT_FINI_ARRAY:
1776 	case DT_HASH:
1777 	case DT_INIT:
1778 	case DT_INIT_ARRAY:
1779 	case DT_JMPREL:
1780 	case DT_PLTGOT:
1781 	case DT_REL:
1782 	case DT_RELA:
1783 	case DT_SYMBOLIC:
1784 	case DT_SYMTAB:
1785 	case DT_VERDEF:
1786 	case DT_VERNEED:
1787 	case DT_VERSYM:
1788 	check_addr:
1789 	  for (n = 0; n < phnum; ++n)
1790 	    {
1791 	      GElf_Phdr phdr_mem;
1792 	      GElf_Phdr *phdr = gelf_getphdr (ebl->elf, n, &phdr_mem);
1793 	      if (phdr != NULL && phdr->p_type == PT_LOAD
1794 		  && phdr->p_vaddr <= dyn->d_un.d_ptr
1795 		  && phdr->p_vaddr + phdr->p_memsz > dyn->d_un.d_ptr)
1796 		break;
1797 	    }
1798 	  if (unlikely (n >= phnum))
1799 	    {
1800 	      char buf[50];
1801 	      ERROR (_("\
1802 section [%2d] '%s': entry %zu: %s value must point into loaded segment\n"),
1803 		     idx, section_name (ebl, idx), cnt,
1804 		     ebl_dynamic_tag_name (ebl, dyn->d_tag, buf,
1805 					   sizeof (buf)));
1806 	    }
1807 	  break;
1808 
1809 	case DT_NEEDED:
1810 	case DT_RPATH:
1811 	case DT_RUNPATH:
1812 	case DT_SONAME:
1813 	  if (dyn->d_un.d_ptr >= strshdr->sh_size)
1814 	    {
1815 	      char buf[50];
1816 	      ERROR (_("\
1817 section [%2d] '%s': entry %zu: %s value must be valid offset in section [%2d] '%s'\n"),
1818 		     idx, section_name (ebl, idx), cnt,
1819 		     ebl_dynamic_tag_name (ebl, dyn->d_tag, buf,
1820 					   sizeof (buf)),
1821 		     shdr->sh_link, section_name (ebl, shdr->sh_link));
1822 	    }
1823 	  break;
1824 	}
1825     }
1826 
1827   for (cnt = 1; cnt < DT_NUM; ++cnt)
1828     if (has_dt[cnt])
1829       {
1830 	for (int inner = 0; inner < DT_NUM; ++inner)
1831 	  if (dependencies[cnt][inner] && ! has_dt[inner])
1832 	    {
1833 	      char buf1[50];
1834 	      char buf2[50];
1835 
1836 	      ERROR (_("\
1837 section [%2d] '%s': contains %s entry but not %s\n"),
1838 		     idx, section_name (ebl, idx),
1839 		     ebl_dynamic_tag_name (ebl, cnt, buf1, sizeof (buf1)),
1840 		     ebl_dynamic_tag_name (ebl, inner, buf2, sizeof (buf2)));
1841 	    }
1842       }
1843     else
1844       {
1845 	if (mandatory[cnt])
1846 	  {
1847 	    char buf[50];
1848 	    ERROR (_("\
1849 section [%2d] '%s': mandatory tag %s not present\n"),
1850 		   idx, section_name (ebl, idx),
1851 		   ebl_dynamic_tag_name (ebl, cnt, buf, sizeof (buf)));
1852 	  }
1853       }
1854 
1855   /* Make sure we have an hash table.  */
1856   if (!has_dt[DT_HASH] && !has_addr_dt[DT_ADDRTAGIDX (DT_GNU_HASH)])
1857     ERROR (_("\
1858 section [%2d] '%s': no hash section present\n"),
1859 	   idx, section_name (ebl, idx));
1860 
1861   /* The GNU-style hash table also needs a symbol table.  */
1862   if (!has_dt[DT_HASH] && has_addr_dt[DT_ADDRTAGIDX (DT_GNU_HASH)]
1863       && !has_dt[DT_SYMTAB])
1864     ERROR (_("\
1865 section [%2d] '%s': contains %s entry but not %s\n"),
1866 	   idx, section_name (ebl, idx),
1867 	   "DT_GNU_HASH", "DT_SYMTAB");
1868 
1869   /* Check the rel/rela tags.  At least one group must be available.  */
1870   if ((has_dt[DT_RELA] || has_dt[DT_RELASZ] || has_dt[DT_RELAENT])
1871       && (!has_dt[DT_RELA] || !has_dt[DT_RELASZ] || !has_dt[DT_RELAENT]))
1872     ERROR (_("\
1873 section [%2d] '%s': not all of %s, %s, and %s are present\n"),
1874 	   idx, section_name (ebl, idx),
1875 	   "DT_RELA", "DT_RELASZ", "DT_RELAENT");
1876 
1877   if ((has_dt[DT_REL] || has_dt[DT_RELSZ] || has_dt[DT_RELENT])
1878       && (!has_dt[DT_REL] || !has_dt[DT_RELSZ] || !has_dt[DT_RELENT]))
1879     ERROR (_("\
1880 section [%2d] '%s': not all of %s, %s, and %s are present\n"),
1881 	   idx, section_name (ebl, idx),
1882 	   "DT_REL", "DT_RELSZ", "DT_RELENT");
1883 
1884   /* Check that all prelink sections are present if any of them is.  */
1885   if (has_val_dt[DT_VALTAGIDX (DT_GNU_PRELINKED)]
1886       || has_val_dt[DT_VALTAGIDX (DT_CHECKSUM)])
1887     {
1888       if (!has_val_dt[DT_VALTAGIDX (DT_GNU_PRELINKED)])
1889 	ERROR (_("\
1890 section [%2d] '%s': %s tag missing in DSO marked during prelinking\n"),
1891 	       idx, section_name (ebl, idx), "DT_GNU_PRELINKED");
1892       if (!has_val_dt[DT_VALTAGIDX (DT_CHECKSUM)])
1893 	ERROR (_("\
1894 section [%2d] '%s': %s tag missing in DSO marked during prelinking\n"),
1895 	       idx, section_name (ebl, idx), "DT_CHECKSUM");
1896 
1897       /* Only DSOs can be marked like this.  */
1898       if (ehdr->e_type != ET_DYN)
1899 	ERROR (_("\
1900 section [%2d] '%s': non-DSO file marked as dependency during prelink\n"),
1901 	       idx, section_name (ebl, idx));
1902     }
1903 
1904   if (has_val_dt[DT_VALTAGIDX (DT_GNU_CONFLICTSZ)]
1905       || has_val_dt[DT_VALTAGIDX (DT_GNU_LIBLISTSZ)]
1906       || has_addr_dt[DT_ADDRTAGIDX (DT_GNU_CONFLICT)]
1907       || has_addr_dt[DT_ADDRTAGIDX (DT_GNU_LIBLIST)])
1908     {
1909       if (!has_val_dt[DT_VALTAGIDX (DT_GNU_CONFLICTSZ)])
1910 	ERROR (_("\
1911 section [%2d] '%s': %s tag missing in prelinked executable\n"),
1912 	       idx, section_name (ebl, idx), "DT_GNU_CONFLICTSZ");
1913       if (!has_val_dt[DT_VALTAGIDX (DT_GNU_LIBLISTSZ)])
1914 	ERROR (_("\
1915 section [%2d] '%s': %s tag missing in prelinked executable\n"),
1916 	       idx, section_name (ebl, idx), "DT_GNU_LIBLISTSZ");
1917       if (!has_addr_dt[DT_ADDRTAGIDX (DT_GNU_CONFLICT)])
1918 	ERROR (_("\
1919 section [%2d] '%s': %s tag missing in prelinked executable\n"),
1920 	       idx, section_name (ebl, idx), "DT_GNU_CONFLICT");
1921       if (!has_addr_dt[DT_ADDRTAGIDX (DT_GNU_LIBLIST)])
1922 	ERROR (_("\
1923 section [%2d] '%s': %s tag missing in prelinked executable\n"),
1924 	       idx, section_name (ebl, idx), "DT_GNU_LIBLIST");
1925     }
1926 }
1927 
1928 
1929 static void
check_symtab_shndx(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1930 check_symtab_shndx (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1931 {
1932   if (ehdr->e_type != ET_REL)
1933     {
1934       ERROR (_("\
1935 section [%2d] '%s': only relocatable files can have extended section index\n"),
1936 	     idx, section_name (ebl, idx));
1937       return;
1938     }
1939 
1940   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1941   GElf_Shdr symshdr_mem;
1942   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1943   if (symshdr != NULL && symshdr->sh_type != SHT_SYMTAB)
1944     ERROR (_("\
1945 section [%2d] '%s': extended section index section not for symbol table\n"),
1946 	   idx, section_name (ebl, idx));
1947   else if (symshdr == NULL)
1948     ERROR (_("\
1949 section [%2d] '%s': sh_link extended section index [%2d] is invalid\n"),
1950 	   idx, section_name (ebl, idx), shdr->sh_link);
1951   Elf_Data *symdata = elf_getdata (symscn, NULL);
1952   if (symdata == NULL)
1953     ERROR (_("cannot get data for symbol section\n"));
1954 
1955   if (shdr->sh_entsize != sizeof (Elf32_Word))
1956     ERROR (_("\
1957 section [%2d] '%s': entry size does not match Elf32_Word\n"),
1958 	   idx, section_name (ebl, idx));
1959 
1960   if (symshdr != NULL
1961       && shdr->sh_entsize != 0
1962       && symshdr->sh_entsize != 0
1963       && (shdr->sh_size / shdr->sh_entsize
1964 	  < symshdr->sh_size / symshdr->sh_entsize))
1965     ERROR (_("\
1966 section [%2d] '%s': extended index table too small for symbol table\n"),
1967 	   idx, section_name (ebl, idx));
1968 
1969   if (shdr->sh_info != 0)
1970     ERROR (_("section [%2d] '%s': sh_info not zero\n"),
1971 	   idx, section_name (ebl, idx));
1972 
1973   for (size_t cnt = idx + 1; cnt < shnum; ++cnt)
1974     {
1975       GElf_Shdr rshdr_mem;
1976       GElf_Shdr *rshdr = gelf_getshdr (elf_getscn (ebl->elf, cnt), &rshdr_mem);
1977       if (rshdr != NULL && rshdr->sh_type == SHT_SYMTAB_SHNDX
1978 	  && rshdr->sh_link == shdr->sh_link)
1979 	{
1980 	  ERROR (_("\
1981 section [%2d] '%s': extended section index in section [%2zu] '%s' refers to same symbol table\n"),
1982 		 idx, section_name (ebl, idx),
1983 		 cnt, section_name (ebl, cnt));
1984 	  break;
1985 	}
1986     }
1987 
1988   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
1989   if (data == NULL || data->d_buf == NULL)
1990     {
1991       ERROR (_("section [%2d] '%s': cannot get section data\n"),
1992 	     idx, section_name (ebl, idx));
1993       return;
1994     }
1995 
1996   if (data->d_size < sizeof (Elf32_Word)
1997       || *((Elf32_Word *) data->d_buf) != 0)
1998     ERROR (_("symbol 0 should have zero extended section index\n"));
1999 
2000   for (size_t cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
2001     {
2002       Elf32_Word xndx = ((Elf32_Word *) data->d_buf)[cnt];
2003 
2004       if (xndx != 0)
2005 	{
2006 	  GElf_Sym sym_data;
2007 	  GElf_Sym *sym = gelf_getsym (symdata, cnt, &sym_data);
2008 	  if (sym == NULL)
2009 	    {
2010 	      ERROR (_("cannot get data for symbol %zu\n"), cnt);
2011 	      continue;
2012 	    }
2013 
2014 	  if (sym->st_shndx != SHN_XINDEX)
2015 	    ERROR (_("\
2016 extended section index is %" PRIu32 " but symbol index is not XINDEX\n"),
2017 		   (uint32_t) xndx);
2018 	}
2019     }
2020 }
2021 
2022 
2023 static void
check_sysv_hash(Ebl * ebl,GElf_Shdr * shdr,Elf_Data * data,int idx,GElf_Shdr * symshdr)2024 check_sysv_hash (Ebl *ebl, GElf_Shdr *shdr, Elf_Data *data, int idx,
2025 		 GElf_Shdr *symshdr)
2026 {
2027   Elf32_Word nbucket = ((Elf32_Word *) data->d_buf)[0];
2028   Elf32_Word nchain = ((Elf32_Word *) data->d_buf)[1];
2029 
2030   if (shdr->sh_size < (2ULL + nbucket + nchain) * sizeof (Elf32_Word))
2031     {
2032       ERROR (_("\
2033 section [%2d] '%s': hash table section is too small (is %ld, expected %ld)\n"),
2034 	     idx, section_name (ebl, idx), (long int) shdr->sh_size,
2035 	     (long int) ((2 + nbucket + nchain) * sizeof (Elf32_Word)));
2036       return;
2037     }
2038 
2039   size_t maxidx = nchain;
2040 
2041   if (symshdr != NULL && symshdr->sh_entsize != 0)
2042     {
2043       size_t symsize = symshdr->sh_size / symshdr->sh_entsize;
2044 
2045       if (nchain > symshdr->sh_size / symshdr->sh_entsize)
2046 	ERROR (_("section [%2d] '%s': chain array too large\n"),
2047 	       idx, section_name (ebl, idx));
2048 
2049       maxidx = symsize;
2050     }
2051 
2052   Elf32_Word *buf = (Elf32_Word *) data->d_buf;
2053   Elf32_Word *end = (Elf32_Word *) ((char *) data->d_buf + shdr->sh_size);
2054   size_t cnt;
2055   for (cnt = 2; cnt < 2 + nbucket; ++cnt)
2056     {
2057       if (buf + cnt >= end)
2058 	break;
2059       else if (buf[cnt] >= maxidx)
2060       ERROR (_("\
2061 section [%2d] '%s': hash bucket reference %zu out of bounds\n"),
2062 	     idx, section_name (ebl, idx), cnt - 2);
2063     }
2064 
2065   for (; cnt < 2 + nbucket + nchain; ++cnt)
2066     {
2067       if (buf + cnt >= end)
2068 	break;
2069       else if (buf[cnt] >= maxidx)
2070       ERROR (_("\
2071 section [%2d] '%s': hash chain reference %zu out of bounds\n"),
2072 	     idx, section_name (ebl, idx), cnt - 2 - nbucket);
2073     }
2074 }
2075 
2076 
2077 static void
check_sysv_hash64(Ebl * ebl,GElf_Shdr * shdr,Elf_Data * data,int idx,GElf_Shdr * symshdr)2078 check_sysv_hash64 (Ebl *ebl, GElf_Shdr *shdr, Elf_Data *data, int idx,
2079 		 GElf_Shdr *symshdr)
2080 {
2081   Elf64_Xword nbucket = ((Elf64_Xword *) data->d_buf)[0];
2082   Elf64_Xword nchain = ((Elf64_Xword *) data->d_buf)[1];
2083 
2084   uint64_t maxwords = shdr->sh_size / sizeof (Elf64_Xword);
2085   if (maxwords < 2
2086       || maxwords - 2 < nbucket
2087       || maxwords - 2 - nbucket < nchain)
2088     {
2089       ERROR (_("\
2090 section [%2d] '%s': hash table section is too small (is %ld, expected %ld)\n"),
2091 	     idx, section_name (ebl, idx), (long int) shdr->sh_size,
2092 	     (long int) ((2 + nbucket + nchain) * sizeof (Elf64_Xword)));
2093       return;
2094     }
2095 
2096   size_t maxidx = nchain;
2097 
2098   if (symshdr != NULL && symshdr->sh_entsize != 0)
2099     {
2100       size_t symsize = symshdr->sh_size / symshdr->sh_entsize;
2101 
2102       if (nchain > symshdr->sh_size / symshdr->sh_entsize)
2103 	ERROR (_("section [%2d] '%s': chain array too large\n"),
2104 	       idx, section_name (ebl, idx));
2105 
2106       maxidx = symsize;
2107     }
2108 
2109   Elf64_Xword *buf = (Elf64_Xword *) data->d_buf;
2110   Elf64_Xword *end = (Elf64_Xword *) ((char *) data->d_buf + shdr->sh_size);
2111   size_t cnt;
2112   for (cnt = 2; cnt < 2 + nbucket; ++cnt)
2113     {
2114       if (buf + cnt >= end)
2115 	break;
2116       else if (buf[cnt] >= maxidx)
2117       ERROR (_("\
2118 section [%2d] '%s': hash bucket reference %zu out of bounds\n"),
2119 	     idx, section_name (ebl, idx), cnt - 2);
2120     }
2121 
2122   for (; cnt < 2 + nbucket + nchain; ++cnt)
2123     {
2124       if (buf + cnt >= end)
2125 	break;
2126       else if (buf[cnt] >= maxidx)
2127       ERROR (_("\
2128 section [%2d] '%s': hash chain reference %" PRIu64 " out of bounds\n"),
2129 	       idx, section_name (ebl, idx), (uint64_t) cnt - 2 - nbucket);
2130     }
2131 }
2132 
2133 
2134 static void
check_gnu_hash(Ebl * ebl,GElf_Shdr * shdr,Elf_Data * data,int idx,GElf_Shdr * symshdr)2135 check_gnu_hash (Ebl *ebl, GElf_Shdr *shdr, Elf_Data *data, int idx,
2136 		GElf_Shdr *symshdr)
2137 {
2138   if (data->d_size < 4 * sizeof (Elf32_Word))
2139     {
2140       ERROR (_("\
2141 section [%2d] '%s': not enough data\n"),
2142 	     idx, section_name (ebl, idx));
2143       return;
2144     }
2145 
2146   Elf32_Word nbuckets = ((Elf32_Word *) data->d_buf)[0];
2147   Elf32_Word symbias = ((Elf32_Word *) data->d_buf)[1];
2148   Elf32_Word bitmask_words = ((Elf32_Word *) data->d_buf)[2];
2149 
2150   if (bitmask_words == 0 || !powerof2 (bitmask_words))
2151     {
2152       ERROR (_("\
2153 section [%2d] '%s': bitmask size zero or not power of 2: %u\n"),
2154 	     idx, section_name (ebl, idx), bitmask_words);
2155       return;
2156     }
2157 
2158   size_t bitmask_idxmask = bitmask_words - 1;
2159   if (gelf_getclass (ebl->elf) == ELFCLASS64)
2160     bitmask_words *= 2;
2161   Elf32_Word shift = ((Elf32_Word *) data->d_buf)[3];
2162 
2163   /* Is there still room for the sym chain?
2164      Use uint64_t calculation to prevent 32bit overflow.  */
2165   uint64_t used_buf = (4ULL + bitmask_words + nbuckets) * sizeof (Elf32_Word);
2166   if (used_buf > data->d_size)
2167     {
2168       ERROR (_("\
2169 section [%2d] '%s': hash table section is too small (is %ld, expected at least %ld)\n"),
2170 	     idx, section_name (ebl, idx), (long int) shdr->sh_size,
2171 	     (long int) used_buf);
2172       return;
2173     }
2174 
2175   if (shift > 31)
2176     {
2177       ERROR (_("\
2178 section [%2d] '%s': 2nd hash function shift too big: %u\n"),
2179 	     idx, section_name (ebl, idx), shift);
2180       return;
2181     }
2182 
2183   size_t maxidx = shdr->sh_size / sizeof (Elf32_Word) - (4 + bitmask_words
2184 							 + nbuckets);
2185 
2186   if (symshdr != NULL && symshdr->sh_entsize != 0)
2187     maxidx = MIN (maxidx, symshdr->sh_size / symshdr->sh_entsize);
2188 
2189   /* We need the symbol section data.  */
2190   Elf_Data *symdata = elf_getdata (elf_getscn (ebl->elf, shdr->sh_link), NULL);
2191 
2192   union
2193   {
2194     Elf32_Word *p32;
2195     Elf64_Xword *p64;
2196   } bitmask = { .p32 = &((Elf32_Word *) data->d_buf)[4] },
2197       collected = { .p32 = xcalloc (bitmask_words, sizeof (Elf32_Word)) };
2198 
2199   size_t classbits = gelf_getclass (ebl->elf) == ELFCLASS32 ? 32 : 64;
2200 
2201   size_t cnt;
2202   for (cnt = 4 + bitmask_words; cnt < 4 + bitmask_words + nbuckets; ++cnt)
2203     {
2204       Elf32_Word symidx = ((Elf32_Word *) data->d_buf)[cnt];
2205 
2206       if (symidx == 0)
2207 	continue;
2208 
2209       if (symidx < symbias)
2210 	{
2211 	  ERROR (_("\
2212 section [%2d] '%s': hash chain for bucket %zu lower than symbol index bias\n"),
2213 		 idx, section_name (ebl, idx), cnt - (4 + bitmask_words));
2214 	  continue;
2215 	}
2216 
2217       while (symidx - symbias < maxidx)
2218 	{
2219 	  Elf32_Word chainhash = ((Elf32_Word *) data->d_buf)[4
2220 							      + bitmask_words
2221 							      + nbuckets
2222 							      + symidx
2223 							      - symbias];
2224 
2225 	  if (symdata != NULL)
2226 	    {
2227 	      /* Check that the referenced symbol is not undefined.  */
2228 	      GElf_Sym sym_mem;
2229 	      GElf_Sym *sym = gelf_getsym (symdata, symidx, &sym_mem);
2230 	      if (sym != NULL && sym->st_shndx == SHN_UNDEF
2231 		  && GELF_ST_TYPE (sym->st_info) != STT_FUNC)
2232 		ERROR (_("\
2233 section [%2d] '%s': symbol %u referenced in chain for bucket %zu is undefined\n"),
2234 		       idx, section_name (ebl, idx), symidx,
2235 		       cnt - (4 + bitmask_words));
2236 
2237 	      const char *symname = (sym != NULL
2238 				     ? elf_strptr (ebl->elf, symshdr->sh_link,
2239 						   sym->st_name)
2240 				     : NULL);
2241 	      if (symname != NULL)
2242 		{
2243 		  Elf32_Word hval = elf_gnu_hash (symname);
2244 		  if ((hval & ~1u) != (chainhash & ~1u))
2245 		    ERROR (_("\
2246 section [%2d] '%s': hash value for symbol %u in chain for bucket %zu wrong\n"),
2247 			   idx, section_name (ebl, idx), symidx,
2248 			   cnt - (4 + bitmask_words));
2249 
2250 		  /* Set the bits in the bitmask.  */
2251 		  size_t maskidx = (hval / classbits) & bitmask_idxmask;
2252 		  if (maskidx >= bitmask_words)
2253 		    {
2254 		      ERROR (_("\
2255 section [%2d] '%s': mask index for symbol %u in chain for bucket %zu wrong\n"),
2256 			     idx, section_name (ebl, idx), symidx,
2257 			     cnt - (4 + bitmask_words));
2258 		      return;
2259 		    }
2260 		  if (classbits == 32)
2261 		    {
2262 		      collected.p32[maskidx]
2263 			|= UINT32_C (1) << (hval & (classbits - 1));
2264 		      collected.p32[maskidx]
2265 			|= UINT32_C (1) << ((hval >> shift) & (classbits - 1));
2266 		    }
2267 		  else
2268 		    {
2269 		      collected.p64[maskidx]
2270 			|= UINT64_C (1) << (hval & (classbits - 1));
2271 		      collected.p64[maskidx]
2272 			|= UINT64_C (1) << ((hval >> shift) & (classbits - 1));
2273 		    }
2274 		}
2275 	    }
2276 
2277 	  if ((chainhash & 1) != 0)
2278 	    break;
2279 
2280 	  ++symidx;
2281 	}
2282 
2283       if (symidx - symbias >= maxidx)
2284 	ERROR (_("\
2285 section [%2d] '%s': hash chain for bucket %zu out of bounds\n"),
2286 	       idx, section_name (ebl, idx), cnt - (4 + bitmask_words));
2287       else if (symshdr != NULL && symshdr->sh_entsize != 0
2288 	       && symidx > symshdr->sh_size / symshdr->sh_entsize)
2289 	ERROR (_("\
2290 section [%2d] '%s': symbol reference in chain for bucket %zu out of bounds\n"),
2291 	       idx, section_name (ebl, idx), cnt - (4 + bitmask_words));
2292     }
2293 
2294   if (memcmp (collected.p32, bitmask.p32, bitmask_words * sizeof (Elf32_Word)))
2295     ERROR (_("\
2296 section [%2d] '%s': bitmask does not match names in the hash table\n"),
2297 	   idx, section_name (ebl, idx));
2298 
2299   free (collected.p32);
2300 }
2301 
2302 
2303 static void
check_hash(int tag,Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)2304 check_hash (int tag, Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
2305 {
2306   if (ehdr->e_type == ET_REL)
2307     {
2308       ERROR (_("\
2309 section [%2d] '%s': relocatable files cannot have hash tables\n"),
2310 	     idx, section_name (ebl, idx));
2311       return;
2312     }
2313 
2314   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
2315   if (data == NULL || data->d_buf == NULL)
2316     {
2317       ERROR (_("section [%2d] '%s': cannot get section data\n"),
2318 	     idx, section_name (ebl, idx));
2319       return;
2320     }
2321 
2322   GElf_Shdr symshdr_mem;
2323   GElf_Shdr *symshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
2324 				     &symshdr_mem);
2325   if (symshdr != NULL && symshdr->sh_type != SHT_DYNSYM)
2326     ERROR (_("\
2327 section [%2d] '%s': hash table not for dynamic symbol table\n"),
2328 	   idx, section_name (ebl, idx));
2329   else if (symshdr == NULL)
2330     ERROR (_("\
2331 section [%2d] '%s': invalid sh_link symbol table section index [%2d]\n"),
2332 	   idx, section_name (ebl, idx), shdr->sh_link);
2333 
2334   size_t expect_entsize = (tag == SHT_GNU_HASH
2335 			   ? (gelf_getclass (ebl->elf) == ELFCLASS32
2336 			      ? sizeof (Elf32_Word) : 0)
2337 			   : (size_t) ebl_sysvhash_entrysize (ebl));
2338 
2339   if (shdr->sh_entsize != expect_entsize)
2340     ERROR (_("\
2341 section [%2d] '%s': hash table entry size incorrect\n"),
2342 	   idx, section_name (ebl, idx));
2343 
2344   if ((shdr->sh_flags & SHF_ALLOC) == 0)
2345     ERROR (_("section [%2d] '%s': not marked to be allocated\n"),
2346 	   idx, section_name (ebl, idx));
2347 
2348   if (shdr->sh_size < (tag == SHT_GNU_HASH ? 4 : 2) * (expect_entsize ?: 4))
2349     {
2350       ERROR (_("\
2351 section [%2d] '%s': hash table has not even room for initial administrative entries\n"),
2352 	     idx, section_name (ebl, idx));
2353       return;
2354     }
2355 
2356   switch (tag)
2357     {
2358     case SHT_HASH:
2359       if (ebl_sysvhash_entrysize (ebl) == sizeof (Elf64_Xword))
2360 	check_sysv_hash64 (ebl, shdr, data, idx, symshdr);
2361       else
2362 	check_sysv_hash (ebl, shdr, data, idx, symshdr);
2363       break;
2364 
2365     case SHT_GNU_HASH:
2366       check_gnu_hash (ebl, shdr, data, idx, symshdr);
2367       break;
2368 
2369     default:
2370       assert (! "should not happen");
2371     }
2372 }
2373 
2374 
2375 /* Compare content of both hash tables, it must be identical.  */
2376 static void
compare_hash_gnu_hash(Ebl * ebl,GElf_Ehdr * ehdr,size_t hash_idx,size_t gnu_hash_idx)2377 compare_hash_gnu_hash (Ebl *ebl, GElf_Ehdr *ehdr, size_t hash_idx,
2378 		       size_t gnu_hash_idx)
2379 {
2380   Elf_Scn *hash_scn = elf_getscn (ebl->elf, hash_idx);
2381   Elf_Data *hash_data = elf_getdata (hash_scn, NULL);
2382   GElf_Shdr hash_shdr_mem;
2383   GElf_Shdr *hash_shdr = gelf_getshdr (hash_scn, &hash_shdr_mem);
2384   Elf_Scn *gnu_hash_scn = elf_getscn (ebl->elf, gnu_hash_idx);
2385   Elf_Data *gnu_hash_data = elf_getdata (gnu_hash_scn, NULL);
2386   GElf_Shdr gnu_hash_shdr_mem;
2387   GElf_Shdr *gnu_hash_shdr = gelf_getshdr (gnu_hash_scn, &gnu_hash_shdr_mem);
2388 
2389   if (hash_shdr == NULL || gnu_hash_shdr == NULL
2390       || hash_data == NULL || hash_data->d_buf == NULL
2391       || gnu_hash_data == NULL || gnu_hash_data->d_buf == NULL)
2392     /* None of these pointers should be NULL since we used the
2393        sections already.  We are careful nonetheless.  */
2394     return;
2395 
2396   /* The link must point to the same symbol table.  */
2397   if (hash_shdr->sh_link != gnu_hash_shdr->sh_link)
2398     {
2399       ERROR (_("\
2400 sh_link in hash sections [%2zu] '%s' and [%2zu] '%s' not identical\n"),
2401 	     hash_idx, elf_strptr (ebl->elf, shstrndx, hash_shdr->sh_name),
2402 	     gnu_hash_idx,
2403 	     elf_strptr (ebl->elf, shstrndx, gnu_hash_shdr->sh_name));
2404       return;
2405     }
2406 
2407   Elf_Scn *sym_scn = elf_getscn (ebl->elf, hash_shdr->sh_link);
2408   Elf_Data *sym_data = elf_getdata (sym_scn, NULL);
2409   GElf_Shdr sym_shdr_mem;
2410   GElf_Shdr *sym_shdr = gelf_getshdr (sym_scn, &sym_shdr_mem);
2411 
2412   if (sym_data == NULL || sym_data->d_buf == NULL
2413       || sym_shdr == NULL || sym_shdr->sh_entsize == 0)
2414     return;
2415 
2416   const char *hash_name;
2417   const char *gnu_hash_name;
2418   hash_name  = elf_strptr (ebl->elf, shstrndx, hash_shdr->sh_name);
2419   gnu_hash_name  = elf_strptr (ebl->elf, shstrndx, gnu_hash_shdr->sh_name);
2420 
2421   if (gnu_hash_data->d_size < 4 * sizeof (Elf32_Word))
2422     {
2423       ERROR (_("\
2424 hash section [%2zu] '%s' does not contain enough data\n"),
2425 	     gnu_hash_idx, gnu_hash_name);
2426       return;
2427     }
2428 
2429   uint32_t nentries = sym_shdr->sh_size / sym_shdr->sh_entsize;
2430   char *used = alloca (nentries);
2431   memset (used, '\0', nentries);
2432 
2433   /* First go over the GNU_HASH table and mark the entries as used.  */
2434   const Elf32_Word *gnu_hasharr = (Elf32_Word *) gnu_hash_data->d_buf;
2435   Elf32_Word gnu_nbucket = gnu_hasharr[0];
2436   Elf32_Word gnu_symbias = gnu_hasharr[1];
2437   const int bitmap_factor = ehdr->e_ident[EI_CLASS] == ELFCLASS32 ? 1 : 2;
2438   const Elf32_Word *gnu_bucket = (gnu_hasharr
2439 				  + (4 + gnu_hasharr[2] * bitmap_factor));
2440   const Elf32_Word *gnu_chain = gnu_bucket + gnu_hasharr[0];
2441 
2442   if (gnu_hasharr[2] == 0)
2443     {
2444       ERROR (_("\
2445 hash section [%2zu] '%s' has zero bit mask words\n"),
2446 	     gnu_hash_idx, gnu_hash_name);
2447       return;
2448     }
2449 
2450   uint64_t used_buf = ((4ULL + gnu_hasharr[2] * bitmap_factor + gnu_nbucket)
2451 		       * sizeof (Elf32_Word));
2452   uint32_t max_nsyms = (gnu_hash_data->d_size - used_buf) / sizeof (Elf32_Word);
2453   if (used_buf > gnu_hash_data->d_size)
2454     {
2455       ERROR (_("\
2456 hash section [%2zu] '%s' uses too much data\n"),
2457 	     gnu_hash_idx, gnu_hash_name);
2458       return;
2459     }
2460 
2461   for (Elf32_Word cnt = 0; cnt < gnu_nbucket; ++cnt)
2462     {
2463       if (gnu_bucket[cnt] != STN_UNDEF)
2464 	{
2465 	  Elf32_Word symidx = gnu_bucket[cnt] - gnu_symbias;
2466 	  do
2467 	    {
2468 	      if (symidx >= max_nsyms || symidx + gnu_symbias >= nentries)
2469 		{
2470 		  ERROR (_("\
2471 hash section [%2zu] '%s' invalid symbol index %" PRIu32 " (max_nsyms: %" PRIu32 ", nentries: %" PRIu32 "\n"),
2472 			 gnu_hash_idx, gnu_hash_name, symidx, max_nsyms, nentries);
2473 		  return;
2474 		}
2475 	      used[symidx + gnu_symbias] |= 1;
2476 	    }
2477 	  while ((gnu_chain[symidx++] & 1u) == 0);
2478 	}
2479     }
2480 
2481   /* Now go over the old hash table and check that we cover the same
2482      entries.  */
2483   if (hash_shdr->sh_entsize == sizeof (Elf32_Word))
2484     {
2485       const Elf32_Word *hasharr = (Elf32_Word *) hash_data->d_buf;
2486       if (hash_data->d_size < 2 * sizeof (Elf32_Word))
2487 	{
2488 	  ERROR (_("\
2489 hash section [%2zu] '%s' does not contain enough data\n"),
2490 		 hash_idx, hash_name);
2491 	  return;
2492 	}
2493 
2494       Elf32_Word nbucket = hasharr[0];
2495       Elf32_Word nchain = hasharr[1];
2496       uint64_t hash_used = (2ULL + nchain + nbucket) * sizeof (Elf32_Word);
2497       if (hash_used > hash_data->d_size)
2498 	{
2499 	  ERROR (_("\
2500 hash section [%2zu] '%s' uses too much data\n"),
2501 		 hash_idx, hash_name);
2502 	  return;
2503 	}
2504 
2505       const Elf32_Word *bucket = &hasharr[2];
2506       const Elf32_Word *chain = &hasharr[2 + nbucket];
2507 
2508       for (Elf32_Word cnt = 0; cnt < nbucket; ++cnt)
2509 	{
2510 	  Elf32_Word symidx = bucket[cnt];
2511 	  while (symidx != STN_UNDEF && symidx < nentries && symidx < nchain)
2512 	    {
2513 	      used[symidx] |= 2;
2514 	      symidx = chain[symidx];
2515 	    }
2516 	}
2517     }
2518   else if (hash_shdr->sh_entsize == sizeof (Elf64_Xword))
2519     {
2520       const Elf64_Xword *hasharr = (Elf64_Xword *) hash_data->d_buf;
2521       if (hash_data->d_size < 2 * sizeof (Elf32_Word))
2522 	{
2523 	  ERROR (_("\
2524 hash section [%2zu] '%s' does not contain enough data\n"),
2525 		 hash_idx, hash_name);
2526 	  return;
2527 	}
2528 
2529       Elf64_Xword nbucket = hasharr[0];
2530       Elf64_Xword nchain = hasharr[1];
2531       uint64_t maxwords = hash_data->d_size / sizeof (Elf64_Xword);
2532       if (maxwords < 2
2533 	  || maxwords - 2 < nbucket
2534 	  || maxwords - 2 - nbucket < nchain)
2535 	{
2536 	  ERROR (_("\
2537 hash section [%2zu] '%s' uses too much data\n"),
2538 		 hash_idx, hash_name);
2539 	  return;
2540 	}
2541 
2542       const Elf64_Xword *bucket = &hasharr[2];
2543       const Elf64_Xword *chain = &hasharr[2 + nbucket];
2544 
2545       for (Elf64_Xword cnt = 0; cnt < nbucket; ++cnt)
2546 	{
2547 	  Elf64_Xword symidx = bucket[cnt];
2548 	  while (symidx != STN_UNDEF && symidx < nentries && symidx < nchain)
2549 	    {
2550 	      used[symidx] |= 2;
2551 	      symidx = chain[symidx];
2552 	    }
2553 	}
2554     }
2555   else
2556     {
2557       ERROR (_("\
2558 hash section [%2zu] '%s' invalid sh_entsize\n"),
2559 	     hash_idx, hash_name);
2560       return;
2561     }
2562 
2563   /* Now see which entries are not set in one or both hash tables
2564      (unless the symbol is undefined in which case it can be omitted
2565      in the new table format).  */
2566   if ((used[0] & 1) != 0)
2567     ERROR (_("section [%2zu] '%s': reference to symbol index 0\n"),
2568 	   gnu_hash_idx,
2569 	   elf_strptr (ebl->elf, shstrndx, gnu_hash_shdr->sh_name));
2570   if ((used[0] & 2) != 0)
2571     ERROR (_("section [%2zu] '%s': reference to symbol index 0\n"),
2572 	   hash_idx, elf_strptr (ebl->elf, shstrndx, hash_shdr->sh_name));
2573 
2574   for (uint32_t cnt = 1; cnt < nentries; ++cnt)
2575     if (used[cnt] != 0 && used[cnt] != 3)
2576       {
2577 	if (used[cnt] == 1)
2578 	  ERROR (_("\
2579 symbol %d referenced in new hash table in [%2zu] '%s' but not in old hash table in [%2zu] '%s'\n"),
2580 		 cnt, gnu_hash_idx,
2581 		 elf_strptr (ebl->elf, shstrndx, gnu_hash_shdr->sh_name),
2582 		 hash_idx,
2583 		 elf_strptr (ebl->elf, shstrndx, hash_shdr->sh_name));
2584 	else
2585 	  {
2586 	    GElf_Sym sym_mem;
2587 	    GElf_Sym *sym = gelf_getsym (sym_data, cnt, &sym_mem);
2588 
2589 	    if (sym != NULL && sym->st_shndx != STN_UNDEF)
2590 	      ERROR (_("\
2591 symbol %d referenced in old hash table in [%2zu] '%s' but not in new hash table in [%2zu] '%s'\n"),
2592 		     cnt, hash_idx,
2593 		     elf_strptr (ebl->elf, shstrndx, hash_shdr->sh_name),
2594 		     gnu_hash_idx,
2595 		     elf_strptr (ebl->elf, shstrndx, gnu_hash_shdr->sh_name));
2596 	  }
2597       }
2598 }
2599 
2600 
2601 static void
check_null(Ebl * ebl,GElf_Shdr * shdr,int idx)2602 check_null (Ebl *ebl, GElf_Shdr *shdr, int idx)
2603 {
2604 #define TEST(name, extra) \
2605   if (extra && shdr->sh_##name != 0)					      \
2606     ERROR (_("section [%2d] '%s': nonzero sh_%s for NULL section\n"),  \
2607 	   idx, section_name (ebl, idx), #name)
2608 
2609   TEST (name, 1);
2610   TEST (flags, 1);
2611   TEST (addr, 1);
2612   TEST (offset, 1);
2613   TEST (size, idx != 0);
2614   TEST (link, idx != 0);
2615   TEST (info, 1);
2616   TEST (addralign, 1);
2617   TEST (entsize, 1);
2618 }
2619 
2620 
2621 static void
check_group(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)2622 check_group (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
2623 {
2624   if (ehdr->e_type != ET_REL)
2625     {
2626       ERROR (_("\
2627 section [%2d] '%s': section groups only allowed in relocatable object files\n"),
2628 	     idx, section_name (ebl, idx));
2629       return;
2630     }
2631 
2632   /* Check that sh_link is an index of a symbol table.  */
2633   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2634   GElf_Shdr symshdr_mem;
2635   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2636   if (symshdr == NULL)
2637     ERROR (_("section [%2d] '%s': cannot get symbol table: %s\n"),
2638 	   idx, section_name (ebl, idx), elf_errmsg (-1));
2639   else
2640     {
2641       if (symshdr->sh_type != SHT_SYMTAB)
2642 	ERROR (_("\
2643 section [%2d] '%s': section reference in sh_link is no symbol table\n"),
2644 	       idx, section_name (ebl, idx));
2645 
2646       if (shdr->sh_info >= symshdr->sh_size / gelf_fsize (ebl->elf, ELF_T_SYM,
2647 							  1, EV_CURRENT))
2648 	ERROR (_("\
2649 section [%2d] '%s': invalid symbol index in sh_info\n"),
2650 	       idx, section_name (ebl, idx));
2651 
2652       if (shdr->sh_flags != 0)
2653 	ERROR (_("section [%2d] '%s': sh_flags not zero\n"),
2654 	       idx, section_name (ebl, idx));
2655 
2656       GElf_Sym sym_data;
2657       GElf_Sym *sym = gelf_getsym (elf_getdata (symscn, NULL), shdr->sh_info,
2658 				   &sym_data);
2659       if (sym == NULL)
2660 	ERROR (_("\
2661 section [%2d] '%s': cannot get symbol for signature\n"),
2662 	       idx, section_name (ebl, idx));
2663       else if (elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name) == NULL)
2664 	ERROR (_("\
2665 section [%2d] '%s': cannot get symbol name for signature\n"),
2666 	       idx, section_name (ebl, idx));
2667       else if (strcmp (elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name),
2668 		       "") == 0)
2669 	ERROR (_("\
2670 section [%2d] '%s': signature symbol cannot be empty string\n"),
2671 	       idx, section_name (ebl, idx));
2672 
2673       if (be_strict
2674 	  && shdr->sh_entsize != elf32_fsize (ELF_T_WORD, 1, EV_CURRENT))
2675 	ERROR (_("section [%2d] '%s': sh_flags not set correctly\n"),
2676 	       idx, section_name (ebl, idx));
2677     }
2678 
2679   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
2680   if (data == NULL || data->d_buf == NULL)
2681     ERROR (_("section [%2d] '%s': cannot get data: %s\n"),
2682 	   idx, section_name (ebl, idx), elf_errmsg (-1));
2683   else
2684     {
2685       size_t elsize = elf32_fsize (ELF_T_WORD, 1, EV_CURRENT);
2686       size_t cnt;
2687       Elf32_Word val;
2688 
2689       if (data->d_size % elsize != 0)
2690 	ERROR (_("\
2691 section [%2d] '%s': section size not multiple of sizeof(Elf32_Word)\n"),
2692 	       idx, section_name (ebl, idx));
2693 
2694       if (data->d_size < elsize)
2695 	{
2696 	  ERROR (_("\
2697 section [%2d] '%s': section group without flags word\n"),
2698 	       idx, section_name (ebl, idx));
2699 	  return;
2700 	}
2701       else if (be_strict)
2702 	{
2703 	  if (data->d_size < 2 * elsize)
2704 	    ERROR (_("\
2705 section [%2d] '%s': section group without member\n"),
2706 		   idx, section_name (ebl, idx));
2707 	  else if (data->d_size < 3 * elsize)
2708 	    ERROR (_("\
2709 section [%2d] '%s': section group with only one member\n"),
2710 		   idx, section_name (ebl, idx));
2711 	}
2712 
2713 #if ALLOW_UNALIGNED
2714       val = *((Elf32_Word *) data->d_buf);
2715 #else
2716       memcpy (&val, data->d_buf, elsize);
2717 #endif
2718       if ((val & ~GRP_COMDAT) != 0)
2719 	ERROR (_("section [%2d] '%s': unknown section group flags\n"),
2720 	       idx, section_name (ebl, idx));
2721 
2722       for (cnt = elsize; cnt + elsize <= data->d_size; cnt += elsize)
2723 	{
2724 #if ALLOW_UNALIGNED
2725 	  val = *((Elf32_Word *) ((char *) data->d_buf + cnt));
2726 #else
2727 	  memcpy (&val, (char *) data->d_buf + cnt, elsize);
2728 #endif
2729 
2730 	  if (val > shnum)
2731 	    ERROR (_("\
2732 section [%2d] '%s': section index %zu out of range\n"),
2733 		   idx, section_name (ebl, idx), cnt / elsize);
2734 	  else
2735 	    {
2736 	      GElf_Shdr refshdr_mem;
2737 	      GElf_Shdr *refshdr = gelf_getshdr (elf_getscn (ebl->elf, val),
2738 						 &refshdr_mem);
2739 	      if (refshdr == NULL)
2740 		ERROR (_("\
2741 section [%2d] '%s': cannot get section header for element %zu: %s\n"),
2742 		       idx, section_name (ebl, idx), cnt / elsize,
2743 		       elf_errmsg (-1));
2744 	      else
2745 		{
2746 		  if (refshdr->sh_type == SHT_GROUP)
2747 		    ERROR (_("\
2748 section [%2d] '%s': section group contains another group [%2d] '%s'\n"),
2749 			   idx, section_name (ebl, idx),
2750 			   val, section_name (ebl, val));
2751 
2752 		  if ((refshdr->sh_flags & SHF_GROUP) == 0)
2753 		    ERROR (_("\
2754 section [%2d] '%s': element %zu references section [%2d] '%s' without SHF_GROUP flag set\n"),
2755 			   idx, section_name (ebl, idx), cnt / elsize,
2756 			   val, section_name (ebl, val));
2757 		}
2758 
2759 	      if (val < shnum && ++scnref[val] == 2)
2760 		ERROR (_("\
2761 section [%2d] '%s' is contained in more than one section group\n"),
2762 		       val, section_name (ebl, val));
2763 	    }
2764 	}
2765     }
2766 }
2767 
2768 
2769 static const char *
section_flags_string(GElf_Word flags,char * buf,size_t len)2770 section_flags_string (GElf_Word flags, char *buf, size_t len)
2771 {
2772   if (flags == 0)
2773     return "none";
2774 
2775   static const struct
2776   {
2777     GElf_Word flag;
2778     const char *name;
2779   } known_flags[] =
2780     {
2781 #define NEWFLAG(name) { SHF_##name, #name }
2782       NEWFLAG (WRITE),
2783       NEWFLAG (ALLOC),
2784       NEWFLAG (EXECINSTR),
2785       NEWFLAG (MERGE),
2786       NEWFLAG (STRINGS),
2787       NEWFLAG (INFO_LINK),
2788       NEWFLAG (LINK_ORDER),
2789       NEWFLAG (OS_NONCONFORMING),
2790       NEWFLAG (GROUP),
2791       NEWFLAG (TLS),
2792       NEWFLAG (COMPRESSED),
2793       NEWFLAG (GNU_RETAIN),
2794       NEWFLAG (ORDERED),
2795       NEWFLAG (EXCLUDE)
2796     };
2797 #undef NEWFLAG
2798   const size_t nknown_flags = sizeof (known_flags) / sizeof (known_flags[0]);
2799 
2800   char *cp = buf;
2801 
2802   for (size_t cnt = 0; cnt < nknown_flags; ++cnt)
2803     if (flags & known_flags[cnt].flag)
2804       {
2805 	if (cp != buf && len > 1)
2806 	  {
2807 	    *cp++ = '|';
2808 	    --len;
2809 	  }
2810 
2811 	size_t ncopy = MIN (len - 1, strlen (known_flags[cnt].name));
2812 	cp = mempcpy (cp, known_flags[cnt].name, ncopy);
2813 	len -= ncopy;
2814 
2815 	flags ^= known_flags[cnt].flag;
2816       }
2817 
2818   if (flags != 0 || cp == buf)
2819     {
2820       int r = snprintf (cp, len - 1, "%s%" PRIx64,
2821 			(cp == buf) ? "" : "|", (uint64_t) flags);
2822       if (r > 0)
2823 	cp += r;
2824     }
2825   *cp = '\0';
2826 
2827   return buf;
2828 }
2829 
2830 
2831 static int
has_copy_reloc(Ebl * ebl,unsigned int symscnndx,unsigned int symndx)2832 has_copy_reloc (Ebl *ebl, unsigned int symscnndx, unsigned int symndx)
2833 {
2834   /* First find the relocation section for the symbol table.  */
2835   Elf_Scn *scn = NULL;
2836   GElf_Shdr shdr_mem;
2837   GElf_Shdr *shdr = NULL;
2838   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
2839     {
2840       shdr = gelf_getshdr (scn, &shdr_mem);
2841       if (shdr != NULL
2842 	  && (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
2843 	  && shdr->sh_link == symscnndx)
2844 	/* Found the section.  */
2845 	break;
2846     }
2847 
2848   if (scn == NULL)
2849     return 0;
2850 
2851   Elf_Data *data = elf_getdata (scn, NULL);
2852   if (data == NULL || shdr->sh_entsize == 0)
2853     return 0;
2854 
2855   if (shdr->sh_type == SHT_REL)
2856     for (int i = 0; (size_t) i < shdr->sh_size / shdr->sh_entsize; ++i)
2857       {
2858 	GElf_Rel rel_mem;
2859 	GElf_Rel *rel = gelf_getrel (data, i, &rel_mem);
2860 	if (rel == NULL)
2861 	  continue;
2862 
2863 	if (GELF_R_SYM (rel->r_info) == symndx
2864 	    && ebl_copy_reloc_p (ebl, GELF_R_TYPE (rel->r_info)))
2865 	  return 1;
2866       }
2867   else
2868     for (int i = 0; (size_t) i < shdr->sh_size / shdr->sh_entsize; ++i)
2869       {
2870 	GElf_Rela rela_mem;
2871 	GElf_Rela *rela = gelf_getrela (data, i, &rela_mem);
2872 	if (rela == NULL)
2873 	  continue;
2874 
2875 	if (GELF_R_SYM (rela->r_info) == symndx
2876 	    && ebl_copy_reloc_p (ebl, GELF_R_TYPE (rela->r_info)))
2877 	  return 1;
2878       }
2879 
2880   return 0;
2881 }
2882 
2883 
2884 static int
in_nobits_scn(Ebl * ebl,unsigned int shndx)2885 in_nobits_scn (Ebl *ebl, unsigned int shndx)
2886 {
2887   GElf_Shdr shdr_mem;
2888   GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, shndx), &shdr_mem);
2889   return shdr != NULL && shdr->sh_type == SHT_NOBITS;
2890 }
2891 
2892 
2893 static struct version_namelist
2894 {
2895   const char *objname;
2896   const char *name;
2897   GElf_Versym ndx;
2898   enum { ver_def, ver_need } type;
2899   struct version_namelist *next;
2900 } *version_namelist;
2901 
2902 
2903 static int
add_version(const char * objname,const char * name,GElf_Versym ndx,int type)2904 add_version (const char *objname, const char *name, GElf_Versym ndx, int type)
2905 {
2906   /* Check that there are no duplications.  */
2907   struct version_namelist *nlp = version_namelist;
2908   while (nlp != NULL)
2909     {
2910       if (((nlp->objname == NULL && objname == NULL)
2911 	   || (nlp->objname != NULL && objname != NULL
2912 	       && strcmp (nlp->objname, objname) == 0))
2913 	  && strcmp (nlp->name, name) == 0)
2914 	return nlp->type == ver_def ? 1 : -1;
2915       nlp = nlp->next;
2916     }
2917 
2918   nlp = xmalloc (sizeof (*nlp));
2919   nlp->objname = objname;
2920   nlp->name = name;
2921   nlp->ndx = ndx;
2922   nlp->type = type;
2923   nlp->next = version_namelist;
2924   version_namelist = nlp;
2925 
2926   return 0;
2927 }
2928 
2929 
2930 static void
check_versym(Ebl * ebl,int idx)2931 check_versym (Ebl *ebl, int idx)
2932 {
2933   Elf_Scn *scn = elf_getscn (ebl->elf, idx);
2934   GElf_Shdr shdr_mem;
2935   GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
2936   if (shdr == NULL)
2937     /* The error has already been reported.  */
2938     return;
2939 
2940   Elf_Data *data = elf_getdata (scn, NULL);
2941   if (data == NULL)
2942     {
2943       ERROR (_("section [%2d] '%s': cannot get section data\n"),
2944 	     idx, section_name (ebl, idx));
2945       return;
2946     }
2947 
2948   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
2949   GElf_Shdr symshdr_mem;
2950   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
2951   if (symshdr == NULL)
2952     /* The error has already been reported.  */
2953     return;
2954 
2955   if (symshdr->sh_type != SHT_DYNSYM)
2956     {
2957       ERROR (_("\
2958 section [%2d] '%s' refers in sh_link to section [%2d] '%s' which is no dynamic symbol table\n"),
2959 	     idx, section_name (ebl, idx),
2960 	     shdr->sh_link, section_name (ebl, shdr->sh_link));
2961       return;
2962     }
2963 
2964   /* The number of elements in the version symbol table must be the
2965      same as the number of symbols.  */
2966   if (shdr->sh_entsize != 0 && symshdr->sh_entsize != 0
2967       && (shdr->sh_size / shdr->sh_entsize
2968 	  != symshdr->sh_size / symshdr->sh_entsize))
2969     ERROR (_("\
2970 section [%2d] '%s' has different number of entries than symbol table [%2d] '%s'\n"),
2971 	   idx, section_name (ebl, idx),
2972 	   shdr->sh_link, section_name (ebl, shdr->sh_link));
2973 
2974   Elf_Data *symdata = elf_getdata (symscn, NULL);
2975   if (symdata == NULL || shdr->sh_entsize == 0)
2976     /* The error has already been reported.  */
2977     return;
2978 
2979   for (int cnt = 1; (size_t) cnt < shdr->sh_size / shdr->sh_entsize; ++cnt)
2980     {
2981       GElf_Versym versym_mem;
2982       GElf_Versym *versym = gelf_getversym (data, cnt, &versym_mem);
2983       if (versym == NULL)
2984 	{
2985 	  ERROR (_("\
2986 section [%2d] '%s': symbol %d: cannot read version data\n"),
2987 		 idx, section_name (ebl, idx), cnt);
2988 	  break;
2989 	}
2990 
2991       GElf_Sym sym_mem;
2992       GElf_Sym *sym = gelf_getsym (symdata, cnt, &sym_mem);
2993       if (sym == NULL)
2994 	/* Already reported elsewhere.  */
2995 	continue;
2996 
2997       if (*versym == VER_NDX_GLOBAL)
2998 	{
2999 	  /* Global symbol.  Make sure it is not defined as local.  */
3000 	  if (GELF_ST_BIND (sym->st_info) == STB_LOCAL)
3001 	    ERROR (_("\
3002 section [%2d] '%s': symbol %d: local symbol with global scope\n"),
3003 		   idx, section_name (ebl, idx), cnt);
3004 	}
3005       else if (*versym != VER_NDX_LOCAL)
3006 	{
3007 	  /* Versioned symbol.  Make sure it is not defined as local.  */
3008 	  if (!gnuld && GELF_ST_BIND (sym->st_info) == STB_LOCAL)
3009 	    ERROR (_("\
3010 section [%2d] '%s': symbol %d: local symbol with version\n"),
3011 		   idx, section_name (ebl, idx), cnt);
3012 
3013 	  /* Look through the list of defined versions and locate the
3014 	     index we need for this symbol.  */
3015 	  struct version_namelist *runp = version_namelist;
3016 	  while (runp != NULL)
3017 	    if (runp->ndx == (*versym & (GElf_Versym) 0x7fff))
3018 	      break;
3019 	    else
3020 	      runp = runp->next;
3021 
3022 	  if (runp == NULL)
3023 	    ERROR (_("\
3024 section [%2d] '%s': symbol %d: invalid version index %d\n"),
3025 		   idx, section_name (ebl, idx), cnt, (int) *versym);
3026 	  else if (sym->st_shndx == SHN_UNDEF
3027 		   && runp->type == ver_def)
3028 	    ERROR (_("\
3029 section [%2d] '%s': symbol %d: version index %d is for defined version\n"),
3030 		   idx, section_name (ebl, idx), cnt, (int) *versym);
3031 	  else if (sym->st_shndx != SHN_UNDEF
3032 		   && runp->type == ver_need)
3033 	    {
3034 	      /* Unless this symbol has a copy relocation associated
3035 		 this must not happen.  */
3036 	      if (!has_copy_reloc (ebl, shdr->sh_link, cnt)
3037 		  && !in_nobits_scn (ebl, sym->st_shndx))
3038 		ERROR (_("\
3039 section [%2d] '%s': symbol %d: version index %d is for requested version\n"),
3040 		       idx, section_name (ebl, idx), cnt, (int) *versym);
3041 	    }
3042 	}
3043     }
3044 }
3045 
3046 
3047 static int
unknown_dependency_p(Elf * elf,const char * fname)3048 unknown_dependency_p (Elf *elf, const char *fname)
3049 {
3050   GElf_Phdr phdr_mem;
3051   GElf_Phdr *phdr = NULL;
3052 
3053   unsigned int i;
3054   for (i = 0; i < phnum; ++i)
3055     if ((phdr = gelf_getphdr (elf, i, &phdr_mem)) != NULL
3056 	&& phdr->p_type == PT_DYNAMIC)
3057       break;
3058 
3059   if (i == phnum)
3060     return 1;
3061   assert (phdr != NULL);
3062   Elf_Scn *scn = gelf_offscn (elf, phdr->p_offset);
3063   GElf_Shdr shdr_mem;
3064   GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3065   Elf_Data *data = elf_getdata (scn, NULL);
3066   if (shdr != NULL && shdr->sh_type == SHT_DYNAMIC
3067       && data != NULL && shdr->sh_entsize != 0)
3068     for (size_t j = 0; j < shdr->sh_size / shdr->sh_entsize; ++j)
3069       {
3070 	GElf_Dyn dyn_mem;
3071 	GElf_Dyn *dyn = gelf_getdyn (data, j, &dyn_mem);
3072 	if (dyn != NULL && dyn->d_tag == DT_NEEDED)
3073 	  {
3074 	    const char *str = elf_strptr (elf, shdr->sh_link, dyn->d_un.d_val);
3075 	    if (str != NULL && strcmp (str, fname) == 0)
3076 	      /* Found it.  */
3077 	      return 0;
3078 	  }
3079       }
3080 
3081   return 1;
3082 }
3083 
3084 
3085 static unsigned int nverneed;
3086 
3087 static void
check_verneed(Ebl * ebl,GElf_Shdr * shdr,int idx)3088 check_verneed (Ebl *ebl, GElf_Shdr *shdr, int idx)
3089 {
3090   if (++nverneed == 2)
3091     ERROR (_("more than one version reference section present\n"));
3092 
3093   GElf_Shdr strshdr_mem;
3094   GElf_Shdr *strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
3095 				     &strshdr_mem);
3096   if (strshdr == NULL)
3097     return;
3098   if (strshdr->sh_type != SHT_STRTAB)
3099     ERROR (_("\
3100 section [%2d] '%s': sh_link does not link to string table\n"),
3101 	   idx, section_name (ebl, idx));
3102 
3103   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
3104   if (data == NULL)
3105     {
3106       ERROR (_("section [%2d] '%s': cannot get section data\n"),
3107 	     idx, section_name (ebl, idx));
3108       return;
3109     }
3110   unsigned int offset = 0;
3111   for (Elf64_Word cnt = shdr->sh_info; cnt > 0; )
3112     {
3113       cnt--;
3114 
3115       /* Get the data at the next offset.  */
3116       GElf_Verneed needmem;
3117       GElf_Verneed *need = gelf_getverneed (data, offset, &needmem);
3118       if (need == NULL)
3119 	break;
3120 
3121       unsigned int auxoffset = offset + need->vn_aux;
3122 
3123       if (need->vn_version != EV_CURRENT)
3124 	ERROR (_("\
3125 section [%2d] '%s': entry %d has wrong version %d\n"),
3126 	       idx, section_name (ebl, idx), cnt, (int) need->vn_version);
3127 
3128       if (need->vn_cnt > 0 && need->vn_aux < gelf_fsize (ebl->elf, ELF_T_VNEED,
3129 							 1, EV_CURRENT))
3130 	{
3131 	  ERROR (_("\
3132 section [%2d] '%s': entry %d has wrong offset of auxiliary data\n"),
3133 	         idx, section_name (ebl, idx), cnt);
3134 	  break;
3135 	}
3136 
3137       const char *libname = elf_strptr (ebl->elf, shdr->sh_link,
3138 					need->vn_file);
3139       if (libname == NULL)
3140 	{
3141 	  ERROR (_("\
3142 section [%2d] '%s': entry %d has invalid file reference\n"),
3143 		 idx, section_name (ebl, idx), cnt);
3144 	  goto next_need;
3145 	}
3146 
3147       /* Check that there is a DT_NEEDED entry for the referenced library.  */
3148       if (unknown_dependency_p (ebl->elf, libname))
3149 	ERROR (_("\
3150 section [%2d] '%s': entry %d references unknown dependency\n"),
3151 	       idx, section_name (ebl, idx), cnt);
3152 
3153       for (int cnt2 = need->vn_cnt; --cnt2 >= 0; )
3154 	{
3155 	  GElf_Vernaux auxmem;
3156 	  GElf_Vernaux *aux = gelf_getvernaux (data, auxoffset, &auxmem);
3157 	  if (aux == NULL)
3158 	    break;
3159 
3160 	  if ((aux->vna_flags & ~VER_FLG_WEAK) != 0)
3161 	    ERROR (_("\
3162 section [%2d] '%s': auxiliary entry %d of entry %d has unknown flag\n"),
3163 		   idx, section_name (ebl, idx), need->vn_cnt - cnt2, cnt);
3164 
3165 	  const char *verstr = elf_strptr (ebl->elf, shdr->sh_link,
3166 					   aux->vna_name);
3167 	  if (verstr == NULL)
3168 	    {
3169 	      ERROR (_("\
3170 section [%2d] '%s': auxiliary entry %d of entry %d has invalid name reference\n"),
3171 		     idx, section_name (ebl, idx), need->vn_cnt - cnt2, cnt);
3172 	      break;
3173 	    }
3174 	  else
3175 	    {
3176 	      GElf_Word hashval = elf_hash (verstr);
3177 	      if (hashval != aux->vna_hash)
3178 		ERROR (_("\
3179 section [%2d] '%s': auxiliary entry %d of entry %d has wrong hash value: %#x, expected %#x\n"),
3180 		       idx, section_name (ebl, idx), need->vn_cnt - cnt2,
3181 		       cnt, (int) hashval, (int) aux->vna_hash);
3182 
3183 	      int res = add_version (libname, verstr, aux->vna_other,
3184 				     ver_need);
3185 	      if (unlikely (res !=0))
3186 		{
3187 		  ERROR (_("\
3188 section [%2d] '%s': auxiliary entry %d of entry %d has duplicate version name '%s'\n"),
3189 			 idx, section_name (ebl, idx), need->vn_cnt - cnt2,
3190 			 cnt, verstr);
3191 		}
3192 	    }
3193 
3194 	  if ((aux->vna_next != 0 || cnt2 > 0)
3195 	      && aux->vna_next < gelf_fsize (ebl->elf, ELF_T_VNAUX, 1,
3196 					     EV_CURRENT))
3197 	    {
3198 	      ERROR (_("\
3199 section [%2d] '%s': auxiliary entry %d of entry %d has wrong next field\n"),
3200 		     idx, section_name (ebl, idx), need->vn_cnt - cnt2, cnt);
3201 	      break;
3202 	    }
3203 
3204 	  auxoffset += MAX (aux->vna_next,
3205 			    gelf_fsize (ebl->elf, ELF_T_VNAUX, 1, EV_CURRENT));
3206 	}
3207 
3208       /* Find the next offset.  */
3209     next_need:
3210       offset += need->vn_next;
3211 
3212       if ((need->vn_next != 0 || cnt > 0)
3213 	  && offset < auxoffset)
3214 	{
3215 	  ERROR (_("\
3216 section [%2d] '%s': entry %d has invalid offset to next entry\n"),
3217 	         idx, section_name (ebl, idx), cnt);
3218 	  break;
3219 	}
3220 
3221       if (need->vn_next == 0 && cnt > 0)
3222 	{
3223 	  ERROR (_("\
3224 section [%2d] '%s': entry %d has zero offset to next entry, but sh_info says there are more entries\n"),
3225 	         idx, section_name (ebl, idx), cnt);
3226 	  break;
3227 	}
3228     }
3229 }
3230 
3231 
3232 static unsigned int nverdef;
3233 
3234 static void
check_verdef(Ebl * ebl,GElf_Shdr * shdr,int idx)3235 check_verdef (Ebl *ebl, GElf_Shdr *shdr, int idx)
3236 {
3237   if (++nverdef == 2)
3238     ERROR (_("more than one version definition section present\n"));
3239 
3240   GElf_Shdr strshdr_mem;
3241   GElf_Shdr *strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
3242 				     &strshdr_mem);
3243   if (strshdr == NULL)
3244     return;
3245   if (strshdr->sh_type != SHT_STRTAB)
3246     ERROR (_("\
3247 section [%2d] '%s': sh_link does not link to string table\n"),
3248 	   idx, section_name (ebl, idx));
3249 
3250   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
3251   if (data == NULL)
3252     {
3253     no_data:
3254       ERROR (_("section [%2d] '%s': cannot get section data\n"),
3255 	     idx, section_name (ebl, idx));
3256       return;
3257     }
3258 
3259   /* Iterate over all version definition entries.  We check that there
3260      is a BASE entry and that each index is unique.  To do the later
3261      we collection the information in a list which is later
3262      examined.  */
3263   struct namelist
3264   {
3265     const char *name;
3266     struct namelist *next;
3267   } *namelist = NULL;
3268   struct namelist *refnamelist = NULL;
3269 
3270   bool has_base = false;
3271   unsigned int offset = 0;
3272   for (Elf64_Word cnt = shdr->sh_info; cnt > 0; )
3273     {
3274       cnt--;
3275 
3276       /* Get the data at the next offset.  */
3277       GElf_Verdef defmem;
3278       GElf_Verdef *def = gelf_getverdef (data, offset, &defmem);
3279       if (def == NULL)
3280 	goto no_data;
3281 
3282       if ((def->vd_flags & VER_FLG_BASE) != 0)
3283 	{
3284 	  if (has_base)
3285 	    ERROR (_("\
3286 section [%2d] '%s': more than one BASE definition\n"),
3287 		   idx, section_name (ebl, idx));
3288 	  if (def->vd_ndx != VER_NDX_GLOBAL)
3289 	    ERROR (_("\
3290 section [%2d] '%s': BASE definition must have index VER_NDX_GLOBAL\n"),
3291 		   idx, section_name (ebl, idx));
3292 	  has_base = true;
3293 	}
3294       if ((def->vd_flags & ~(VER_FLG_BASE|VER_FLG_WEAK)) != 0)
3295 	ERROR (_("\
3296 section [%2d] '%s': entry %d has unknown flag\n"),
3297 	       idx, section_name (ebl, idx), cnt);
3298 
3299       if (def->vd_version != EV_CURRENT)
3300 	ERROR (_("\
3301 section [%2d] '%s': entry %d has wrong version %d\n"),
3302 	       idx, section_name (ebl, idx), cnt, (int) def->vd_version);
3303 
3304       if (def->vd_cnt > 0 && def->vd_aux < gelf_fsize (ebl->elf, ELF_T_VDEF,
3305 						       1, EV_CURRENT))
3306 	{
3307 	  ERROR (_("\
3308 section [%2d] '%s': entry %d has wrong offset of auxiliary data\n"),
3309 	         idx, section_name (ebl, idx), cnt);
3310 	  break;
3311 	}
3312 
3313       unsigned int auxoffset = offset + def->vd_aux;
3314       GElf_Verdaux auxmem;
3315       GElf_Verdaux *aux = gelf_getverdaux (data, auxoffset, &auxmem);
3316       if (aux == NULL)
3317 	goto no_data;
3318 
3319       const char *name = elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name);
3320       if (name == NULL)
3321 	{
3322 	  ERROR (_("\
3323 section [%2d] '%s': entry %d has invalid name reference\n"),
3324 		 idx, section_name (ebl, idx), cnt);
3325 	  goto next_def;
3326 	}
3327       GElf_Word hashval = elf_hash (name);
3328       if (def->vd_hash != hashval)
3329 	ERROR (_("\
3330 section [%2d] '%s': entry %d has wrong hash value: %#x, expected %#x\n"),
3331 	       idx, section_name (ebl, idx), cnt, (int) hashval,
3332 	       (int) def->vd_hash);
3333 
3334       int res = add_version (NULL, name, def->vd_ndx, ver_def);
3335       if (unlikely (res !=0))
3336 	{
3337 	  ERROR (_("\
3338 section [%2d] '%s': entry %d has duplicate version name '%s'\n"),
3339 		 idx, section_name (ebl, idx), cnt, name);
3340 	}
3341 
3342       struct namelist *newname = alloca (sizeof (*newname));
3343       newname->name = name;
3344       newname->next = namelist;
3345       namelist = newname;
3346 
3347       auxoffset += aux->vda_next;
3348       for (int cnt2 = 1; cnt2 < def->vd_cnt; ++cnt2)
3349 	{
3350 	  aux = gelf_getverdaux (data, auxoffset, &auxmem);
3351 	  if (aux == NULL)
3352 	    goto no_data;
3353 
3354 	  name = elf_strptr (ebl->elf, shdr->sh_link, aux->vda_name);
3355 	  if (name == NULL)
3356 	    {
3357 	      ERROR (_("\
3358 section [%2d] '%s': entry %d has invalid name reference in auxiliary data\n"),
3359 		     idx, section_name (ebl, idx), cnt);
3360 	      break;
3361 	    }
3362 	  else
3363 	    {
3364 	      newname = alloca (sizeof (*newname));
3365 	      newname->name = name;
3366 	      newname->next = refnamelist;
3367 	      refnamelist = newname;
3368 	    }
3369 
3370 	  if ((aux->vda_next != 0 || cnt2 + 1 < def->vd_cnt)
3371 	      && aux->vda_next < gelf_fsize (ebl->elf, ELF_T_VDAUX, 1,
3372 					     EV_CURRENT))
3373 	    {
3374 	      ERROR (_("\
3375 section [%2d] '%s': entry %d has wrong next field in auxiliary data\n"),
3376 		     idx, section_name (ebl, idx), cnt);
3377 	      break;
3378 	    }
3379 
3380 	  auxoffset += MAX (aux->vda_next,
3381 			    gelf_fsize (ebl->elf, ELF_T_VDAUX, 1, EV_CURRENT));
3382 	}
3383 
3384       /* Find the next offset.  */
3385     next_def:
3386       offset += def->vd_next;
3387 
3388       if ((def->vd_next != 0 || cnt > 0)
3389 	  && offset < auxoffset)
3390 	{
3391 	  ERROR (_("\
3392 section [%2d] '%s': entry %d has invalid offset to next entry\n"),
3393 	         idx, section_name (ebl, idx), cnt);
3394 	  break;
3395 	}
3396 
3397       if (def->vd_next == 0 && cnt > 0)
3398 	{
3399 	  ERROR (_("\
3400 section [%2d] '%s': entry %d has zero offset to next entry, but sh_info says there are more entries\n"),
3401 	         idx, section_name (ebl, idx), cnt);
3402 	  break;
3403 	}
3404     }
3405 
3406   if (!has_base)
3407     ERROR (_("section [%2d] '%s': no BASE definition\n"),
3408 	   idx, section_name (ebl, idx));
3409 
3410   /* Check whether the referenced names are available.  */
3411   while (namelist != NULL)
3412     {
3413       struct version_namelist *runp = version_namelist;
3414       while (runp != NULL)
3415 	{
3416 	  if (runp->type == ver_def
3417 	      && strcmp (runp->name, namelist->name) == 0)
3418 	    break;
3419 	  runp = runp->next;
3420 	}
3421 
3422       if (runp == NULL)
3423 	ERROR (_("\
3424 section [%2d] '%s': unknown parent version '%s'\n"),
3425 	       idx, section_name (ebl, idx), namelist->name);
3426 
3427       namelist = namelist->next;
3428     }
3429 }
3430 
3431 static void
check_attributes(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)3432 check_attributes (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
3433 {
3434   if (shdr->sh_size == 0)
3435     {
3436       ERROR (_("section [%2d] '%s': empty object attributes section\n"),
3437 	     idx, section_name (ebl, idx));
3438       return;
3439     }
3440 
3441   Elf_Data *data = elf_rawdata (elf_getscn (ebl->elf, idx), NULL);
3442   if (data == NULL || data->d_size == 0 || data->d_buf == NULL)
3443     {
3444       ERROR (_("section [%2d] '%s': cannot get section data\n"),
3445 	     idx, section_name (ebl, idx));
3446       return;
3447     }
3448 
3449   inline size_t pos (const unsigned char *p)
3450   {
3451     return p - (const unsigned char *) data->d_buf;
3452   }
3453 
3454   const unsigned char *p = data->d_buf;
3455   if (*p++ != 'A')
3456     {
3457       ERROR (_("section [%2d] '%s': unrecognized attribute format\n"),
3458 	     idx, section_name (ebl, idx));
3459       return;
3460     }
3461 
3462   inline size_t left (void)
3463   {
3464     return (const unsigned char *) data->d_buf + data->d_size - p;
3465   }
3466 
3467   while (left () >= 4)
3468     {
3469       uint32_t len;
3470       memcpy (&len, p, sizeof len);
3471 
3472       if (len == 0)
3473 	ERROR (_("\
3474 section [%2d] '%s': offset %zu: zero length field in attribute section\n"),
3475 	       idx, section_name (ebl, idx), pos (p));
3476 
3477       if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3478 	CONVERT (len);
3479 
3480       if (len > left ())
3481 	{
3482 	  ERROR (_("\
3483 section [%2d] '%s': offset %zu: invalid length in attribute section\n"),
3484 		 idx, section_name (ebl, idx), pos (p));
3485 	  break;
3486 	}
3487 
3488       const unsigned char *name = p + sizeof len;
3489       p += len;
3490 
3491       unsigned const char *q = memchr (name, '\0', len);
3492       if (q == NULL)
3493 	{
3494 	  ERROR (_("\
3495 section [%2d] '%s': offset %zu: unterminated vendor name string\n"),
3496 		 idx, section_name (ebl, idx), pos (p));
3497 	  break;
3498 	}
3499       ++q;
3500 
3501       if (q - name == sizeof "gnu" && !memcmp (name, "gnu", sizeof "gnu"))
3502 	while (q < p)
3503 	  {
3504 	    unsigned const char *chunk = q;
3505 
3506 	    unsigned int subsection_tag;
3507 	    get_uleb128 (subsection_tag, q, p);
3508 
3509 	    if (q >= p)
3510 	      {
3511 		ERROR (_("\
3512 section [%2d] '%s': offset %zu: endless ULEB128 in attribute subsection tag\n"),
3513 		       idx, section_name (ebl, idx), pos (chunk));
3514 		break;
3515 	      }
3516 
3517 	    uint32_t subsection_len;
3518 	    if (p - q < (ptrdiff_t) sizeof subsection_len)
3519 	      {
3520 		ERROR (_("\
3521 section [%2d] '%s': offset %zu: truncated attribute section\n"),
3522 		       idx, section_name (ebl, idx), pos (q));
3523 		break;
3524 	      }
3525 
3526 	    memcpy (&subsection_len, q, sizeof subsection_len);
3527 	    if (subsection_len == 0)
3528 	      {
3529 		ERROR (_("\
3530 section [%2d] '%s': offset %zu: zero length field in attribute subsection\n"),
3531 		       idx, section_name (ebl, idx), pos (q));
3532 
3533 		q += sizeof subsection_len;
3534 		continue;
3535 	      }
3536 
3537 	    if (MY_ELFDATA != ehdr->e_ident[EI_DATA])
3538 	      CONVERT (subsection_len);
3539 
3540 	    /* Don't overflow, ptrdiff_t might be 32bits, but signed.  */
3541 	    if (p - chunk < (ptrdiff_t) subsection_len
3542 	        || subsection_len >= (uint32_t) PTRDIFF_MAX)
3543 	      {
3544 		ERROR (_("\
3545 section [%2d] '%s': offset %zu: invalid length in attribute subsection\n"),
3546 		       idx, section_name (ebl, idx), pos (q));
3547 		break;
3548 	      }
3549 
3550 	    const unsigned char *subsection_end = chunk + subsection_len;
3551 	    chunk = q;
3552 	    q = subsection_end;
3553 
3554 	    if (subsection_tag != 1) /* Tag_File */
3555 	      ERROR (_("\
3556 section [%2d] '%s': offset %zu: attribute subsection has unexpected tag %u\n"),
3557 		     idx, section_name (ebl, idx), pos (chunk), subsection_tag);
3558 	    else
3559 	      {
3560 		chunk += sizeof subsection_len;
3561 		while (chunk < q)
3562 		  {
3563 		    unsigned int tag;
3564 		    get_uleb128 (tag, chunk, q);
3565 
3566 		    uint64_t value = 0;
3567 		    const unsigned char *r = chunk;
3568 		    if (tag == 32 || (tag & 1) == 0)
3569 		      {
3570 			get_uleb128 (value, r, q);
3571 			if (r > q)
3572 			  {
3573 			    ERROR (_("\
3574 section [%2d] '%s': offset %zu: endless ULEB128 in attribute tag\n"),
3575 				   idx, section_name (ebl, idx), pos (chunk));
3576 			    break;
3577 			  }
3578 		      }
3579 		    if (tag == 32 || (tag & 1) != 0)
3580 		      {
3581 			r = memchr (r, '\0', q - r);
3582 			if (r == NULL)
3583 			  {
3584 			    ERROR (_("\
3585 section [%2d] '%s': offset %zu: unterminated string in attribute\n"),
3586 				   idx, section_name (ebl, idx), pos (chunk));
3587 			    break;
3588 			  }
3589 			++r;
3590 		      }
3591 
3592 		    const char *tag_name = NULL;
3593 		    const char *value_name = NULL;
3594 		    if (!ebl_check_object_attribute (ebl, (const char *) name,
3595 						     tag, value,
3596 						     &tag_name, &value_name))
3597 		      ERROR (_("\
3598 section [%2d] '%s': offset %zu: unrecognized attribute tag %u\n"),
3599 			     idx, section_name (ebl, idx), pos (chunk), tag);
3600 		    else if ((tag & 1) == 0 && value_name == NULL)
3601 		      ERROR (_("\
3602 section [%2d] '%s': offset %zu: unrecognized %s attribute value %" PRIu64 "\n"),
3603 			     idx, section_name (ebl, idx), pos (chunk),
3604 			     tag_name, value);
3605 
3606 		    chunk = r;
3607 		  }
3608 	      }
3609 	  }
3610       else
3611 	ERROR (_("\
3612 section [%2d] '%s': offset %zu: vendor '%s' unknown\n"),
3613 	       idx, section_name (ebl, idx), pos (p), name);
3614     }
3615 
3616   if (left () != 0)
3617     ERROR (_("\
3618 section [%2d] '%s': offset %zu: extra bytes after last attribute section\n"),
3619 	   idx, section_name (ebl, idx), pos (p));
3620 }
3621 
3622 static bool has_loadable_segment;
3623 static bool has_interp_segment;
3624 
3625 static const struct
3626 {
3627   const char *name;
3628   size_t namelen;
3629   GElf_Word type;
3630   enum { unused, exact, atleast, exact_or_gnuld } attrflag;
3631   GElf_Word attr;
3632   GElf_Word attr2;
3633 } special_sections[] =
3634   {
3635     /* See figure 4-14 in the gABI.  */
3636     { ".bss", 5, SHT_NOBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
3637     { ".comment", 8, SHT_PROGBITS, atleast, 0, SHF_MERGE | SHF_STRINGS },
3638     { ".data", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
3639     { ".data1", 7, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
3640     { ".debug_str", 11, SHT_PROGBITS, exact_or_gnuld, SHF_MERGE | SHF_STRINGS, 0 },
3641     { ".debug_line_str", 16, SHT_PROGBITS, exact_or_gnuld, SHF_MERGE | SHF_STRINGS, 0 },
3642     { ".debug", 6, SHT_PROGBITS, exact, 0, 0 },
3643     { ".dynamic", 9, SHT_DYNAMIC, atleast, SHF_ALLOC, SHF_WRITE },
3644     { ".dynstr", 8, SHT_STRTAB, exact, SHF_ALLOC, 0 },
3645     { ".dynsym", 8, SHT_DYNSYM, exact, SHF_ALLOC, 0 },
3646     { ".fini", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 },
3647     { ".fini_array", 12, SHT_FINI_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
3648     { ".got", 5, SHT_PROGBITS, unused, 0, 0 }, // XXX more info?
3649     { ".hash", 6, SHT_HASH, exact, SHF_ALLOC, 0 },
3650     { ".init", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 },
3651     { ".init_array", 12, SHT_INIT_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
3652     { ".interp", 8, SHT_PROGBITS, atleast, 0, SHF_ALLOC }, // XXX more tests?
3653     { ".line", 6, SHT_PROGBITS, exact, 0, 0 },
3654     { ".note", 6, SHT_NOTE, atleast, 0, SHF_ALLOC },
3655     { ".plt", 5, SHT_PROGBITS, unused, 0, 0 }, // XXX more tests
3656     { ".preinit_array", 15, SHT_PREINIT_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
3657     { ".rela", 5, SHT_RELA, atleast, 0, SHF_ALLOC | SHF_INFO_LINK }, // XXX more tests
3658     { ".rel", 4, SHT_REL, atleast, 0, SHF_ALLOC | SHF_INFO_LINK }, // XXX more tests
3659     { ".rodata", 8, SHT_PROGBITS, atleast, SHF_ALLOC, SHF_MERGE | SHF_STRINGS },
3660     { ".rodata1", 9, SHT_PROGBITS, atleast, SHF_ALLOC, SHF_MERGE | SHF_STRINGS },
3661     { ".shstrtab", 10, SHT_STRTAB, exact, 0, 0 },
3662     { ".strtab", 8, SHT_STRTAB, atleast, 0, SHF_ALLOC }, // XXX more tests
3663     { ".symtab", 8, SHT_SYMTAB, atleast, 0, SHF_ALLOC }, // XXX more tests
3664     { ".symtab_shndx", 14, SHT_SYMTAB_SHNDX, atleast, 0, SHF_ALLOC }, // XXX more tests
3665     { ".tbss", 6, SHT_NOBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
3666     { ".tdata", 7, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
3667     { ".tdata1", 8, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
3668     { ".text", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 },
3669 
3670     /* The following are GNU extensions.  */
3671     { ".gnu.version", 13, SHT_GNU_versym, exact, SHF_ALLOC, 0 },
3672     { ".gnu.version_d", 15, SHT_GNU_verdef, exact, SHF_ALLOC, 0 },
3673     { ".gnu.version_r", 15, SHT_GNU_verneed, exact, SHF_ALLOC, 0 },
3674     { ".gnu.attributes", 16, SHT_GNU_ATTRIBUTES, exact, 0, 0 },
3675   };
3676 #define nspecial_sections \
3677   (sizeof (special_sections) / sizeof (special_sections[0]))
3678 
3679 #define IS_KNOWN_SPECIAL(idx, string, prefix)			      \
3680   (special_sections[idx].namelen == sizeof string - (prefix ? 1 : 0)  \
3681    && !memcmp (special_sections[idx].name, string, \
3682 	       sizeof string - (prefix ? 1 : 0)))
3683 
3684 /* Extra section flags that might or might not be added to the section
3685    and have to be ignored.  */
3686 #define EXTRA_SHFLAGS (SHF_LINK_ORDER \
3687 		       | SHF_GNU_RETAIN \
3688 		       | SHF_GROUP \
3689 		       | SHF_COMPRESSED)
3690 
3691 
3692 /* Indices of some sections we need later.  */
3693 static size_t eh_frame_hdr_scnndx;
3694 static size_t eh_frame_scnndx;
3695 static size_t gcc_except_table_scnndx;
3696 
3697 
3698 static void
check_sections(Ebl * ebl,GElf_Ehdr * ehdr)3699 check_sections (Ebl *ebl, GElf_Ehdr *ehdr)
3700 {
3701   if (ehdr->e_shoff == 0)
3702     /* No section header.  */
3703     return;
3704 
3705   /* Allocate array to count references in section groups.  */
3706   scnref = (int *) xcalloc (shnum, sizeof (int));
3707 
3708   /* Check the zeroth section first.  It must not have any contents
3709      and the section header must contain nonzero value at most in the
3710      sh_size and sh_link fields.  */
3711   GElf_Shdr shdr_mem;
3712   GElf_Shdr *shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
3713   if (shdr == NULL)
3714     ERROR (_("cannot get section header of zeroth section\n"));
3715   else
3716     {
3717       if (shdr->sh_name != 0)
3718 	ERROR (_("zeroth section has nonzero name\n"));
3719       if (shdr->sh_type != 0)
3720 	ERROR (_("zeroth section has nonzero type\n"));
3721       if (shdr->sh_flags != 0)
3722 	ERROR (_("zeroth section has nonzero flags\n"));
3723       if (shdr->sh_addr != 0)
3724 	ERROR (_("zeroth section has nonzero address\n"));
3725       if (shdr->sh_offset != 0)
3726 	ERROR (_("zeroth section has nonzero offset\n"));
3727       if (shdr->sh_addralign != 0)
3728 	ERROR (_("zeroth section has nonzero align value\n"));
3729       if (shdr->sh_entsize != 0)
3730 	ERROR (_("zeroth section has nonzero entry size value\n"));
3731 
3732       if (shdr->sh_size != 0 && ehdr->e_shnum != 0)
3733 	ERROR (_("\
3734 zeroth section has nonzero size value while ELF header has nonzero shnum value\n"));
3735 
3736       if (shdr->sh_link != 0 && ehdr->e_shstrndx != SHN_XINDEX)
3737 	ERROR (_("\
3738 zeroth section has nonzero link value while ELF header does not signal overflow in shstrndx\n"));
3739 
3740       if (shdr->sh_info != 0 && ehdr->e_phnum != PN_XNUM)
3741 	ERROR (_("\
3742 zeroth section has nonzero link value while ELF header does not signal overflow in phnum\n"));
3743     }
3744 
3745   int *segment_flags = xcalloc (phnum, sizeof segment_flags[0]);
3746 
3747   bool dot_interp_section = false;
3748 
3749   size_t hash_idx = 0;
3750   size_t gnu_hash_idx = 0;
3751 
3752   size_t versym_scnndx = 0;
3753   for (size_t cnt = 1; cnt < shnum; ++cnt)
3754     {
3755       Elf_Scn *scn = elf_getscn (ebl->elf, cnt);
3756       shdr = gelf_getshdr (scn, &shdr_mem);
3757       if (shdr == NULL)
3758 	{
3759 	  ERROR (_("\
3760 cannot get section header for section [%2zu] '%s': %s\n"),
3761 		 cnt, section_name (ebl, cnt), elf_errmsg (-1));
3762 	  continue;
3763 	}
3764 
3765       const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
3766 
3767       if (scnname == NULL)
3768 	ERROR (_("section [%2zu]: invalid name\n"), cnt);
3769       else
3770 	{
3771 	  /* Check whether it is one of the special sections defined in
3772 	     the gABI.  */
3773 	  size_t s;
3774 	  for (s = 0; s < nspecial_sections; ++s)
3775 	    if (strncmp (scnname, special_sections[s].name,
3776 			 special_sections[s].namelen) == 0)
3777 	      {
3778 		char stbuf1[100];
3779 		char stbuf2[100];
3780 		char stbuf3[100];
3781 
3782 		GElf_Word good_type = special_sections[s].type;
3783 		if (IS_KNOWN_SPECIAL (s, ".plt", false)
3784 		    && ebl_bss_plt_p (ebl))
3785 		  good_type = SHT_NOBITS;
3786 
3787 		/* In a debuginfo file, any normal section can be SHT_NOBITS.
3788 		   This is only invalid for DWARF sections and .shstrtab.  */
3789 		if (shdr->sh_type != good_type
3790 		    && (shdr->sh_type != SHT_NOBITS
3791 			|| !is_debuginfo
3792 			|| IS_KNOWN_SPECIAL (s, ".debug_str", false)
3793 			|| IS_KNOWN_SPECIAL (s, ".debug", true)
3794 			|| IS_KNOWN_SPECIAL (s, ".shstrtab", false)))
3795 		  ERROR (_("\
3796 section [%2d] '%s' has wrong type: expected %s, is %s\n"),
3797 			 (int) cnt, scnname,
3798 			 ebl_section_type_name (ebl, special_sections[s].type,
3799 						stbuf1, sizeof (stbuf1)),
3800 			 ebl_section_type_name (ebl, shdr->sh_type,
3801 						stbuf2, sizeof (stbuf2)));
3802 
3803 		if (special_sections[s].attrflag == exact
3804 		    || special_sections[s].attrflag == exact_or_gnuld)
3805 		  {
3806 		    /* Except for the link order, retain, group bit and
3807 		       compression flag all the other bits should
3808 		       match exactly.  */
3809 		    if ((shdr->sh_flags & ~EXTRA_SHFLAGS)
3810 			!= special_sections[s].attr
3811 			&& (special_sections[s].attrflag == exact || !gnuld))
3812 		      ERROR (_("\
3813 section [%2zu] '%s' has wrong flags: expected %s, is %s\n"),
3814 			     cnt, scnname,
3815 			     section_flags_string (special_sections[s].attr,
3816 						   stbuf1, sizeof (stbuf1)),
3817 			     section_flags_string (shdr->sh_flags
3818 						   & ~EXTRA_SHFLAGS,
3819 						   stbuf2, sizeof (stbuf2)));
3820 		  }
3821 		else if (special_sections[s].attrflag == atleast)
3822 		  {
3823 		    if ((shdr->sh_flags & special_sections[s].attr)
3824 			!= special_sections[s].attr
3825 			|| ((shdr->sh_flags
3826 			     & ~(EXTRA_SHFLAGS
3827 				 | special_sections[s].attr
3828 				 | special_sections[s].attr2))
3829 			    != 0))
3830 		      ERROR (_("\
3831 section [%2zu] '%s' has wrong flags: expected %s and possibly %s, is %s\n"),
3832 			     cnt, scnname,
3833 			     section_flags_string (special_sections[s].attr,
3834 						   stbuf1, sizeof (stbuf1)),
3835 			     section_flags_string (special_sections[s].attr2,
3836 						   stbuf2, sizeof (stbuf2)),
3837 			     section_flags_string (shdr->sh_flags
3838 						   & ~EXTRA_SHFLAGS,
3839 						   stbuf3, sizeof (stbuf3)));
3840 		  }
3841 
3842 		if (strcmp (scnname, ".interp") == 0)
3843 		  {
3844 		    dot_interp_section = true;
3845 
3846 		    if (ehdr->e_type == ET_REL)
3847 		      ERROR (_("\
3848 section [%2zu] '%s' present in object file\n"),
3849 			     cnt, scnname);
3850 
3851 		    if ((shdr->sh_flags & SHF_ALLOC) != 0
3852 			&& !has_loadable_segment)
3853 		      ERROR (_("\
3854 section [%2zu] '%s' has SHF_ALLOC flag set but there is no loadable segment\n"),
3855 			     cnt, scnname);
3856 		    else if ((shdr->sh_flags & SHF_ALLOC) == 0
3857 			     && has_loadable_segment)
3858 		      ERROR (_("\
3859 section [%2zu] '%s' has SHF_ALLOC flag not set but there are loadable segments\n"),
3860 			     cnt, scnname);
3861 		  }
3862 		else
3863 		  {
3864 		    if (strcmp (scnname, ".symtab_shndx") == 0
3865 			&& ehdr->e_type != ET_REL)
3866 		      ERROR (_("\
3867 section [%2zu] '%s' is extension section index table in non-object file\n"),
3868 			     cnt, scnname);
3869 
3870 		    /* These sections must have the SHF_ALLOC flag set iff
3871 		       a loadable segment is available.
3872 
3873 		       .relxxx
3874 		       .strtab
3875 		       .symtab
3876 		       .symtab_shndx
3877 
3878 		       Check that if there is a reference from the
3879 		       loaded section these sections also have the
3880 		       ALLOC flag set.  */
3881 #if 0
3882 		    // XXX TODO
3883 		    if ((shdr->sh_flags & SHF_ALLOC) != 0
3884 			&& !has_loadable_segment)
3885 		      ERROR (_("\
3886 section [%2zu] '%s' has SHF_ALLOC flag set but there is no loadable segment\n"),
3887 			     cnt, scnname);
3888 		    else if ((shdr->sh_flags & SHF_ALLOC) == 0
3889 			     && has_loadable_segment)
3890 		      ERROR (_("\
3891 section [%2zu] '%s' has SHF_ALLOC flag not set but there are loadable segments\n"),
3892 			     cnt, scnname);
3893 #endif
3894 		  }
3895 
3896 		break;
3897 	      }
3898 
3899 	  /* Remember a few special sections for later.  */
3900 	  if (strcmp (scnname, ".eh_frame_hdr") == 0)
3901 	    eh_frame_hdr_scnndx = cnt;
3902 	  else if (strcmp (scnname, ".eh_frame") == 0)
3903 	    eh_frame_scnndx = cnt;
3904 	  else if (strcmp (scnname, ".gcc_except_table") == 0)
3905 	    gcc_except_table_scnndx = cnt;
3906 	}
3907 
3908       if (shdr->sh_entsize != 0 && shdr->sh_size % shdr->sh_entsize)
3909 	ERROR (_("\
3910 section [%2zu] '%s': size not multiple of entry size\n"),
3911 	       cnt, section_name (ebl, cnt));
3912 
3913       if (elf_strptr (ebl->elf, shstrndx, shdr->sh_name) == NULL)
3914 	ERROR (_("cannot get section header\n"));
3915 
3916       if (shdr->sh_type >= SHT_NUM
3917 	  && shdr->sh_type != SHT_GNU_ATTRIBUTES
3918 	  && shdr->sh_type != SHT_GNU_LIBLIST
3919 	  && shdr->sh_type != SHT_CHECKSUM
3920 	  && shdr->sh_type != SHT_GNU_verdef
3921 	  && shdr->sh_type != SHT_GNU_verneed
3922 	  && shdr->sh_type != SHT_GNU_versym
3923 	  && ebl_section_type_name (ebl, shdr->sh_type, NULL, 0) == NULL)
3924 	ERROR (_("section [%2zu] '%s' has unsupported type %d\n"),
3925 	       cnt, section_name (ebl, cnt),
3926 	       (int) shdr->sh_type);
3927 
3928 #define ALL_SH_FLAGS (SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR | SHF_MERGE \
3929 		      | SHF_STRINGS | SHF_INFO_LINK | SHF_LINK_ORDER \
3930 		      | SHF_OS_NONCONFORMING | SHF_GROUP | SHF_TLS \
3931 		      | SHF_COMPRESSED | SHF_GNU_RETAIN)
3932       if (shdr->sh_flags & ~(GElf_Xword) ALL_SH_FLAGS)
3933 	{
3934 	  GElf_Xword sh_flags = shdr->sh_flags & ~(GElf_Xword) ALL_SH_FLAGS;
3935 	  if (sh_flags & SHF_MASKPROC)
3936 	    {
3937 	      /* Strictly speaking SHF_EXCLUDE is a processor specific
3938 		 section flag, but it is used generically in the GNU
3939 		 toolchain.  */
3940 	      if (gnuld)
3941 		sh_flags &= ~(GElf_Xword) SHF_EXCLUDE;
3942 	      if (!ebl_machine_section_flag_check (ebl,
3943 						   sh_flags & SHF_MASKPROC))
3944 		ERROR (_("section [%2zu] '%s'"
3945 				" contains invalid processor-specific flag(s)"
3946 				" %#" PRIx64 "\n"),
3947 		       cnt, section_name (ebl, cnt), sh_flags & SHF_MASKPROC);
3948 	      sh_flags &= ~(GElf_Xword) SHF_MASKPROC;
3949 	    }
3950 	  if (sh_flags & SHF_MASKOS)
3951 	    if (gnuld)
3952 	      sh_flags &= ~(GElf_Xword) SHF_GNU_RETAIN;
3953 	  if (sh_flags != 0)
3954 	    ERROR (_("section [%2zu] '%s' contains unknown flag(s)"
3955 			    " %#" PRIx64 "\n"),
3956 		   cnt, section_name (ebl, cnt), sh_flags);
3957 	}
3958       if (shdr->sh_flags & SHF_TLS)
3959 	{
3960 	  // XXX Correct?
3961 	  if (shdr->sh_addr != 0 && !gnuld)
3962 	    ERROR (_("\
3963 section [%2zu] '%s': thread-local data sections address not zero\n"),
3964 		   cnt, section_name (ebl, cnt));
3965 
3966 	  // XXX TODO more tests!?
3967 	}
3968 
3969       if (shdr->sh_flags & SHF_COMPRESSED)
3970 	{
3971 	  if (shdr->sh_flags & SHF_ALLOC)
3972 	    ERROR (_("\
3973 section [%2zu] '%s': allocated section cannot be compressed\n"),
3974 		   cnt, section_name (ebl, cnt));
3975 
3976 	  if (shdr->sh_type == SHT_NOBITS)
3977 	    ERROR (_("\
3978 section [%2zu] '%s': nobits section cannot be compressed\n"),
3979 		   cnt, section_name (ebl, cnt));
3980 
3981 	  GElf_Chdr chdr;
3982 	  if (gelf_getchdr (scn, &chdr) == NULL)
3983 	    ERROR (_("\
3984 section [%2zu] '%s': compressed section with no compression header: %s\n"),
3985 		   cnt, section_name (ebl, cnt), elf_errmsg (-1));
3986 	}
3987 
3988       if (shdr->sh_link >= shnum)
3989 	ERROR (_("\
3990 section [%2zu] '%s': invalid section reference in link value\n"),
3991 	       cnt, section_name (ebl, cnt));
3992 
3993       if (SH_INFO_LINK_P (shdr) && shdr->sh_info >= shnum)
3994 	ERROR (_("\
3995 section [%2zu] '%s': invalid section reference in info value\n"),
3996 	       cnt, section_name (ebl, cnt));
3997 
3998       if ((shdr->sh_flags & SHF_MERGE) == 0
3999 	  && (shdr->sh_flags & SHF_STRINGS) != 0
4000 	  && be_strict)
4001 	ERROR (_("\
4002 section [%2zu] '%s': strings flag set without merge flag\n"),
4003 	       cnt, section_name (ebl, cnt));
4004 
4005       if ((shdr->sh_flags & SHF_MERGE) != 0 && shdr->sh_entsize == 0)
4006 	ERROR (_("\
4007 section [%2zu] '%s': merge flag set but entry size is zero\n"),
4008 	       cnt, section_name (ebl, cnt));
4009 
4010       if (shdr->sh_flags & SHF_GROUP)
4011 	check_scn_group (ebl, cnt);
4012 
4013       if (shdr->sh_flags & SHF_EXECINSTR)
4014 	{
4015 	  switch (shdr->sh_type)
4016 	    {
4017 	    case SHT_PROGBITS:
4018 	      break;
4019 
4020 	    case SHT_NOBITS:
4021 	      if (is_debuginfo)
4022 		break;
4023 	      FALLTHROUGH;
4024 	    default:
4025 	      ERROR (_("\
4026 section [%2zu] '%s' has unexpected type %d for an executable section\n"),
4027 		     cnt, section_name (ebl, cnt), shdr->sh_type);
4028 	      break;
4029 	    }
4030 
4031 	  if (shdr->sh_flags & SHF_WRITE)
4032 	    {
4033 	      if (is_debuginfo && shdr->sh_type != SHT_NOBITS)
4034 		ERROR (_("\
4035 section [%2zu] '%s' must be of type NOBITS in debuginfo files\n"),
4036 		       cnt, section_name (ebl, cnt));
4037 
4038 	      if (!is_debuginfo
4039 		  && !ebl_check_special_section (ebl, cnt, shdr,
4040 						 section_name (ebl, cnt)))
4041 		ERROR (_("\
4042 section [%2zu] '%s' is both executable and writable\n"),
4043 		       cnt, section_name (ebl, cnt));
4044 	    }
4045 	}
4046 
4047       if (ehdr->e_type != ET_REL && (shdr->sh_flags & SHF_ALLOC) != 0
4048 	  && !is_debuginfo)
4049 	{
4050 	  /* Make sure the section is contained in a loaded segment
4051 	     and that the initialization part matches NOBITS sections.  */
4052 	  unsigned int pcnt;
4053 	  GElf_Phdr phdr_mem;
4054 	  GElf_Phdr *phdr;
4055 
4056 	  for (pcnt = 0; pcnt < phnum; ++pcnt)
4057 	    if ((phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem)) != NULL
4058 		&& ((phdr->p_type == PT_LOAD
4059 		     && (shdr->sh_flags & SHF_TLS) == 0)
4060 		    || (phdr->p_type == PT_TLS
4061 			&& (shdr->sh_flags & SHF_TLS) != 0))
4062 		&& phdr->p_offset <= shdr->sh_offset
4063 		&& ((shdr->sh_offset - phdr->p_offset <= phdr->p_filesz
4064 		     && (shdr->sh_offset - phdr->p_offset < phdr->p_filesz
4065 			 || shdr->sh_size == 0))
4066 		    || (shdr->sh_offset - phdr->p_offset < phdr->p_memsz
4067 			&& shdr->sh_type == SHT_NOBITS)))
4068 	      {
4069 		/* Found the segment.  */
4070 		if (phdr->p_offset + phdr->p_memsz
4071 		    < shdr->sh_offset + shdr->sh_size)
4072 		  ERROR (_("\
4073 section [%2zu] '%s' not fully contained in segment of program header entry %d\n"),
4074 			 cnt, section_name (ebl, cnt), pcnt);
4075 
4076 		if (shdr->sh_type == SHT_NOBITS)
4077 		  {
4078 		    if (shdr->sh_offset < phdr->p_offset + phdr->p_filesz
4079 			&& !is_debuginfo)
4080 		      {
4081 			if (!gnuld)
4082 			  ERROR (_("\
4083 section [%2zu] '%s' has type NOBITS but is read from the file in segment of program header entry %d\n"),
4084 				 cnt, section_name (ebl, cnt), pcnt);
4085 			else
4086 			  {
4087 			    /* This is truly horrible. GNU ld might put a
4088 			       NOBITS section in the middle of a PT_LOAD
4089 			       segment, assuming the next gap in the file
4090 			       actually consists of zero bits...
4091 			       So it really is like a PROGBITS section
4092 			       where the data is all zeros.  Check those
4093 			       zero bytes are really there.  */
4094 			    bool bad;
4095 			    Elf_Data *databits;
4096 			    databits = elf_getdata_rawchunk (ebl->elf,
4097 							     shdr->sh_offset,
4098 							     shdr->sh_size,
4099 							     ELF_T_BYTE);
4100 			    bad = (databits == NULL
4101 				   || databits->d_size != shdr->sh_size);
4102 			    for (size_t idx = 0;
4103 				 idx < databits->d_size && ! bad;
4104 				 idx++)
4105 			      bad = ((char *) databits->d_buf)[idx] != 0;
4106 
4107 			    if (bad)
4108 			      ERROR (_("\
4109 section [%2zu] '%s' has type NOBITS but is read from the file in segment of program header entry %d and file contents is non-zero\n"),
4110 				     cnt, section_name (ebl, cnt), pcnt);
4111 			  }
4112 		      }
4113 		  }
4114 		else
4115 		  {
4116 		    const GElf_Off end = phdr->p_offset + phdr->p_filesz;
4117 		    if (shdr->sh_offset > end ||
4118 			(shdr->sh_offset == end && shdr->sh_size != 0))
4119 		      ERROR (_("\
4120 section [%2zu] '%s' has not type NOBITS but is not read from the file in segment of program header entry %d\n"),
4121 			 cnt, section_name (ebl, cnt), pcnt);
4122 		  }
4123 
4124 		if (shdr->sh_type != SHT_NOBITS)
4125 		  {
4126 		    if ((shdr->sh_flags & SHF_EXECINSTR) != 0)
4127 		      {
4128 			segment_flags[pcnt] |= PF_X;
4129 			if ((phdr->p_flags & PF_X) == 0)
4130 			  ERROR (_("\
4131 section [%2zu] '%s' is executable in nonexecutable segment %d\n"),
4132 				 cnt, section_name (ebl, cnt), pcnt);
4133 		      }
4134 
4135 		    if ((shdr->sh_flags & SHF_WRITE) != 0)
4136 		      {
4137 			segment_flags[pcnt] |= PF_W;
4138 			if (0	/* XXX vdso images have this */
4139 			    && (phdr->p_flags & PF_W) == 0)
4140 			  ERROR (_("\
4141 section [%2zu] '%s' is writable in unwritable segment %d\n"),
4142 				 cnt, section_name (ebl, cnt), pcnt);
4143 		      }
4144 		  }
4145 
4146 		break;
4147 	      }
4148 
4149 	  if (pcnt == phnum)
4150 	    ERROR (_("\
4151 section [%2zu] '%s': alloc flag set but section not in any loaded segment\n"),
4152 		   cnt, section_name (ebl, cnt));
4153 	}
4154 
4155       if (cnt == shstrndx && shdr->sh_type != SHT_STRTAB)
4156 	ERROR (_("\
4157 section [%2zu] '%s': ELF header says this is the section header string table but type is not SHT_TYPE\n"),
4158 	       cnt, section_name (ebl, cnt));
4159 
4160       switch (shdr->sh_type)
4161 	{
4162 	case SHT_DYNSYM:
4163 	  if (ehdr->e_type == ET_REL)
4164 	    ERROR (_("\
4165 section [%2zu] '%s': relocatable files cannot have dynamic symbol tables\n"),
4166 		   cnt, section_name (ebl, cnt));
4167 	  FALLTHROUGH;
4168 	case SHT_SYMTAB:
4169 	  check_symtab (ebl, ehdr, shdr, cnt);
4170 	  break;
4171 
4172 	case SHT_RELA:
4173 	  check_rela (ebl, ehdr, shdr, cnt);
4174 	  break;
4175 
4176 	case SHT_REL:
4177 	  check_rel (ebl, ehdr, shdr, cnt);
4178 	  break;
4179 
4180 	case SHT_DYNAMIC:
4181 	  check_dynamic (ebl, ehdr, shdr, cnt);
4182 	  break;
4183 
4184 	case SHT_SYMTAB_SHNDX:
4185 	  check_symtab_shndx (ebl, ehdr, shdr, cnt);
4186 	  break;
4187 
4188 	case SHT_HASH:
4189 	  check_hash (shdr->sh_type, ebl, ehdr, shdr, cnt);
4190 	  hash_idx = cnt;
4191 	  break;
4192 
4193 	case SHT_GNU_HASH:
4194 	  check_hash (shdr->sh_type, ebl, ehdr, shdr, cnt);
4195 	  gnu_hash_idx = cnt;
4196 	  break;
4197 
4198 	case SHT_NULL:
4199 	  check_null (ebl, shdr, cnt);
4200 	  break;
4201 
4202 	case SHT_GROUP:
4203 	  check_group (ebl, ehdr, shdr, cnt);
4204 	  break;
4205 
4206 	case SHT_NOTE:
4207 	  check_note_section (ebl, ehdr, shdr, cnt);
4208 	  break;
4209 
4210 	case SHT_GNU_versym:
4211 	  /* We cannot process this section now since we have no guarantee
4212 	     that the verneed and verdef sections have already been read.
4213 	     Just remember the section index.  */
4214 	  if (versym_scnndx != 0)
4215 	    ERROR (_("more than one version symbol table present\n"));
4216 	  versym_scnndx = cnt;
4217 	  break;
4218 
4219 	case SHT_GNU_verneed:
4220 	  check_verneed (ebl, shdr, cnt);
4221 	  break;
4222 
4223 	case SHT_GNU_verdef:
4224 	  check_verdef (ebl, shdr, cnt);
4225 	  break;
4226 
4227 	case SHT_GNU_ATTRIBUTES:
4228 	  check_attributes (ebl, ehdr, shdr, cnt);
4229 	  break;
4230 
4231 	default:
4232 	  /* Nothing.  */
4233 	  break;
4234 	}
4235     }
4236 
4237   if (has_interp_segment && !dot_interp_section)
4238     ERROR (_("INTERP program header entry but no .interp section\n"));
4239 
4240   if (!is_debuginfo)
4241     for (unsigned int pcnt = 0; pcnt < phnum; ++pcnt)
4242       {
4243 	GElf_Phdr phdr_mem;
4244 	GElf_Phdr *phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
4245 	if (phdr != NULL && (phdr->p_type == PT_LOAD || phdr->p_type == PT_TLS))
4246 	  {
4247 	    if ((phdr->p_flags & PF_X) != 0
4248 		&& (segment_flags[pcnt] & PF_X) == 0)
4249 	      ERROR (_("\
4250 loadable segment [%u] is executable but contains no executable sections\n"),
4251 		     pcnt);
4252 
4253 	    if ((phdr->p_flags & PF_W) != 0
4254 		&& (segment_flags[pcnt] & PF_W) == 0)
4255 	      ERROR (_("\
4256 loadable segment [%u] is writable but contains no writable sections\n"),
4257 		     pcnt);
4258 	  }
4259       }
4260 
4261   free (segment_flags);
4262 
4263   if (version_namelist != NULL)
4264     {
4265       if (versym_scnndx == 0)
4266     ERROR (_("\
4267 no .gnu.versym section present but .gnu.versym_d or .gnu.versym_r section exist\n"));
4268       else
4269 	check_versym (ebl, versym_scnndx);
4270 
4271       /* Check for duplicate index numbers.  */
4272       do
4273 	{
4274 	  struct version_namelist *runp = version_namelist->next;
4275 	  while (runp != NULL)
4276 	    {
4277 	      if (version_namelist->ndx == runp->ndx)
4278 		{
4279 		  ERROR (_("duplicate version index %d\n"),
4280 			 (int) version_namelist->ndx);
4281 		  break;
4282 		}
4283 	      runp = runp->next;
4284 	    }
4285 
4286 	  struct version_namelist *old = version_namelist;
4287 	  version_namelist = version_namelist->next;
4288 	  free (old);
4289 	}
4290       while (version_namelist != NULL);
4291     }
4292   else if (versym_scnndx != 0)
4293     ERROR (_("\
4294 .gnu.versym section present without .gnu.versym_d or .gnu.versym_r\n"));
4295 
4296   if (hash_idx != 0 && gnu_hash_idx != 0)
4297     compare_hash_gnu_hash (ebl, ehdr, hash_idx, gnu_hash_idx);
4298 
4299   free (scnref);
4300 }
4301 
4302 
4303 static GElf_Off
check_note_data(Ebl * ebl,const GElf_Ehdr * ehdr,Elf_Data * data,int shndx,int phndx,GElf_Off start)4304 check_note_data (Ebl *ebl, const GElf_Ehdr *ehdr,
4305 		 Elf_Data *data, int shndx, int phndx, GElf_Off start)
4306 {
4307   size_t offset = 0;
4308   size_t last_offset = 0;
4309   GElf_Nhdr nhdr;
4310   size_t name_offset;
4311   size_t desc_offset;
4312   while (offset < data->d_size
4313 	 && (offset = gelf_getnote (data, offset,
4314 				    &nhdr, &name_offset, &desc_offset)) > 0)
4315     {
4316       last_offset = offset;
4317 
4318       /* Make sure it is one of the note types we know about.  */
4319       if (ehdr->e_type == ET_CORE)
4320 	switch (nhdr.n_type)
4321 	  {
4322 	  case NT_PRSTATUS:
4323 	  case NT_FPREGSET:
4324 	  case NT_PRPSINFO:
4325 	  case NT_TASKSTRUCT:		/* NT_PRXREG on Solaris.  */
4326 	  case NT_PLATFORM:
4327 	  case NT_AUXV:
4328 	  case NT_GWINDOWS:
4329 	  case NT_ASRS:
4330 	  case NT_PSTATUS:
4331 	  case NT_PSINFO:
4332 	  case NT_PRCRED:
4333 	  case NT_UTSNAME:
4334 	  case NT_LWPSTATUS:
4335 	  case NT_LWPSINFO:
4336 	  case NT_PRFPXREG:
4337 	    /* Known type.  */
4338 	    break;
4339 
4340 	  default:
4341 	    if (shndx == 0)
4342 	      ERROR (_("\
4343 phdr[%d]: unknown core file note type %" PRIu32 " at offset %" PRIu64 "\n"),
4344 		     phndx, (uint32_t) nhdr.n_type, start + offset);
4345 	    else
4346 	      ERROR (_("\
4347 section [%2d] '%s': unknown core file note type %" PRIu32
4348 			      " at offset %zu\n"),
4349 		     shndx, section_name (ebl, shndx),
4350 		     (uint32_t) nhdr.n_type, offset);
4351 	  }
4352       else
4353 	switch (nhdr.n_type)
4354 	  {
4355 	  case NT_GNU_ABI_TAG:
4356 	  case NT_GNU_HWCAP:
4357 	  case NT_GNU_BUILD_ID:
4358 	  case NT_GNU_GOLD_VERSION:
4359 	  case NT_GNU_PROPERTY_TYPE_0:
4360 	    if (nhdr.n_namesz == sizeof ELF_NOTE_GNU
4361 		&& strcmp (data->d_buf + name_offset, ELF_NOTE_GNU) == 0)
4362 	      break;
4363 	    else
4364 	      {
4365 		/* NT_VERSION is 1, same as NT_GNU_ABI_TAG.  It has no
4366 		   descriptor and (ab)uses the name as version string.  */
4367 		if (nhdr.n_descsz == 0 && nhdr.n_type == NT_VERSION)
4368 		  break;
4369 	      }
4370 	      goto unknown_note;
4371 
4372 	  case NT_GNU_BUILD_ATTRIBUTE_OPEN:
4373 	  case NT_GNU_BUILD_ATTRIBUTE_FUNC:
4374 	    /* GNU Build Attributes store most data in the owner
4375 	       name, which must start with the
4376 	       ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX "GA".  */
4377 	    if (nhdr.n_namesz >= sizeof ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX
4378 		&& strncmp (data->d_buf + name_offset,
4379 			    ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX,
4380 			    strlen (ELF_NOTE_GNU_BUILD_ATTRIBUTE_PREFIX)) == 0)
4381 	      break;
4382 	    else
4383 	      goto unknown_note;
4384 
4385 	  case 0:
4386 	    /* Linux vDSOs use a type 0 note for the kernel version word.  */
4387 	    if (nhdr.n_namesz == sizeof "Linux"
4388 		&& !memcmp (data->d_buf + name_offset, "Linux", sizeof "Linux"))
4389 	      break;
4390 	    FALLTHROUGH;
4391 	  default:
4392 	    {
4393 	    unknown_note:
4394 	    if (shndx == 0)
4395 	      ERROR (_("\
4396 phdr[%d]: unknown object file note type %" PRIu32 " with owner name '%s' at offset %zu\n"),
4397 		     phndx, (uint32_t) nhdr.n_type,
4398 		     (char *) data->d_buf + name_offset, offset);
4399 	    else
4400 	      ERROR (_("\
4401 section [%2d] '%s': unknown object file note type %" PRIu32
4402 			      " with owner name '%s' at offset %zu\n"),
4403 		     shndx, section_name (ebl, shndx),
4404 		     (uint32_t) nhdr.n_type,
4405 		     (char *) data->d_buf + name_offset, offset);
4406 	    }
4407 	  }
4408     }
4409 
4410   return last_offset;
4411 }
4412 
4413 
4414 static void
check_note(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Phdr * phdr,int cnt)4415 check_note (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Phdr *phdr, int cnt)
4416 {
4417   if (ehdr->e_type != ET_CORE && ehdr->e_type != ET_REL
4418       && ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
4419     ERROR (_("\
4420 phdr[%d]: no note entries defined for the type of file\n"),
4421 	   cnt);
4422 
4423   if (is_debuginfo)
4424     /* The p_offset values in a separate debug file are bogus.  */
4425     return;
4426 
4427   if (phdr->p_filesz == 0)
4428     return;
4429 
4430   GElf_Off notes_size = 0;
4431   Elf_Data *data = elf_getdata_rawchunk (ebl->elf,
4432 					 phdr->p_offset, phdr->p_filesz,
4433 					 (phdr->p_align == 8
4434 					  ? ELF_T_NHDR8 : ELF_T_NHDR));
4435   if (data != NULL && data->d_buf != NULL)
4436     notes_size = check_note_data (ebl, ehdr, data, 0, cnt, phdr->p_offset);
4437 
4438   if (notes_size == 0)
4439     ERROR (_("phdr[%d]: cannot get content of note section: %s\n"),
4440 	   cnt, elf_errmsg (-1));
4441   else if (notes_size != phdr->p_filesz)
4442     ERROR (_("phdr[%d]: extra %" PRIu64 " bytes after last note\n"),
4443 	   cnt, phdr->p_filesz - notes_size);
4444 }
4445 
4446 
4447 static void
check_note_section(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)4448 check_note_section (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
4449 {
4450   if (shdr->sh_size == 0)
4451     return;
4452 
4453   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
4454   if (data == NULL || data->d_buf == NULL)
4455     {
4456       ERROR (_("section [%2d] '%s': cannot get section data\n"),
4457 	     idx, section_name (ebl, idx));
4458       return;
4459     }
4460 
4461   if (ehdr->e_type != ET_CORE && ehdr->e_type != ET_REL
4462       && ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
4463     ERROR (_("\
4464 section [%2d] '%s': no note entries defined for the type of file\n"),
4465 	     idx, section_name (ebl, idx));
4466 
4467   GElf_Off notes_size = check_note_data (ebl, ehdr, data, idx, 0, 0);
4468 
4469   if (notes_size == 0)
4470     ERROR (_("section [%2d] '%s': cannot get content of note section\n"),
4471 	   idx, section_name (ebl, idx));
4472   else if (notes_size != shdr->sh_size)
4473     ERROR (_("section [%2d] '%s': extra %" PRIu64
4474 		    " bytes after last note\n"),
4475 	   idx, section_name (ebl, idx), shdr->sh_size - notes_size);
4476 }
4477 
4478 
4479 /* Index of the PT_GNU_EH_FRAME program eader entry.  */
4480 static int pt_gnu_eh_frame_pndx;
4481 
4482 
4483 static void
check_program_header(Ebl * ebl,GElf_Ehdr * ehdr)4484 check_program_header (Ebl *ebl, GElf_Ehdr *ehdr)
4485 {
4486   if (ehdr->e_phoff == 0)
4487     return;
4488 
4489   if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN
4490       && ehdr->e_type != ET_CORE)
4491     ERROR (_("\
4492 only executables, shared objects, and core files can have program headers\n"));
4493 
4494   int num_pt_interp = 0;
4495   int num_pt_tls = 0;
4496   int num_pt_relro = 0;
4497 
4498   for (unsigned int cnt = 0; cnt < phnum; ++cnt)
4499     {
4500       GElf_Phdr phdr_mem;
4501       GElf_Phdr *phdr;
4502 
4503       phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
4504       if (phdr == NULL)
4505 	{
4506 	  ERROR (_("cannot get program header entry %d: %s\n"),
4507 		 cnt, elf_errmsg (-1));
4508 	  continue;
4509 	}
4510 
4511       if (phdr->p_type >= PT_NUM && phdr->p_type != PT_GNU_EH_FRAME
4512 	  && phdr->p_type != PT_GNU_STACK && phdr->p_type != PT_GNU_RELRO
4513 	  && phdr->p_type != PT_GNU_PROPERTY
4514 	  /* Check for a known machine-specific type.  */
4515 	  && ebl_segment_type_name (ebl, phdr->p_type, NULL, 0) == NULL)
4516 	ERROR (_("\
4517 program header entry %d: unknown program header entry type %#" PRIx64 "\n"),
4518 	       cnt, (uint64_t) phdr->p_type);
4519 
4520       if (phdr->p_type == PT_LOAD)
4521 	has_loadable_segment = true;
4522       else if (phdr->p_type == PT_INTERP)
4523 	{
4524 	  if (++num_pt_interp != 1)
4525 	    {
4526 	      if (num_pt_interp == 2)
4527 		ERROR (_("\
4528 more than one INTERP entry in program header\n"));
4529 	    }
4530 	  has_interp_segment = true;
4531 	}
4532       else if (phdr->p_type == PT_TLS)
4533 	{
4534 	  if (++num_pt_tls == 2)
4535 	    ERROR (_("more than one TLS entry in program header\n"));
4536 	}
4537       else if (phdr->p_type == PT_NOTE)
4538 	check_note (ebl, ehdr, phdr, cnt);
4539       else if (phdr->p_type == PT_DYNAMIC)
4540 	{
4541 	  if (ehdr->e_type == ET_EXEC && ! has_interp_segment)
4542 	    ERROR (_("\
4543 static executable cannot have dynamic sections\n"));
4544 	  else
4545 	    {
4546 	      /* Check that the .dynamic section, if it exists, has
4547 		 the same address.  */
4548 	      Elf_Scn *scn = NULL;
4549 	      while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
4550 		{
4551 		  GElf_Shdr shdr_mem;
4552 		  GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
4553 		  if (shdr != NULL && shdr->sh_type == SHT_DYNAMIC)
4554 		    {
4555 		      if (phdr->p_offset != shdr->sh_offset)
4556 			ERROR (_("\
4557 dynamic section reference in program header has wrong offset\n"));
4558 		      if (phdr->p_memsz != shdr->sh_size)
4559 			ERROR (_("\
4560 dynamic section size mismatch in program and section header\n"));
4561 		      break;
4562 		    }
4563 		}
4564 	    }
4565 	}
4566       else if (phdr->p_type == PT_GNU_RELRO)
4567 	{
4568 	  if (++num_pt_relro == 2)
4569 	    ERROR (_("\
4570 more than one GNU_RELRO entry in program header\n"));
4571 	  else
4572 	    {
4573 	      /* Check that the region is in a writable segment.  */
4574 	      unsigned int inner;
4575 	      for (inner = 0; inner < phnum; ++inner)
4576 		{
4577 		  GElf_Phdr phdr2_mem;
4578 		  GElf_Phdr *phdr2;
4579 
4580 		  phdr2 = gelf_getphdr (ebl->elf, inner, &phdr2_mem);
4581 		  if (phdr2 == NULL)
4582 		    continue;
4583 
4584 		  if (phdr2->p_type == PT_LOAD
4585 		      && phdr->p_vaddr >= phdr2->p_vaddr
4586 		      && (phdr->p_vaddr + phdr->p_memsz
4587 			  <= phdr2->p_vaddr + phdr2->p_memsz))
4588 		    {
4589 		      if ((phdr2->p_flags & PF_W) == 0)
4590 			ERROR (_("\
4591 loadable segment GNU_RELRO applies to is not writable\n"));
4592 		      /* Unless fully covered, relro flags could be a
4593 			 subset of the phdrs2 flags.  For example the load
4594 			 segment could also have PF_X set.  */
4595 		      if (phdr->p_vaddr == phdr2->p_vaddr
4596 			  && (phdr->p_vaddr + phdr->p_memsz
4597 			      == phdr2->p_vaddr + phdr2->p_memsz))
4598 			{
4599 			  if ((phdr2->p_flags & ~PF_W)
4600 			      != (phdr->p_flags & ~PF_W))
4601 			    ERROR (_("\
4602 loadable segment [%u] flags do not match GNU_RELRO [%u] flags\n"),
4603 				   cnt, inner);
4604 			}
4605 		      else
4606 			{
4607 			  if ((phdr->p_flags & ~phdr2->p_flags) != 0)
4608 			    ERROR (_("\
4609 GNU_RELRO [%u] flags are not a subset of the loadable segment [%u] flags\n"),
4610 				   inner, cnt);
4611 			}
4612 		      break;
4613 		    }
4614 		}
4615 
4616 	      if (inner >= phnum)
4617 		ERROR (_("\
4618 %s segment not contained in a loaded segment\n"), "GNU_RELRO");
4619 	    }
4620 	}
4621       else if (phdr->p_type == PT_PHDR)
4622 	{
4623 	  /* Check that the region is in a writable segment.  */
4624 	  unsigned int inner;
4625 	  for (inner = 0; inner < phnum; ++inner)
4626 	    {
4627 	      GElf_Phdr phdr2_mem;
4628 	      GElf_Phdr *phdr2;
4629 
4630 	      phdr2 = gelf_getphdr (ebl->elf, inner, &phdr2_mem);
4631 	      if (phdr2 != NULL
4632 		  && phdr2->p_type == PT_LOAD
4633 		  && phdr->p_vaddr >= phdr2->p_vaddr
4634 		  && (phdr->p_vaddr + phdr->p_memsz
4635 		      <= phdr2->p_vaddr + phdr2->p_memsz))
4636 		break;
4637 	    }
4638 
4639 	  if (inner >= phnum)
4640 	    ERROR (_("\
4641 %s segment not contained in a loaded segment\n"), "PHDR");
4642 
4643 	  /* Check that offset in segment corresponds to offset in ELF
4644 	     header.  */
4645 	  if (phdr->p_offset != ehdr->e_phoff)
4646 	    ERROR (_("\
4647 program header offset in ELF header and PHDR entry do not match"));
4648 	}
4649       else if (phdr->p_type == PT_GNU_EH_FRAME)
4650 	{
4651 	  /* If there is an .eh_frame_hdr section it must be
4652 	     referenced by this program header entry.  */
4653 	  Elf_Scn *scn = NULL;
4654 	  GElf_Shdr shdr_mem;
4655 	  GElf_Shdr *shdr = NULL;
4656 	  bool any = false;
4657 	  while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
4658 	    {
4659 	      any = true;
4660 	      shdr = gelf_getshdr (scn, &shdr_mem);
4661 	      if (shdr != NULL
4662 		  && ((is_debuginfo && shdr->sh_type == SHT_NOBITS)
4663 		      || (! is_debuginfo
4664 			  && (shdr->sh_type == SHT_PROGBITS
4665 			      || shdr->sh_type == SHT_X86_64_UNWIND)))
4666 		  && elf_strptr (ebl->elf, shstrndx, shdr->sh_name) != NULL
4667 		  && ! strcmp (".eh_frame_hdr",
4668 			       elf_strptr (ebl->elf, shstrndx, shdr->sh_name)))
4669 		{
4670 		  if (! is_debuginfo)
4671 		    {
4672 		      if (phdr->p_offset != shdr->sh_offset)
4673 			ERROR (_("\
4674 call frame search table reference in program header has wrong offset\n"));
4675 		      if (phdr->p_memsz != shdr->sh_size)
4676 			ERROR (_("\
4677 call frame search table size mismatch in program and section header\n"));
4678 		    }
4679 		  break;
4680 		}
4681 	    }
4682 
4683 	  if (scn == NULL)
4684 	    {
4685 	      /* If there is no section header table we don't
4686 		 complain.  But if there is one there should be an
4687 		 entry for .eh_frame_hdr.  */
4688 	      if (any)
4689 		ERROR (_("\
4690 PT_GNU_EH_FRAME present but no .eh_frame_hdr section\n"));
4691 	    }
4692 	  else
4693 	    {
4694 	      /* The section must be allocated and not be writable and
4695 		 executable.  */
4696 	      if ((phdr->p_flags & PF_R) == 0)
4697 		ERROR (_("\
4698 call frame search table must be allocated\n"));
4699 	      else if (shdr != NULL && (shdr->sh_flags & SHF_ALLOC) == 0)
4700 		ERROR (_("\
4701 section [%2zu] '%s' must be allocated\n"), elf_ndxscn (scn), ".eh_frame_hdr");
4702 
4703 	      if ((phdr->p_flags & PF_W) != 0)
4704 		ERROR (_("\
4705 call frame search table must not be writable\n"));
4706 	      else if (shdr != NULL && (shdr->sh_flags & SHF_WRITE) != 0)
4707 		ERROR (_("\
4708 section [%2zu] '%s' must not be writable\n"),
4709 		       elf_ndxscn (scn), ".eh_frame_hdr");
4710 
4711 	      if ((phdr->p_flags & PF_X) != 0)
4712 		ERROR (_("\
4713 call frame search table must not be executable\n"));
4714 	      else if (shdr != NULL && (shdr->sh_flags & SHF_EXECINSTR) != 0)
4715 		ERROR (_("\
4716 section [%2zu] '%s' must not be executable\n"),
4717 		       elf_ndxscn (scn), ".eh_frame_hdr");
4718 	    }
4719 
4720 	  /* Remember which entry this is.  */
4721 	  pt_gnu_eh_frame_pndx = cnt;
4722 	}
4723 
4724       if (phdr->p_filesz > phdr->p_memsz
4725 	  && (phdr->p_memsz != 0 || phdr->p_type != PT_NOTE))
4726 	ERROR (_("\
4727 program header entry %d: file size greater than memory size\n"),
4728 	       cnt);
4729 
4730       if (phdr->p_align > 1)
4731 	{
4732 	  if (!powerof2 (phdr->p_align))
4733 	    ERROR (_("\
4734 program header entry %d: alignment not a power of 2\n"), cnt);
4735 	  else if ((phdr->p_vaddr - phdr->p_offset) % phdr->p_align != 0)
4736 	    ERROR (_("\
4737 program header entry %d: file offset and virtual address not module of alignment\n"), cnt);
4738 	}
4739     }
4740 }
4741 
4742 
4743 static void
check_exception_data(Ebl * ebl,GElf_Ehdr * ehdr)4744 check_exception_data (Ebl *ebl __attribute__ ((unused)),
4745 		      GElf_Ehdr *ehdr __attribute__ ((unused)))
4746 {
4747   if ((ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN)
4748       && pt_gnu_eh_frame_pndx == 0 && eh_frame_hdr_scnndx != 0)
4749     ERROR (_("executable/DSO with .eh_frame_hdr section does not have "
4750 		    "a PT_GNU_EH_FRAME program header entry"));
4751 }
4752 
4753 
4754 /* Process one file.  */
4755 static void
process_elf_file(Elf * elf,const char * prefix,const char * suffix,const char * fname,size_t size,bool only_one)4756 process_elf_file (Elf *elf, const char *prefix, const char *suffix,
4757 		  const char *fname, size_t size, bool only_one)
4758 {
4759   /* Reset variables.  */
4760   ndynamic = 0;
4761   nverneed = 0;
4762   nverdef = 0;
4763   textrel = false;
4764   needed_textrel = false;
4765   has_loadable_segment = false;
4766   has_interp_segment = false;
4767 
4768   GElf_Ehdr ehdr_mem;
4769   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
4770   Ebl *ebl;
4771 
4772   /* Print the file name.  */
4773   if (!only_one)
4774     {
4775       if (prefix != NULL)
4776 	printf ("\n%s(%s)%s:\n", prefix, fname, suffix);
4777       else
4778 	printf ("\n%s:\n", fname);
4779     }
4780 
4781   if (ehdr == NULL)
4782     {
4783       ERROR (_("cannot read ELF header: %s\n"), elf_errmsg (-1));
4784       return;
4785     }
4786 
4787   ebl = ebl_openbackend (elf);
4788   /* If there is no appropriate backend library we cannot test
4789      architecture and OS specific features.  Any encountered extension
4790      is an error.  Often we'll get a "dummy" ebl, except if something
4791      really bad happen, like a totally corrupted ELF file or out of
4792      memory situation.  */
4793   if (ebl == NULL)
4794     {
4795       ERROR (_("cannot create backend for ELF file\n"));
4796       return;
4797     }
4798 
4799   /* Go straight by the gABI, check all the parts in turn.  */
4800   check_elf_header (ebl, ehdr, size);
4801 
4802   /* Check the program header.  */
4803   check_program_header (ebl, ehdr);
4804 
4805   /* Next the section headers.  It is OK if there are no section
4806      headers at all.  */
4807   check_sections (ebl, ehdr);
4808 
4809   /* Check the exception handling data, if it exists.  */
4810   if (pt_gnu_eh_frame_pndx != 0 || eh_frame_hdr_scnndx != 0
4811       || eh_frame_scnndx != 0 || gcc_except_table_scnndx != 0)
4812     check_exception_data (ebl, ehdr);
4813 
4814   /* Report if no relocation section needed the text relocation flag.  */
4815   if (textrel && !needed_textrel)
4816     ERROR (_("text relocation flag set but not needed\n"));
4817 
4818   /* Free the resources.  */
4819   ebl_closebackend (ebl);
4820 }
4821 
4822 
4823 #include "debugpred.h"
4824