Home | History | Annotate | Download | only in Unit
      1 //===-- clear_cache_test.c - Test clear_cache -----------------------------===//
      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 
     18 extern void __clear_cache(void* start, void* end);
     19 
     20 typedef int (*pfunc)(void);
     21 
     22 int func1()
     23 {
     24     return 1;
     25 }
     26 
     27 int func2()
     28 {
     29     return 2;
     30 }
     31 
     32 
     33 
     34 unsigned char execution_buffer[128];
     35 
     36 int main()
     37 {
     38     // make executable the page containing execution_buffer
     39     char* start = (char*)((uintptr_t)execution_buffer & (-4095));
     40     char* end = (char*)((uintptr_t)(&execution_buffer[128+4096]) & (-4095));
     41     if ( mprotect(start, end-start, PROT_READ|PROT_WRITE|PROT_EXEC) != 0 )
     42         return 1;
     43 
     44     // verify you can copy and execute a function
     45     memcpy(execution_buffer, (void *)(uintptr_t)&func1, 128);
     46     __clear_cache(execution_buffer, &execution_buffer[128]);
     47     pfunc f1 = (pfunc)(uintptr_t)execution_buffer;
     48     if ( (*f1)() != 1 )
     49         return 1;
     50 
     51     // verify you can overwrite a function with another
     52     memcpy(execution_buffer, (void *)(uintptr_t)&func2, 128);
     53     __clear_cache(execution_buffer, &execution_buffer[128]);
     54     pfunc f2 = (pfunc)(uintptr_t)execution_buffer;
     55     if ( (*f2)() != 2 )
     56         return 1;
     57 
     58     return 0;
     59 }
     60