Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect at runtime whether symbols are stripped?

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 definition which returns true if stripped, otherwise false.

Would using dlsym() on "main()" work to detect this reliably?

like image 981
WilliamKF Avatar asked Feb 28 '11 16:02

WilliamKF


2 Answers

I know the file command can tell the difference, so you could possibly look at its source to see what mechanism it uses.

like image 153
Mark B Avatar answered Sep 21 '22 16:09

Mark B


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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

/* Include for ELF processing */
#include <libelf.h>
#include <gelf.h>

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);
}
like image 21
jschmier Avatar answered Sep 18 '22 16:09

jschmier