xref: /illumos-gate/usr/src/cmd/sgs/libelf/common/getshnum.c (revision 1a2d662a91cee3bf82f41cd47c7ae6f3825d9db2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <string.h>
27 #include <gelf.h>
28 #include <decl.h>
29 #include <msg.h>
30 
31 
32 /*
33  * Return number of entries in the section header array, taking
34  * extended headers into account.
35  *
36  * elf_getshnum() and elf_getshstrndx() were defined during the 2002 gABI
37  * meetings. They were supposed to return -1 for failure, and 0 for success.
38  * Our manpage documented them as such, but we then implemented them to
39  * return 0 for failure and 1 for success. This makes elf_getshnum() and
40  * elf_getshstrnum() non-portable to systems that implement the 2002 gABI
41  * definition.
42  *
43  * In 2005, the manpage was modified to match the code.
44  * In 2009, the discrepency was identified. elf_getshdrnum() and
45  * elf_getshdrstrndx() were created to provide a portable implementation.
46  * The older two functions are considered to be obsolete, and are retained
47  * for backward compatability.
48  */
49 
50 int
51 elf_getshdrnum(Elf *elf, size_t *shnum)
52 {
53 	GElf_Ehdr	ehdr;
54 	Elf_Scn		*scn;
55 	GElf_Shdr	shdr0;
56 
57 	if (gelf_getehdr(elf, &ehdr) == 0)
58 		return (-1);
59 	if (ehdr.e_shnum > 0) {
60 		*shnum = ehdr.e_shnum;
61 		return (0);
62 	}
63 	if ((ehdr.e_shnum == 0) && (ehdr.e_shoff == 0)) {
64 		*shnum = 0;
65 		return (0);
66 	}
67 	if ((scn = elf_getscn(elf, 0)) == 0)
68 		return (-1);
69 	if (gelf_getshdr(scn, &shdr0) == 0)
70 		return (-1);
71 	*shnum = shdr0.sh_size;
72 	return (0);
73 }
74 
75 int
76 elf_getshnum(Elf *elf, size_t *shnum)
77 {
78 	return (elf_getshdrnum(elf, shnum) == 0);
79 }
80