commit d862928733ed2b39cd38364710d82715d4f01929 Author: uvos Date: Sat Sep 30 15:28:30 2023 +0200 inital commit diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..efe50d8 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.5) + +project(ksmexec C) + +set(SRC_FILES main.c) +set(LIBS) + +add_executable(${PROJECT_NAME} ${SRC_FILES}) +target_link_libraries(${PROJECT_NAME} ${LIBS}) + +add_executable(${PROJECT_NAME}_test test.c) +target_link_libraries(${PROJECT_NAME} ${LIBS}) + +set(CMAKE_INSTALL_PREFIX /usr) +install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin) diff --git a/main.c b/main.c new file mode 100644 index 0000000..1e0f5af --- /dev/null +++ b/main.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + if(argc < 2) + { + fprintf(stderr, "A process to execute is required\n"); + return 1; + } + + int ret = prctl(PR_SET_MEMORY_MERGE, 1, 0, 0, 0); + if(ret != 0) + { + fprintf(stderr, "Unable to enable KSM for process: %s\n", strerror(errno)); + return 2; + } + + printf("PR_SET_MEMORY_MERGE set to %u\n", prctl(PR_GET_MEMORY_MERGE, 0, 0, 0, 0)); + + pid_t parent_pid = getpid(); + pid_t pid = fork(); + if(pid == 0) + { + printf("PR_SET_MEMORY_MERGE in child is %u\n", prctl(PR_GET_MEMORY_MERGE, 0, 0, 0, 0)); + execvp(argv[1], argv+1); + fprintf(stderr, "Unable exec process: %s\n", strerror(errno)); + return 3; + } + else if(pid == -1) + { + fprintf(stderr, "Unable fork: %s\n", strerror(errno)); + } + else if(pid == -1) + { + waitpid(pid, NULL, 0); + } + return 0; +} + diff --git a/test.c b/test.c new file mode 100644 index 0000000..017f465 --- /dev/null +++ b/test.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) +{ + int merge = prctl(PR_GET_MEMORY_MERGE, 0, 0, 0, 0); + printf("PR_SET_MEMORY_MERGE is %u after exec\n", merge); + + if(merge != 1) + { + fprintf(stderr, "KSM merging not enabled!\n"); + return 1; + } + + printf("allocating memory\n"); + char* buf = malloc(100000000); + + printf("writeing memory\n"); + for(size_t i = 0; i < 100000000; i++) + buf[i] = 0x44; + + printf("reading memory\n"); + volatile char read; + while(true) + { + for(size_t i = 0; i < 100000000; i++) + { + read = buf[i]; + if(read != 0x44) + return 2; + } + sleep(1); + } + return 0; +}