1 //===-- clear_cache_test.c - Test clear_cache -----------------------------===//
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 }
21 #else
22 #include <sys/mman.h>
23 extern void __clear_cache(void* start, void* end);
24 #endif
25 
26 
27 
28 
29 typedef int (*pfunc)(void);
30 
func1()31 int func1()
32 {
33     return 1;
34 }
35 
func2()36 int func2()
37 {
38     return 2;
39 }
40 
41 void *__attribute__((noinline))
memcpy_f(void * dst,const void * src,size_t n)42 memcpy_f(void *dst, const void *src, size_t n) {
43 // ARM and MIPS nartually align functions, but use the LSB for ISA selection
44 // (THUMB, MIPS16/uMIPS respectively).  Ensure that the ISA bit is ignored in
45 // the memcpy
46 #if defined(__arm__) || defined(__mips__)
47   return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) |
48                   ((uintptr_t)src & 1));
49 #else
50   return memcpy(dst, (void *)((uintptr_t)src), n);
51 #endif
52 }
53 
54 unsigned char execution_buffer[128];
55 
main()56 int main()
57 {
58     // make executable the page containing execution_buffer
59     char* start = (char*)((uintptr_t)execution_buffer & (-4095));
60     char* end = (char*)((uintptr_t)(&execution_buffer[128+4096]) & (-4095));
61 #if defined(_WIN32)
62     DWORD dummy_oldProt;
63     MEMORY_BASIC_INFORMATION b;
64     if (!VirtualQuery(start, &b, sizeof(b)))
65         return 1;
66     if (!VirtualProtect(b.BaseAddress, b.RegionSize, PAGE_EXECUTE_READWRITE, &b.Protect))
67 #else
68     if (mprotect(start, end-start, PROT_READ|PROT_WRITE|PROT_EXEC) != 0)
69 #endif
70         return 1;
71 
72     // verify you can copy and execute a function
73     pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128);
74     __clear_cache(execution_buffer, &execution_buffer[128]);
75     if ((*f1)() != 1)
76         return 1;
77 
78     // verify you can overwrite a function with another
79     pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128);
80     __clear_cache(execution_buffer, &execution_buffer[128]);
81     if ((*f2)() != 2)
82         return 1;
83 
84     return 0;
85 }
86