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>
8extern void __clear_cache(void* start, void* end);
9extern void __enable_execute_stack(void* addr);
10
11typedef int (*pfunc)(void);
12
13// Make these static to avoid ILT jumps for incremental linking on Windows.
14static int func1() { return 1; }
15static int func2() { return 2; }
16
17void *__attribute__((noinline))
18memcpy_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(dest: dst, src: (void *)((uintptr_t)src), n: n);
27#endif
28}
29
30int 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(addr: execution_buffer);
39
40 // verify you can copy and execute a function
41 pfunc f1 = (pfunc)memcpy_f(dst: execution_buffer, src: func1, n: 128);
42 __clear_cache(start: execution_buffer, end: &execution_buffer[128]);
43 printf(format: "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(dst: execution_buffer, src: func2, n: 128);
49 __clear_cache(start: execution_buffer, end: &execution_buffer[128]);
50 if ((*f2)() != 2)
51 return 1;
52
53 return 0;
54}
55

source code of compiler-rt/test/builtins/Unit/enable_execute_stack_test.c