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