1 // REQUIRES: native-run 2 // UNSUPPORTED: arm, aarch64 3 // RUN: %clang_builtins %s %librt -o %t && %run %t 4 //===-- clear_cache_test.c - Test clear_cache -----------------------------===// 5 // 6 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 7 // See https://llvm.org/LICENSE.txt for license information. 8 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 9 // 10 //===----------------------------------------------------------------------===// 11 12 13 #include <stdio.h> 14 #include <string.h> 15 #include <stdint.h> 16 17 #if defined(_WIN32) 18 #include <windows.h> 19 #else 20 #include <unistd.h> 21 #include <sys/mman.h> 22 #endif 23 24 extern void __clear_cache(void* start, void* end); 25 26 typedef int (*pfunc)(void); 27 28 // Make these static to avoid ILT jumps for incremental linking on Windows. 29 static int func1() { return 1; } 30 static int func2() { return 2; } 31 32 void *__attribute__((noinline)) 33 memcpy_f(void *dst, const void *src, size_t n) { 34 // ARM and MIPS nartually align functions, but use the LSB for ISA selection 35 // (THUMB, MIPS16/uMIPS respectively). Ensure that the ISA bit is ignored in 36 // the memcpy 37 #if defined(__arm__) || defined(__mips__) 38 return (void *)((uintptr_t)memcpy(dst, (void *)((uintptr_t)src & ~1), n) | 39 ((uintptr_t)src & 1)); 40 #else 41 return memcpy(dst, (void *)((uintptr_t)src), n); 42 #endif 43 } 44 45 int main() 46 { 47 const int kSize = 128; 48 #if !defined(_WIN32) 49 uint8_t *execution_buffer = mmap(0, kSize, 50 PROT_READ | PROT_WRITE | PROT_EXEC, 51 MAP_ANON | MAP_PRIVATE, 0, 0); 52 if (execution_buffer == MAP_FAILED) 53 return 1; 54 #else 55 HANDLE mapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, 56 PAGE_EXECUTE_READWRITE, 0, kSize, NULL); 57 if (mapping == NULL) 58 return 1; 59 60 uint8_t* execution_buffer = MapViewOfFile( 61 mapping, FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, 0, 0, 0); 62 if (execution_buffer == NULL) 63 return 1; 64 #endif 65 66 // verify you can copy and execute a function 67 pfunc f1 = (pfunc)memcpy_f(execution_buffer, func1, kSize); 68 __clear_cache(execution_buffer, execution_buffer + kSize); 69 if ((*f1)() != 1) 70 return 1; 71 72 // verify you can overwrite a function with another 73 pfunc f2 = (pfunc)memcpy_f(execution_buffer, func2, kSize); 74 __clear_cache(execution_buffer, execution_buffer + kSize); 75 if ((*f2)() != 2) 76 return 1; 77 78 return 0; 79 } 80