made script and finished for read write malloc and calloc

This commit is contained in:
whaffman 2025-01-19 16:24:13 +01:00
parent 8cb9e873a9
commit b8e31ab825
2 changed files with 83 additions and 0 deletions

57
funfail.sh Executable file
View File

@ -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 "$@"

View File

@ -0,0 +1,26 @@
#include <dlfcn.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
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;
}