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