brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.0 KiB · d706231 Raw
38 lines · c
1#include <stdint.h>2#include <stdio.h>3#include <string.h>4#include <sys/mman.h>5#include <unistd.h>6 7extern uint8_t __start_target_section[];8extern uint8_t __stop_target_section[];9 10__attribute__((used, section("target_section"))) int target_function(void) {11  return 42;12}13 14typedef int (*target_function_t)(void);15 16int main(void) {17  size_t target_function_size = __stop_target_section - __start_target_section;18  size_t page_size = sysconf(_SC_PAGESIZE);19  size_t page_aligned_size =20      (target_function_size + page_size - 1) & ~(page_size - 1);21 22  void *executable_memory =23      mmap(NULL, page_aligned_size, PROT_READ | PROT_WRITE | PROT_EXEC,24           MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);25  if (executable_memory == MAP_FAILED) {26    perror("mmap");27    return 1;28  }29 30  memcpy(executable_memory, __start_target_section, target_function_size);31 32  target_function_t func = (target_function_t)executable_memory;33  int result = func(); // Break here34  printf("Result from target function: %d\n", result);35 36  return 0;37}38