Skip to content

Instantly share code, notes, and snippets.

@ammarfaizi2
Last active May 20, 2025 09:24
Show Gist options
  • Save ammarfaizi2/1e1424f987cfbe3e3c3b571b6e590923 to your computer and use it in GitHub Desktop.
Save ammarfaizi2/1e1424f987cfbe3e3c3b571b6e590923 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
static FILE *log_file = NULL;
static void init_log(void)
{
const char *log_path;
if (log_file)
return;
log_path = getenv("GWLOG_PATH");
if (!log_path)
log_path = "/dev/null";
log_file = fopen(log_path, "a");
assert(log_file);
}
int open(const char *file, int flags, int mode)
{
int fd;
__asm__ volatile (
"syscall"
: "=a" (fd) /* %rax */
: "a" (2), /* %rax */
"D" (file), /* %rdi */
"S" (flags), /* %rsi */
"d" (mode) /* %rdx */
: "memory", "rcx", "r11", "cc"
);
init_log();
fprintf(log_file, "open(\"%s\", %d, %d) = %d\n", file, flags, mode, fd);
fflush(log_file);
if (fd < 0) {
errno = -fd;
fd = -1;
}
return fd;
}
int openat(int fd, const char *file, int flags, int mode)
{
register int __mode __asm__("%r10") = mode;
int fd2;
__asm__ volatile (
"syscall"
: "=a" (fd2) /* %rax */
: "a" (257), /* %rax */
"D" (fd), /* %rdi */
"S" (file), /* %rsi */
"d" (flags), /* %rdx */
"r" (__mode) /* %r10 */
: "memory", "rcx", "r11", "cc"
);
init_log();
fprintf(log_file, "openat(%d, %s, %d, %d) = %d\n", fd, file, flags, mode, fd2);
fflush(log_file);
if (fd2 < 0) {
errno = -fd2;
fd2 = -1;
}
return fd2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment