1//===-- enable_execute_stack_test.c - Test __enable_execute_stack ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include <stdio.h>
12#include <string.h>
13#include <stdint.h>
14#include <sys/mman.h>
15
16
17
18extern void __clear_cache(void* start, void* end);
19extern void __enable_execute_stack(void* addr);
20
21typedef int (*pfunc)(void);
22
23int func1()
24{
25    return 1;
26}
27
28int func2()
29{
30    return 2;
31}
32
33
34
35
36int main()
37{
38    unsigned char execution_buffer[128];
39    // mark stack page containing execution_buffer to be executable
40    __enable_execute_stack(execution_buffer);
41
42    // verify you can copy and execute a function
43    memcpy(execution_buffer, (void *)(uintptr_t)&func1, 128);
44    __clear_cache(execution_buffer, &execution_buffer[128]);
45    pfunc f1 = (pfunc)(uintptr_t)execution_buffer;
46    if ( (*f1)() != 1 )
47        return 1;
48
49    // verify you can overwrite a function with another
50    memcpy(execution_buffer, (void *)(uintptr_t)&func2, 128);
51    __clear_cache(execution_buffer, &execution_buffer[128]);
52    pfunc f2 = (pfunc)(uintptr_t)execution_buffer;
53    if ( (*f2)() != 2 )
54        return 1;
55
56    return 0;
57}
58