• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 void *__attribute__((noinline))
memcpy_f(void * dst,const void * src,size_t n)49 memcpy_f(void *dst, const void *src, size_t n) {
50 // ARM and MIPS nartually align functions, but use the LSB for ISA selection
51 // (THUMB, MIPS16/uMIPS respectively).  Ensure that the ISA bit is ignored in
52 // the memcpy
53 #if defined(__arm__) || defined(__mips__)
54   return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) |
55                   ((uintptr_t)src & 1));
56 #else
57   return memcpy(dst, (void *)((uintptr_t)src), n);
58 #endif
59 }
60 
main()61 int main()
62 {
63     unsigned char execution_buffer[128];
64     // mark stack page containing execution_buffer to be executable
65     __enable_execute_stack(execution_buffer);
66 
67     // verify you can copy and execute a function
68     pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, 128);
69     __clear_cache(execution_buffer, &execution_buffer[128]);
70     if ((*f1)() != 1)
71         return 1;
72 
73     // verify you can overwrite a function with another
74     pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, 128);
75     __clear_cache(execution_buffer, &execution_buffer[128]);
76     if ((*f2)() != 2)
77         return 1;
78 
79     return 0;
80 }
81