Skip to content

Instantly share code, notes, and snippets.

@rfletchr
Last active June 29, 2021 11:13
Show Gist options
  • Save rfletchr/7e28dabd169614a879a84711030badff to your computer and use it in GitHub Desktop.
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
CC=gcc
all: src/shim.c
$(CC) -shared -fPIC -o shim.so src/shim.c -ldl
// 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);
}
#! /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