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