• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Pedantic checking of ELF files compliance with gABI/psABI spec.
2    Copyright (C) 2001, 2002, 2003, 2004 Red Hat, Inc.
3    Written by Ulrich Drepper <drepper@redhat.com>, 2001.
4 
5    This program is Open Source software; you can redistribute it and/or
6    modify it under the terms of the Open Software License version 1.0 as
7    published by the Open Source Initiative.
8 
9    You should have received a copy of the Open Software License along
10    with this program; if not, you may obtain a copy of the Open Software
11    License version 1.0 from http://www.opensource.org/licenses/osl.php or
12    by writing the Open Source Initiative c/o Lawrence Rosen, Esq.,
13    3001 King Ranch Road, Ukiah, CA 95482.   */
14 
15 #ifdef HAVE_CONFIG_H
16 # include <config.h>
17 #endif
18 
19 #include <argp.h>
20 #include <assert.h>
21 #include <byteswap.h>
22 #include <endian.h>
23 #include <error.h>
24 #include <fcntl.h>
25 #include <gelf.h>
26 #include <inttypes.h>
27 #include <libebl.h>
28 #include <libintl.h>
29 #include <locale.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <sys/param.h>
35 
36 #include <elf-knowledge.h>
37 #include <system.h>
38 
39 
40 /* Name and version of program.  */
41 static void print_version (FILE *stream, struct argp_state *state);
42 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
43 
44 
45 #define ARGP_strict	300
46 #define ARGP_gnuld	301
47 
48 /* Definitions of arguments for argp functions.  */
49 static const struct argp_option options[] =
50 {
51 
52   { "strict", ARGP_strict, NULL, 0,
53     N_("Be extremely strict, flag level 2 features.") },
54   { "quiet", 'q', NULL, 0, N_("Do not print anything if successful") },
55   { "gnu-ld", ARGP_gnuld, NULL, 0,
56     N_("Binary has been created with GNU ld and is therefore known to be \
57 broken in certain ways") },
58   { NULL, 0, NULL, 0, NULL }
59 };
60 
61 /* Short description of program.  */
62 static const char doc[] = N_("\
63 Pedantic checking of ELF files compliance with gABI/psABI spec.");
64 
65 /* Strings for arguments in help texts.  */
66 static const char args_doc[] = N_("FILE...");
67 
68 /* Prototype for option handler.  */
69 static error_t parse_opt (int key, char *arg, struct argp_state *state);
70 
71 /* Function to print some extra text in the help message.  */
72 static char *more_help (int key, const char *text, void *input);
73 
74 /* Data structure to communicate with argp functions.  */
75 static struct argp argp =
76 {
77   options, parse_opt, args_doc, doc, NULL, more_help
78 };
79 
80 
81 /* Declarations of local functions.  */
82 static void process_file (int fd, Elf *elf, const char *prefix,
83 			  const char *suffix, const char *fname, size_t size,
84 			  bool only_one);
85 static void process_elf_file (Elf *elf, const char *prefix, const char *suffix,
86 			      const char *fname, size_t size, bool only_one);
87 
88 /* Report an error.  */
89 #define ERROR(str, args...) \
90   do {									      \
91     printf (str, ##args);						      \
92     ++error_count;							      \
93   } while (0)
94 static int error_count;
95 
96 /* True if we should perform very strict testing.  */
97 static bool be_strict;
98 
99 /* True if no message is to be printed if the run is succesful.  */
100 static bool be_quiet;
101 
102 /* True if binary is assumed to be generated with GNU ld.  */
103 static bool gnuld;
104 
105 /* Index of section header string table.  */
106 static uint32_t shstrndx;
107 
108 /* Array to count references in section groups.  */
109 static int *scnref;
110 
111 
112 int
main(int argc,char * argv[])113 main (int argc, char *argv[])
114 {
115   int remaining;
116   bool only_one;
117 
118   /* Set locale.  */
119   setlocale (LC_ALL, "");
120 
121   /* Initialize the message catalog.  */
122   textdomain (PACKAGE);
123 
124   /* Parse and process arguments.  */
125   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
126 
127   /* If no ELF file is given punt.  */
128   if (remaining >= argc)
129     {
130       argp_help (&argp, stdout, ARGP_HELP_SEE | ARGP_HELP_EXIT_ERR,
131 		 program_invocation_short_name);
132       exit (1);
133     }
134 
135   /* Before we start tell the ELF library which version we are using.  */
136   elf_version (EV_CURRENT);
137 
138   /* Now process all the files given at the command line.  */
139   only_one = remaining + 1 == argc;
140   do
141     {
142       int fd;
143       Elf *elf;
144 
145       /* Open the file.  */
146       fd = open (argv[remaining], O_RDONLY);
147       if (fd == -1)
148 	{
149 	  error (0, errno, gettext ("cannot open input file"));
150 	  continue;
151 	}
152 
153       /* Create an `Elf' descriptor.  */
154       elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
155       if (elf == NULL)
156 	ERROR (gettext ("cannot generate Elf descriptor: %s\n"),
157 	       elf_errmsg (-1));
158       else
159 	{
160 	  unsigned int prev_error_count = error_count;
161 	  struct stat64 st;
162 
163 	  if (fstat64 (fd, &st) != 0)
164 	    {
165 	      printf ("cannot stat '%s': %m\n", argv[remaining]);
166 	      close (fd);
167 	      continue;
168 	    }
169 
170 	  process_file (fd, elf, NULL, NULL, argv[remaining], st.st_size,
171 			only_one);
172 
173 	  /* Now we can close the descriptor.  */
174 	  if (elf_end (elf) != 0)
175 	    ERROR (gettext ("error while closing Elf descriptor: %s\n"),
176 		   elf_errmsg (-1));
177 
178 	  if (prev_error_count == error_count && !be_quiet)
179 	    puts (gettext ("No errors"));
180 	}
181 
182       close (fd);
183     }
184   while (++remaining < argc);
185 
186   return error_count != 0;
187 }
188 
189 
190 /* Handle program arguments.  */
191 static error_t
parse_opt(int key,char * arg,struct argp_state * state)192 parse_opt (int key, char *arg, struct argp_state *state)
193 {
194   switch (key)
195     {
196     case ARGP_strict:
197       be_strict = true;
198       break;
199 
200     case 'q':
201       be_quiet = true;
202       break;
203 
204     case ARGP_gnuld:
205       gnuld = true;
206       break;
207 
208     default:
209       return ARGP_ERR_UNKNOWN;
210     }
211   return 0;
212 }
213 
214 
215 static char *
more_help(int key,const char * text,void * input)216 more_help (int key, const char *text, void *input)
217 {
218   char *buf;
219 
220   switch (key)
221     {
222     case ARGP_KEY_HELP_EXTRA:
223       /* We print some extra information.  */
224       if (asprintf (&buf, gettext ("Please report bugs to %s.\n"),
225 		    PACKAGE_BUGREPORT) < 0)
226 	buf = NULL;
227       return buf;
228 
229     default:
230       break;
231     }
232   return (char *) text;
233 }
234 
235 
236 /* Print the version information.  */
237 static void
print_version(FILE * stream,struct argp_state * state)238 print_version (FILE *stream, struct argp_state *state)
239 {
240   fprintf (stream, "elflint (%s) %s\n", PACKAGE_NAME, VERSION);
241   fprintf (stream, gettext ("\
242 Copyright (C) %s Red Hat, Inc.\n\
243 This is free software; see the source for copying conditions.  There is NO\n\
244 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
245 "), "2004");
246   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
247 }
248 
249 
250 /* Process one file.  */
251 static void
process_file(int fd,Elf * elf,const char * prefix,const char * suffix,const char * fname,size_t size,bool only_one)252 process_file (int fd, Elf *elf, const char *prefix, const char *suffix,
253 	      const char *fname, size_t size, bool only_one)
254 {
255   /* We can handle two types of files: ELF files and archives.  */
256   Elf_Kind kind = elf_kind (elf);
257 
258   switch (kind)
259     {
260     case ELF_K_ELF:
261       /* Yes!  It's an ELF file.  */
262       process_elf_file (elf, prefix, suffix, fname, size, only_one);
263       break;
264 
265     case ELF_K_AR:
266       {
267 	Elf *subelf;
268 	Elf_Cmd cmd = ELF_C_READ_MMAP;
269 	size_t prefix_len = prefix == NULL ? 0 : strlen (prefix);
270 	size_t fname_len = strlen (fname) + 1;
271 	char new_prefix[prefix_len + 1 + fname_len];
272 	char new_suffix[(suffix == NULL ? 0 : strlen (suffix)) + 2];
273 	char *cp = new_prefix;
274 
275 	/* Create the full name of the file.  */
276 	if (prefix != NULL)
277 	  {
278 	    cp = mempcpy (cp, prefix, prefix_len);
279 	    *cp++ = '(';
280 	    strcpy (stpcpy (new_suffix, suffix), ")");
281 	  }
282 	else
283 	  new_suffix[0] = '\0';
284 	memcpy (cp, fname, fname_len);
285 
286 	/* It's an archive.  We process each file in it.  */
287 	while ((subelf = elf_begin (fd, cmd, elf)) != NULL)
288 	  {
289 	    kind = elf_kind (subelf);
290 
291 	    /* Call this function recursively.  */
292 	    if (kind == ELF_K_ELF || kind == ELF_K_AR)
293 	      {
294 		Elf_Arhdr *arhdr = elf_getarhdr (subelf);
295 		assert (arhdr != NULL);
296 
297 		process_file (fd, subelf, new_prefix, new_suffix,
298 			      arhdr->ar_name, arhdr->ar_size, false);
299 	      }
300 
301 	    /* Get next archive element.  */
302 	    cmd = elf_next (subelf);
303 	    if (elf_end (subelf) != 0)
304 	      ERROR (gettext (" error while freeing sub-ELF descriptor: %s\n"),
305 		     elf_errmsg (-1));
306 	  }
307       }
308       break;
309 
310     default:
311       /* We cannot do anything.  */
312       ERROR (gettext ("\
313 Not an ELF file - it has the wrong magic bytes at the start"));
314       break;
315     }
316 }
317 
318 
319 static const char *
section_name(Ebl * ebl,GElf_Ehdr * ehdr,int idx)320 section_name (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
321 {
322   GElf_Shdr shdr_mem;
323   GElf_Shdr *shdr;
324 
325   shdr = gelf_getshdr (elf_getscn (ebl->elf, idx), &shdr_mem);
326 
327   return elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
328 }
329 
330 
331 static const int valid_e_machine[] =
332   {
333     EM_M32, EM_SPARC, EM_386, EM_68K, EM_88K, EM_860, EM_MIPS, EM_S370,
334     EM_MIPS_RS3_LE, EM_PARISC, EM_VPP500, EM_SPARC32PLUS, EM_960, EM_PPC,
335     EM_PPC64, EM_S390, EM_V800, EM_FR20, EM_RH32, EM_RCE, EM_ARM,
336     EM_FAKE_ALPHA, EM_SH, EM_SPARCV9, EM_TRICORE, EM_ARC, EM_H8_300,
337     EM_H8_300H, EM_H8S, EM_H8_500, EM_IA_64, EM_MIPS_X, EM_COLDFIRE,
338     EM_68HC12, EM_MMA, EM_PCP, EM_NCPU, EM_NDR1, EM_STARCORE, EM_ME16,
339     EM_ST100, EM_TINYJ, EM_X86_64, EM_PDSP, EM_FX66, EM_ST9PLUS, EM_ST7,
340     EM_68HC16, EM_68HC11, EM_68HC08, EM_68HC05, EM_SVX, EM_ST19, EM_VAX,
341     EM_CRIS, EM_JAVELIN, EM_FIREPATH, EM_ZSP, EM_MMIX, EM_HUANY, EM_PRISM,
342     EM_AVR, EM_FR30, EM_D10V, EM_D30V, EM_V850, EM_M32R, EM_MN10300,
343     EM_MN10200, EM_PJ, EM_OPENRISC, EM_ARC_A5, EM_XTENSA
344   };
345 #define nvalid_e_machine \
346   (sizeof (valid_e_machine) / sizeof (valid_e_machine[0]))
347 
348 
349 /* Number of sections.  */
350 static unsigned int shnum;
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.  */
384   if (ehdr->e_ident[EI_OSABI] != ELFOSABI_NONE)
385     ERROR (gettext ("unsupported OS ABI e_ident[%d] == \"%s\"\n"),
386 	   EI_OSABI,
387 	   ebl_osabi_name (ebl, ehdr->e_ident[EI_OSABI], buf, sizeof (buf)));
388 
389   /* No ABI versions other than zero supported either.  */
390   if (ehdr->e_ident[EI_ABIVERSION] != 0)
391     ERROR (gettext ("unsupport ABI version e_ident[%d] == %d\n"),
392 	   EI_ABIVERSION, ehdr->e_ident[EI_ABIVERSION]);
393 
394   for (cnt = EI_PAD; cnt < EI_NIDENT; ++cnt)
395     if (ehdr->e_ident[cnt] != 0)
396       ERROR (gettext ("e_ident[%zu] is not zero\n"), cnt);
397 
398   /* Check the e_type field.  */
399   if (ehdr->e_type != ET_REL && ehdr->e_type != ET_EXEC
400       && ehdr->e_type != ET_DYN && ehdr->e_type != ET_CORE)
401     ERROR (gettext ("unknown object file type %d\n"), ehdr->e_type);
402 
403   /* Check the e_machine field.  */
404   for (cnt = 0; cnt < nvalid_e_machine; ++cnt)
405     if (valid_e_machine[cnt] == ehdr->e_machine)
406       break;
407   if (cnt == nvalid_e_machine)
408     ERROR (gettext ("unknown machine type %d\n"), ehdr->e_machine);
409 
410   /* Check the e_version field.  */
411   if (ehdr->e_version != EV_CURRENT)
412     ERROR (gettext ("unknown object file version\n"));
413 
414   /* Check the e_phoff and e_phnum fields.  */
415   if (ehdr->e_phoff == 0)
416     {
417       if (ehdr->e_phnum != 0)
418 	ERROR (gettext ("invalid program header offset\n"));
419       else if (ehdr->e_type == ET_EXEC || ehdr->e_type == ET_DYN)
420 	ERROR (gettext ("\
421 executables and DSOs cannot have zero program header offset\n"));
422     }
423   else if (ehdr->e_phnum == 0)
424     ERROR (gettext ("invalid number of program header entries\n"));
425 
426   /* Check the e_shoff field.  */
427   shnum = ehdr->e_shnum;
428   shstrndx = ehdr->e_shstrndx;
429   if (ehdr->e_shoff == 0)
430     {
431       if (ehdr->e_shnum != 0)
432 	ERROR (gettext ("invalid section header table offset\n"));
433       else if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN
434 	       && ehdr->e_type != ET_CORE)
435 	ERROR (gettext ("section header table must be present\n"));
436     }
437   else
438     {
439       if (ehdr->e_shnum == 0)
440 	{
441 	  /* Get the header of the zeroth section.  The sh_size field
442 	     might contain the section number.  */
443 	  GElf_Shdr shdr_mem;
444 	  GElf_Shdr *shdr;
445 
446 	  shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
447 	  if (shdr != NULL)
448 	    {
449 	      /* The error will be reported later.  */
450 	      if (shdr->sh_size == 0)
451 		ERROR (gettext ("\
452 invalid number of section header table entries\n"));
453 	      else
454 		shnum = shdr->sh_size;
455 	    }
456 	}
457 
458       if (ehdr->e_shstrndx == SHN_XINDEX)
459 	{
460 	  /* Get the header of the zeroth section.  The sh_size field
461 	     might contain the section number.  */
462 	  GElf_Shdr shdr_mem;
463 	  GElf_Shdr *shdr;
464 
465 	  shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
466 	  if (shdr != NULL)
467 	    {
468 	      /* The error will be reported later.  */
469 	      if (shdr->sh_link >= shnum)
470 		ERROR (gettext ("invalid section header index\n"));
471 	      else
472 		shstrndx = shdr->sh_link;
473 	    }
474 	}
475       else if (shstrndx >= shnum)
476 	ERROR (gettext ("invalid section header index\n"));
477     }
478 
479   /* Check the e_flags field.  */
480   if (!ebl_machine_flag_check (ebl, ehdr->e_flags))
481     ERROR (gettext ("invalid machine flags: %s\n"),
482 	   ebl_machine_flag_name (ebl, ehdr->e_flags, buf, sizeof (buf)));
483 
484   /* Check e_ehsize, e_phentsize, and e_shentsize fields.  */
485   if (gelf_getclass (ebl->elf) == ELFCLASS32)
486     {
487       if (ehdr->e_ehsize != 0 && ehdr->e_ehsize != sizeof (Elf32_Ehdr))
488 	ERROR (gettext ("invalid ELF header size: %hd\n"), ehdr->e_ehsize);
489 
490       if (ehdr->e_phentsize != 0 && ehdr->e_phentsize != sizeof (Elf32_Phdr))
491 	ERROR (gettext ("invalid program header size: %hd\n"),
492 	       ehdr->e_phentsize);
493       else if (ehdr->e_phoff + ehdr->e_phnum * ehdr->e_phentsize > size)
494 	ERROR (gettext ("invalid program header position or size\n"));
495 
496       if (ehdr->e_shentsize != 0 && ehdr->e_shentsize != sizeof (Elf32_Shdr))
497 	ERROR (gettext ("invalid section header size: %hd\n"),
498 	       ehdr->e_shentsize);
499       else if (ehdr->e_shoff + ehdr->e_shnum * ehdr->e_shentsize > size)
500 	ERROR (gettext ("invalid section header position or size\n"));
501     }
502   else if (gelf_getclass (ebl->elf) == ELFCLASS64)
503     {
504       if (ehdr->e_ehsize != 0 && ehdr->e_ehsize != sizeof (Elf64_Ehdr))
505 	ERROR (gettext ("invalid ELF header size: %hd\n"), ehdr->e_ehsize);
506 
507       if (ehdr->e_phentsize != 0 && ehdr->e_phentsize != sizeof (Elf64_Phdr))
508 	ERROR (gettext ("invalid program header size: %hd\n"),
509 	       ehdr->e_phentsize);
510       else if (ehdr->e_phoff + ehdr->e_phnum * ehdr->e_phentsize > size)
511 	ERROR (gettext ("invalid program header position or size\n"));
512 
513       if (ehdr->e_shentsize != 0 && ehdr->e_shentsize != sizeof (Elf64_Shdr))
514 	ERROR (gettext ("invalid section header size: %hd\n"),
515 	       ehdr->e_shentsize);
516       else if (ehdr->e_shoff + ehdr->e_shnum * ehdr->e_shentsize > size)
517 	ERROR (gettext ("invalid section header position or size\n"));
518     }
519 }
520 
521 
522 /* Check that there is a section group section with index < IDX which
523    contains section IDX and that there is exactly one.  */
524 static void
check_scn_group(Ebl * ebl,GElf_Ehdr * ehdr,int idx)525 check_scn_group (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
526 {
527   if (scnref[idx] == 0)
528     {
529       /* No reference so far.  Search following sections, maybe the
530 	 order is wrong.  */
531       size_t cnt;
532 
533       for (cnt = idx + 1; cnt < shnum; ++cnt)
534 	{
535 	  Elf_Scn *scn;
536 	  GElf_Shdr shdr_mem;
537 	  GElf_Shdr *shdr;
538 	  Elf_Data *data;
539 	  Elf32_Word *grpdata;
540 	  size_t inner;
541 
542 	  scn = elf_getscn (ebl->elf, cnt);
543 	  shdr = gelf_getshdr (scn, &shdr_mem);
544 	  if (shdr == NULL)
545 	    /* We cannot get the section header so we cannot check it.
546 	       The error to get the section header will be shown
547 	       somewhere else.  */
548 	    continue;
549 
550 	  if (shdr->sh_type != SHT_GROUP)
551 	    continue;
552 
553 	  data = elf_getdata (scn, NULL);
554 	  if (data == NULL || data->d_size < sizeof (Elf32_Word))
555 	    /* Cannot check the section.  */
556 	    continue;
557 
558 	  grpdata = (Elf32_Word *) data->d_buf;
559 	  for (inner = 1; inner < data->d_size / sizeof (Elf32_Word); ++inner)
560 	    if (grpdata[inner] == (Elf32_Word) idx)
561 	      goto out;
562 	}
563 
564     out:
565       if (cnt == shnum)
566 	ERROR (gettext ("\
567 section [%2d] '%s': section with SHF_GROUP flag set not part of a section group\n"),
568 	       idx, section_name (ebl, ehdr, idx));
569       else
570 	ERROR (gettext ("\
571 section [%2d] '%s': section group [%2zu] '%s' does not preceed group member\n"),
572 	       idx, section_name (ebl, ehdr, idx),
573 	       cnt, section_name (ebl, ehdr, cnt));
574     }
575 }
576 
577 
578 static void
check_symtab(Ebl * ebl,GElf_Ehdr * ehdr,int idx)579 check_symtab (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
580 {
581   bool no_xndx_warned = false;
582   int no_pt_tls = 0;
583 
584   Elf_Scn *scn = elf_getscn (ebl->elf, idx);
585   GElf_Shdr shdr_mem;
586   GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
587   GElf_Shdr strshdr_mem;
588   GElf_Shdr *strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
589 				     &strshdr_mem);
590   if (shdr == NULL || strshdr == NULL)
591     return;
592   Elf_Data *data = elf_getdata (scn, NULL);
593   if (data == NULL)
594     {
595       ERROR (gettext ("section [%2d] '%s': cannot get section data\n"),
596 	     idx, section_name (ebl, ehdr, idx));
597       return;
598     }
599 
600   if (strshdr->sh_type != SHT_STRTAB)
601     ERROR (gettext ("section [%2d] '%s': referenced as string table for section [%2d] '%s' but type is not SHT_STRTAB\n"),
602 	   shdr->sh_link, section_name (ebl, ehdr, shdr->sh_link),
603 	   idx, section_name (ebl, ehdr, idx));
604 
605   /* Search for an extended section index table section.  */
606   size_t cnt;
607   GElf_Shdr xndxshdr_mem;
608   GElf_Shdr *xndxshdr = NULL;
609   Elf_Data *xndxdata = NULL;
610   Elf32_Word xndxscnidx = 0;
611   for (cnt = 1; cnt < shnum; ++cnt)
612     if (cnt != (size_t) idx)
613       {
614 	Elf_Scn *xndxscn = elf_getscn (ebl->elf, cnt);
615 	xndxshdr = gelf_getshdr (xndxscn, &xndxshdr_mem);
616 	xndxdata = elf_getdata (xndxscn, NULL);
617 	xndxscnidx = elf_ndxscn (xndxscn);
618 
619 	if (xndxshdr == NULL || xndxdata == NULL)
620 	  continue;
621 
622 	if (xndxshdr->sh_type == SHT_SYMTAB_SHNDX
623 	    && xndxshdr->sh_link == (GElf_Word) idx)
624 	  break;
625       }
626   if (cnt == shnum)
627     {
628       xndxshdr = NULL;
629       xndxdata = NULL;
630     }
631 
632   if (shdr->sh_entsize != gelf_fsize (ebl->elf, ELF_T_SYM, 1, EV_CURRENT))
633     ERROR (gettext ("\
634 section [%2zu] '%s': entry size is does not match ElfXX_Sym\n"),
635 	   cnt, section_name (ebl, ehdr, cnt));
636 
637   /* Test the zeroth entry.  */
638   GElf_Sym sym_mem;
639   Elf32_Word xndx;
640   GElf_Sym *sym = gelf_getsymshndx (data, xndxdata, 0, &sym_mem, &xndx);
641   if (sym == NULL)
642       ERROR (gettext ("section [%2d] '%s': cannot get symbol %d: %s\n"),
643 	     idx, section_name (ebl, ehdr, idx), 0, elf_errmsg (-1));
644   else
645     {
646       if (sym->st_name != 0)
647 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
648 	       idx, section_name (ebl, ehdr, idx), "st_name");
649       if (sym->st_value != 0)
650 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
651 	       idx, section_name (ebl, ehdr, idx), "st_value");
652       if (sym->st_size != 0)
653 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
654 	       idx, section_name (ebl, ehdr, idx), "st_size");
655       if (sym->st_info != 0)
656 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
657 	       idx, section_name (ebl, ehdr, idx), "st_info");
658       if (sym->st_other != 0)
659 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
660 	       idx, section_name (ebl, ehdr, idx), "st_other");
661       if (sym->st_shndx != 0)
662 	ERROR (gettext ("section [%2d] '%s': '%s' in zeroth entry not zero\n"),
663 	       idx, section_name (ebl, ehdr, idx), "st_shndx");
664       if (xndxdata != NULL && xndx != 0)
665 	ERROR (gettext ("\
666 section [%2d] '%s': XINDEX for zeroth entry not zero\n"),
667 	       xndxscnidx, section_name (ebl, ehdr, xndxscnidx));
668     }
669 
670   for (cnt = 1; cnt < shdr->sh_size / shdr->sh_entsize; ++cnt)
671     {
672       sym = gelf_getsymshndx (data, xndxdata, cnt, &sym_mem, &xndx);
673       if (sym == NULL)
674 	{
675 	  ERROR (gettext ("section [%2d] '%s': cannot get symbol %zu: %s\n"),
676 		 idx, section_name (ebl, ehdr, idx), cnt, elf_errmsg (-1));
677 	  continue;
678 	}
679 
680       const char *name = NULL;
681       if (sym->st_name >= strshdr->sh_size)
682 	ERROR (gettext ("\
683 section [%2d] '%s': symbol %zu: invalid name value\n"),
684 	       idx, section_name (ebl, ehdr, idx), cnt);
685       else
686 	{
687 	  name = elf_strptr (ebl->elf, shdr->sh_link, sym->st_name);
688 	  assert (name != NULL);
689 	}
690 
691       if (sym->st_shndx == SHN_XINDEX)
692 	{
693 	  if (xndxdata == NULL)
694 	    {
695 	      ERROR (gettext ("\
696 section [%2d] '%s': symbol %zu: too large section index but no extended section index section\n"),
697 		     idx, section_name (ebl, ehdr, idx), cnt);
698 	      no_xndx_warned = true;
699 	    }
700 	  else if (xndx < SHN_LORESERVE)
701 	    ERROR (gettext ("\
702 section [%2d] '%s': symbol %zu: XINDEX used for index which would fit in st_shndx (%" PRIu32 ")\n"),
703 		   xndxscnidx, section_name (ebl, ehdr, xndxscnidx), cnt,
704 		   xndx);
705 	}
706       else if ((sym->st_shndx >= SHN_LORESERVE
707 		// && sym->st_shndx <= SHN_HIRESERVE    always true
708 		&& sym->st_shndx != SHN_ABS
709 		&& sym->st_shndx != SHN_COMMON)
710 	       || (sym->st_shndx >= shnum
711 		   && (sym->st_shndx < SHN_LORESERVE
712 		       /* || sym->st_shndx > SHN_HIRESERVE  always false */)))
713 	ERROR (gettext ("\
714 section [%2d] '%s': symbol %zu: invalid section index\n"),
715 	       idx, section_name (ebl, ehdr, idx), cnt);
716       else
717 	xndx = sym->st_shndx;
718 
719       if (GELF_ST_TYPE (sym->st_info) >= STT_NUM)
720 	ERROR (gettext ("section [%2d] '%s': symbol %zu: unknown type\n"),
721 	       idx, section_name (ebl, ehdr, idx), cnt);
722 
723       if (GELF_ST_BIND (sym->st_info) >= STB_NUM)
724 	ERROR (gettext ("\
725 section [%2d] '%s': symbol %zu: unknown symbol binding\n"),
726 	       idx, section_name (ebl, ehdr, idx), cnt);
727 
728       if (xndx == SHN_COMMON)
729 	{
730 	  /* Common symbols can only appear in relocatable files.  */
731 	  if (ehdr->e_type != ET_REL)
732 	    ERROR (gettext ("\
733 section [%2d] '%s': symbol %zu: COMMON only allowed in relocatable files\n"),
734 		   idx, section_name (ebl, ehdr, idx), cnt);
735 	  if (cnt < shdr->sh_info)
736 	    ERROR (gettext ("\
737 section [%2d] '%s': symbol %zu: local COMMON symbols are nonsense\n"),
738 		   idx, section_name (ebl, ehdr, idx), cnt);
739 	  if (GELF_R_TYPE (sym->st_info) == STT_FUNC)
740 	    ERROR (gettext ("\
741 section [%2d] '%s': symbol %zu: function in COMMON section is nonsense\n"),
742 		   idx, section_name (ebl, ehdr, idx), cnt);
743 	}
744       else if (xndx > 0 && xndx < shnum)
745 	{
746 	  GElf_Shdr destshdr_mem;
747 	  GElf_Shdr *destshdr;
748 
749 	  destshdr = gelf_getshdr (elf_getscn (ebl->elf, xndx), &destshdr_mem);
750 	  if (destshdr != NULL)
751 	    {
752 	      if (GELF_ST_TYPE (sym->st_info) != STT_TLS)
753 		{
754 		  if ((sym->st_value - destshdr->sh_addr) > destshdr->sh_size)
755 		    ERROR (gettext ("\
756 section [%2d] '%s': symbol %zu: st_value out of bounds\n"),
757 			   idx, section_name (ebl, ehdr, idx), cnt);
758 		  else if ((sym->st_value - destshdr->sh_addr + sym->st_size)
759 			   > destshdr->sh_size)
760 		    ERROR (gettext ("\
761 section [%2d] '%s': symbol %zu does not fit completely in referenced section [%2d] '%s'\n"),
762 			   idx, section_name (ebl, ehdr, idx), cnt,
763 			   (int) xndx, section_name (ebl, ehdr, xndx));
764 		}
765 	      else
766 		{
767 		  if ((destshdr->sh_flags & SHF_TLS) == 0)
768 		    ERROR (gettext ("\
769 section [%2d] '%s': symbol %zu: referenced section [%2d] '%s' does not have SHF_TLS flag set\n"),
770 			   idx, section_name (ebl, ehdr, idx), cnt,
771 			   (int) xndx, section_name (ebl, ehdr, xndx));
772 
773 		  if (ehdr->e_type == ET_REL)
774 		    {
775 		      /* For object files the symbol value must fall
776                          into the section.  */
777 		      if (sym->st_value > destshdr->sh_size)
778 			ERROR (gettext ("\
779 section [%2d] '%s': symbol %zu: st_value out of bounds of referenced section [%2d] '%s'\n"),
780 			       idx, section_name (ebl, ehdr, idx), cnt,
781 			       (int) xndx, section_name (ebl, ehdr, xndx));
782 		      else if (sym->st_value + sym->st_size
783 			       > destshdr->sh_size)
784 			ERROR (gettext ("\
785 section [%2d] '%s': symbol %zu does not fit completely in referenced section [%2d] '%s'\n"),
786 			       idx, section_name (ebl, ehdr, idx), cnt,
787 			       (int) xndx, section_name (ebl, ehdr, xndx));
788 		    }
789 		  else
790 		    {
791 		      GElf_Phdr phdr_mem;
792 		      GElf_Phdr *phdr = NULL;
793 		      int pcnt;
794 
795 		      for (pcnt = 0; pcnt < ehdr->e_phnum; ++pcnt)
796 			{
797 			  phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
798 			  if (phdr != NULL && phdr->p_type == PT_TLS)
799 			    break;
800 			}
801 
802 		      if (pcnt == ehdr->e_phnum)
803 			{
804 			  if (no_pt_tls++ == 0)
805 			    ERROR (gettext ("\
806 section [%2d] '%s': symbol %zu: TLS symbol but no TLS program header entry\n"),
807 				   idx, section_name (ebl, ehdr, idx), cnt);
808 			}
809 		      else
810 			{
811 			  if (sym->st_value
812 			      < destshdr->sh_offset - phdr->p_offset)
813 			    ERROR (gettext ("\
814 section [%2d] '%s': symbol %zu: st_value short of referenced section [%2d] '%s'\n"),
815 				   idx, section_name (ebl, ehdr, idx), cnt,
816 				   (int) xndx, section_name (ebl, ehdr, xndx));
817 			  else if (sym->st_value
818 				   > (destshdr->sh_offset - phdr->p_offset
819 				      + destshdr->sh_size))
820 			    ERROR (gettext ("\
821 section [%2d] '%s': symbol %zu: st_value out of bounds of referenced section [%2d] '%s'\n"),
822 				   idx, section_name (ebl, ehdr, idx), cnt,
823 				   (int) xndx, section_name (ebl, ehdr, xndx));
824 			  else if (sym->st_value + sym->st_size
825 				   > (destshdr->sh_offset - phdr->p_offset
826 				      + destshdr->sh_size))
827 			    ERROR (gettext ("\
828 section [%2d] '%s': symbol %zu does not fit completely in referenced section [%2d] '%s'\n"),
829 				   idx, section_name (ebl, ehdr, idx), cnt,
830 				   (int) xndx, section_name (ebl, ehdr, xndx));
831 			}
832 		    }
833 		}
834 	    }
835 	}
836 
837       if (GELF_ST_BIND (sym->st_info) == STB_LOCAL)
838 	{
839 	  if (cnt >= shdr->sh_info)
840 	    ERROR (gettext ("\
841 section [%2d] '%s': symbol %zu: local symbol outside range described in sh_info\n"),
842 		   idx, section_name (ebl, ehdr, idx), cnt);
843 	}
844       else
845 	{
846 	  if (cnt < shdr->sh_info)
847 	    ERROR (gettext ("\
848 section [%2d] '%s': symbol %zu: non-local symbol outside range described in sh_info\n"),
849 		   idx, section_name (ebl, ehdr, idx), cnt);
850 	}
851 
852       if (GELF_ST_TYPE (sym->st_info) == STT_SECTION
853 	  && GELF_ST_BIND (sym->st_info) != STB_LOCAL)
854 	ERROR (gettext ("\
855 section [%2d] '%s': symbol %zu: non-local section symbol\n"),
856 	       idx, section_name (ebl, ehdr, idx), cnt);
857 
858       if (name != NULL)
859 	{
860 	  if (strcmp (name, "_GLOBAL_OFFSET_TABLE_") == 0)
861 	    {
862 	      /* Check that address and size match the global offset
863 		 table.  We have to locate the GOT by searching for a
864 		 section named ".got".  */
865 	      Elf_Scn *gscn = NULL;
866 
867 	      while ((gscn = elf_nextscn (ebl->elf, gscn)) != NULL)
868 		{
869 		  GElf_Shdr gshdr_mem;
870 		  GElf_Shdr *gshdr = gelf_getshdr (gscn, &gshdr_mem);
871 		  assert (gshdr != NULL);
872 
873 		  const char *sname = elf_strptr (ebl->elf, ehdr->e_shstrndx,
874 						  gshdr->sh_name);
875 		  if (sname != NULL && strcmp (sname, ".got") == 0)
876 		    {
877 		      /* Found it.  */
878 		      if (sym->st_value != gshdr->sh_addr)
879 			/* This test is more strict than the psABIs
880 			   which usually allow the symbol to be in the
881 			   middle of the .got section, allowing
882 			   negative offsets.  */
883 			ERROR (gettext ("\
884 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol value %#" PRIx64 " does not match .got section address %#" PRIx64 "\n"),
885 			       idx, section_name (ebl, ehdr, idx),
886 			       (uint64_t) sym->st_value,
887 			       (uint64_t) gshdr->sh_addr);
888 
889 		      if (sym->st_size != gshdr->sh_size)
890 			ERROR (gettext ("\
891 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol size %" PRIu64 " does not match .got section size %" PRIu64 "\n"),
892 			       idx, section_name (ebl, ehdr, idx),
893 			       (uint64_t) sym->st_size,
894 			       (uint64_t) gshdr->sh_size);
895 
896 		      break;
897 		    }
898 		}
899 
900 	      if (gscn == NULL)
901 		ERROR (gettext ("\
902 section [%2d] '%s': _GLOBAL_OFFSET_TABLE_ symbol present, but no .got section\n"),
903 		       idx, section_name (ebl, ehdr, idx));
904 	    }
905 	  else if (strcmp (name, "_DYNAMIC") == 0)
906 	    {
907 	      /* Check that address and size match the dynamic
908 		 section.  We locate the dynamic section via the
909 		 program header entry.  */
910 	      int pcnt;
911 
912 	      for (pcnt = 0; pcnt < ehdr->e_phnum; ++pcnt)
913 		{
914 		  GElf_Phdr phdr_mem;
915 		  GElf_Phdr *phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem);
916 
917 		  if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
918 		    {
919 		      if (sym->st_value != phdr->p_vaddr)
920 			ERROR (gettext ("\
921 section [%2d] '%s': _DYNAMIC_ symbol value %#" PRIx64 " does not match dynamic segment address %#" PRIx64 "\n"),
922 			       idx, section_name (ebl, ehdr, idx),
923 			       (uint64_t) sym->st_value,
924 			       (uint64_t) phdr->p_vaddr);
925 
926 		      if (sym->st_size != phdr->p_memsz)
927 			ERROR (gettext ("\
928 section [%2d] '%s': _DYNAMIC symbol size %" PRIu64 " does not match dynamic segment size %" PRIu64 "\n"),
929 			       idx, section_name (ebl, ehdr, idx),
930 			       (uint64_t) sym->st_size,
931 			       (uint64_t) phdr->p_memsz);
932 
933 		      break;
934 		    }
935 		}
936 	    }
937 	}
938     }
939 }
940 
941 
942 static bool
is_rel_dyn(Ebl * ebl,GElf_Ehdr * ehdr,int idx,GElf_Shdr * shdr,bool rela)943 is_rel_dyn (Ebl *ebl, GElf_Ehdr *ehdr, int idx, GElf_Shdr *shdr, bool rela)
944 {
945   /* If this is no executable or DSO it cannot be a .rel.dyn section.  */
946   if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
947     return false;
948 
949   /* Check the section name.  Unfortunately necessary.  */
950   if (strcmp (section_name (ebl, ehdr, idx), rela ? ".rela.dyn" : ".rel.dyn"))
951     return false;
952 
953   /* When a .rel.dyn section is used a DT_RELCOUNT dynamic section
954      entry can be present as well.  */
955   Elf_Scn *scn = NULL;
956   while ((scn = elf_nextscn (ebl->elf, scn)) != NULL)
957     {
958       GElf_Shdr rcshdr_mem;
959       const GElf_Shdr *rcshdr = gelf_getshdr (scn, &rcshdr_mem);
960       assert (rcshdr != NULL);
961 
962       if (rcshdr->sh_type == SHT_DYNAMIC)
963 	{
964 	  /* Found the dynamic section.  Look through it.  */
965 	  Elf_Data *d = elf_getdata (scn, NULL);
966 	  int cnt;
967 
968 	  for (cnt = 1; cnt < rcshdr->sh_size / rcshdr->sh_entsize; ++cnt)
969 	    {
970 	      GElf_Dyn dyn_mem;
971 	      GElf_Dyn *dyn = gelf_getdyn (d, cnt, &dyn_mem);
972 	      assert (dyn != NULL);
973 
974 	      if (dyn->d_tag == DT_RELCOUNT)
975 		{
976 		  /* Found it.  One last check: does the number
977 		     specified number of relative relocations exceed
978 		     the total number of relocations?  */
979 		  if (dyn->d_un.d_val > shdr->sh_size / shdr->sh_entsize)
980 		    ERROR (gettext ("\
981 section [%2d] '%s': DT_RELCOUNT value %d too high for this section\n"),
982 			   idx, section_name (ebl, ehdr, idx),
983 			   (int) dyn->d_un.d_val);
984 		}
985 	    }
986 
987 	  break;
988 	}
989     }
990 
991   return true;
992 }
993 
994 
995 static void
check_rela(Ebl * ebl,GElf_Ehdr * ehdr,int idx)996 check_rela (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
997 {
998   Elf_Scn *scn;
999   GElf_Shdr shdr_mem;
1000   GElf_Shdr *shdr;
1001   Elf_Data *data;
1002   GElf_Shdr destshdr_mem;
1003   GElf_Shdr *destshdr = NULL;
1004   size_t cnt;
1005   bool reldyn = false;
1006   bool known_broken = gnuld;
1007 
1008   scn = elf_getscn (ebl->elf, idx);
1009   shdr = gelf_getshdr (scn, &shdr_mem);
1010   if (shdr == NULL)
1011     return;
1012   data = elf_getdata (scn, NULL);
1013   if (data == NULL)
1014     {
1015       ERROR (gettext ("section [%2d] '%s': cannot get section data\n"),
1016 	     idx, section_name (ebl, ehdr, idx));
1017       return;
1018     }
1019 
1020   /* Check whether the link to the section we relocate is reasonable.  */
1021   if (shdr->sh_info >= shnum)
1022     ERROR (gettext ("section [%2d] '%s': invalid destination section index\n"),
1023 	   idx, section_name (ebl, ehdr, idx));
1024   else
1025     {
1026       destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1027 			       &destshdr_mem);
1028       if (destshdr != NULL)
1029 	{
1030 	  if(destshdr->sh_type != SHT_PROGBITS
1031 	     && destshdr->sh_type != SHT_NOBITS)
1032 	    {
1033 	      reldyn = is_rel_dyn (ebl, ehdr, idx, shdr, true);
1034 	      if (!reldyn)
1035 		ERROR (gettext ("\
1036 section [%2d] '%s': invalid destination section type\n"),
1037 		       idx, section_name (ebl, ehdr, idx));
1038 	      else
1039 		{
1040 		  /* There is no standard, but we require that .rela.dyn
1041 		     sections have a sh_info value of zero.  */
1042 		  if (shdr->sh_info != 0)
1043 		    ERROR (gettext ("\
1044 section [%2d] '%s': sh_info should be zero\n"),
1045 			   idx, section_name (ebl, ehdr, idx));
1046 		}
1047 	    }
1048 
1049 	  if ((destshdr->sh_flags & (SHF_MERGE | SHF_STRINGS)) != 0)
1050 	    ERROR (gettext ("\
1051 section [%2d] '%s': no relocations for merge-able sections possible\n"),
1052 		   idx, section_name (ebl, ehdr, idx));
1053 	}
1054     }
1055 
1056   if (shdr->sh_entsize != gelf_fsize (ebl->elf, ELF_T_RELA, 1, EV_CURRENT))
1057     ERROR (gettext ("\
1058 section [%2d] '%s': section entry size does not match ElfXX_Rela\n"),
1059 	   idx, section_name (ebl, ehdr, idx));
1060 
1061   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1062   GElf_Shdr symshdr_mem;
1063   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1064   Elf_Data *symdata = elf_getdata (symscn, NULL);
1065 
1066   for (cnt = 0; cnt < shdr->sh_size / shdr->sh_entsize; ++cnt)
1067     {
1068       GElf_Rela rela_mem;
1069       GElf_Rela *rela;
1070 
1071       rela = gelf_getrela (data, cnt, &rela_mem);
1072       if (rela == NULL)
1073 	{
1074 	  ERROR (gettext ("\
1075 section [%2d] '%s': cannot get relocation %zu: %s\n"),
1076 		 idx, section_name (ebl, ehdr, idx), cnt, elf_errmsg (-1));
1077 	  continue;
1078 	}
1079 
1080       if (!ebl_reloc_type_check (ebl, GELF_R_TYPE (rela->r_info)))
1081 	ERROR (gettext ("section [%2d] '%s': relocation %zu: invalid type\n"),
1082 	       idx, section_name (ebl, ehdr, idx), cnt);
1083       else if (!ebl_reloc_valid_use (ebl, GELF_R_TYPE (rela->r_info)))
1084 	ERROR (gettext ("\
1085 section [%2d] '%s': relocation %zu: relocation type invalid for the file type\n"),
1086 	       idx, section_name (ebl, ehdr, idx), cnt);
1087 
1088       if (symshdr != NULL
1089 	  && ((GELF_R_SYM (rela->r_info) + 1)
1090 	      * gelf_fsize (ebl->elf, ELF_T_SYM, 1, EV_CURRENT)
1091 	      > symshdr->sh_size))
1092 	ERROR (gettext ("\
1093 section [%2d] '%s': relocation %zu: invalid symbol index\n"),
1094 	       idx, section_name (ebl, ehdr, idx), cnt);
1095 
1096       if (ebl_gotpc_reloc_check (ebl, GELF_R_TYPE (rela->r_info)))
1097 	{
1098 	  const char *name;
1099 	  char buf[64];
1100 	  GElf_Sym sym_mem;
1101 	  GElf_Sym *sym = gelf_getsym (symdata, GELF_R_SYM (rela->r_info),
1102 				       &sym_mem);
1103 	  if (sym != NULL
1104 	      /* Get the name for the symbol.  */
1105 	      && (name = elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1106 	      && strcmp (name, "_GLOBAL_OFFSET_TABLE_") !=0 )
1107 	    ERROR (gettext ("\
1108 section [%2d] '%s': relocation %zu: only symbol '_GLOBAL_OFFSET_TABLE_' can be used with %s\n"),
1109 		   idx, section_name (ebl, ehdr, idx), cnt,
1110 		   ebl_reloc_type_name (ebl, GELF_R_SYM (rela->r_info),
1111 					buf, sizeof (buf)));
1112 	}
1113 
1114       if (reldyn)
1115 	{
1116 	  // XXX TODO Check .rel.dyn section addresses.
1117 	}
1118       else if (!known_broken)
1119 	{
1120 	  if (destshdr != NULL
1121 	      && (rela->r_offset - destshdr->sh_addr) >= destshdr->sh_size)
1122 	    ERROR (gettext ("\
1123 section [%2d] '%s': relocation %zu: offset out of bounds\n"),
1124 	       idx, section_name (ebl, ehdr, idx), cnt);
1125 	}
1126     }
1127 }
1128 
1129 
1130 static void
check_rel(Ebl * ebl,GElf_Ehdr * ehdr,int idx)1131 check_rel (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
1132 {
1133   Elf_Scn *scn;
1134   GElf_Shdr shdr_mem;
1135   GElf_Shdr *shdr;
1136   Elf_Data *data;
1137   GElf_Shdr destshdr_mem;
1138   GElf_Shdr *destshdr = NULL;
1139   size_t cnt;
1140   bool reldyn = false;
1141   bool known_broken = gnuld;
1142 
1143   scn = elf_getscn (ebl->elf, idx);
1144   shdr = gelf_getshdr (scn, &shdr_mem);
1145   if (shdr == NULL)
1146     return;
1147   data = elf_getdata (scn, NULL);
1148   if (data == NULL)
1149     {
1150       ERROR (gettext ("section [%2d] '%s': cannot get section data\n"),
1151 	     idx, section_name (ebl, ehdr, idx));
1152       return;
1153     }
1154 
1155   /* Check whether the link to the section we relocate is reasonable.  */
1156   if (shdr->sh_info >= shnum)
1157     ERROR (gettext ("section [%2d] '%s': invalid destination section index\n"),
1158 	   idx, section_name (ebl, ehdr, idx));
1159   else
1160     {
1161       destshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_info),
1162 			       &destshdr_mem);
1163       if (destshdr != NULL)
1164 	{
1165 	  if (destshdr->sh_type != SHT_PROGBITS
1166 	      && destshdr->sh_type != SHT_NOBITS)
1167 	    {
1168 	      reldyn = is_rel_dyn (ebl, ehdr, idx, shdr, false);
1169 	      if (!reldyn)
1170 		ERROR (gettext ("\
1171 section [%2d] '%s': invalid destination section type\n"),
1172 		       idx, section_name (ebl, ehdr, idx));
1173 	      else
1174 		{
1175 		  /* There is no standard, but we require that .rela.dyn
1176 		     sections have a sh_info value of zero.  */
1177 		  if (shdr->sh_info != 0)
1178 		    ERROR (gettext ("\
1179 section [%2d] '%s': sh_info should be zero\n"),
1180 			   idx, section_name (ebl, ehdr, idx));
1181 		}
1182 	    }
1183 
1184 	  if ((destshdr->sh_flags & (SHF_MERGE | SHF_STRINGS)) != 0)
1185 	    ERROR (gettext ("\
1186 section [%2d] '%s': no relocations for merge-able sections possible\n"),
1187 		   idx, section_name (ebl, ehdr, idx));
1188 	}
1189     }
1190 
1191   if (shdr->sh_entsize != gelf_fsize (ebl->elf, ELF_T_REL, 1, EV_CURRENT))
1192     ERROR (gettext ("\
1193 section [%2d] '%s': section entry size does not match ElfXX_Rel\n"),
1194 	   idx, section_name (ebl, ehdr, idx));
1195 
1196   Elf_Scn *symscn = elf_getscn (ebl->elf, shdr->sh_link);
1197   GElf_Shdr symshdr_mem;
1198   GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1199   Elf_Data *symdata = elf_getdata (symscn, NULL);
1200 
1201   for (cnt = 0; cnt < shdr->sh_size / shdr->sh_entsize; ++cnt)
1202     {
1203       GElf_Rel rel_mem;
1204       GElf_Rel *rel;
1205 
1206       rel = gelf_getrel (data, cnt, &rel_mem);
1207       if (rel == NULL)
1208 	{
1209 	  ERROR (gettext ("\
1210 section [%2d] '%s': cannot get relocation %zu: %s\n"),
1211 		 idx, section_name (ebl, ehdr, idx), cnt, elf_errmsg (-1));
1212 	  continue;
1213 	}
1214 
1215       if (!ebl_reloc_type_check (ebl, GELF_R_TYPE (rel->r_info)))
1216 	ERROR (gettext ("section [%2d] '%s': relocation %zu: invalid type\n"),
1217 	       idx, section_name (ebl, ehdr, idx), cnt);
1218       else if (!ebl_reloc_valid_use (ebl, GELF_R_TYPE (rel->r_info)))
1219 	ERROR (gettext ("\
1220 section [%2d] '%s': relocation %zu: relocation type invalid for the file type\n"),
1221 	       idx, section_name (ebl, ehdr, idx), cnt);
1222 
1223       if (symshdr != NULL
1224 	  && ((GELF_R_SYM (rel->r_info) + 1)
1225 	      * gelf_fsize (ebl->elf, ELF_T_SYM, 1, EV_CURRENT)
1226 	      > symshdr->sh_size))
1227 	ERROR (gettext ("\
1228 section [%2d] '%s': relocation %zu: invalid symbol index\n"),
1229 	       idx, section_name (ebl, ehdr, idx), cnt);
1230 
1231       if (ebl_gotpc_reloc_check (ebl, GELF_R_TYPE (rel->r_info)))
1232 	{
1233 	  const char *name;
1234 	  char buf[64];
1235 	  GElf_Sym sym_mem;
1236 	  GElf_Sym *sym = gelf_getsym (symdata, GELF_R_SYM (rel->r_info),
1237 				       &sym_mem);
1238 	  if (sym != NULL
1239 	      /* Get the name for the symbol.  */
1240 	      && (name = elf_strptr (ebl->elf, symshdr->sh_link, sym->st_name))
1241 	      && strcmp (name, "_GLOBAL_OFFSET_TABLE_") !=0 )
1242 	    ERROR (gettext ("\
1243 section [%2d] '%s': relocation %zu: only symbol '_GLOBAL_OFFSET_TABLE_' can be used with %s\n"),
1244 		   idx, section_name (ebl, ehdr, idx), cnt,
1245 		   ebl_reloc_type_name (ebl, GELF_R_SYM (rel->r_info),
1246 					buf, sizeof (buf)));
1247 	}
1248 
1249       if (reldyn)
1250 	{
1251 	  // XXX TODO Check .rel.dyn section addresses.
1252 	}
1253       else if (!known_broken)
1254 	{
1255 	  if (destshdr != NULL
1256 	      && GELF_R_TYPE (rel->r_info) != 0
1257 	      && (rel->r_offset - destshdr->sh_addr) >= destshdr->sh_size)
1258 	    ERROR (gettext ("\
1259 section [%2d] '%s': relocation %zu: offset out of bounds\n"),
1260 		   idx, section_name (ebl, ehdr, idx), cnt);
1261 	}
1262     }
1263 }
1264 
1265 
1266 /* Number of dynamic sections.  */
1267 static int ndynamic;
1268 
1269 
1270 static void
check_dynamic(Ebl * ebl,GElf_Ehdr * ehdr,int idx)1271 check_dynamic (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
1272 {
1273   Elf_Scn *scn;
1274   GElf_Shdr shdr_mem;
1275   GElf_Shdr *shdr;
1276   Elf_Data *data;
1277   GElf_Shdr strshdr_mem;
1278   GElf_Shdr *strshdr;
1279   size_t cnt;
1280   static const bool dependencies[DT_NUM][DT_NUM] =
1281     {
1282       [DT_NEEDED] = { [DT_STRTAB] = true },
1283       [DT_PLTRELSZ] = { [DT_JMPREL] = true },
1284       [DT_HASH] = { [DT_SYMTAB] = true },
1285       [DT_STRTAB] = { [DT_STRSZ] = true },
1286       [DT_SYMTAB] = { [DT_STRTAB] = true, [DT_HASH] = true,
1287 		      [DT_SYMENT] = true },
1288       [DT_RELA] = { [DT_RELASZ] = true, [DT_RELAENT] = true },
1289       [DT_RELASZ] = { [DT_RELA] = true },
1290       [DT_RELAENT] = { [DT_RELA] = true },
1291       [DT_STRSZ] = { [DT_STRTAB] = true },
1292       [DT_SYMENT] = { [DT_SYMTAB] = true },
1293       [DT_SONAME] = { [DT_STRTAB] = true },
1294       [DT_RPATH] = { [DT_STRTAB] = true },
1295       [DT_REL] = { [DT_RELSZ] = true, [DT_RELENT] = true },
1296       [DT_RELSZ] = { [DT_REL] = true },
1297       [DT_RELENT] = { [DT_REL] = true },
1298       [DT_JMPREL] = { [DT_PLTRELSZ] = true, [DT_PLTREL] = true },
1299       [DT_RUNPATH] = { [DT_STRTAB] = true },
1300       [DT_PLTREL] = { [DT_JMPREL] = true },
1301       [DT_PLTRELSZ] = { [DT_JMPREL] = true }
1302     };
1303   bool has_dt[DT_NUM];
1304   static const bool level2[DT_NUM] =
1305     {
1306       [DT_RPATH] = true,
1307       [DT_SYMBOLIC] = true,
1308       [DT_TEXTREL] = true,
1309       [DT_BIND_NOW] = true
1310     };
1311   static const bool mandatory[DT_NUM] =
1312     {
1313       [DT_NULL] = true,
1314       [DT_HASH] = true,
1315       [DT_STRTAB] = true,
1316       [DT_SYMTAB] = true,
1317       [DT_STRSZ] = true,
1318       [DT_SYMENT] = true
1319     };
1320   GElf_Addr reladdr = 0;
1321   GElf_Word relsz = 0;
1322   GElf_Addr pltreladdr = 0;
1323   GElf_Word pltrelsz = 0;
1324 
1325   memset (has_dt, '\0', sizeof (has_dt));
1326 
1327   if (++ndynamic == 2)
1328     ERROR (gettext ("more than one dynamic section present\n"));
1329 
1330   scn = elf_getscn (ebl->elf, idx);
1331   shdr = gelf_getshdr (scn, &shdr_mem);
1332   if (shdr == NULL)
1333     return;
1334   data = elf_getdata (scn, NULL);
1335   if (data == NULL)
1336     {
1337       ERROR (gettext ("section [%2d] '%s': cannot get section data\n"),
1338 	     idx, section_name (ebl, ehdr, idx));
1339       return;
1340     }
1341 
1342   strshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &strshdr_mem);
1343   if (strshdr != NULL && strshdr->sh_type != SHT_STRTAB)
1344     ERROR (gettext ("\
1345 section [%2d] '%s': referenced as string table for section [%2d] '%s' but type is not SHT_STRTAB\n"),
1346 	   shdr->sh_link, section_name (ebl, ehdr, shdr->sh_link),
1347 	   idx, section_name (ebl, ehdr, idx));
1348 
1349   if (shdr->sh_entsize != gelf_fsize (ebl->elf, ELF_T_DYN, 1, EV_CURRENT))
1350     ERROR (gettext ("\
1351 section [%2d] '%s': section entry size does not match ElfXX_Dyn\n"),
1352 	   idx, section_name (ebl, ehdr, idx));
1353 
1354   if (shdr->sh_info != 0)
1355     ERROR (gettext ("section [%2d] '%s': sh_info not zero\n"),
1356 	   idx, section_name (ebl, ehdr, idx));
1357 
1358   bool non_null_warned = false;
1359   for (cnt = 0; cnt < shdr->sh_size / shdr->sh_entsize; ++cnt)
1360     {
1361       GElf_Dyn dyn_mem;
1362       GElf_Dyn *dyn;
1363 
1364       dyn = gelf_getdyn (data, cnt, &dyn_mem);
1365       if (dyn == NULL)
1366 	{
1367 	  ERROR (gettext ("\
1368 section [%2d] '%s': cannot get dynamic section entry %zu: %s\n"),
1369 		 idx, section_name (ebl, ehdr, idx), cnt, elf_errmsg (-1));
1370 	  continue;
1371 	}
1372 
1373       if (has_dt[DT_NULL] && dyn->d_tag != DT_NULL && ! non_null_warned)
1374 	{
1375 	  ERROR (gettext ("\
1376 section [%2d] '%s': non-DT_NULL entries follow DT_NULL entry\n"),
1377 		 idx, section_name (ebl, ehdr, idx));
1378 	  non_null_warned = true;
1379 	}
1380 
1381       if (!ebl_dynamic_tag_check (ebl, dyn->d_tag))
1382 	ERROR (gettext ("section [%2d] '%s': entry %zu: unknown tag\n"),
1383 	       idx, section_name (ebl, ehdr, idx), cnt);
1384 
1385       if (dyn->d_tag < DT_NUM)
1386 	{
1387 	  if (has_dt[dyn->d_tag]
1388 	      && dyn->d_tag != DT_NEEDED
1389 	      && dyn->d_tag != DT_NULL
1390 	      && dyn->d_tag != DT_POSFLAG_1)
1391 	    {
1392 	      char buf[50];
1393 	      ERROR (gettext ("\
1394 section [%2d] '%s': entry %zu: more than one entry with tag %s\n"),
1395 		     idx, section_name (ebl, ehdr, idx), cnt,
1396 		     ebl_dynamic_tag_name (ebl, dyn->d_tag,
1397 					   buf, sizeof (buf)));
1398 	    }
1399 
1400 	  if (be_strict && level2[dyn->d_tag])
1401 	    {
1402 	      char buf[50];
1403 	      ERROR (gettext ("\
1404 section [%2d] '%s': entry %zu: level 2 tag %s used\n"),
1405 		     idx, section_name (ebl, ehdr, idx), cnt,
1406 		     ebl_dynamic_tag_name (ebl, dyn->d_tag,
1407 					   buf, sizeof (buf)));
1408 	    }
1409 
1410 	  has_dt[dyn->d_tag] = true;
1411 	}
1412 
1413       if (dyn->d_tag == DT_PLTREL && dyn->d_un.d_val != DT_REL
1414 	  && dyn->d_un.d_val != DT_RELA)
1415 	ERROR (gettext ("\
1416 section [%2d] '%s': entry %zu: DT_PLTREL value must be DT_REL or DT_RELA\n"),
1417 	       idx, section_name (ebl, ehdr, idx), cnt);
1418 
1419       if (dyn->d_tag == DT_REL)
1420 	reladdr = dyn->d_un.d_ptr;
1421       if (dyn->d_tag == DT_RELSZ)
1422 	relsz = dyn->d_un.d_val;
1423       if (dyn->d_tag == DT_JMPREL)
1424 	pltreladdr = dyn->d_un.d_ptr;
1425       if (dyn->d_tag == DT_PLTRELSZ)
1426 	pltrelsz = dyn->d_un.d_val;
1427     }
1428 
1429   for (cnt = 1; cnt < DT_NUM; ++cnt)
1430     if (has_dt[cnt])
1431       {
1432 	int inner;
1433 
1434 	for (inner = 0; inner < DT_NUM; ++inner)
1435 	  if (dependencies[cnt][inner] && ! has_dt[inner])
1436 	    {
1437 	      char buf1[50];
1438 	      char buf2[50];
1439 
1440 	      ERROR (gettext ("\
1441 section [%2d] '%s': contains %s entry but not %s\n"),
1442 		     idx, section_name (ebl, ehdr, idx),
1443 		     ebl_dynamic_tag_name (ebl, cnt, buf1, sizeof (buf1)),
1444 		     ebl_dynamic_tag_name (ebl, inner, buf2, sizeof (buf2)));
1445 	    }
1446       }
1447     else
1448       {
1449 	if (mandatory[cnt])
1450 	  {
1451 	    char buf[50];
1452 	    ERROR (gettext ("\
1453 section [%2d] '%s': mandatory tag %s not present\n"),
1454 		   idx, section_name (ebl, ehdr, idx),
1455 		   ebl_dynamic_tag_name (ebl, cnt, buf, sizeof (buf)));
1456 	  }
1457       }
1458 
1459   /* Check the rel/rela tags.  At least one group must be available.  */
1460   if ((has_dt[DT_RELA] || has_dt[DT_RELASZ] || has_dt[DT_RELAENT])
1461       && (!has_dt[DT_RELA] || !has_dt[DT_RELASZ] || !has_dt[DT_RELAENT]))
1462     ERROR (gettext ("\
1463 section [%2d] '%s': not all of %s, %s, and %s are present\n"),
1464 	   idx, section_name (ebl, ehdr, idx),
1465 	   "DT_RELA", "DT_RELASZ", "DT_RELAENT");
1466 
1467   if ((has_dt[DT_REL] || has_dt[DT_RELSZ] || has_dt[DT_RELENT])
1468       && (!has_dt[DT_REL] || !has_dt[DT_RELSZ] || !has_dt[DT_RELENT]))
1469     ERROR (gettext ("\
1470 section [%2d] '%s': not all of %s, %s, and %s are present\n"),
1471 	   idx, section_name (ebl, ehdr, idx),
1472 	   "DT_REL", "DT_RELSZ", "DT_RELENT");
1473 }
1474 
1475 
1476 static void
check_symtab_shndx(Ebl * ebl,GElf_Ehdr * ehdr,int idx)1477 check_symtab_shndx (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
1478 {
1479   Elf_Scn *scn;
1480   GElf_Shdr shdr_mem;
1481   GElf_Shdr *shdr;
1482   GElf_Shdr symshdr_mem;
1483   GElf_Shdr *symshdr;
1484   Elf_Scn *symscn;
1485   size_t cnt;
1486   Elf_Data *data;
1487   Elf_Data *symdata;
1488 
1489   scn = elf_getscn (ebl->elf, idx);
1490   shdr = gelf_getshdr (scn, &shdr_mem);
1491   if (shdr == NULL)
1492     return;
1493 
1494   symscn = elf_getscn (ebl->elf, shdr->sh_link);
1495   symshdr = gelf_getshdr (symscn, &symshdr_mem);
1496   if (symshdr != NULL && symshdr->sh_type != SHT_SYMTAB)
1497     ERROR (gettext ("\
1498 section [%2d] '%s': extended section index section not for symbol table\n"),
1499 	   idx, section_name (ebl, ehdr, idx));
1500   symdata = elf_getdata (symscn, NULL);
1501   if (symdata == NULL)
1502     ERROR (gettext ("cannot get data for symbol section\n"));
1503 
1504   if (shdr->sh_entsize != sizeof (Elf32_Word))
1505     ERROR (gettext ("\
1506 section [%2d] '%s': entry size does not match Elf32_Word\n"),
1507 	   idx, section_name (ebl, ehdr, idx));
1508 
1509   if (symshdr != NULL
1510       && (shdr->sh_size / shdr->sh_entsize
1511 	  < symshdr->sh_size / symshdr->sh_entsize))
1512     ERROR (gettext ("\
1513 section [%2d] '%s': extended index table too small for symbol table\n"),
1514 	   idx, section_name (ebl, ehdr, idx));
1515 
1516   if (shdr->sh_info != 0)
1517     ERROR (gettext ("section [%2d] '%s': sh_info not zero\n"),
1518 	   idx, section_name (ebl, ehdr, idx));
1519 
1520   for (cnt = idx + 1; cnt < shnum; ++cnt)
1521     {
1522       GElf_Shdr rshdr_mem;
1523       GElf_Shdr *rshdr;
1524 
1525       rshdr = gelf_getshdr (elf_getscn (ebl->elf, cnt), &rshdr_mem);
1526       if (rshdr != NULL && rshdr->sh_type == SHT_SYMTAB_SHNDX
1527 	  && rshdr->sh_link == shdr->sh_link)
1528 	{
1529 	  ERROR (gettext ("\
1530 section [%2d] '%s': extended section index in section [%2zu] '%s' refers to same symbol table\n"),
1531 		 idx, section_name (ebl, ehdr, idx),
1532 		 cnt, section_name (ebl, ehdr, cnt));
1533 	  break;
1534 	}
1535     }
1536 
1537   data = elf_getdata (scn, NULL);
1538 
1539   if (*((Elf32_Word *) data->d_buf) != 0)
1540     ERROR (gettext ("symbol 0 should have zero extended section index\n"));
1541 
1542   for (cnt = 1; cnt < data->d_size / sizeof (Elf32_Word); ++cnt)
1543     {
1544       Elf32_Word xndx = ((Elf32_Word *) data->d_buf)[cnt];
1545 
1546       if (xndx != 0)
1547 	{
1548 	  GElf_Sym sym_data;
1549 	  GElf_Sym *sym = gelf_getsym (symdata, cnt, &sym_data);
1550 	  if (sym == NULL)
1551 	    {
1552 	      ERROR (gettext ("cannot get data for symbol %zu\n"), cnt);
1553 	      continue;
1554 	    }
1555 
1556 	  if (sym->st_shndx != SHN_XINDEX)
1557 	    ERROR (gettext ("\
1558 extended section index is %" PRIu32 " but symbol index is not XINDEX\n"),
1559 		   (uint32_t) xndx);
1560 	}
1561     }
1562 }
1563 
1564 
1565 static void
check_hash(Ebl * ebl,GElf_Ehdr * ehdr,int idx)1566 check_hash (Ebl *ebl, GElf_Ehdr *ehdr, int idx)
1567 {
1568   Elf_Scn *scn;
1569   GElf_Shdr shdr_mem;
1570   GElf_Shdr *shdr;
1571   Elf_Data *data;
1572   Elf32_Word nbucket;
1573   Elf32_Word nchain;
1574   GElf_Shdr symshdr_mem;
1575   GElf_Shdr *symshdr;
1576 
1577   scn = elf_getscn (ebl->elf, idx);
1578   shdr = gelf_getshdr (scn, &shdr_mem);
1579   if (shdr == NULL)
1580     return;
1581   data = elf_getdata (scn, NULL);
1582   if (data == NULL)
1583     {
1584       ERROR (gettext ("section [%2d] '%s': cannot get section data\n"),
1585 	     idx, section_name (ebl, ehdr, idx));
1586       return;
1587     }
1588 
1589   symshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link), &symshdr_mem);
1590   if (symshdr != NULL && symshdr->sh_type != SHT_DYNSYM)
1591     ERROR (gettext ("\
1592 section [%2d] '%s': hash table not for dynamic symbol table\n"),
1593 	   idx, section_name (ebl, ehdr, idx));
1594 
1595   if (shdr->sh_entsize != sizeof (Elf32_Word))
1596     ERROR (gettext ("\
1597 section [%2d] '%s': entry size does not match Elf32_Word\n"),
1598 	   idx, section_name (ebl, ehdr, idx));
1599 
1600   if ((shdr->sh_flags & SHF_ALLOC) == 0)
1601     ERROR (gettext ("section [%2d] '%s': not marked to be allocated\n"),
1602 	   idx, section_name (ebl, ehdr, idx));
1603 
1604   if (shdr->sh_size < 2 * shdr->sh_entsize)
1605     {
1606       ERROR (gettext ("\
1607 section [%2d] '%s': hash table has not even room for nbucket and nchain\n"),
1608 	     idx, section_name (ebl, ehdr, idx));
1609       return;
1610     }
1611 
1612   nbucket = ((Elf32_Word *) data->d_buf)[0];
1613   nchain = ((Elf32_Word *) data->d_buf)[1];
1614 
1615   if (shdr->sh_size < (2 + nbucket + nchain) * shdr->sh_entsize)
1616     ERROR (gettext ("\
1617 section [%2d] '%s': hash table section is too small (is %ld, expected %ld)\n"),
1618 	   idx, section_name (ebl, ehdr, idx), (long int) shdr->sh_size,
1619 	   (long int) ((2 + nbucket + nchain) * shdr->sh_entsize));
1620 
1621   if (symshdr != NULL)
1622     {
1623       size_t symsize = symshdr->sh_size / symshdr->sh_entsize;
1624       size_t cnt;
1625 
1626       if (nchain < symshdr->sh_size / symshdr->sh_entsize)
1627 	ERROR (gettext ("section [%2d] '%s': chain array not large enough\n"),
1628 	       idx, section_name (ebl, ehdr, idx));
1629 
1630       for (cnt = 2; cnt < 2 + nbucket; ++cnt)
1631 	if (((Elf32_Word *) data->d_buf)[cnt] >= symsize)
1632 	  ERROR (gettext ("\
1633 section [%2d] '%s': hash bucket reference %zu out of bounds\n"),
1634 		 idx, section_name (ebl, ehdr, idx), cnt - 2);
1635 
1636       for (; cnt < 2 + nbucket + nchain; ++cnt)
1637 	if (((Elf32_Word *) data->d_buf)[cnt] >= symsize)
1638 	  ERROR (gettext ("\
1639 section [%2d] '%s': hash chain reference %zu out of bounds\n"),
1640 		 idx, section_name (ebl, ehdr, idx), cnt - 2 - nbucket);
1641     }
1642 }
1643 
1644 
1645 static void
check_null(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1646 check_null (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1647 {
1648 #define TEST(name, extra) \
1649   if (extra && shdr->sh_##name != 0)					      \
1650     ERROR (gettext ("section [%2d] '%s': nonzero sh_%s for NULL section\n"),  \
1651 	   idx, section_name (ebl, ehdr, idx), #name)
1652 
1653   TEST (name, 1);
1654   TEST (flags, 1);
1655   TEST (addr, 1);
1656   TEST (offset, 1);
1657   TEST (size, idx != 0);
1658   TEST (link, idx != 0);
1659   TEST (info, 1);
1660   TEST (addralign, 1);
1661   TEST (entsize, 1);
1662 }
1663 
1664 
1665 static void
check_group(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1666 check_group (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1667 {
1668   if (ehdr->e_type != ET_REL)
1669     {
1670       ERROR (gettext ("\
1671 section [%2d] '%s': section groups only allowed in relocatable object files\n"),
1672 	     idx, section_name (ebl, ehdr, idx));
1673       return;
1674     }
1675 
1676   /* Check that sh_link is an index of a symbol table.  */
1677   GElf_Shdr symshdr_mem;
1678   GElf_Shdr *symshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
1679 				     &symshdr_mem);
1680   if (symshdr == NULL)
1681     ERROR (gettext ("section [%2d] '%s': cannot get symbol table: %s\n"),
1682 	   idx, section_name (ebl, ehdr, idx), elf_errmsg (-1));
1683   else
1684     {
1685       if (symshdr->sh_type != SHT_SYMTAB)
1686 	ERROR (gettext ("\
1687 section [%2d] '%s': section reference in sh_link is no symbol table\n"),
1688 	       idx, section_name (ebl, ehdr, idx));
1689 
1690       if (shdr->sh_info >= symshdr->sh_size / gelf_fsize (ebl->elf, ELF_T_SYM,
1691 							  1, EV_CURRENT))
1692 	ERROR (gettext ("\
1693 section [%2d] '%s': invalid symbol index in sh_info\n"),
1694 	       idx, section_name (ebl, ehdr, idx));
1695 
1696       if (shdr->sh_flags != 0)
1697 	ERROR (gettext ("section [%2d] '%s': sh_flags not zero\n"),
1698 	       idx, section_name (ebl, ehdr, idx));
1699 
1700       if (be_strict
1701 	  && shdr->sh_entsize != elf32_fsize (ELF_T_WORD, 1, EV_CURRENT))
1702 	ERROR (gettext ("section [%2d] '%s': sh_flags not set correctly\n"),
1703 	       idx, section_name (ebl, ehdr, idx));
1704     }
1705 
1706   Elf_Data *data = elf_getdata (elf_getscn (ebl->elf, idx), NULL);
1707   if (data == NULL)
1708     ERROR (gettext ("section [%2d] '%s': cannot get data: %s\n"),
1709 	   idx, section_name (ebl, ehdr, idx), elf_errmsg (-1));
1710   else
1711     {
1712       size_t elsize = elf32_fsize (ELF_T_WORD, 1, EV_CURRENT);
1713       size_t cnt;
1714       Elf32_Word val;
1715 
1716       if (data->d_size % elsize != 0)
1717 	ERROR (gettext ("\
1718 section [%2d] '%s': section size not multiple of sizeof(Elf32_Word)\n"),
1719 	       idx, section_name (ebl, ehdr, idx));
1720 
1721       if (data->d_size < elsize)
1722 	ERROR (gettext ("\
1723 section [%2d] '%s': section group without flags word\n"),
1724 	       idx, section_name (ebl, ehdr, idx));
1725       else if (be_strict)
1726 	{
1727 	  if (data->d_size < 2 * elsize)
1728 	    ERROR (gettext ("\
1729 section [%2d] '%s': section group without member\n"),
1730 		   idx, section_name (ebl, ehdr, idx));
1731 	  else if (data->d_size < 3 * elsize)
1732 	    ERROR (gettext ("\
1733 section [%2d] '%s': section group with only one member\n"),
1734 		   idx, section_name (ebl, ehdr, idx));
1735 	}
1736 
1737 #if ALLOW_UNALIGNED
1738       val = *((Elf32_Word *) data->d_buf);
1739 #else
1740       memcpy (&val, data->d_buf, elsize);
1741 #endif
1742       if ((val & ~GRP_COMDAT) != 0)
1743 	ERROR (gettext ("section [%2d] '%s': unknown section group flags\n"),
1744 	       idx, section_name (ebl, ehdr, idx));
1745 
1746       for (cnt = elsize; cnt < data->d_size; cnt += elsize)
1747 	{
1748 #if ALLOW_UNALIGNED
1749 	  val = *((Elf32_Word *) ((char *) data->d_buf + cnt));
1750 #else
1751 	  memcpy (&val, (char *) data->d_buf + cnt, elsize);
1752 #endif
1753 
1754 	  if (val > shnum)
1755 	    ERROR (gettext ("\
1756 section [%2d] '%s': section index %Zu out of range\n"),
1757 		   idx, section_name (ebl, ehdr, idx), cnt / elsize);
1758 	  else
1759 	    {
1760 	      GElf_Shdr refshdr_mem;
1761 	      GElf_Shdr *refshdr;
1762 
1763 	      refshdr = gelf_getshdr (elf_getscn (ebl->elf, val),
1764 				      &refshdr_mem);
1765 	      if (refshdr == NULL)
1766 		ERROR (gettext ("\
1767 section [%2d] '%s': cannot get section header for element %zu: %s\n"),
1768 		       idx, section_name (ebl, ehdr, idx), cnt / elsize,
1769 		       elf_errmsg (-1));
1770 	      else
1771 		{
1772 		  if (refshdr->sh_type == SHT_GROUP)
1773 		    ERROR (gettext ("\
1774 section [%2d] '%s': section group contains another group [%2d] '%s'\n"),
1775 			   idx, section_name (ebl, ehdr, idx),
1776 			   val, section_name (ebl, ehdr, val));
1777 
1778 		  if ((refshdr->sh_flags & SHF_GROUP) == 0)
1779 		    ERROR (gettext ("\
1780 section [%2d] '%s': element %Zu references section [%2d] '%s' without SHF_GROUP flag set\n"),
1781 			   idx, section_name (ebl, ehdr, idx), cnt / elsize,
1782 			   val, section_name (ebl, ehdr, val));
1783 		}
1784 
1785 	      if (++scnref[val] == 2)
1786 		ERROR (gettext ("\
1787 section [%2d] '%s' is contained in more than one section group\n"),
1788 		       val, section_name (ebl, ehdr, val));
1789 	    }
1790 	}
1791     }
1792 }
1793 
1794 
1795 static bool has_loadable_segment;
1796 static bool has_interp_segment;
1797 
1798 static const struct
1799 {
1800   const char *name;
1801   size_t namelen;
1802   GElf_Word type;
1803   enum { unused, exact, atleast } attrflag;
1804   GElf_Word attr;
1805   GElf_Word attr2;
1806 } special_sections[] =
1807   {
1808     /* See figure 4-14 in the gABI.  */
1809     { ".bss", 5, SHT_NOBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
1810     { ".comment", 8, SHT_PROGBITS, exact, 0, 0 },
1811     { ".data", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
1812     { ".data1", 7, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE, 0 },
1813     { ".debug", 7, SHT_PROGBITS, exact, 0, 0 },
1814     { ".dynamic", 9, SHT_DYNAMIC, atleast, SHF_ALLOC, SHF_WRITE },
1815     { ".dynstr", 8, SHT_STRTAB, exact, SHF_ALLOC, 0 },
1816     { ".dynsym", 8, SHT_DYNSYM, exact, SHF_ALLOC, 0 },
1817     { ".fini", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 },
1818     { ".fini_array", 12, SHT_FINI_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
1819     { ".got", 5, SHT_PROGBITS, unused, 0, 0 }, // XXX more info?
1820     { ".hash", 6, SHT_HASH, exact, SHF_ALLOC, 0 },
1821     { ".init", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 },
1822     { ".init_array", 12, SHT_INIT_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
1823     { ".interp", 8, SHT_PROGBITS, atleast, 0, SHF_ALLOC }, // XXX more tests?
1824     { ".line", 6, SHT_PROGBITS, exact, 0, 0 },
1825     { ".note", 6, SHT_NOTE, exact, 0, 0 },
1826     { ".plt", 5, SHT_PROGBITS, unused, 0, 0 }, // XXX more tests
1827     { ".preinit_array", 15, SHT_PREINIT_ARRAY, exact, SHF_ALLOC | SHF_WRITE, 0 },
1828     { ".rela", 5, SHT_RELA, atleast, 0, SHF_ALLOC }, // XXX more tests
1829     { ".rel", 4, SHT_REL, atleast, 0, SHF_ALLOC }, // XXX more tests
1830     { ".rodata", 8, SHT_PROGBITS, exact, SHF_ALLOC, 0 },
1831     { ".rodata1", 9, SHT_PROGBITS, exact, SHF_ALLOC, 0 },
1832     { ".shstrtab", 10, SHT_STRTAB, exact, 0, 0 },
1833     { ".strtab", 8, SHT_STRTAB, atleast, 0, SHF_ALLOC }, // XXX more tests
1834     { ".symtab", 8, SHT_SYMTAB, atleast, 0, SHF_ALLOC }, // XXX more tests
1835     { ".symtab_shndx", 14, SHT_SYMTAB_SHNDX, atleast, 0, SHF_ALLOC }, // XXX more tests
1836     { ".tbss", 6, SHT_NOBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
1837     { ".tdata", 7, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
1838     { ".tdata1", 8, SHT_PROGBITS, exact, SHF_ALLOC | SHF_WRITE | SHF_TLS, 0 },
1839     { ".text", 6, SHT_PROGBITS, exact, SHF_ALLOC | SHF_EXECINSTR, 0 }
1840   };
1841 #define nspecial_sections \
1842   (sizeof (special_sections) / sizeof (special_sections[0]))
1843 
1844 
1845 static const char *
section_flags_string(GElf_Word flags,char * buf,size_t len)1846 section_flags_string (GElf_Word flags, char *buf, size_t len)
1847 {
1848   static const struct
1849   {
1850     GElf_Word flag;
1851     const char *name;
1852   } known_flags[] =
1853     {
1854 #define NEWFLAG(name) { SHF_##name, #name }
1855       NEWFLAG (WRITE),
1856       NEWFLAG (ALLOC),
1857       NEWFLAG (EXECINSTR),
1858       NEWFLAG (MERGE),
1859       NEWFLAG (STRINGS),
1860       NEWFLAG (INFO_LINK),
1861       NEWFLAG (LINK_ORDER),
1862       NEWFLAG (OS_NONCONFORMING),
1863       NEWFLAG (GROUP),
1864       NEWFLAG (TLS)
1865     };
1866 #undef NEWFLAG
1867   const size_t nknown_flags = sizeof (known_flags) / sizeof (known_flags[0]);
1868 
1869   char *cp = buf;
1870   size_t cnt;
1871 
1872   for (cnt = 0; cnt < nknown_flags; ++cnt)
1873     if (flags & known_flags[cnt].flag)
1874       {
1875 	if (cp != buf && len > 1)
1876 	  {
1877 	    *cp++ = '|';
1878 	    --len;
1879 	  }
1880 
1881 	size_t ncopy = MIN (len - 1, strlen (known_flags[cnt].name));
1882 	cp = mempcpy (cp, known_flags[cnt].name, ncopy);
1883 	len -= ncopy;
1884 
1885 	flags ^= known_flags[cnt].flag;
1886       }
1887 
1888   if (flags != 0 || cp == buf)
1889     snprintf (cp, len - 1, "%" PRIx64, (uint64_t) flags);
1890 
1891   *cp = '\0';
1892 
1893   return buf;
1894 }
1895 
1896 
1897 static void
check_versym(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Shdr * shdr,int idx)1898 check_versym (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Shdr *shdr, int idx)
1899 {
1900   /* The number of elements in the version symbol table must be the
1901      same as the number of symbols.  */
1902   GElf_Shdr symshdr_mem;
1903   GElf_Shdr *symshdr = gelf_getshdr (elf_getscn (ebl->elf, shdr->sh_link),
1904 				     &symshdr_mem);
1905   if (symshdr == NULL)
1906     /* The error has already been reported.  */
1907     return;
1908 
1909   if (symshdr->sh_type != SHT_DYNSYM)
1910     {
1911       ERROR (gettext ("\
1912 section [%2d] '%s' refers in sh_link to section [%2d] '%s' which is no dynamic symbol table\n"),
1913 	     idx, section_name (ebl, ehdr, idx),
1914 	     shdr->sh_link, section_name (ebl, ehdr, shdr->sh_link));
1915       return;
1916     }
1917 
1918   if (shdr->sh_size / shdr->sh_entsize
1919       != symshdr->sh_size / symshdr->sh_entsize)
1920     ERROR (gettext ("\
1921 section [%2d] '%s' has different number of entries than symbol table [%2d] '%s'\n"),
1922 	   idx, section_name (ebl, ehdr, idx),
1923 	   shdr->sh_link, section_name (ebl, ehdr, shdr->sh_link));
1924 
1925   // XXX TODO A lot more tests
1926   // check value of the fields.  local symbols must have zero entries.
1927   // nonlocal symbols refer to valid version.  Check that version index
1928   // in bound.
1929 }
1930 
1931 
1932 static void
check_sections(Ebl * ebl,GElf_Ehdr * ehdr)1933 check_sections (Ebl *ebl, GElf_Ehdr *ehdr)
1934 {
1935   GElf_Shdr shdr_mem;
1936   GElf_Shdr *shdr;
1937   size_t cnt;
1938   bool dot_interp_section = false;
1939 
1940   if (ehdr->e_shoff == 0)
1941     /* No section header.  */
1942     return;
1943 
1944   /* Allocate array to count references in section groups.  */
1945   scnref = (int *) xcalloc (shnum, sizeof (int));
1946 
1947   /* Check the zeroth section first.  It must not have any contents
1948      and the section header must contain nonzero value at most in the
1949      sh_size and sh_link fields.  */
1950   shdr = gelf_getshdr (elf_getscn (ebl->elf, 0), &shdr_mem);
1951   if (shdr == NULL)
1952     ERROR (gettext ("cannot get section header of zeroth section\n"));
1953   else
1954     {
1955       if (shdr->sh_name != 0)
1956 	ERROR (gettext ("zeroth section has nonzero name\n"));
1957       if (shdr->sh_type != 0)
1958 	ERROR (gettext ("zeroth section has nonzero type\n"));
1959       if (shdr->sh_flags != 0)
1960 	ERROR (gettext ("zeroth section has nonzero flags\n"));
1961       if (shdr->sh_addr != 0)
1962 	ERROR (gettext ("zeroth section has nonzero address\n"));
1963       if (shdr->sh_offset != 0)
1964 	ERROR (gettext ("zeroth section has nonzero offset\n"));
1965       if (shdr->sh_info != 0)
1966 	ERROR (gettext ("zeroth section has nonzero info field\n"));
1967       if (shdr->sh_addralign != 0)
1968 	ERROR (gettext ("zeroth section has nonzero align value\n"));
1969       if (shdr->sh_entsize != 0)
1970 	ERROR (gettext ("zeroth section has nonzero entry size value\n"));
1971 
1972       if (shdr->sh_size != 0 && ehdr->e_shnum != 0)
1973 	ERROR (gettext ("\
1974 zeroth section has nonzero size value while ELF header has nonzero shnum value\n"));
1975 
1976       if (shdr->sh_link != 0 && ehdr->e_shstrndx != SHN_XINDEX)
1977 	ERROR (gettext ("\
1978 zeroth section has nonzero link value while ELF header does not signal overflow in shstrndx\n"));
1979     }
1980 
1981   for (cnt = 1; cnt < shnum; ++cnt)
1982     {
1983       Elf_Scn *scn;
1984 
1985       scn = elf_getscn (ebl->elf, cnt);
1986       shdr = gelf_getshdr (scn, &shdr_mem);
1987       if (shdr == NULL)
1988 	{
1989 	  ERROR (gettext ("\
1990 cannot get section header for section [%2zu] '%s': %s\n"),
1991 		 cnt, section_name (ebl, ehdr, cnt), elf_errmsg (-1));
1992 	  continue;
1993 	}
1994 
1995       const char *scnname = elf_strptr (ebl->elf, shstrndx, shdr->sh_name);
1996 
1997       if (scnname == NULL)
1998 	ERROR (gettext ("section [%2zu]: invalid name\n"), cnt);
1999       else
2000 	{
2001 	  /* Check whether it is one of the special sections defined in
2002 	     the gABI.  */
2003 	  size_t s;
2004 	  for (s = 0; s < nspecial_sections; ++s)
2005 	    if (strncmp (scnname, special_sections[s].name,
2006 			 special_sections[s].namelen) == 0)
2007 	      {
2008 		char stbuf1[100];
2009 		char stbuf2[100];
2010 		char stbuf3[100];
2011 
2012 		if (shdr->sh_type != special_sections[s].type)
2013 		  ERROR (gettext ("\
2014 section [%2d] '%s' has wrong type: expected %s, is %s\n"),
2015 			 (int) cnt, scnname,
2016 			 ebl_section_type_name (ebl, special_sections[s].type,
2017 						stbuf1, sizeof (stbuf1)),
2018 			 ebl_section_type_name (ebl, shdr->sh_type,
2019 						stbuf2, sizeof (stbuf2)));
2020 
2021 		if (special_sections[s].attrflag == exact)
2022 		  {
2023 		    /* Except for the link order and group bit all the
2024 		       other bits should match exactly.  */
2025 		    if ((shdr->sh_flags & ~(SHF_LINK_ORDER | SHF_GROUP))
2026 			!= special_sections[s].attr)
2027 		      ERROR (gettext ("\
2028 section [%2zu] '%s' has wrong flags: expected %s, is %s\n"),
2029 			     cnt, scnname,
2030 			     section_flags_string (special_sections[s].attr,
2031 						   stbuf1, sizeof (stbuf1)),
2032 			     section_flags_string (shdr->sh_flags
2033 						   & ~SHF_LINK_ORDER,
2034 						   stbuf2, sizeof (stbuf2)));
2035 		  }
2036 		else if (special_sections[s].attrflag == atleast)
2037 		  {
2038 		    if ((shdr->sh_flags & special_sections[s].attr)
2039 			!= special_sections[s].attr
2040 			|| ((shdr->sh_flags & ~(SHF_LINK_ORDER | SHF_GROUP
2041 						| special_sections[s].attr
2042 						| special_sections[s].attr2))
2043 			    != 0))
2044 		      ERROR (gettext ("\
2045 section [%2zu] '%s' has wrong flags: expected %s and possibly %s, is %s\n"),
2046 			     cnt, scnname,
2047 			     section_flags_string (special_sections[s].attr,
2048 						   stbuf1, sizeof (stbuf1)),
2049 			     section_flags_string (special_sections[s].attr2,
2050 						   stbuf2, sizeof (stbuf2)),
2051 			     section_flags_string (shdr->sh_flags
2052 						   & ~(SHF_LINK_ORDER
2053 						       | SHF_GROUP),
2054 						   stbuf3, sizeof (stbuf3)));
2055 		  }
2056 
2057 		if (strcmp (scnname, ".interp") == 0)
2058 		  {
2059 		    dot_interp_section = true;
2060 
2061 		    if (ehdr->e_type == ET_REL)
2062 		      ERROR (gettext ("\
2063 section [%2zu] '%s' present in object file\n"),
2064 			     cnt, scnname);
2065 
2066 		    if ((shdr->sh_flags & SHF_ALLOC) != 0
2067 			&& !has_loadable_segment)
2068 		      ERROR (gettext ("\
2069 section [%2zu] '%s' has SHF_ALLOC flag set but there is no loadable segment\n"),
2070 			     cnt, scnname);
2071 		    else if ((shdr->sh_flags & SHF_ALLOC) == 0
2072 			     && has_loadable_segment)
2073 		      ERROR (gettext ("\
2074 section [%2zu] '%s' has SHF_ALLOC flag not set but there are loadable segments\n"),
2075 			     cnt, scnname);
2076 		  }
2077 		else
2078 		  {
2079 		    if (strcmp (scnname, ".symtab_shndx") == 0
2080 			&& ehdr->e_type != ET_REL)
2081 		      ERROR (gettext ("\
2082 section [%2zu] '%s' is extension section index table in non-object file\n"),
2083 			     cnt, scnname);
2084 
2085 		    /* These sections must have the SHF_ALLOC flag set iff
2086 		       a loadable segment is available.
2087 
2088 		       .relxxx
2089 		       .strtab
2090 		       .symtab
2091 		       .symtab_shndx
2092 
2093 		       Check that if there is a reference from the
2094 		       loaded section these sections also have the
2095 		       ALLOC flag set.  */
2096 #if 0
2097 		    // XXX TODO
2098 		    if ((shdr->sh_flags & SHF_ALLOC) != 0
2099 			&& !has_loadable_segment)
2100 		      ERROR (gettext ("\
2101 section [%2zu] '%s' has SHF_ALLOC flag set but there is no loadable segment\n"),
2102 			     cnt, scnname);
2103 		    else if ((shdr->sh_flags & SHF_ALLOC) == 0
2104 			     && has_loadable_segment)
2105 		      ERROR (gettext ("\
2106 section [%2zu] '%s' has SHF_ALLOC flag not set but there are loadable segments\n"),
2107 			     cnt, scnname);
2108 #endif
2109 		  }
2110 
2111 		break;
2112 	      }
2113 	}
2114 
2115       if (shdr->sh_entsize != 0 && shdr->sh_size % shdr->sh_entsize)
2116 	ERROR (gettext ("\
2117 section [%2zu] '%s': size not multiple of entry size\n"),
2118 	       cnt, section_name (ebl, ehdr, cnt));
2119 
2120       if (elf_strptr (ebl->elf, shstrndx, shdr->sh_name) == NULL)
2121 	ERROR (gettext ("cannot get section header\n"));
2122 
2123       if (shdr->sh_type >= SHT_NUM
2124 	  && shdr->sh_type != SHT_GNU_LIBLIST
2125 	  && shdr->sh_type != SHT_CHECKSUM
2126 	  && shdr->sh_type != SHT_GNU_verdef
2127 	  && shdr->sh_type != SHT_GNU_verneed
2128 	  && shdr->sh_type != SHT_GNU_versym)
2129 	ERROR (gettext ("unsupported section type %d\n"), (int) shdr->sh_type);
2130 
2131 #define ALL_SH_FLAGS (SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR | SHF_MERGE \
2132 		      | SHF_STRINGS | SHF_INFO_LINK | SHF_LINK_ORDER \
2133 		      | SHF_OS_NONCONFORMING | SHF_GROUP | SHF_TLS)
2134       if (shdr->sh_flags & ~ALL_SH_FLAGS)
2135 	ERROR (gettext ("section [%2zu] '%s' contain unknown flag(s) %d\n"),
2136 	       cnt, section_name (ebl, ehdr, cnt),
2137 	       (int) shdr->sh_flags & ~ALL_SH_FLAGS);
2138       else if (shdr->sh_flags & SHF_TLS)
2139 	{
2140 	  // XXX Correct?
2141 	  if (shdr->sh_addr != 0 && !gnuld)
2142 	    ERROR (gettext ("\
2143 section [%2zu] '%s': thread-local data sections address not zero\n"),
2144 		   cnt, section_name (ebl, ehdr, cnt));
2145 
2146 	  // XXX TODO more tests!?
2147 	}
2148 
2149       if (shdr->sh_link >= shnum)
2150 	ERROR (gettext ("\
2151 section [%2zu] '%s': invalid section reference in link value\n"),
2152 	       cnt, section_name (ebl, ehdr, cnt));
2153 
2154       if (SH_INFO_LINK_P (shdr) && shdr->sh_info >= shnum)
2155 	ERROR (gettext ("\
2156 section [%2zu] '%s': invalid section reference in info value\n"),
2157 	       cnt, section_name (ebl, ehdr, cnt));
2158 
2159       if ((shdr->sh_flags & SHF_MERGE) == 0
2160 	  && (shdr->sh_flags & SHF_STRINGS) != 0
2161 	  && be_strict)
2162 	ERROR (gettext ("\
2163 section [%2zu] '%s': strings flag set without merge flag\n"),
2164 	       cnt, section_name (ebl, ehdr, cnt));
2165 
2166       if ((shdr->sh_flags & SHF_MERGE) != 0 && shdr->sh_entsize == 0)
2167 	ERROR (gettext ("\
2168 section [%2zu] '%s': merge flag set but entry size is zero\n"),
2169 	       cnt, section_name (ebl, ehdr, cnt));
2170 
2171       if (shdr->sh_flags & SHF_GROUP)
2172 	check_scn_group (ebl, ehdr, cnt);
2173 
2174       if (ehdr->e_type != ET_REL && (shdr->sh_flags & SHF_ALLOC) != 0)
2175 	{
2176 	  /* Make sure the section is contained in a loaded segment
2177 	     and that the initialization part matches NOBITS sections.  */
2178 	  int pcnt;
2179 	  GElf_Phdr phdr_mem;
2180 	  GElf_Phdr *phdr;
2181 
2182 	  for (pcnt = 0; pcnt < ehdr->e_phnum; ++pcnt)
2183 	    if ((phdr = gelf_getphdr (ebl->elf, pcnt, &phdr_mem)) != NULL
2184 		&& ((phdr->p_type == PT_LOAD
2185 		     && (shdr->sh_flags & SHF_TLS) == 0)
2186 		    || (phdr->p_type == PT_TLS
2187 			&& (shdr->sh_flags & SHF_TLS) != 0))
2188 		&& phdr->p_offset <= shdr->sh_offset
2189 		&& phdr->p_offset + phdr->p_memsz > shdr->sh_offset)
2190 	      {
2191 		/* Found the segment.  */
2192 		if (phdr->p_offset + phdr->p_memsz
2193 		    < shdr->sh_offset + shdr->sh_size)
2194 		  ERROR (gettext ("\
2195 section [%2zu] '%s' not fully contained in segment of program header entry %d\n"),
2196 			 cnt, section_name (ebl, ehdr, cnt), pcnt);
2197 
2198 		if (shdr->sh_type == SHT_NOBITS)
2199 		  {
2200 		    if (shdr->sh_offset < phdr->p_offset + phdr->p_filesz)
2201 		      ERROR (gettext ("\
2202 section [%2zu] '%s' has type NOBITS but is read from the file in segment of program header entry %d\n"),
2203 			 cnt, section_name (ebl, ehdr, cnt), pcnt);
2204 		  }
2205 		else
2206 		  {
2207 		    if (shdr->sh_offset >= phdr->p_offset + phdr->p_filesz)
2208 		      ERROR (gettext ("\
2209 section [%2zu] '%s' has not type NOBITS but is not read from the file in segment of program header entry %d\n"),
2210 			 cnt, section_name (ebl, ehdr, cnt), pcnt);
2211 		  }
2212 
2213 		break;
2214 	      }
2215 
2216 	  if (pcnt == ehdr->e_phnum)
2217 	    ERROR (gettext ("\
2218 section [%2zu] '%s': alloc flag set but section not in any loaded segment\n"),
2219 		   cnt, section_name (ebl, ehdr, cnt));
2220 	}
2221 
2222       if (cnt == shstrndx && shdr->sh_type != SHT_STRTAB)
2223 	ERROR (gettext ("\
2224 section [%2zu] '%s': ELF header says this is the section header string table but type is not SHT_TYPE\n"),
2225 	       cnt, section_name (ebl, ehdr, cnt));
2226 
2227       switch (shdr->sh_type)
2228 	{
2229 	case SHT_SYMTAB:
2230 	case SHT_DYNSYM:
2231 	  check_symtab (ebl, ehdr, cnt);
2232 	  break;
2233 
2234 	case SHT_RELA:
2235 	  check_rela (ebl, ehdr, cnt);
2236 	  break;
2237 
2238 	case SHT_REL:
2239 	  check_rel (ebl, ehdr, cnt);
2240 	  break;
2241 
2242 	case SHT_DYNAMIC:
2243 	  check_dynamic (ebl, ehdr, cnt);
2244 	  break;
2245 
2246 	case SHT_SYMTAB_SHNDX:
2247 	  check_symtab_shndx (ebl, ehdr, cnt);
2248 	  break;
2249 
2250 	case SHT_HASH:
2251 	  check_hash (ebl, ehdr, cnt);
2252 	  break;
2253 
2254 	case SHT_NULL:
2255 	  check_null (ebl, ehdr, shdr, cnt);
2256 	  break;
2257 
2258 	case SHT_GROUP:
2259 	  check_group (ebl, ehdr, shdr, cnt);
2260 	  break;
2261 
2262 	case SHT_GNU_versym:
2263 	  check_versym (ebl, ehdr, shdr, cnt);
2264 	  break;
2265 
2266 	default:
2267 	  /* Nothing.  */
2268 	  break;
2269 	}
2270     }
2271 
2272   if (has_interp_segment && !dot_interp_section)
2273     ERROR (gettext ("INTERP program header entry but no .interp section\n"));
2274 
2275   free (scnref);
2276 }
2277 
2278 
2279 static void
check_note(Ebl * ebl,GElf_Ehdr * ehdr,GElf_Phdr * phdr,int cnt)2280 check_note (Ebl *ebl, GElf_Ehdr *ehdr, GElf_Phdr *phdr, int cnt)
2281 {
2282   if (ehdr->e_type != ET_CORE && ehdr->e_type != ET_REL
2283       && ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN)
2284     ERROR (gettext ("\
2285 phdr[%d]: no note entries defined for the type of file\n"),
2286 	   cnt);
2287 
2288   char *notemem = gelf_rawchunk (ebl->elf, phdr->p_offset, phdr->p_filesz);
2289 
2290   /* ELF64 files often use note section entries in the 32-bit format.
2291      The p_align field is set to 8 in case the 64-bit format is used.
2292      In case the p_align value is 0 or 4 the 32-bit format is
2293      used.  */
2294   GElf_Xword align = phdr->p_align == 0 || phdr->p_align == 4 ? 4 : 8;
2295 #define ALIGNED_LEN(len) (((len) + align - 1) & ~(align - 1))
2296 
2297   GElf_Xword idx = 0;
2298   while (idx < phdr->p_filesz)
2299     {
2300       uint64_t namesz;
2301       uint64_t descsz;
2302       uint64_t type;
2303       uint32_t namesz32;
2304       uint32_t descsz32;
2305 
2306       if (align == 4)
2307 	{
2308 	  uint32_t *ptr = (uint32_t *) (notemem + idx);
2309 
2310 	  if ((__BYTE_ORDER == __LITTLE_ENDIAN
2311 	       && ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
2312 	      || (__BYTE_ORDER == __BIG_ENDIAN
2313 		  && ehdr->e_ident[EI_DATA] == ELFDATA2LSB))
2314 	    {
2315 	      namesz32 = namesz = bswap_32 (*ptr);
2316 	      ++ptr;
2317 	      descsz32 = descsz = bswap_32 (*ptr);
2318 	      ++ptr;
2319 	      type = bswap_32 (*ptr);
2320 	    }
2321 	  else
2322 	    {
2323 	      namesz32 = namesz = *ptr++;
2324 	      descsz32 = descsz = *ptr++;
2325 	      type = *ptr;
2326 	    }
2327 	}
2328       else
2329 	{
2330 	  uint64_t *ptr = (uint64_t *) (notemem + idx);
2331 	  uint32_t *ptr32 = (uint32_t *) (notemem + idx);
2332 
2333 	  if ((__BYTE_ORDER == __LITTLE_ENDIAN
2334 	       && ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
2335 	      || (__BYTE_ORDER == __BIG_ENDIAN
2336 		  && ehdr->e_ident[EI_DATA] == ELFDATA2LSB))
2337 	    {
2338 	      namesz = bswap_64 (*ptr);
2339 	      ++ptr;
2340 	      descsz = bswap_64 (*ptr);
2341 	      ++ptr;
2342 	      type = bswap_64 (*ptr);
2343 
2344 	      namesz32 = bswap_32 (*ptr32);
2345 	      ++ptr32;
2346 	      descsz32 = bswap_32 (*ptr32);
2347 	    }
2348 	  else
2349 	    {
2350 	      namesz = *ptr++;
2351 	      descsz = *ptr++;
2352 	      type = *ptr;
2353 
2354 	      namesz32 = *ptr32++;
2355 	      descsz32 = *ptr32;
2356 	    }
2357 	}
2358 
2359       if (idx + 3 * align > phdr->p_filesz
2360 	  || (idx + 3 * align + ALIGNED_LEN (namesz) + ALIGNED_LEN (descsz)
2361 	      > phdr->p_filesz))
2362 	{
2363 	  if (ehdr->e_ident[EI_CLASS] == ELFCLASS64
2364 	      && idx + 3 * 4 <= phdr->p_filesz
2365 	      && (idx + 3 * 4 + ALIGNED_LEN (namesz32) + ALIGNED_LEN (descsz32)
2366 		  <= phdr->p_filesz))
2367 	    ERROR (gettext ("\
2368 phdr[%d]: note entries probably in form of a 32-bit ELF file\n"), cnt);
2369 	  else
2370 	    ERROR (gettext ("phdr[%d]: extra %zu bytes after last note\n"),
2371 		   cnt, (size_t) (phdr->p_filesz - idx));
2372 	  break;
2373 	}
2374 
2375       /* Make sure it is one of the note types we know about.  */
2376       if (ehdr->e_type == ET_CORE)
2377 	{
2378 	  switch (type)
2379 	    {
2380 	    case NT_PRSTATUS:
2381 	    case NT_FPREGSET:
2382 	    case NT_PRPSINFO:
2383 	    case NT_TASKSTRUCT:		/* NT_PRXREG on Solaris.  */
2384 	    case NT_PLATFORM:
2385 	    case NT_AUXV:
2386 	    case NT_GWINDOWS:
2387 	    case NT_ASRS:
2388 	    case NT_PSTATUS:
2389 	    case NT_PSINFO:
2390 	    case NT_PRCRED:
2391 	    case NT_UTSNAME:
2392 	    case NT_LWPSTATUS:
2393 	    case NT_LWPSINFO:
2394 	    case NT_PRFPXREG:
2395 	      /* Known type.  */
2396 	      break;
2397 
2398 	    default:
2399 	      ERROR (gettext ("\
2400 phdr[%d]: unknown core file note type %" PRIu64 " at offset %" PRIu64 "\n"),
2401 		     cnt, type, idx);
2402 	    }
2403 	}
2404       else
2405 	{
2406 	  if (type != NT_VERSION)
2407 	    ERROR (gettext ("\
2408 phdr[%d]: unknown object file note type %" PRIu64 " at offset %" PRIu64 "\n"),
2409 		   cnt, type, idx);
2410 	}
2411 
2412       /* Move to the next entry.  */
2413       idx += 3 * align + ALIGNED_LEN (namesz) + ALIGNED_LEN (descsz);
2414 
2415     }
2416 
2417   gelf_freechunk (ebl->elf, notemem);
2418 }
2419 
2420 
2421 static void
check_program_header(Ebl * ebl,GElf_Ehdr * ehdr)2422 check_program_header (Ebl *ebl, GElf_Ehdr *ehdr)
2423 {
2424   if (ehdr->e_phoff == 0)
2425     return;
2426 
2427   if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN
2428       && ehdr->e_type != ET_CORE)
2429     ERROR (gettext ("\
2430 only executables, shared objects, and core files can have program headers\n"));
2431 
2432   int num_pt_interp = 0;
2433   int num_pt_tls = 0;
2434   int num_pt_relro = 0;
2435 
2436   for (int cnt = 0; cnt < ehdr->e_phnum; ++cnt)
2437     {
2438       GElf_Phdr phdr_mem;
2439       GElf_Phdr *phdr;
2440 
2441       phdr = gelf_getphdr (ebl->elf, cnt, &phdr_mem);
2442       if (phdr == NULL)
2443 	{
2444 	  ERROR (gettext ("cannot get program header entry %d: %s\n"),
2445 		 cnt, elf_errmsg (-1));
2446 	  continue;
2447 	}
2448 
2449       if (phdr->p_type >= PT_NUM && phdr->p_type != PT_GNU_EH_FRAME
2450 	  && phdr->p_type != PT_GNU_STACK)
2451 	ERROR (gettext ("\
2452 program header entry %d: unknown program header entry type\n"),
2453 	       cnt);
2454 
2455       if (phdr->p_type == PT_LOAD)
2456 	has_loadable_segment = true;
2457       else if (phdr->p_type == PT_INTERP)
2458 	{
2459 	  if (++num_pt_interp != 1)
2460 	    {
2461 	      if (num_pt_interp == 2)
2462 		ERROR (gettext ("\
2463 more than one INTERP entry in program header\n"));
2464 	    }
2465 	  has_interp_segment = true;
2466 	}
2467       else if (phdr->p_type == PT_TLS)
2468 	{
2469 	  if (++num_pt_tls == 2)
2470 	    ERROR (gettext ("more than one TLS entry in program header\n"));
2471 	}
2472       else if (phdr->p_type == PT_NOTE)
2473 	check_note (ebl, ehdr, phdr, cnt);
2474       else if (phdr->p_type == PT_DYNAMIC
2475 	       && ehdr->e_type == ET_EXEC && ! has_interp_segment)
2476 	ERROR (gettext ("static executable cannot have dynamic sections\n"));
2477       else if (phdr->p_type == PT_GNU_RELRO)
2478 	{
2479 	  if (++num_pt_relro == 2)
2480 	    ERROR (gettext ("\
2481 more than one GNU_RELRO entry in program header\n"));
2482 	  else
2483 	    {
2484 	      /* Check that the region is in a writable segment.  */
2485 	      int inner;
2486 	      for (inner = 0; inner < ehdr->e_phnum; ++inner)
2487 		{
2488 		  GElf_Phdr phdr2_mem;
2489 		  GElf_Phdr *phdr2;
2490 
2491 		  phdr2 = gelf_getphdr (ebl->elf, cnt, &phdr2_mem);
2492 		  if (phdr2 == NULL)
2493 		    continue;
2494 
2495 		  if (phdr2->p_type == PT_LOAD
2496 		      && phdr->p_vaddr >= phdr2->p_vaddr
2497 		      && (phdr->p_vaddr + phdr->p_memsz
2498 			  <= phdr2->p_vaddr + phdr2->p_memsz))
2499 		    {
2500 		      if ((phdr2->p_flags & PF_W) == 0)
2501 			ERROR (gettext ("\
2502 loadable segment GNU_RELRO applies to is not writable\n"));
2503 		      if ((phdr2->p_flags & PF_X) != 0)
2504 			ERROR (gettext ("\
2505 loadable segment GNU_RELRO applies to is executable\n"));
2506 		      break;
2507 		    }
2508 		}
2509 
2510 	      if (inner >= ehdr->e_phnum)
2511 		ERROR (gettext ("\
2512 GNU_RELRO segment not contained in a loaded segment\n"));
2513 	    }
2514 	}
2515 
2516       if (phdr->p_filesz > phdr->p_memsz)
2517 	ERROR (gettext ("\
2518 program header entry %d: file size greater than memory size\n"),
2519 	       cnt);
2520 
2521       if (phdr->p_align > 1)
2522 	{
2523 	  if (!powerof2 (phdr->p_align))
2524 	    ERROR (gettext ("\
2525 program header entry %d: alignment not a power of 2\n"), cnt);
2526 	  else if ((phdr->p_vaddr - phdr->p_offset) % phdr->p_align != 0)
2527 	    ERROR (gettext ("\
2528 program header entry %d: file offset and virtual address not module of alignment\n"), cnt);
2529 	}
2530     }
2531 }
2532 
2533 
2534 /* Process one file.  */
2535 static void
process_elf_file(Elf * elf,const char * prefix,const char * suffix,const char * fname,size_t size,bool only_one)2536 process_elf_file (Elf *elf, const char *prefix, const char *suffix,
2537 		  const char *fname, size_t size, bool only_one)
2538 {
2539   /* Reset variables.  */
2540   ndynamic = 0;
2541 
2542   GElf_Ehdr ehdr_mem;
2543   GElf_Ehdr *ehdr = gelf_getehdr (elf, &ehdr_mem);
2544   Ebl *ebl;
2545 
2546   /* Print the file name.  */
2547   if (!only_one)
2548     {
2549       if (prefix != NULL)
2550 	printf ("\n%s(%s)%s:\n", prefix, fname, suffix);
2551       else
2552 	printf ("\n%s:\n", fname);
2553     }
2554 
2555   if (ehdr == NULL)
2556     {
2557       ERROR (gettext ("cannot read ELF header: %s\n"), elf_errmsg (-1));
2558       return;
2559     }
2560 
2561   ebl = ebl_openbackend (elf);
2562   /* If there is no appropriate backend library we cannot test
2563      architecture and OS specific features.  Any encountered extension
2564      is an error.  */
2565 
2566   /* Go straight by the gABI, check all the parts in turn.  */
2567   check_elf_header (ebl, ehdr, size);
2568 
2569   /* Check the program header.  */
2570   check_program_header (ebl, ehdr);
2571 
2572   /* Next the section headers.  It is OK if there are no section
2573      headers at all.  */
2574   check_sections (ebl, ehdr);
2575 
2576   /* Free the resources.  */
2577   ebl_closebackend (ebl);
2578 }
2579