blob: c0f67b3379396d49fddb0fb7c4e167fa2f2a43af [file] [log] [blame]
Daniel Dunbarb3a69012009-06-26 16:47:03 +00001//===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Howard Hinnant9ad441f2010-11-16 22:13:33 +00005// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
Daniel Dunbarb3a69012009-06-26 16:47:03 +00007//
8//===----------------------------------------------------------------------===//
9
10
11#include <stdio.h>
12#include <string.h>
13#include <stdint.h>
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000014#if defined(_WIN32)
15#include <windows.h>
16void __clear_cache(void* start, void* end)
17{
18 if (!FlushInstructionCache(GetCurrentProcess(), start, end-start))
19 exit(1);
20}
21void __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
Daniel Dunbarb3a69012009-06-26 16:47:03 +000031#include <sys/mman.h>
Daniel Dunbarb3a69012009-06-26 16:47:03 +000032extern void __clear_cache(void* start, void* end);
33extern void __enable_execute_stack(void* addr);
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000034#endif
Daniel Dunbarb3a69012009-06-26 16:47:03 +000035
36typedef int (*pfunc)(void);
37
38int func1()
39{
40 return 1;
41}
42
43int func2()
44{
45 return 2;
46}
47
48
49
50
51int main()
52{
Shantonu Sena07fa292009-10-28 15:54:04 +000053 unsigned char execution_buffer[128];
54 // mark stack page containing execution_buffer to be executable
55 __enable_execute_stack(execution_buffer);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000056
57 // verify you can copy and execute a function
Shantonu Sena07fa292009-10-28 15:54:04 +000058 memcpy(execution_buffer, (void *)(uintptr_t)&func1, 128);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000059 __clear_cache(execution_buffer, &execution_buffer[128]);
Shantonu Sena07fa292009-10-28 15:54:04 +000060 pfunc f1 = (pfunc)(uintptr_t)execution_buffer;
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000061 if ((*f1)() != 1)
Daniel Dunbarb3a69012009-06-26 16:47:03 +000062 return 1;
63
64 // verify you can overwrite a function with another
Shantonu Sena07fa292009-10-28 15:54:04 +000065 memcpy(execution_buffer, (void *)(uintptr_t)&func2, 128);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000066 __clear_cache(execution_buffer, &execution_buffer[128]);
Shantonu Sena07fa292009-10-28 15:54:04 +000067 pfunc f2 = (pfunc)(uintptr_t)execution_buffer;
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000068 if ((*f2)() != 2)
Daniel Dunbarb3a69012009-06-26 16:47:03 +000069 return 1;
70
71 return 0;
72}