From b8e31ab82537c47c5b632c78b91b28fd41087e5a Mon Sep 17 00:00:00 2001 From: whaffman Date: Sun, 19 Jan 2025 16:24:13 +0100 Subject: [PATCH] made script and finished for read write malloc and calloc --- funfail.sh | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/read.c | 26 +++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100755 funfail.sh diff --git a/funfail.sh b/funfail.sh new file mode 100755 index 0000000..88b66cf --- /dev/null +++ b/funfail.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# Check if funfail.so exists, else make it +if [ ! -f ./funfail.so ]; then + echo "funfail.so not found, attempting to build it..." + make || { echo "Build failed. Exiting."; exit 1; } +fi + +# Function to display the menu +display_menu() { + echo "Select the function to fail:" + echo "1) malloc" + echo "2) calloc" + echo "3) read" + echo "4) write" + echo "5) exit" + echo -n "Enter your choice [1-5]: " +} + +# Function to get the number of calls after which the function should fail +get_fail_after_calls() { + echo -n "Enter the number of calls after which the function should fail: " + read fail_after_calls + if ! [[ "$fail_after_calls" =~ ^[0-9]+$ ]] || [ "$fail_after_calls" -le 0 ]; then + echo "Invalid input. Please enter a positive integer." + exit 1 + fi +} + +# Display the menu and get user input +display_menu +read choice + +# Get the number of calls after which the function should fail +get_fail_after_calls + +# Set the environment variables based on user input +case $choice in + 1) export FAIL_FUNC="malloc" ;; + 2) export FAIL_FUNC="calloc" ;; + 3) export FAIL_FUNC="read" ;; + 4) export FAIL_FUNC="write" ;; + 5) exit 0 ;; + *) echo "Invalid choice"; exit 1 ;; +esac + + +# Set the specific environment variable for the chosen function +case $FAIL_FUNC in + "malloc") export MAX_MALLOC_CALLS=$fail_after_calls ;; + "calloc") export MAX_CALLOC_CALLS=$fail_after_calls ;; + "read") export MAX_READ_CALLS=$fail_after_calls ;; + "write") export MAX_WRITE_CALLS=$fail_after_calls ;; +esac + +# Run the user program with its arguments while preloading funfail.so +LD_PRELOAD=./funfail.so "$@" diff --git a/src/read.c b/src/read.c index e69de29..2794d26 100644 --- a/src/read.c +++ b/src/read.c @@ -0,0 +1,26 @@ +#include +#include +#include +#include + +typedef ssize_t (*f)(int fd, void *buf, size_t count); + +ssize_t read(int fd, void *buf, size_t count) +{ + static f og_read = NULL; + static int calls = 0; + const int MAX_CALLS = getenv("MAX_READ_CALLS") ? atoi(getenv("MAX_READ_CALLS")) : -1; + + if (!og_read) + { + og_read = (f)dlsym(RTLD_NEXT, "read"); + } + + calls++; + if (MAX_CALLS < 0 || calls <= MAX_CALLS) + { + return og_read(fd, buf, count); + } + errno = EBADF; + return -1; +} \ No newline at end of file