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 nartually 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
30int main()
31{
32 unsigned char execution_buffer[128];
33 // mark stack page containing execution_buffer to be executable
34 __enable_execute_stack(execution_buffer);
35
36 // verify you can copy and execute a function
37 pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128);
38 __clear_cache(execution_buffer, &execution_buffer[128]);
39 printf("f1: %p\n", f1);
40 if ((*f1)() != 1)
41 return 1;
42
43 // verify you can overwrite a function with another
44 pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128);
45 __clear_cache(execution_buffer, &execution_buffer[128]);
46 if ((*f2)() != 2)
47 return 1;
48
49 return 0;
50}
51