1 //===-- clear_cache_test.c - Test clear_cache -----------------------------===//
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
))
23 extern void __clear_cache(void* start
, void* end
);
29 typedef int (*pfunc
)(void);
43 unsigned char execution_buffer
[128];
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));
52 MEMORY_BASIC_INFORMATION b
;
53 if (!VirtualQuery(start
, &b
, sizeof(b
)))
55 if (!VirtualProtect(b
.BaseAddress
, b
.RegionSize
, PAGE_EXECUTE_READWRITE
, &b
.Protect
))
57 if (mprotect(start
, end
-start
, PROT_READ
|PROT_WRITE
|PROT_EXEC
) != 0)
61 // verify you can copy and execute a function
62 memcpy(execution_buffer
, (void *)(uintptr_t)&func1
, 128);
63 __clear_cache(execution_buffer
, &execution_buffer
[128]);
64 pfunc f1
= (pfunc
)(uintptr_t)execution_buffer
;
68 // verify you can overwrite a function with another
69 memcpy(execution_buffer
, (void *)(uintptr_t)&func2
, 128);
70 __clear_cache(execution_buffer
, &execution_buffer
[128]);
71 pfunc f2
= (pfunc
)(uintptr_t)execution_buffer
;