Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From where in libc source code, is open() getting linked?

I basically need to customize few linux system call interfaces (say sys_open) for my purpose. I am very much aware of GNU Linker ld --wrap=symbol option and use that logic to alter the open() libc wrapper. Although that serves the purpose, I really want to know where in libc source codes, the actual implementation comes into play.

The following two places are my major suspects (Note that the fcntrl.h has just the declarations)

  • GLIBC_DIR/io/open.c
  • GLIBC_DIR/ports/sysdeps/unix/sysv/linux/generic/open.c

Sample Driver:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    int fd;

    if ((fd = open("sample.c", O_RDONLY)) == -1) {
        fprintf(stderr, "file not found\n");
        exit(1);
    }

    return 0;
}

Concerned snippet:

main:
  401dd1:       bf 44 90 48 00          mov    $0x489044,%edi
  401dd6:       b8 00 00 00 00          mov    $0x0,%eax
  401ddb:       e8 10 03 03 00          callq  4320f0 <__libc_open>

......
......

 __libc_open:
  4320f0:       83 3d 69 8e 28 00 00    cmpl   $0x0,0x288e69(%rip)        
  4320f7:       75 14                   jne    43210d <__open_nocancel+0x14>

__open_nocancel:
  4320f9:       b8 02 00 00 00          mov    $0x2,%eax
  4320fe:       0f 05                   syscall 

For simplicity, I had prepared all the libc sources executable statically. Also was careful enough to make GCC rightly pick the custom libc.a. I tried adding a puts statement but the mentioned two source codes are NOT getting invoked at all. Taking a look at the assembly of executable [shown above], the sys_open call (0x2 in __open_nocancel) has been somehow placed in the executable.

So my question is the following:

  • From where exactly in libc, the open()-related code logic magically come?
  • How is the linker able to successfully hook the open() function when there is no function explicitly named open in libc source tree?
like image 718
Sandhya Kumar Avatar asked Sep 27 '22 08:09

Sandhya Kumar


1 Answers

From where exactly in libc, the open()-related code logic magically come?

In comes from sysdeps/unix/syscall-template.S

How is the linker able to successfully hook the open() function when there is no function explicitly named open in libc source tree?

If you preprocess above source with correct -DSYSCALL_SYMBOL=..., you'll discover that there is a mention of open in the source.

like image 149
Employed Russian Avatar answered Oct 03 '22 03:10

Employed Russian