Search code examples
cgccglibcaddr2line

glibc function to retrieve current executable name?


i'm wondering if there is a glibc function that i can use from gcc/g++ that will retrieve the current executable.

The purpose of this is to provide the -e argument to addr2line as shown in this answer


Solution

  • In standard C and glibc, you have argv[0]:

    int main (int argc, char *argv[])
    

    the first element of the argv array is the program name.

    However it's not necessarily enough on its own to determine where exactly the executable is. The argument is actually set by the program that ran your program - be it a shell or a window manager - and they aren't terribly helpful. If your program is in the path and you run the program simply with

    your_program

    at a bash shell, then "your_program" is all you will get in argv[0].

    For the full executable path, linux has the /proc filesystem. Under /proc each running process gets its own "directory", named by its process id. The running process can also see its own subtree under /proc/self. One of the files that each process gets is /proc/[pid]/exe, which is a symbolic link to the actual executable the process is running.

    So you can get the actual full executable path like this:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int main(void) {
        char exe[1024];
        int ret;
    
        ret = readlink("/proc/self/exe",exe,sizeof(exe)-1);
        if(ret ==-1) {
            fprintf(stderr,"ERRORRRRR\n");
            exit(1);
        }
        exe[ret] = 0;
        printf("I am %s\n",exe);
    }
    

    You may also be able to pass /proc/[pid]/exe directly to addr2line().