1 //===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdint.h>
14 #if defined(_WIN32)
15 #include <windows.h>
__clear_cache(void * start,void * end)16 void __clear_cache(void* start, void* end)
17 {
18     if (!FlushInstructionCache(GetCurrentProcess(), start, end-start))
19         exit(1);
20 }
__enable_execute_stack(void * addr)21 void __enable_execute_stack(void *addr)
22 {
23     MEMORY_BASIC_INFORMATION b;
24 
25     if (!VirtualQuery(addr, &b, sizeof(b)))
26         exit(1);
27     if (!VirtualProtect(b.BaseAddress, b.RegionSize, PAGE_EXECUTE_READWRITE, &b.Protect))
28         exit(1);
29 }
30 #else
31 #include <sys/mman.h>
32 extern void __clear_cache(void* start, void* end);
33 extern void __enable_execute_stack(void* addr);
34 #endif
35 
36 typedef int (*pfunc)(void);
37 
func1()38 int func1()
39 {
40     return 1;
41 }
42 
func2()43 int func2()
44 {
45     return 2;
46 }
47 
48 
49 
50 
main()51 int main()
52 {
53     unsigned char execution_buffer[128];
54     // mark stack page containing execution_buffer to be executable
55     __enable_execute_stack(execution_buffer);
56 
57     // verify you can copy and execute a function
58     memcpy(execution_buffer, (void *)(uintptr_t)&func1, 128);
59     __clear_cache(execution_buffer, &execution_buffer[128]);
60     pfunc f1 = (pfunc)(uintptr_t)execution_buffer;
61     if ((*f1)() != 1)
62         return 1;
63 
64     // verify you can overwrite a function with another
65     memcpy(execution_buffer, (void *)(uintptr_t)&func2, 128);
66     __clear_cache(execution_buffer, &execution_buffer[128]);
67     pfunc f2 = (pfunc)(uintptr_t)execution_buffer;
68     if ((*f2)() != 2)
69         return 1;
70 
71     return 0;
72 }
73