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