Last active
June 29, 2021 11:13
-
-
Save rfletchr/7e28dabd169614a879a84711030badff to your computer and use it in GitHub Desktop.
record all open system calls of a program by shimming the open function via LD_PRELOAD
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CC=gcc | |
all: src/shim.c | |
$(CC) -shared -fPIC -o shim.so src/shim.c -ldl |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// required for RTLD_NEXT | |
#define _GNU_SOURCE | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <dlfcn.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <stdarg.h> | |
typedef int (*func_ptr_open)(const char*, int, ...); | |
void write_to_log(const char* prefix, const char* pathname, func_ptr_open original_open){ | |
pid_t pid = getpid(); | |
pid_t tid = gettid(); | |
const char* pattern = "%s/%d_%d.log"; | |
int path_len = snprintf(NULL, 0, pattern, prefix, pid, tid); | |
char* log_filepath = malloc(path_len + 1); | |
sprintf(log_filepath, pattern, prefix, pid, tid); | |
int fd = original_open(log_filepath, O_WRONLY | O_APPEND | O_CREAT); | |
write(fd, pathname, strlen(pathname)); | |
write(fd, "\n", 1); | |
close(fd); | |
free(log_filepath); | |
} | |
int open(const char *pathname, int flags, ...){ | |
func_ptr_open original_open = (func_ptr_open) dlsym(RTLD_NEXT, "open"); | |
const char* prefix = getenv("IO_SHIM_PREFIX"); | |
if (prefix != NULL) { | |
write_to_log(prefix, pathname, original_open); | |
} | |
/* | |
open is variadic and will accept a mode argument when the O_CREAT or O_TMPFILE are set | |
*/ | |
mode_t mode; | |
if(flags & O_CREAT == O_CREAT || flags & O_TMPFILE == O_TMPFILE) { | |
va_list open_args_ptr; | |
va_start(open_args_ptr, flags); | |
mode = va_arg(open_args_ptr, mode_t); | |
} | |
return original_open(pathname, flags, mode); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env bash | |
mkdir logs | |
IO_SHIM_PREFIX=`realpath ./logs` LD_PRELOAD=./shim.so "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment