1 // REQUIRES: native-run
2 // RUN: %clang_builtins %s %librt -o %t && %run_nomprotect %t
3 // REQUIRES: librt_has_enable_execute_stack
8 extern void __clear_cache(void* start
, void* end
);
9 extern void __enable_execute_stack(void* addr
);
11 typedef int (*pfunc
)(void);
13 // Make these static to avoid ILT jumps for incremental linking on Windows.
14 static int func1() { return 1; }
15 static int func2() { return 2; }
17 void *__attribute__((noinline
))
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
22 #if defined(__arm__) || defined(__mips__)
23 return (void *)((uintptr_t)memcpy(dst
, (void *)((uintptr_t)src
& ~1), n
) |
24 ((uintptr_t)src
& 1));
26 return memcpy(dst
, (void *)((uintptr_t)src
), n
);
33 unsigned char execution_buffer
[128] __attribute__((__aligned__(8)));
35 unsigned char execution_buffer
[128];
37 // mark stack page containing execution_buffer to be executable
38 __enable_execute_stack(execution_buffer
);
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
);
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]);