1 //===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
16 void __clear_cache(void* start
, void* end
)
18 if (!FlushInstructionCache(GetCurrentProcess(), start
, end
-start
))
21 void __enable_execute_stack(void *addr
)
23 MEMORY_BASIC_INFORMATION b
;
25 if (!VirtualQuery(addr
, &b
, sizeof(b
)))
27 if (!VirtualProtect(b
.BaseAddress
, b
.RegionSize
, PAGE_EXECUTE_READWRITE
, &b
.Protect
))
32 extern void __clear_cache(void* start
, void* end
);
33 extern void __enable_execute_stack(void* addr
);
36 typedef int (*pfunc
)(void);
48 void *__attribute__((noinline
))
49 memcpy_f(void *dst
, const void *src
, size_t n
) {
50 // ARM and MIPS nartually align functions, but use the LSB for ISA selection
51 // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in
53 #if defined(__arm__) || defined(__mips__)
54 return (void *)((uintptr_t)memcpy(dst
, (void *)((uintptr_t)src
& ~1), n
) |
55 ((uintptr_t)src
& 1));
57 return memcpy(dst
, (void *)((uintptr_t)src
), n
);
63 unsigned char execution_buffer
[128];
64 // mark stack page containing execution_buffer to be executable
65 __enable_execute_stack(execution_buffer
);
67 // verify you can copy and execute a function
68 pfunc f1
= (pfunc
)memcpy_f(execution_buffer
, func1
, 128);
69 __clear_cache(execution_buffer
, &execution_buffer
[128]);
73 // verify you can overwrite a function with another
74 pfunc f2
= (pfunc
)memcpy_f(execution_buffer
, func2
, 128);
75 __clear_cache(execution_buffer
, &execution_buffer
[128]);