19b7bbecaSWeiming Zhao // REQUIRES: native-run 2190b9110SMichał Górny // RUN: %clang_builtins %s %librt -o %t && %run_nomprotect %t 35be7eb3aSDan Liew // REQUIRES: librt_has_enable_execute_stack 48c1441f8SAlexey Samsonov 58c1441f8SAlexey Samsonov #include <stdio.h> 68c1441f8SAlexey Samsonov #include <string.h> 78c1441f8SAlexey Samsonov #include <stdint.h> 88c1441f8SAlexey Samsonov extern void __clear_cache(void* start, void* end); 98c1441f8SAlexey Samsonov extern void __enable_execute_stack(void* addr); 108c1441f8SAlexey Samsonov 118c1441f8SAlexey Samsonov typedef int (*pfunc)(void); 128c1441f8SAlexey Samsonov 138c78ca2eSReid Kleckner // Make these static to avoid ILT jumps for incremental linking on Windows. 148c78ca2eSReid Kleckner static int func1() { return 1; } 158c78ca2eSReid Kleckner static int func2() { return 2; } 168c1441f8SAlexey Samsonov 176e6c1c3eSSaleem Abdulrasool void *__attribute__((noinline)) 186e6c1c3eSSaleem Abdulrasool memcpy_f(void *dst, const void *src, size_t n) { 19*a1e7e401SKazuaki Ishizaki // ARM and MIPS naturally align functions, but use the LSB for ISA selection 206e6c1c3eSSaleem Abdulrasool // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in 216e6c1c3eSSaleem Abdulrasool // the memcpy 226e6c1c3eSSaleem Abdulrasool #if defined(__arm__) || defined(__mips__) 236e6c1c3eSSaleem Abdulrasool return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) | 246e6c1c3eSSaleem Abdulrasool ((uintptr_t)src & 1)); 256e6c1c3eSSaleem Abdulrasool #else 266e6c1c3eSSaleem Abdulrasool return memcpy(dst, (void *)((uintptr_t)src), n); 276e6c1c3eSSaleem Abdulrasool #endif 286e6c1c3eSSaleem Abdulrasool } 298c1441f8SAlexey Samsonov 308c1441f8SAlexey Samsonov int main() 318c1441f8SAlexey Samsonov { 328c1441f8SAlexey Samsonov unsigned char execution_buffer[128]; 338c1441f8SAlexey Samsonov // mark stack page containing execution_buffer to be executable 348c1441f8SAlexey Samsonov __enable_execute_stack(execution_buffer); 358c1441f8SAlexey Samsonov 368c1441f8SAlexey Samsonov // verify you can copy and execute a function 376e6c1c3eSSaleem Abdulrasool pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128); 388c1441f8SAlexey Samsonov __clear_cache(execution_buffer, &execution_buffer[128]); 398c78ca2eSReid Kleckner printf("f1: %p\n", f1); 408c1441f8SAlexey Samsonov if ((*f1)() != 1) 418c1441f8SAlexey Samsonov return 1; 428c1441f8SAlexey Samsonov 438c1441f8SAlexey Samsonov // verify you can overwrite a function with another 446e6c1c3eSSaleem Abdulrasool pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128); 458c1441f8SAlexey Samsonov __clear_cache(execution_buffer, &execution_buffer[128]); 468c1441f8SAlexey Samsonov if ((*f2)() != 2) 478c1441f8SAlexey Samsonov return 1; 488c1441f8SAlexey Samsonov 498c1441f8SAlexey Samsonov return 0; 508c1441f8SAlexey Samsonov } 51