blob: 3507fd80b288b67e9ef739b354790e26b7a7db9a [file] [log] [blame]
Daniel Dunbarb3a69012009-06-26 16:47:03 +00001//===-- clear_cache_test.c - Test clear_cache -----------------------------===//
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}
21#else
Daniel Dunbarb3a69012009-06-26 16:47:03 +000022#include <sys/mman.h>
Daniel Dunbarb3a69012009-06-26 16:47:03 +000023extern void __clear_cache(void* start, void* end);
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000024#endif
25
26
27
Daniel Dunbarb3a69012009-06-26 16:47:03 +000028
29typedef int (*pfunc)(void);
30
31int func1()
32{
33 return 1;
34}
35
36int func2()
37{
38 return 2;
39}
40
41
42
43unsigned char execution_buffer[128];
44
45int main()
46{
47 // make executable the page containing execution_buffer
48 char* start = (char*)((uintptr_t)execution_buffer & (-4095));
49 char* end = (char*)((uintptr_t)(&execution_buffer[128+4096]) & (-4095));
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000050#if defined(_WIN32)
51 DWORD dummy_oldProt;
52 MEMORY_BASIC_INFORMATION b;
53 if (!VirtualQuery(start, &b, sizeof(b)))
54 return 1;
55 if (!VirtualProtect(b.BaseAddress, b.RegionSize, PAGE_EXECUTE_READWRITE, &b.Protect))
56#else
57 if (mprotect(start, end-start, PROT_READ|PROT_WRITE|PROT_EXEC) != 0)
58#endif
Daniel Dunbarb3a69012009-06-26 16:47:03 +000059 return 1;
60
61 // verify you can copy and execute a function
Shantonu Sena07fa292009-10-28 15:54:04 +000062 memcpy(execution_buffer, (void *)(uintptr_t)&func1, 128);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000063 __clear_cache(execution_buffer, &execution_buffer[128]);
Shantonu Sena07fa292009-10-28 15:54:04 +000064 pfunc f1 = (pfunc)(uintptr_t)execution_buffer;
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000065 if ((*f1)() != 1)
Daniel Dunbarb3a69012009-06-26 16:47:03 +000066 return 1;
67
68 // verify you can overwrite a function with another
Shantonu Sena07fa292009-10-28 15:54:04 +000069 memcpy(execution_buffer, (void *)(uintptr_t)&func2, 128);
Daniel Dunbarb3a69012009-06-26 16:47:03 +000070 __clear_cache(execution_buffer, &execution_buffer[128]);
Shantonu Sena07fa292009-10-28 15:54:04 +000071 pfunc f2 = (pfunc)(uintptr_t)execution_buffer;
Anton Korobeynikov7e8904f2012-01-12 21:13:48 +000072 if ((*f2)() != 2)
Daniel Dunbarb3a69012009-06-26 16:47:03 +000073 return 1;
74
75 return 0;
76}