1 // REQUIRES: native-run 2 // RUN: %clang_builtins %s %librt -o %t && %run %t 3 //===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===// 4 // 5 // The LLVM Compiler Infrastructure 6 // 7 // This file is dual licensed under the MIT and the University of Illinois Open 8 // Source Licenses. See LICENSE.TXT for details. 9 // 10 //===----------------------------------------------------------------------===// 11 12 13 #include <stdio.h> 14 #include <string.h> 15 #include <stdint.h> 16 #if defined(_WIN32) 17 #include <windows.h> 18 void __clear_cache(void* start, void* end) 19 { 20 if (!FlushInstructionCache(GetCurrentProcess(), start, end-start)) 21 exit(1); 22 } 23 void __enable_execute_stack(void *addr) 24 { 25 MEMORY_BASIC_INFORMATION b; 26 27 if (!VirtualQuery(addr, &b, sizeof(b))) 28 exit(1); 29 if (!VirtualProtect(b.BaseAddress, b.RegionSize, PAGE_EXECUTE_READWRITE, &b.Protect)) 30 exit(1); 31 } 32 #else 33 #include <sys/mman.h> 34 extern void __clear_cache(void* start, void* end); 35 extern void __enable_execute_stack(void* addr); 36 #endif 37 38 typedef int (*pfunc)(void); 39 40 int func1() 41 { 42 return 1; 43 } 44 45 int func2() 46 { 47 return 2; 48 } 49 50 void *__attribute__((noinline)) 51 memcpy_f(void *dst, const void *src, size_t n) { 52 // ARM and MIPS nartually align functions, but use the LSB for ISA selection 53 // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in 54 // the memcpy 55 #if defined(__arm__) || defined(__mips__) 56 return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) | 57 ((uintptr_t)src & 1)); 58 #else 59 return memcpy(dst, (void *)((uintptr_t)src), n); 60 #endif 61 } 62 63 int main() 64 { 65 unsigned char execution_buffer[128]; 66 // mark stack page containing execution_buffer to be executable 67 __enable_execute_stack(execution_buffer); 68 69 // verify you can copy and execute a function 70 pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128); 71 __clear_cache(execution_buffer, &execution_buffer[128]); 72 if ((*f1)() != 1) 73 return 1; 74 75 // verify you can overwrite a function with another 76 pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128); 77 __clear_cache(execution_buffer, &execution_buffer[128]); 78 if ((*f2)() != 2) 79 return 1; 80 81 return 0; 82 } 83