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