1 /* Return number of program headers in the ELF file.
2 Copyright (C) 2010, 2014, 2015 Red Hat, Inc.
3 This file is part of elfutils.
5 This file is free software; you can redistribute it and/or modify
6 it under the terms of either
8 * the GNU Lesser General Public License as published by the Free
9 Software Foundation; either version 3 of the License, or (at
10 your option) any later version
14 * the GNU General Public License as published by the Free
15 Software Foundation; either version 2 of the License, or (at
16 your option) any later version
18 or both in parallel, as here.
20 elfutils is distributed in the hope that it will be useful, but
21 WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 General Public License for more details.
25 You should have received copies of the GNU General Public License and
26 the GNU Lesser General Public License along with this program. If
27 not, see <http://www.gnu.org/licenses/>. */
42 __elf_getphdrnum_rdlock (Elf *elf, size_t *dst)
44 if (unlikely (elf->state.elf64.ehdr == NULL))
46 /* Maybe no ELF header was created yet. */
47 __libelf_seterrno (ELF_E_WRONG_ORDER_EHDR);
51 *dst = (elf->class == ELFCLASS32
52 ? elf->state.elf32.ehdr->e_phnum
53 : elf->state.elf64.ehdr->e_phnum);
57 const Elf_ScnList *const scns = (elf->class == ELFCLASS32
58 ? &elf->state.elf32.scns
59 : &elf->state.elf64.scns);
61 /* If there are no section headers, perhaps this is really just 65536
62 written without PN_XNUM support. Either that or it's bad data. */
64 if (elf->class == ELFCLASS32)
66 if (likely (scns->cnt > 0
67 && elf->state.elf32.scns.data[0].shdr.e32 != NULL))
68 *dst = scns->data[0].shdr.e32->sh_info;
72 if (likely (scns->cnt > 0
73 && elf->state.elf64.scns.data[0].shdr.e64 != NULL))
74 *dst = scns->data[0].shdr.e64->sh_info;
83 __elf_getphdrnum_chk_rdlock (Elf *elf, size_t *dst)
85 int result = __elf_getphdrnum_rdlock (elf, dst);
87 /* Do some sanity checking to make sure phnum and phoff are consistent. */
88 Elf64_Off off = (elf->class == ELFCLASS32
89 ? elf->state.elf32.ehdr->e_phoff
90 : elf->state.elf64.ehdr->e_phoff);
91 if (unlikely (off == 0))
97 if (unlikely (off >= elf->maximum_size))
99 __libelf_seterrno (ELF_E_INVALID_DATA);
103 /* Check for too many sections. */
104 size_t phdr_size = (elf->class == ELFCLASS32
105 ? sizeof (Elf32_Phdr) : sizeof (Elf64_Phdr));
106 if (unlikely (*dst > SIZE_MAX / phdr_size))
108 __libelf_seterrno (ELF_E_INVALID_DATA);
112 /* Truncated file? Don't return more than can be indexed. */
113 if (unlikely (elf->maximum_size - off < *dst * phdr_size))
114 *dst = (elf->maximum_size - off) / phdr_size;
120 elf_getphdrnum (Elf *elf, size_t *dst)
127 if (unlikely (elf->kind != ELF_K_ELF))
129 __libelf_seterrno (ELF_E_INVALID_HANDLE);
133 rwlock_rdlock (elf->lock);
134 result = __elf_getphdrnum_chk_rdlock (elf, dst);
135 rwlock_unlock (elf->lock);