Search code examples
clinkerllvmglibcllvm-ir

How does my compiler find the stat (file status) function?


I have the following C program:

#include <sys/stat.h>

int main(int argc, char **argv) {
    struct stat fileStat;
    if(stat(argv[1],&fileStat) < 0)    
        return 1;
}

When I compile it to LLVM IR using Clang, I can see that stat is declared as following:

declare i32 @stat(i8*, %struct.stat*)

Usually, such an external call to a system function directly maps to a C standard library function. For example, I can find malloc with the following:

nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep malloc

However, the stat function seems to be treated differently. When grepping for stat, I can find related functions such as __xstat but not the stat function itself.

When I trace the call to the external library with ltrace I see the following call: __xstat(1, ".", 0x7fff7928c6f0). Also the code in the executable confirms that instead of calling the stat function the __xstat function is called.

I did not observe other function calls to the C standard library that have other names than those declared in the C program. Why is there no direct equivalent in the standard library and how does my compiler find out that it should produce a call to __xstat and not to stat?


Solution

  • Header sys/stat.h defines stat as a macro that calls __xstat in glibc:

    #define stat(fname, buf) __xstat (_STAT_VER, fname, buf)