1 // REQUIRES: native-run 2 // RUN: %clang_builtins %s %librt -o %t && %run %t 3 // REQUIRES: librt_has_enable_execute_stack 4 //===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===// 5 // 6 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 7 // See https://llvm.org/LICENSE.txt for license information. 8 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 9 // 10 //===----------------------------------------------------------------------===// 11 12 13 #include <stdio.h> 14 #include <string.h> 15 #include <stdint.h> 16 extern void __clear_cache(void* start, void* end); 17 extern void __enable_execute_stack(void* addr); 18 19 typedef int (*pfunc)(void); 20 21 // Make these static to avoid ILT jumps for incremental linking on Windows. 22 static int func1() { return 1; } 23 static int func2() { return 2; } 24 25 void *__attribute__((noinline)) 26 memcpy_f(void *dst, const void *src, size_t n) { 27 // ARM and MIPS nartually align functions, but use the LSB for ISA selection 28 // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in 29 // the memcpy 30 #if defined(__arm__) || defined(__mips__) 31 return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) | 32 ((uintptr_t)src & 1)); 33 #else 34 return memcpy(dst, (void *)((uintptr_t)src), n); 35 #endif 36 } 37 38 int main() 39 { 40 unsigned char execution_buffer[128]; 41 // mark stack page containing execution_buffer to be executable 42 __enable_execute_stack(execution_buffer); 43 44 // verify you can copy and execute a function 45 pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128); 46 __clear_cache(execution_buffer, &execution_buffer[128]); 47 printf("f1: %p\n", f1); 48 if ((*f1)() != 1) 49 return 1; 50 51 // verify you can overwrite a function with another 52 pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128); 53 __clear_cache(execution_buffer, &execution_buffer[128]); 54 if ((*f2)() != 2) 55 return 1; 56 57 return 0; 58 } 59