Mocking the `open()` system call in C - generating coverage fails

58 Views Asked by At

I've encountered some strange behaviour generating code coverage with gcov while mocking out, specifically, the open() system call, like this:

// my-coverage.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const char *open_file_arg = NULL;
int open_oflag_arg = -1;
int open_return_value = -1;

int open(const char *file, int oflag, ...)
{
    open_file_arg = file;
    open_oflag_arg = oflag;
    return open_return_value;
}

int main()
{
    int file = open("./foo", O_RDWR, 0644);
}
$ make CFLAGS=--coverage LDFLAGS=--coverage my-coverage
cc --coverage  --coverage  my-coverage.c   -o my-coverage
$ ./my-coverage 
profiling:/home/deck/playground/my-coverage.gcda:Cannot open
$ 

Other system calls work fine:

// my-coverage.c
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int pread_fd_arg = -1;
void *pread_buf_arg = NULL;
size_t pread_count_arg = 0;
off_t pread_offset_arg = -1;
ssize_t pread_return_value = -1;

ssize_t pread(int fd, void *buf, size_t count, off_t offset)
{
    pread_fd_arg = fd;
    pread_buf_arg = buf;
    pread_count_arg = count;
    pread_offset_arg = offset;
    return pread_return_value;
}

int main()
{
    ssize_t result = pread(0, 0, 0, 0);
}

$ make CFLAGS=--coverage LDFLAGS=--coverage my-coverage
cc --coverage  --coverage  my-coverage.c   -o my-coverage
$ ./my-coverage 
$ gcov my-coverage.gcda 
File 'my-coverage.c'
Lines executed:100.00% of 7
Creating 'my-coverage.c.gcov'

File '/usr/include/unistd.h'
Lines executed:100.00% of 1
Creating 'unistd.h.gcov'

Lines executed:100.00% of 8
$ 

As do non-system-call functions which use the variable arguments syntax:

// my-coverage.c

int foo(int bar, ...)
{
    return 0;
}

int main()
{
    return foo(4, 5, 6, 7);
}
$ make CFLAGS=--coverage LDFLAGS=--coverage my-coverage
cc --coverage  --coverage  my-coverage.c   -o my-coverage
$ ./my-coverage 
$ gcov my-coverage.gcda 
File 'my-coverage.c'
Lines executed:100.00% of 4
Creating 'my-coverage.c.gcov'

Lines executed:100.00% of 4
$ 

My question is, why is gcov failing to generate code coverage for open() specifically? I don't understand what the difference is between open() and other system calls I've stubbed, or other library calls I've stubbed. I've not been able to find anything more specific about this issue than, "it affects open()".

0

There are 0 best solutions below