In my C++ program, how can I detect programmatically at runtime whether symbols have been stripped via the \'strip\' gnu development tool on Linux?
I\'d like a function
From a comment left for another answer:
A stripped ELF will lack a .symtab
entry. The file
command traverses through all the ELF section headers until a symbol table section is found. If one cannot be found, the binary is considered stripped.
The libelf library allows a program to manipulate ELF object files, archive files, and archive members. The elf(3E) man pages provide documentation related to using the library. The following code provides an example on determining if the executable is stripped by looking for the existence of a symbol table section (.symtab
).
#include
#include
#include
#include
/* Include for ELF processing */
#include
#include
int main(int argc, char ** argv)
{
int fd;
const char *file = argv[0];
Elf *elf; /* ELF pointer for libelf */
Elf_Scn *scn; /* section descriptor pointer */
GElf_Shdr shdr; /* section header */
/* Open ELF file to obtain file descriptor */
if((fd = open(file, O_RDONLY)) < 0)
{
fprintf(stderr, "Error opening file %s\n", file);
exit(EXIT_FAILURE);
}
/* Protect program from using an older library */
if(elf_version(EV_CURRENT) == EV_NONE)
{
fprintf(stderr, "WARNING - ELF Library is out of date!\n");
exit(EXIT_FAILURE);
}
/* Initialize elf pointer for examining contents of file */
elf = elf_begin(fd, ELF_C_READ, NULL);
/* Initialize section descriptor pointer so that elf_nextscn()
* returns a pointer to the section descriptor at index 1. */
scn = NULL;
/* Iterate through ELF sections */
while((scn = elf_nextscn(elf, scn)) != NULL)
{
/* Retrieve section header */
gelf_getshdr(scn, &shdr);
/* If a section header holding a symbol table (.symtab)
* is found, this ELF file has not been stripped. */
if(shdr.sh_type == SHT_SYMTAB)
{
printf("NOT STRIPPED\n");
break;
}
}
elf_end(elf);
close(fd);
exit(EXIT_SUCCESS);
}