├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── LICENSE ├── README.md ├── src └── compiler_pass │ ├── .clang-format │ ├── CMakeLists.txt │ ├── Protection.cpp │ └── config.h ├── test ├── basic │ ├── CMakeLists.txt │ ├── bullet.c │ ├── cmp.c │ ├── deps.c │ ├── escape.c │ ├── fakeoob.c │ ├── loop.c │ ├── pressure.c │ ├── prime.cpp │ ├── recursive.c │ ├── safe.cpp │ ├── uaf_ex.c │ └── unsafe.cpp ├── cpu2006 │ ├── native.cfg │ └── violet.cfg ├── cpu2017 │ ├── native.cfg │ ├── runall.sh │ └── violet.cfg └── juliet │ ├── test.py │ └── test_uaf.py └── tools ├── v++ ├── vcc └── vcc.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # Build 35 | build 36 | 37 | # VSCode 38 | .vscode 39 | 40 | # Config 41 | .config -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/safe_tcmalloc"] 2 | path = src/safe_tcmalloc 3 | url = https://github.com/Markakd/safe_tcmalloc.git 4 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(violet-pass) 3 | 4 | set(CMAKE_CXX_STANDARD 17) 5 | 6 | find_package(LLVM REQUIRED CONFIG) 7 | 8 | separate_arguments(LLVM_DEFINITIONS_LIST NATIVE_COMMAND ${LLVM_DEFINITIONS}) 9 | add_definitions(${LLVM_DEFINITIONS_LIST}) 10 | include_directories(${LLVM_INCLUDE_DIRS}) 11 | 12 | add_subdirectory(src/compiler_pass) 13 | add_subdirectory(src/safe_tcmalloc) 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://raw.githubusercontent.com/cla7aye15I4nd/cla7aye15i4nd.github.io/main/static/usenixbadges-available.png) 2 | ![](https://raw.githubusercontent.com/cla7aye15I4nd/cla7aye15i4nd.github.io/main/static/usenixbadges-functional.png) 3 | ![](https://raw.githubusercontent.com/cla7aye15I4nd/cla7aye15i4nd.github.io/main/static/usenixbadges-reproduced.png) 4 | 5 | # CAMP: Compiler and Allocator-based Heap Memory Protection 6 | 7 | ## Overview 8 | 9 | CAMP is a new sanitizer for detecting and capturing heap memory corruption. CAMP leverages a compiler and a customized memory allocator. The compiler adds boundary-checking and escape-tracking instructions to the target program, while the memory allocator tracks memory ranges, coordinates with the instrumentation, and neutralizes dangling pointers. With the novel error detection scheme, CAMP enables various compiler optimization strategies and thus eliminates redundant and unnecessary check instrumentation. 10 | 11 | 12 | [CAMP's allocator](https://github.com/Markakd/safe_tcmalloc) is built on tcmalloc. Users can use `python3 menuconfig.py` to modify the behavior when the allocator detects an error. 13 | 14 | CAMP has modified tcmalloc, with the most significant changes being in the cache design and the addition of a checking function. These modifications can be found at https://github.com/Markakd/safe_tcmalloc/blob/main/tcmalloc/tcmalloc.cc. 15 | 16 | [CAMP's compiler](src/compiler_pass) is built on top of the LLVM12 compiler framework. We implement the instrumentation and optimization within an LLVM pass, loadable by Clang. To defend against heap overflow, it instruments all pointer arithmetic and type-casting instructions. Users can enable or disable specific optimizations or checks by changing the value in [config.h](src/compiler_pass/config.h). 17 | 18 | For each optimization's implementation, we point out its location in the code: 19 | - Optimizing range checks with type information [src](src/compiler_pass/Protection.cpp#L548) 20 | - Removing Redundant Instructions [src](src/compiler_pass/Protection.cpp#L993) 21 | - Merging Runtime Calls [src](src/compiler_pass/Protection.cpp#L980) 22 | 23 | ## Prerequisite 24 | 25 | Before beginning the installation and setup process, ensure that your system meets the following requirements: 26 | - Ubuntu 22.04: This software is designed to run on Ubuntu 22.04, ensuring compatibility and smooth operation. 27 | - Clang 12.0.1: Clang, a compiler for the C family of programming languages, is required at version 12.0.1 to compile and run this software efficiently. 28 | 29 | ## Build 30 | 31 | To install CAMP on your system, follow these steps: 32 | ```bash 33 | git clone https://github.com/cla7aye15I4nd/CAMP.git 34 | cd CAMP 35 | git submodule update --init --recursive 36 | cd src/safe_tcmalloc && python3 menuconfig.py 37 | mkdir build && cd build 38 | cmake .. && make 39 | ``` 40 | These commands clone the repository, set up necessary submodules, configure settings, and compile the project, preparing it for use. 41 | 42 | ## Usage 43 | 44 | To use the CAMP tools, run the following commands: 45 | ```bash 46 | tools/vcc # Use vcc tool with specified compile options 47 | tools/v++ # Use v++ tool with specified compile options 48 | ``` 49 | These commands allow you to utilize the `vcc` and `v++` tools included with CAMP, enabling you to compile your projects with the specific options you need. 50 | 51 | ## Experiments 52 | 53 | [CAMP Experiment](https://github.com/cla7aye15I4nd/camp-experiment) include all documents and scripts that we used in evaluation and artfact. 54 | 55 | ## Bibtex 56 | ``` 57 | @inproceedings{lin2024camp, 58 | title = {{CAMP}: Compiler and Allocator-based Heap Memory Protection}, 59 | author={Lin, Zhenpeng and Yu, Zheng and Guo, Ziyi and Campanoni, Simone and Dinda, Peter and Xing, Xinyu}, 60 | booktitle = {33rd USENIX Security Symposium (USENIX Security 24)}, 61 | year = {2024}, 62 | } 63 | ``` 64 | -------------------------------------------------------------------------------- /src/compiler_pass/.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | -------------------------------------------------------------------------------- /src/compiler_pass/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(ProtectionPass MODULE 2 | Protection.cpp 3 | ) 4 | -------------------------------------------------------------------------------- /src/compiler_pass/Protection.cpp: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | #include "llvm/ADT/ArrayRef.h" 3 | #include "llvm/ADT/SmallSet.h" 4 | #include "llvm/ADT/StringRef.h" 5 | #include "llvm/ADT/StringSet.h" 6 | #include "llvm/Analysis/AliasAnalysis.h" 7 | #include "llvm/Analysis/LoopInfo.h" 8 | #include "llvm/Analysis/MemoryBuiltins.h" 9 | #include "llvm/Analysis/PostDominators.h" 10 | #include "llvm/Analysis/ScalarEvolution.h" 11 | #include "llvm/Analysis/TargetFolder.h" 12 | #include "llvm/Analysis/TargetLibraryInfo.h" 13 | #include "llvm/IR/Dominators.h" 14 | #include "llvm/IR/Function.h" 15 | #include "llvm/IR/IRBuilder.h" 16 | #include "llvm/IR/Instructions.h" 17 | #include "llvm/IR/LegacyPassManager.h" 18 | #include "llvm/IR/Module.h" 19 | #include "llvm/Pass.h" 20 | #include "llvm/Support/Debug.h" 21 | #include "llvm/Support/raw_ostream.h" 22 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" 23 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" 24 | #include 25 | using namespace llvm; 26 | 27 | #define DEBUG_TYPE "" 28 | 29 | /* Runtime Function List */ 30 | #define __GEP_CHECK "__gep_check_boundary" 31 | #define __BITCAST_CHECK "__bc_check_boundary" 32 | #define __REPORT_STATISTIC "__report_statistic" 33 | #define __REPORT_ERROR "__report_error" 34 | #define __GET_CHUNK_RANGE "__get_chunk_range" 35 | #define __ESCAPE "__escape" 36 | #define __STRCPY_CHECK "__strcpy_check" 37 | #define __STRNCPY_CHECK "__strncpy_check" 38 | #define __STRCAT_CHECK "__strcat_check" 39 | #define __STRNCAT_CHECK "__strncat_check" 40 | 41 | namespace { 42 | struct VProtectionPass : public FunctionPass { 43 | static char ID; 44 | VProtectionPass() : FunctionPass(ID) {} 45 | 46 | // Basic 47 | Module *M; 48 | Function *F; 49 | const DataLayout *DL; 50 | 51 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 52 | // Analysis 53 | const TargetLibraryInfo *TLI; 54 | ScalarEvolution *SE; 55 | ObjectSizeOffsetEvaluator *OSOE; 56 | DominatorTree *DT; 57 | PostDominatorTree *PDT; 58 | LoopInfo *LI; 59 | #endif 60 | // Type Utils 61 | Type *voidType; 62 | Type *int32Type; 63 | Type *int64Type; 64 | Type *voidPointerType; 65 | Type *int64PointerType; 66 | 67 | // Statistic 68 | int64_t gepIgnoreOptimized; 69 | int64_t gepDepOptimized; 70 | int64_t gepPartialCheck; 71 | int64_t gepRuntimeCheck; 72 | int64_t gepBuiltinCheck; 73 | int64_t bitcastIgnoreOptimized; 74 | int64_t bitcastDepOptimized; 75 | int64_t bitcastPartialCheck; 76 | int64_t bitcastBuiltinCheck; 77 | int64_t bitcastRuntimeCheck; 78 | int64_t escapeTrace; 79 | int64_t escapeOptimized; 80 | 81 | // Instruction 82 | DenseMap source; 83 | DenseMap *> cluster; 84 | 85 | SmallSet escaped; 86 | SmallSet auxiliary; 87 | SmallVector runtimeCheck; 88 | SmallVector, 16> builtinCheck; 89 | SmallVector *>, 16> 90 | partialCheck; 91 | 92 | SmallVector storeInsts; 93 | 94 | StringRef getPassName() const override { return "VProtectionPass"; } 95 | 96 | bool runOnFunction(Function &F) override { 97 | if (!F.isIntrinsic() && !isInternalFunction(F.getName()) && 98 | F.getInstructionCount() > 0) { 99 | 100 | this->F = &F; 101 | 102 | M = F.getParent(); 103 | DL = &M->getDataLayout(); 104 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 105 | TLI = &getAnalysis().getTLI(F); 106 | SE = &getAnalysis().getSE(); 107 | LI = &getAnalysis().getLoopInfo(); 108 | 109 | ObjectSizeOpts EvalOpts; 110 | EvalOpts.RoundToAlign = true; 111 | OSOE = new ObjectSizeOffsetEvaluator(*DL, TLI, F.getContext(), EvalOpts); 112 | DT = new DominatorTree(F); 113 | PDT = new PostDominatorTree(F); 114 | #endif 115 | gepIgnoreOptimized = 0; 116 | gepDepOptimized = 0; 117 | gepRuntimeCheck = 0; 118 | gepPartialCheck = 0; 119 | gepBuiltinCheck = 0; 120 | bitcastIgnoreOptimized = 0; 121 | bitcastDepOptimized = 0; 122 | bitcastBuiltinCheck = 0; 123 | bitcastPartialCheck = 0; 124 | bitcastRuntimeCheck = 0; 125 | escapeTrace = 0; 126 | escapeOptimized = 0; 127 | 128 | source.clear(); 129 | cluster.clear(); 130 | escaped.clear(); 131 | auxiliary.clear(); 132 | runtimeCheck.clear(); 133 | builtinCheck.clear(); 134 | partialCheck.clear(); 135 | storeInsts.clear(); 136 | 137 | bindRuntime(); 138 | hookInstruction(); 139 | 140 | if (F.getName() == "main") 141 | insertReport(); 142 | 143 | report(); 144 | return true; 145 | } 146 | return false; 147 | } 148 | 149 | static bool isInternalFunction(StringRef name) { 150 | static StringSet<> ifunc = { 151 | __GEP_CHECK, __BITCAST_CHECK, __REPORT_STATISTIC, 152 | __REPORT_ERROR, __GET_CHUNK_RANGE, __ESCAPE, 153 | }; 154 | 155 | return ifunc.count(name) != 0; 156 | } 157 | 158 | void bindRuntime() { 159 | LLVMContext &context = M->getContext(); 160 | voidType = Type::getVoidTy(context); 161 | int32Type = Type::getInt32Ty(context); 162 | int64Type = Type::getInt64Ty(context); 163 | voidPointerType = Type::getInt8PtrTy(context, 0); 164 | int64PointerType = Type::getInt64PtrTy(context, 0); 165 | 166 | M->getOrInsertFunction( 167 | __GEP_CHECK, 168 | FunctionType::get( 169 | int32Type, {voidPointerType, voidPointerType, int64Type}, false)); 170 | 171 | M->getOrInsertFunction( 172 | __BITCAST_CHECK, 173 | FunctionType::get(int32Type, {voidPointerType, int64Type}, false)); 174 | 175 | M->getOrInsertFunction(__REPORT_STATISTIC, 176 | FunctionType::get(voidType, {}, false)); 177 | 178 | M->getOrInsertFunction(__REPORT_ERROR, 179 | FunctionType::get(voidType, {}, false)); 180 | 181 | M->getOrInsertFunction( 182 | __GET_CHUNK_RANGE, 183 | FunctionType::get(int64Type, {int64Type, int64PointerType}, false)); 184 | 185 | M->getOrInsertFunction( 186 | __ESCAPE, FunctionType::get(int32Type, 187 | {voidPointerType, voidPointerType}, false)); 188 | 189 | M->getOrInsertFunction(__STRCPY_CHECK, 190 | FunctionType::get(voidPointerType, 191 | {voidPointerType, voidPointerType}, 192 | false)); 193 | 194 | M->getOrInsertFunction( 195 | __STRNCPY_CHECK, 196 | FunctionType::get(voidPointerType, 197 | {voidPointerType, voidPointerType, int64Type}, 198 | false)); 199 | 200 | M->getOrInsertFunction(__STRCAT_CHECK, 201 | FunctionType::get(voidPointerType, 202 | {voidPointerType, voidPointerType}, 203 | false)); 204 | 205 | M->getOrInsertFunction( 206 | __STRNCAT_CHECK, 207 | FunctionType::get(voidPointerType, 208 | {voidPointerType, voidPointerType, int64Type}, 209 | false)); 210 | } 211 | 212 | void insertReport() { 213 | SmallVector returns; 214 | SmallVector calls; 215 | for (BasicBlock &BB : *F) 216 | for (Instruction &I : BB) { 217 | if (ReturnInst *ret = dyn_cast(&I)) 218 | returns.push_back(ret); 219 | if (CallInst *call = dyn_cast(&I)) 220 | calls.push_back(call); 221 | } 222 | 223 | for (auto ret : returns) { 224 | IRBuilder<> irBuilder(ret); 225 | irBuilder.CreateCall(M->getFunction(__REPORT_STATISTIC)); 226 | } 227 | 228 | // Avoid directly call exit(status) in main() function, instead of return, 229 | // like 600.perlbench_s 230 | for (auto I : calls) { 231 | CallInst *call = dyn_cast(I); 232 | Function *fp = call->getCalledFunction(); 233 | 234 | if (fp != nullptr && fp->getName() == "exit") { 235 | IRBuilder<> irBuilder(call); 236 | irBuilder.CreateCall(M->getFunction(__REPORT_STATISTIC)); 237 | } 238 | } 239 | } 240 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 241 | void getAnalysisUsage(AnalysisUsage &AU) const override { 242 | AU.addRequired(); 243 | AU.addRequired(); 244 | AU.addRequired(); 245 | AU.addRequired(); 246 | AU.addRequired(); 247 | AU.addRequired(); 248 | } 249 | #endif 250 | void report() { 251 | dbgs() << "[REPORT:" << F->getName() << "]\n"; 252 | if (bitcastRuntimeCheck > 0 || bitcastPartialCheck > 0 || 253 | bitcastBuiltinCheck > 0) { 254 | dbgs() << " [BitCast]\n"; 255 | dbgs() << " Ignore Optimized: " << bitcastIgnoreOptimized << " \n"; 256 | dbgs() << " Dep Optimized: " << bitcastDepOptimized << " \n"; 257 | dbgs() << " Runtime Check: " << bitcastRuntimeCheck << " \n"; 258 | dbgs() << " Partial Check: " << bitcastPartialCheck << " \n"; 259 | dbgs() << " Builtin Check: " << bitcastBuiltinCheck << " \n"; 260 | } 261 | if (gepRuntimeCheck > 0 || gepPartialCheck > 0 || gepBuiltinCheck > 0) { 262 | 263 | dbgs() << " [GepElementPtr] \n"; 264 | dbgs() << " Ignore Optimized: " << gepIgnoreOptimized << " \n"; 265 | dbgs() << " Dep Optimized: " << gepDepOptimized << " \n"; 266 | dbgs() << " Runtime Check: " << gepRuntimeCheck << " \n"; 267 | dbgs() << " Partial Check: " << gepPartialCheck << " \n"; 268 | dbgs() << " Builtin Check: " << gepBuiltinCheck << " \n"; 269 | } 270 | if (escapeTrace > 0) { 271 | dbgs() << " [Escape]\n"; 272 | dbgs() << " Escape Optimized: " << escapeOptimized << " \n"; 273 | dbgs() << " Escape Trace: " << escapeTrace << " \n"; 274 | } 275 | } 276 | 277 | void hookInstruction() { 278 | collectInformation(); 279 | 280 | builtinOptimize(); 281 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 282 | partialBuiltinOptimize(); 283 | #endif 284 | escapeOptimize(); 285 | applyInstrument(); 286 | } 287 | 288 | static Instruction *getInsertionPointAfterDef(Instruction *I) { 289 | assert(!I->getType()->isVoidTy() && "Instruction must define result"); 290 | 291 | BasicBlock *InsertBB; 292 | BasicBlock::iterator InsertPt; 293 | if (auto *PN = dyn_cast(I)) { 294 | InsertBB = PN->getParent(); 295 | InsertPt = InsertBB->getFirstInsertionPt(); 296 | } else if (auto *II = dyn_cast(I)) { 297 | InsertBB = II->getNormalDest(); 298 | InsertPt = InsertBB->getFirstInsertionPt(); 299 | } else if (auto *CB = dyn_cast(I)) { 300 | InsertBB = CB->getDefaultDest(); 301 | InsertPt = InsertBB->getFirstInsertionPt(); 302 | } else { 303 | assert(!I->isTerminator() && 304 | "Only invoke/callbr terminators return value"); 305 | InsertBB = I->getParent(); 306 | InsertPt = std::next(I->getIterator()); 307 | } 308 | 309 | // catchswitch blocks don't have any legal insertion point (because they 310 | // are both an exception pad and a terminator). 311 | if (InsertPt == InsertBB->end()) 312 | return nullptr; 313 | return &*InsertPt; 314 | } 315 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 316 | void addBuiltinCheck(Instruction *I, Value *Cond) { 317 | /* 318 | llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp 319 | */ 320 | 321 | IRBuilder<> irBuilder( 322 | SplitBlockAndInsertIfThen(Cond, fetchBestInsertPoint(I), false)); 323 | irBuilder.CreateCall(M->getFunction(__REPORT_ERROR), {}); 324 | } 325 | 326 | void addPartialCheck(Value *V, SmallVector *S) { 327 | Instruction *InsertPoint = nullptr; 328 | 329 | if (isa(V)) 330 | InsertPoint = getInsertionPointAfterDef(dyn_cast(V)); 331 | else if (isa(V)) 332 | InsertPoint = &(F->getEntryBlock().front()); 333 | 334 | assert(InsertPoint != nullptr); 335 | 336 | IRBuilder<> irBuilder(&F->getEntryBlock().front()); 337 | auto base_ptr = irBuilder.CreateAlloca(int64Type); 338 | 339 | irBuilder.SetInsertPoint(InsertPoint); 340 | 341 | auto ptr = irBuilder.CreatePtrToInt(V, int64Type); 342 | 343 | Value *base; 344 | Value *end; 345 | 346 | if (MaybeStack(V)) { 347 | Value *rsp = readRegister(irBuilder, "rsp"); 348 | Value *valueNotOnStack = irBuilder.CreateICmpULT(ptr, rsp); 349 | 350 | irBuilder.SetInsertPoint( 351 | SplitBlockAndInsertIfThen(valueNotOnStack, InsertPoint, false)); 352 | auto if_end = irBuilder.CreateCall(M->getFunction(__GET_CHUNK_RANGE), 353 | {ptr, base_ptr}); 354 | auto if_base = irBuilder.CreateLoad(base_ptr); 355 | 356 | irBuilder.SetInsertPoint(InsertPoint); 357 | PHINode *base_phi = irBuilder.CreatePHI(int64Type, 2); 358 | base_phi->addIncoming( 359 | ConstantInt::get(int64Type, 0), 360 | dyn_cast(valueNotOnStack)->getParent()); 361 | base_phi->addIncoming(if_base, if_base->getParent()); 362 | 363 | PHINode *end_phi = irBuilder.CreatePHI(int64Type, 2); 364 | end_phi->addIncoming(ConstantInt::get(int64Type, 0x1000000000000), 365 | dyn_cast(valueNotOnStack)->getParent()); 366 | end_phi->addIncoming(if_end, if_end->getParent()); 367 | 368 | base = base_phi; 369 | end = end_phi; 370 | } else { 371 | end = irBuilder.CreateCall(M->getFunction(__GET_CHUNK_RANGE), 372 | {ptr, base_ptr}); 373 | base = irBuilder.CreateLoad(base_ptr); 374 | } 375 | 376 | int64_t osize = -1; 377 | Value *realEnd = nullptr; 378 | 379 | if (V->getType()->getPointerElementType()->isSized()) { 380 | osize = DL->getTypeAllocSize(V->getType()->getPointerElementType()); 381 | realEnd = irBuilder.CreateSub(end, ConstantInt::get(int64Type, osize)); 382 | } 383 | 384 | for (auto I : *S) { 385 | InsertPoint = fetchBestInsertPoint(I); 386 | irBuilder.SetInsertPoint(InsertPoint); 387 | 388 | auto Ptr = irBuilder.CreatePtrToInt(I, int64Type); 389 | auto offset = irBuilder.CreateSub(Ptr, base); 390 | 391 | Value *Cond = nullptr; 392 | int64_t nsize = 393 | auxiliary.count(I) 394 | ? 0 395 | : DL->getTypeAllocSize(I->getType()->getPointerElementType()); 396 | if (nsize == osize) { 397 | Cond = irBuilder.CreateICmpSLT(realEnd, Ptr); 398 | } else { 399 | Value *needsize = ConstantInt::get(int64Type, nsize); 400 | Cond = irBuilder.CreateICmpSLT(irBuilder.CreateSub(end, needsize), Ptr); 401 | } 402 | 403 | if (SE->getSignedRangeMin(SE->getSCEV(offset)).isNegative()) 404 | Cond = irBuilder.CreateOr(Cond, irBuilder.CreateICmpSLT(Ptr, base)); 405 | 406 | assert(isa(offset)); 407 | dyn_cast(offset)->eraseFromParent(); 408 | 409 | irBuilder.SetInsertPoint( 410 | SplitBlockAndInsertIfThen(Cond, InsertPoint, false)); 411 | irBuilder.CreateCall(M->getFunction(__REPORT_ERROR), {}); 412 | } 413 | } 414 | #endif 415 | void addGepRuntimeCheck(Instruction *I) { 416 | /* 417 | Before: 418 | %result = gep %base %offset 419 | 420 | After: 421 | %result = gep %base %offset 422 | __gep_check(%base, %result, size) 423 | */ 424 | auto gep = dyn_cast_or_null(I); 425 | assert(gep != nullptr && "addGepRuntimeCheck: Require GetElementPtrInst"); 426 | 427 | uint64_t typeSize = 428 | auxiliary.count(I) 429 | ? 0 430 | : DL->getTypeAllocSize(gep->getType()->getPointerElementType()); 431 | 432 | Instruction *InsertPoint = fetchBestInsertPoint(gep); 433 | IRBuilder<> irBuilder(InsertPoint); 434 | 435 | Value *base = 436 | irBuilder.CreatePointerCast(gep->getPointerOperand(), voidPointerType); 437 | Value *result = irBuilder.CreatePointerCast(gep, voidPointerType); 438 | Value *size = irBuilder.getInt64(typeSize); 439 | 440 | if (MaybeStack(source[I])) { 441 | Value *rsp = readRegister(irBuilder, "rsp"); 442 | 443 | Value *value = 444 | irBuilder.CreatePtrToInt(gep->getPointerOperand(), int64Type); 445 | Value *valueNotOnStack = irBuilder.CreateICmpULT(value, rsp); 446 | 447 | irBuilder.SetInsertPoint( 448 | SplitBlockAndInsertIfThen(valueNotOnStack, InsertPoint, false)); 449 | } 450 | irBuilder.CreateCall(M->getFunction(__GEP_CHECK), {base, result, size}); 451 | } 452 | 453 | bool MaybeStack(Value *V) { 454 | if (isa(V)) 455 | return false; 456 | if (isa(V)) 457 | return false; 458 | if (isa(V)) 459 | return false; 460 | 461 | return true; 462 | } 463 | 464 | void addBitcastRuntimeCheck(Instruction *I) { 465 | /* 466 | Before: 467 | %dst = bitcast %src ty1 ty2 468 | 469 | After: 470 | %dst = bitcast %src ty1 ty2 471 | __bitcast_check(%dst, size) 472 | */ 473 | 474 | auto bc = dyn_cast_or_null(I); 475 | assert(bc != nullptr && "addBitcastRuntimeCheck: Require BitCastInst"); 476 | 477 | IRBuilder<> irBuilder(fetchBestInsertPoint(bc)); 478 | 479 | Value *ptr = irBuilder.CreatePointerCast(bc, voidPointerType); 480 | Value *size = irBuilder.getInt64( 481 | DL->getTypeAllocSize(bc->getDestTy()->getPointerElementType())); 482 | 483 | irBuilder.CreateCall(M->getFunction(__BITCAST_CHECK), {ptr, size}); 484 | } 485 | 486 | Instruction *fetchBestInsertPoint(Instruction *I) { 487 | User *U = nullptr; 488 | for (auto user : I->users()) { 489 | if (isMustEscapeInstruction(user)) { 490 | if (U != nullptr) 491 | return getInsertionPointAfterDef(I); 492 | U = user; 493 | } 494 | } 495 | 496 | Instruction *P = dyn_cast_or_null(U); 497 | return P != nullptr ? P : getInsertionPointAfterDef(I); 498 | } 499 | 500 | Value *readRegister(IRBuilder<> &IRB, StringRef Name) { 501 | Function *readReg = Intrinsic::getDeclaration(M, Intrinsic::read_register, 502 | IRB.getIntPtrTy(*DL)); 503 | 504 | LLVMContext &context = M->getContext(); 505 | MDNode *MD = MDNode::get(context, {MDString::get(context, Name)}); 506 | return IRB.CreateCall(readReg, {MetadataAsValue::get(context, MD)}); 507 | } 508 | 509 | void addEscape(StoreInst *SI) { 510 | IRBuilder<> IRB(SI); 511 | 512 | // x86-64 only 513 | // heap address < stack address 514 | 515 | Value *rsp = readRegister(IRB, "rsp"); 516 | 517 | Value *value = IRB.CreatePtrToInt(SI->getValueOperand(), int64Type); 518 | Value *valueNotOnStack = IRB.CreateICmpULT(value, rsp); 519 | Value *valueIsNotNull = 520 | IRB.CreateICmpNE(value, Constant::getNullValue(int64Type)); 521 | 522 | Value *cond = IRB.CreateAnd(valueNotOnStack, valueIsNotNull); 523 | #if CONFIG_ENABLE_STACK_ESCAPE_OPTIMIZATION 524 | Value *locNotOnStack = IRB.CreateICmpULT( 525 | IRB.CreatePtrToInt(SI->getPointerOperand(), int64Type), rsp); 526 | cond = IRB.CreateAnd(cond, locNotOnStack); 527 | #endif 528 | IRB.SetInsertPoint(SplitBlockAndInsertIfThen(cond, SI, false)); 529 | IRB.CreateCall( 530 | M->getFunction(__ESCAPE), 531 | {IRB.CreatePointerCast(SI->getPointerOperand(), voidPointerType), 532 | IRB.CreatePointerCast(SI->getValueOperand(), voidPointerType)}); 533 | } 534 | 535 | bool allocateChecker( 536 | Instruction *Ptr, SmallVector &runtimeCheck, 537 | SmallVector, 16> &builtinCheck) { 538 | assert(Ptr->getType()->isPointerTy() && 539 | "allocateChecker(): Ptr should be pointer type"); 540 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 541 | if (escaped.count(Ptr) == 0) 542 | return false; 543 | 544 | SmallSet Visit; 545 | if (!isHeapAddress(Ptr, Visit)) 546 | return false; 547 | 548 | #if CONFIG_ENABLE_TYPE_BASE_OPTIMIZATION 549 | if (GetElementPtrInst *Gep = dyn_cast(Ptr)) { 550 | if (isExtractMember(Gep)) 551 | return false; 552 | if (isZeroIndex(Gep)) 553 | return false; 554 | if (isVirtualTable(Gep)) 555 | return false; 556 | } 557 | #endif // CONFIG_ENABLE_TYPE_BASE_OPTIMIZATION 558 | 559 | SizeOffsetEvalType SizeOffset; 560 | Value *Or = getBoundsCheckCond(Ptr, SizeOffset); 561 | ConstantInt *C = dyn_cast_or_null(Or); 562 | 563 | if (C && !C->getZExtValue()) 564 | return false; 565 | 566 | #if CONFIG_ENABLE_BUILTIN_OPTIMIZATION 567 | // TODO: Built in optimization is not always better 568 | if (Or != nullptr) 569 | // We need save the `Cond` before instrument. 570 | // Because the analysis result will changed after instrument, 571 | // but our instrument will not change the semantic. 572 | builtinCheck.push_back(std::make_pair(Ptr, Or)); 573 | else 574 | runtimeCheck.push_back(Ptr); 575 | #else // CONFIG_ENABLE_BUILTIN_OPTIMIZATION 576 | runtimeCheck.push_back(Ptr); 577 | #endif // CONFIG_ENABLE_BUILTIN_OPTIMIZATION 578 | 579 | #else // CONFIG_ENABLE_OOB_OPTIMIZATION 580 | runtimeCheck.push_back(Ptr); 581 | #endif // CONFIG_ENABLE_OOB_OPTIMIZATION 582 | return true; 583 | } 584 | 585 | bool isHeapAddress(Value *Ptr, SmallSet &Visit) { 586 | Value *S = findSource(Ptr); 587 | if (isa(S) || isa(S) || isa(S)) 588 | return false; 589 | 590 | if (Visit.count(S)) 591 | return false; 592 | 593 | Visit.insert(S); 594 | 595 | if (auto PN = dyn_cast(S)) { 596 | for (int i = 0; i < PN->getNumIncomingValues(); ++i) { 597 | Value *V = PN->getIncomingValue(i); 598 | if (isHeapAddress(V, Visit)) 599 | return true; 600 | } 601 | return false; 602 | } 603 | return true; 604 | } 605 | 606 | bool isZeroIndex(GetElementPtrInst *Gep) { 607 | for (auto &index : Gep->indices()) { 608 | if (auto c = dyn_cast(index)) { 609 | if (c->getSExtValue() != 0) 610 | return false; 611 | } else 612 | return false; 613 | } 614 | return true; 615 | } 616 | 617 | bool isSizedStruct(Type *ty) { 618 | if (isUnionTy(ty)) 619 | return false; 620 | 621 | if (StructType *sty = dyn_cast(ty)) { 622 | assert(!sty->isOpaque()); 623 | if (!sty->isSized()) 624 | return false; 625 | if (ArrayType *aty = dyn_cast(sty->elements().back())) 626 | return aty->getNumElements() != 0; 627 | return true; 628 | } 629 | 630 | return false; 631 | } 632 | 633 | bool isSizedArray(Type *ty) { 634 | if (ArrayType *aty = dyn_cast(ty)) 635 | return true; 636 | return false; 637 | } 638 | 639 | bool isExtractMember(GetElementPtrInst *Gep) { 640 | Type *ty = Gep->getPointerOperand()->getType()->getPointerElementType(); 641 | if (!isSizedStruct(ty) && !isSizedArray(ty)) 642 | return false; 643 | 644 | for (auto &index : Gep->indices()) { 645 | if (auto c = dyn_cast(index)) { 646 | if (c->getSExtValue() != 0) { 647 | return false; 648 | } 649 | } else { 650 | return false; 651 | } 652 | break; 653 | } 654 | return true; 655 | } 656 | 657 | bool isVirtualTable(GetElementPtrInst *Gep) { 658 | if (auto pty = dyn_cast( 659 | Gep->getPointerOperand()->getType()->getPointerElementType())) { 660 | if (auto fty = dyn_cast(pty->getPointerElementType())) { 661 | if (fty->getNumParams() >= 1) { 662 | if (auto fpty = dyn_cast(fty->getParamType(0))) { 663 | if (fpty->getPointerElementType()->isStructTy()) { 664 | return true; 665 | } 666 | } 667 | } 668 | } 669 | } 670 | return false; 671 | } 672 | 673 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 674 | Value *getBoundsCheckCond(Instruction *Ptr, SizeOffsetEvalType &SizeOffset) { 675 | assert(Ptr->getType()->isPointerTy() && 676 | "getBoundsCheckCond(): Ptr should be pointer type"); 677 | 678 | uint32_t NeededSize = 679 | auxiliary.count(Ptr) 680 | ? 0 681 | : DL->getTypeAllocSize(Ptr->getType()->getPointerElementType()); 682 | IRBuilder IRB(Ptr->getParent(), BasicBlock::iterator(Ptr), 683 | TargetFolder(*DL)); 684 | 685 | SizeOffset = OSOE->compute(Ptr); 686 | if (!OSOE->bothKnown(SizeOffset)) 687 | return nullptr; 688 | 689 | Value *Size = SizeOffset.first; 690 | Value *Offset = SizeOffset.second; 691 | ConstantInt *SizeCI = dyn_cast(Size); 692 | 693 | Type *IntTy = DL->getIntPtrType(Ptr->getType()); 694 | Value *NeededSizeVal = ConstantInt::get(IntTy, NeededSize); 695 | 696 | auto SizeRange = SE->getUnsignedRange(SE->getSCEV(Size)); 697 | auto OffsetRange = SE->getUnsignedRange(SE->getSCEV(Offset)); 698 | auto NeededSizeRange = SE->getUnsignedRange(SE->getSCEV(NeededSizeVal)); 699 | 700 | Value *ObjSize = IRB.CreateSub(Size, Offset); 701 | Value *Cmp2 = SizeRange.getUnsignedMin().uge(OffsetRange.getUnsignedMax()) 702 | ? ConstantInt::getFalse(Ptr->getContext()) 703 | : IRB.CreateICmpULT(Size, Offset); 704 | Value *Cmp3 = SizeRange.sub(OffsetRange) 705 | .getUnsignedMin() 706 | .uge(NeededSizeRange.getUnsignedMax()) 707 | ? ConstantInt::getFalse(Ptr->getContext()) 708 | : IRB.CreateICmpULT(ObjSize, NeededSizeVal); 709 | Value *Or = IRB.CreateOr(Cmp2, Cmp3); 710 | if ((!SizeCI || SizeCI->getValue().slt(0)) && 711 | !SizeRange.getSignedMin().isNonNegative()) { 712 | Value *Cmp1 = IRB.CreateICmpSLT(Offset, ConstantInt::get(IntTy, 0)); 713 | Or = IRB.CreateOr(Cmp1, Or); 714 | } 715 | 716 | return Or; 717 | } 718 | #endif 719 | 720 | bool searchPhi(Value *V, Value *&src, SmallSet &Visit) { 721 | if (Visit.count(V)) 722 | return true; 723 | Visit.insert(V); 724 | if (PHINode *phi = dyn_cast(V)) { 725 | for (int i = 0; i < phi->getNumIncomingValues(); ++i) { 726 | if (!searchPhi(phi->getIncomingValue(i), src, Visit)) 727 | return false; 728 | } 729 | return true; 730 | } 731 | if (GetElementPtrInst *gep = dyn_cast(V)) { 732 | return searchPhi(gep->getPointerOperand(), src, Visit); 733 | } 734 | if (BitCastInst *bc = dyn_cast(V)) { 735 | return searchPhi(bc->getOperand(0), src, Visit); 736 | } 737 | if (GEPOperator *gepo = dyn_cast(V)) { 738 | return searchPhi(gepo->getPointerOperand(), src, Visit); 739 | } 740 | if (src == nullptr) { 741 | src = V; 742 | return true; 743 | } 744 | return src == V; 745 | } 746 | 747 | Value *findSource(Value *V) { 748 | if (Instruction *I = dyn_cast(V)) { 749 | if (source.count(I)) { 750 | return source[I]; 751 | } 752 | } 753 | if (PHINode *phi = dyn_cast(V)) { 754 | Value *src = nullptr; 755 | SmallSet Visit; 756 | if (searchPhi(phi, src, Visit)) 757 | return source[phi] = src; 758 | else 759 | return source[phi] = phi; 760 | } 761 | if (GetElementPtrInst *gep = dyn_cast(V)) { 762 | return source[gep] = findSource(gep->getPointerOperand()); 763 | } 764 | if (BitCastInst *bc = dyn_cast(V)) { 765 | return source[bc] = findSource(bc->getOperand(0)); 766 | } 767 | if (GEPOperator *gepo = dyn_cast(V)) { 768 | return findSource(gepo->getPointerOperand()); 769 | } 770 | 771 | return V; 772 | } 773 | 774 | void collectInformation() { 775 | #if CONFIG_ENABLE_OOB_CHECK 776 | for (BasicBlock &BB : *F) 777 | for (Instruction &I : BB) 778 | if (CallInst *CI = dyn_cast(&I)) { 779 | Function *fp = CI->getCalledFunction(); 780 | if (fp != nullptr) { 781 | StringRef name = fp->getName(); 782 | if (name.startswith("llvm.memcpy") || 783 | name.startswith("llvm.memmove")) { 784 | 785 | addAuxInstruction(CI, CI->getArgOperand(0), CI->getArgOperand(2)); 786 | addAuxInstruction(CI, CI->getArgOperand(1), CI->getArgOperand(2)); 787 | } else if (name.startswith("llvm.memset")) { 788 | addAuxInstruction(CI, CI->getArgOperand(0), CI->getArgOperand(2)); 789 | } else if (name == "snprintf") { 790 | addAuxInstruction(CI, CI->getArgOperand(0), CI->getArgOperand(1)); 791 | } else if (name == "strncpy") { 792 | CI->setCalledFunction(M->getFunction(__STRNCPY_CHECK)); 793 | } else if (name == "strcpy") { 794 | CI->setCalledFunction(M->getFunction(__STRCPY_CHECK)); 795 | } else if (name == "strncat") { 796 | CI->setCalledFunction(M->getFunction(__STRNCAT_CHECK)); 797 | } else if (name == "strcat") { 798 | CI->setCalledFunction(M->getFunction(__STRCAT_CHECK)); 799 | } 800 | } 801 | } 802 | #endif 803 | for (BasicBlock &BB : *F) 804 | for (Instruction &I : BB) { 805 | if (isa(I) || isa(I)) { 806 | if (auxiliary.count(&I)) 807 | escaped.insert(&I); 808 | else { 809 | SmallSet Visit; 810 | if (isEscaped(&I, Visit)) { 811 | escaped.insert(&I); 812 | } 813 | } 814 | } else if (StoreInst *SI = dyn_cast(&I)) { 815 | if (SI->getValueOperand()->getType()->isPointerTy()) { 816 | #if CONFIG_ENABLE_ESCAPE_TYPE_ONLY 817 | if (!cast(SI->getValueOperand()->getType()) 818 | ->getElementType() 819 | ->isStructTy()) { 820 | escapeOptimized++; 821 | continue; 822 | } 823 | #endif 824 | if (isa(SI->getValueOperand()) || 825 | isa(SI->getValueOperand())) { 826 | escapeOptimized++; 827 | continue; 828 | } 829 | 830 | Instruction *ptr = 831 | dyn_cast_or_null(SI->getValueOperand()); 832 | if (ptr && source.count(ptr) && isa(source[ptr])) { 833 | escapeOptimized++; 834 | continue; 835 | } 836 | #if CONFIG_ENABLE_STACK_ESCAPE_OPTIMIZATION 837 | 838 | Instruction *loc = 839 | dyn_cast_or_null(SI->getPointerOperand()); 840 | if (loc && source.count(loc) && 841 | (isa(source[loc]) || 842 | isa(SI->getPointerOperand()))) { 843 | escapeOptimized++; 844 | continue; 845 | } 846 | #endif 847 | storeInsts.push_back(SI); 848 | } 849 | } 850 | } 851 | for (BasicBlock &BB : *F) 852 | for (Instruction &I : BB) 853 | findSource(&I); 854 | } 855 | 856 | void addAuxInstruction(CallInst *CI, Value *Ptr, Value *Len) { 857 | IRBuilder<> irBuilder(CI); 858 | auto BC = irBuilder.CreatePointerCast(Ptr, voidPointerType); 859 | auto GEP = 860 | irBuilder.CreateGEP(BC, irBuilder.CreatePointerCast(Len, int64Type)); 861 | 862 | if (auto I = dyn_cast(BC)) 863 | auxiliary.insert(I); 864 | if (auto I = dyn_cast(GEP)) 865 | auxiliary.insert(I); 866 | } 867 | 868 | bool isMustEscapeInstruction(User *I) { 869 | #if CONFIG_ENABLE_READ_CHECK 870 | if (isa(I)) 871 | return true; 872 | #endif 873 | if (isa(I) || isa(I)) 874 | return true; 875 | 876 | if (auto CB = dyn_cast(I)) { 877 | Function *F = CB->getCalledFunction(); 878 | if (F != nullptr) { 879 | static SmallVector whitelist = { 880 | "llvm.prefetch.", 881 | "llvm.lifetime.start", 882 | "llvm.lifetime.end", 883 | }; 884 | 885 | for (auto name : whitelist) { 886 | if (F->getName().startswith(name)) 887 | return false; 888 | } 889 | } 890 | return true; 891 | } 892 | 893 | return false; 894 | } 895 | 896 | bool isEscaped(Instruction *I, SmallSet &Visit) { 897 | if (Visit.count(I)) 898 | return false; 899 | 900 | Visit.insert(I); 901 | for (auto user : I->users()) 902 | if (isMustEscapeInstruction(user)) 903 | return true; 904 | for (auto user : I->users()) 905 | if (auto PN = dyn_cast(user)) 906 | if (isEscaped(PN, Visit)) 907 | return true; 908 | return false; 909 | } 910 | 911 | void builtinOptimize() { 912 | for (BasicBlock &BB : *F) { 913 | for (Instruction &I : BB) { 914 | if (GetElementPtrInst *gep = dyn_cast(&I)) { 915 | // TODO: Simply ignoring it may cause some bugs 916 | if (gep->getType()->isPointerTy()) { 917 | if (!allocateChecker(gep, runtimeCheck, builtinCheck)) { 918 | gepIgnoreOptimized++; 919 | } 920 | } 921 | } else if (BitCastInst *bc = dyn_cast(&I)) { 922 | if (bc->getSrcTy()->isPointerTy() && bc->getDestTy()->isPointerTy()) { 923 | Type *srcTy = bc->getSrcTy()->getPointerElementType(); 924 | Type *dstTy = bc->getDestTy()->getPointerElementType(); 925 | 926 | if (!srcTy->isSized() || !dstTy->isSized()) 927 | continue; 928 | 929 | if (isUnionTy(dstTy)) 930 | continue; 931 | 932 | if (!isUnionTy(srcTy)) { 933 | unsigned int srcSize = DL->getTypeAllocSize(srcTy); 934 | unsigned int dstSize = DL->getTypeAllocSize(dstTy); 935 | 936 | if (srcSize >= dstSize) 937 | continue; 938 | } 939 | 940 | if (!allocateChecker(bc, runtimeCheck, builtinCheck)) 941 | bitcastIgnoreOptimized++; 942 | } 943 | } 944 | } 945 | } 946 | } 947 | 948 | bool isUnionTy(Type *ty) { 949 | if (auto sty = dyn_cast(ty)) 950 | return sty->hasName() && sty->getName().startswith("union."); 951 | return false; 952 | } 953 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 954 | void partialBuiltinOptimize() { 955 | for (auto &I : runtimeCheck) { 956 | auto src = source[I]; 957 | if (!cluster.count(src)) 958 | cluster[src] = new SmallVector(); 959 | cluster[src]->push_back(I); 960 | } 961 | 962 | SmallVector newRuntimeCheck; 963 | for (auto &[key, value] : cluster) { 964 | if (isa(key)) { 965 | dbgs() << "[WARNING] Unhandled Value: " << *key << "\n"; 966 | continue; 967 | } 968 | 969 | Instruction *InsertPoint = dependenceOptimize(key, value); 970 | int64_t weight = 0, dom = 0; 971 | for (auto ins : *value) { 972 | if (ins->getParent() == InsertPoint->getParent()) { 973 | dom += 1; 974 | } else { 975 | weight += 1; 976 | if (Loop *Lop = LI->getLoopFor(ins->getParent())) 977 | weight += 5; 978 | } 979 | } 980 | #if CONFIG_ENABLE_MERGE_OPTIMIZATION 981 | if (dom > 1 || weight > 2) 982 | partialCheck.push_back(std::make_pair(key, value)); 983 | else 984 | newRuntimeCheck.append(*value); 985 | #else 986 | newRuntimeCheck.append(*value); 987 | #endif 988 | } 989 | 990 | runtimeCheck.swap(newRuntimeCheck); 991 | } 992 | 993 | Instruction *dependenceOptimize(Value *key, 994 | SmallVector *value) { 995 | Instruction *InsertPoint = nullptr; 996 | 997 | if (isa(key)) 998 | InsertPoint = getInsertionPointAfterDef(dyn_cast(key)); 999 | else if (isa(key)) 1000 | InsertPoint = &(F->getEntryBlock().front()); 1001 | 1002 | #if CONFIG_ENABLE_REMOVE_REDUNDANT_OPTIMIZATION 1003 | IRBuilder irBuilder( 1004 | InsertPoint->getParent(), 1005 | BasicBlock::iterator(InsertPoint->getIterator()), TargetFolder(*DL)); 1006 | 1007 | SmallVector newvalue; 1008 | for (size_t i = 0; i < value->size(); ++i) { 1009 | bool optimized = false; 1010 | if (auto I = dyn_cast((*value)[i])) { 1011 | for (size_t j = 0; j < value->size(); ++j) { 1012 | if (i != j) { 1013 | if (auto J = dyn_cast((*value)[j])) { 1014 | if (DT->dominates(J, I) || PDT->dominates(J, I)) { 1015 | if (I->getPointerOperand() == J->getPointerOperand()) { 1016 | if (isSizedStruct(I->getType()->getPointerElementType())) { 1017 | Value *Iindex = GetSingleIndex(I); 1018 | Value *Jindex = GetSingleIndex(J); 1019 | if (Iindex->getType() == Jindex->getType()) { 1020 | irBuilder.SetInsertPoint(J); 1021 | auto Offset = irBuilder.CreateSub(Jindex, Iindex); 1022 | auto OffsetRange = 1023 | SE->getSignedRange(SE->getSCEV(Offset)); 1024 | if (!OffsetRange.getSignedMin().isNegative()) { 1025 | optimized = true; 1026 | break; 1027 | } 1028 | } 1029 | } 1030 | if (I->getNumIndices() == 1 && J->getNumIndices() == 1) { 1031 | Value *Iindex = GetSingleIndex(I); 1032 | Value *Jindex = GetSingleIndex(J); 1033 | if (Iindex->getType() == Jindex->getType()) { 1034 | irBuilder.SetInsertPoint(J); 1035 | auto Offset = irBuilder.CreateSub(Jindex, Iindex); 1036 | auto OffsetRange = 1037 | SE->getSignedRange(SE->getSCEV(Offset)); 1038 | if (!OffsetRange.getSignedMin().isNegative()) { 1039 | optimized = true; 1040 | break; 1041 | } 1042 | } 1043 | } 1044 | } 1045 | } 1046 | } 1047 | } 1048 | } 1049 | if (optimized) 1050 | gepDepOptimized++; 1051 | else { 1052 | newvalue.push_back(I); 1053 | } 1054 | } 1055 | } 1056 | value->swap(newvalue); 1057 | #endif 1058 | return InsertPoint; 1059 | } 1060 | 1061 | Value *GetSingleIndex(GetElementPtrInst *gep) { 1062 | for (auto &Ind : gep->indices()) { 1063 | auto V = Ind.get(); 1064 | while (true) { 1065 | if (auto I = dyn_cast(V)) { 1066 | if (I->getNumOperands() == 1) 1067 | V = I->getOperand(0); 1068 | else 1069 | break; 1070 | } else 1071 | break; 1072 | } 1073 | return V; 1074 | } 1075 | return nullptr; 1076 | } 1077 | #endif 1078 | void escapeOptimize() { 1079 | SmallVector newStoreInsts; 1080 | 1081 | for (auto *SI : storeInsts) { 1082 | bool flag = false; 1083 | if (auto I = dyn_cast(SI->getValueOperand())) 1084 | if (source.count(I)) 1085 | if (LoadInst *LI = dyn_cast(source[I])) 1086 | if (LI->getPointerOperand() == SI->getPointerOperand()) 1087 | flag = true; 1088 | if (flag) 1089 | escapeOptimized++; 1090 | else 1091 | newStoreInsts.push_back(SI); 1092 | } 1093 | storeInsts.swap(newStoreInsts); 1094 | } 1095 | 1096 | void applyInstrument() { 1097 | #if CONFIG_ENABLE_OOB_CHECK 1098 | for (auto &I : runtimeCheck) { 1099 | if (isa(I)) { 1100 | gepRuntimeCheck++; 1101 | addGepRuntimeCheck(I); 1102 | } else { 1103 | bitcastRuntimeCheck++; 1104 | addBitcastRuntimeCheck(I); 1105 | } 1106 | } 1107 | #if CONFIG_ENABLE_OOB_OPTIMIZATION 1108 | for (auto &[V, S] : partialCheck) { 1109 | for (auto &I : *S) 1110 | if (isa(I)) 1111 | gepPartialCheck++; 1112 | else 1113 | bitcastPartialCheck++; 1114 | 1115 | addPartialCheck(V, S); 1116 | } 1117 | 1118 | for (auto &[I, cond] : builtinCheck) { 1119 | if (isa(I)) 1120 | gepBuiltinCheck++; 1121 | else 1122 | bitcastBuiltinCheck++; 1123 | 1124 | addBuiltinCheck(I, cond); 1125 | } 1126 | #endif 1127 | #endif 1128 | #if CONFIG_ENABLE_UAF_CHECK 1129 | for (auto SI : storeInsts) { 1130 | escapeTrace++; 1131 | addEscape(SI); 1132 | } 1133 | #endif 1134 | } 1135 | }; 1136 | } // namespace 1137 | 1138 | char VProtectionPass::ID = 0; 1139 | 1140 | static void registerPass(const PassManagerBuilder &, 1141 | legacy::PassManagerBase &PM) { 1142 | PM.add(new VProtectionPass()); 1143 | } 1144 | 1145 | static RegisterStandardPasses 1146 | RegisterMyPass(PassManagerBuilder::EP_OptimizerLast, registerPass); 1147 | 1148 | #if CONFIG_ENABLE_OOB_OPTIMIZATION == 0 1149 | static RegisterStandardPasses 1150 | RegisterNoOptPass(PassManagerBuilder::EP_EnabledOnOptLevel0, registerPass); 1151 | #endif -------------------------------------------------------------------------------- /src/compiler_pass/config.h: -------------------------------------------------------------------------------- 1 | #define CONFIG_ENABLE_UAF_CHECK 1 2 | #define CONFIG_ENABLE_OOB_CHECK 1 3 | #define CONFIG_ENABLE_READ_CHECK 1 4 | #define CONFIG_ENABLE_OOB_OPTIMIZATION 1 5 | #define CONFIG_ENABLE_TYPE_BASE_OPTIMIZATION 1 6 | #define CONFIG_ENABLE_BUILTIN_OPTIMIZATION 1 7 | #define CONFIG_ENABLE_MERGE_OPTIMIZATION 1 8 | #define CONFIG_ENABLE_REMOVE_REDUNDANT_OPTIMIZATION 1 9 | #define CONFIG_ENABLE_REPORT 1 10 | #define CONFIG_ENABLE_STACK_ESCAPE_OPTIMIZATION 0 11 | #define CONFIG_ENABLE_ESCAPE_TYPE_ONLY 0 -------------------------------------------------------------------------------- /test/basic/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(CMAKE_C_COMPILER ${CMAKE_SOURCE_DIR}/tools/vcc) 2 | set(CMAKE_CXX_COMPILER ${CMAKE_SOURCE_DIR}/tools/v++) 3 | 4 | add_executable(recursive recursive.c) 5 | add_executable(loop loop.c) 6 | add_executable(pressure pressure.c) 7 | add_executable(prime prime.cpp) 8 | add_executable(safe safe.cpp) 9 | add_executable(unsafe unsafe.cpp) 10 | add_executable(fakeoob fakeoob.c) 11 | -------------------------------------------------------------------------------- /test/basic/bullet.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int **a = (int **)malloc(sizeof(int *) * 8); 7 | for (int i = 0; i < 8; ++i) 8 | { 9 | a[i] = (int *)malloc(sizeof(int)); 10 | a[i][0] = i; 11 | } 12 | 13 | int x = 2; 14 | for (int i = 0; i < 8; ++i) 15 | if ((x *= 2) > 32) { 16 | printf("free %d\n", i); 17 | free(a[i]); 18 | break; 19 | } 20 | 21 | for (int i = 0; i < 8; ++i) 22 | printf("%d\r", a[i][0]); 23 | } -------------------------------------------------------------------------------- /test/basic/cmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define LEN 1000000000 5 | 6 | char randc() { 7 | static unsigned int c = 100; 8 | return (char)((c = c * c) % 26 + 'a'); 9 | } 10 | 11 | void gstr(char *s) { 12 | for (int i = 0; i < LEN; ++i) 13 | *s++ = randc(); 14 | } 15 | 16 | int diff(char *s, char *t) { 17 | int count = 0; 18 | for (int i = 0; i < LEN; ++i) 19 | count += *s++ != *t++; 20 | return count; 21 | } 22 | 23 | int main() { 24 | char* s = malloc(LEN); 25 | char* t = malloc(LEN); 26 | gstr(s); 27 | gstr(t); 28 | printf("%d\n", diff(s, t)); 29 | } -------------------------------------------------------------------------------- /test/basic/deps.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node { 5 | int *xs; 6 | int len; 7 | }; 8 | 9 | void __attribute__((noinline)) create(struct node *nd, int extra) 10 | { 11 | nd->xs[nd->len - 1] = 1; 12 | nd->xs[nd->len - 2] = 2; 13 | nd->xs[nd->len - 3] = 3; 14 | 15 | 16 | nd->xs[extra - 1] = 1; 17 | nd->xs[extra - 2] = 2; 18 | nd->xs[extra - 3] = 3; 19 | } 20 | 21 | int main() { 22 | struct node *nd = malloc(sizeof(struct node)); 23 | nd->len = 3; 24 | nd->xs = malloc(nd->len * sizeof(int)); 25 | create(nd, 3); 26 | printf("%d %d %d\n", nd->xs[0], nd->xs[1], nd->xs[2]); 27 | } -------------------------------------------------------------------------------- /test/basic/escape.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define SIZE 0x1000 5 | char **pool; 6 | 7 | unsigned int randnum() 8 | { 9 | static unsigned int a = 2, b = 3, c = 5, x = 7; 10 | return x = x * x * a + b * x + c; 11 | } 12 | 13 | int main() 14 | { 15 | pool = (char **)malloc(sizeof(char *) * SIZE); 16 | for (int i = 0; i < SIZE; ++i) 17 | { 18 | pool[i] = (char *)malloc(sizeof(char)); 19 | pool[i][0] = (i % 26) + 'a'; 20 | } 21 | 22 | for (int k = 0; k < SIZE; ++k) 23 | { 24 | for (int i = 1; i < SIZE; ++i) 25 | { 26 | int j = randnum() % i; 27 | char *tmp = pool[i]; 28 | pool[i] = pool[j]; 29 | pool[j] = tmp; 30 | } 31 | } 32 | 33 | for (int i = 0; i < SIZE; ++i) { 34 | putchar(*pool[i]); 35 | free(pool[i]); 36 | } 37 | putchar(10); 38 | free(pool); 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /test/basic/fakeoob.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | unsigned int random() 5 | { 6 | static unsigned int a = 2, b = 3, c = 5, x = 7; 7 | return x = a * x * x + b * x + c; 8 | } 9 | 10 | char str[] = "0123456789"; 11 | 12 | int main() 13 | { 14 | int len = strlen(str); 15 | char* ptr; 16 | unsigned int j; 17 | 18 | for (int i = 1; i < 1000; ++i) 19 | { 20 | j = random() % 0x7fff; 21 | ptr = str + j; 22 | if (j < 10) { 23 | *ptr = '7'; 24 | } 25 | } 26 | 27 | printf("Tester 0: "); 28 | putchar(*(ptr - j)); 29 | printf("\nTester 1: "); 30 | putchar(*(ptr - 1)); 31 | puts(str); 32 | } 33 | -------------------------------------------------------------------------------- /test/basic/loop.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int __attribute__((noinline)) fib(int *a, int n) 5 | { 6 | a[2] = 2; 7 | a[0] = 1; 8 | a[1] = 1; 9 | for (int i = 3; i <= n; ++i) 10 | a[i] = a[i - 1] + a[i - 2]; 11 | 12 | return a[n]; 13 | } 14 | 15 | int __attribute__((noinline)) square_sum(int *a, int n) 16 | { 17 | int sum = 0; 18 | for (int i = 0; i < n; ++i) 19 | a[i] = i * i; 20 | for (int i = 0; i < n; ++i) 21 | sum += a[i]; 22 | 23 | return sum; 24 | } 25 | 26 | int main() 27 | { 28 | int *a = (int *)malloc(sizeof(int) * 1001); 29 | 30 | int x = 0; 31 | for (int j = 0; j < 99999; ++j) 32 | { 33 | for (int n = 2; n <= 1000; ++n) 34 | { 35 | x ^= fib(a, 20); 36 | x ^= square_sum(a, 100); 37 | } 38 | } 39 | 40 | printf("%d\n", x); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /test/basic/pressure.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int __attribute__ ((noinline)) Eratosthenes(int *is_prime, int n) 5 | { 6 | int max_prime = 0; 7 | 8 | for (int i = 0; i < n; ++i) 9 | is_prime[i] = 1; 10 | 11 | is_prime[0] = is_prime[1] = 0; 12 | for (int i = 2; i < n; ++i) 13 | { 14 | if (is_prime[i]) 15 | { 16 | max_prime = i; 17 | if ((long long)i * i < n) 18 | for (int j = i * i; j < n; j += i) 19 | is_prime[j] = 0; 20 | } 21 | } 22 | 23 | return max_prime; 24 | } 25 | 26 | int __attribute__ ((noinline)) Euler(int *is_prime, int n) 27 | { 28 | int *prime = (int*) malloc(sizeof(int) * n); 29 | int cnt = 0; 30 | 31 | for (int i = 0; i < n; ++i) 32 | is_prime[i] = 1; 33 | 34 | is_prime[0] = is_prime[1] = 0; 35 | 36 | for (int i = 2; i < n; ++i) 37 | { 38 | 39 | if (is_prime[i]) 40 | prime[cnt++] = i; 41 | 42 | for (int j = 0; j < cnt; ++j) 43 | { 44 | if ((long long)i * prime[j] >= n) 45 | break; 46 | is_prime[i * prime[j]] = 0; 47 | if (i % prime[j] == 0) 48 | { 49 | break; 50 | } 51 | } 52 | } 53 | 54 | free(prime); 55 | return cnt; 56 | } 57 | 58 | int main() 59 | { 60 | int *is_prime = (int*) malloc(sizeof(int) * 100000); 61 | 62 | int res = 0; 63 | for (int n = 0; n < 100000; n += 10) 64 | res ^= Eratosthenes(is_prime, n) ^ Euler(is_prime, n); 65 | 66 | printf("FLAG: %d\n", res); 67 | free(is_prime); 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /test/basic/prime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int Eratosthenes(int n) 4 | { 5 | int *is_prime = new int[n]; 6 | int max_prime = 0; 7 | 8 | for (int i = 0; i < n; ++i) 9 | is_prime[i] = 1; 10 | 11 | is_prime[0] = is_prime[1] = 0; 12 | for (int i = 2; i < n; ++i) 13 | { 14 | if (is_prime[i]) 15 | { 16 | max_prime = i; 17 | if ((long long)i * i < n) 18 | for (int j = i * i; j < n; j += i) 19 | is_prime[j] = 0; 20 | } 21 | } 22 | 23 | return max_prime; 24 | } 25 | 26 | int Euler(int n) 27 | { 28 | int *is_prime = new int[n]; 29 | int *prime = new int[n]; 30 | int cnt = 0; 31 | 32 | for (int i = 0; i < n; ++i) 33 | is_prime[i] = 1; 34 | 35 | is_prime[0] = is_prime[1] = 0; 36 | 37 | for (int i = 2; i < n; ++i) 38 | { 39 | 40 | if (is_prime[i]) 41 | prime[cnt++] = i; 42 | 43 | for (int j = 0; j < cnt; ++j) 44 | { 45 | if ((long long)i * prime[j] >= n) 46 | break; 47 | is_prime[i * prime[j]] = 0; 48 | if (i % prime[j] == 0) 49 | { 50 | break; 51 | } 52 | } 53 | } 54 | 55 | return cnt; 56 | } 57 | 58 | int main() 59 | { 60 | printf("The maximum prime between 1 ~ 100000 is %d\n", Eratosthenes(100000)); 61 | printf("The maximum prime between 1 ~ 1000000 is %d\n", Eratosthenes(1000000)); 62 | printf("The maximum prime between 1 ~ 10000000 is %d\n", Eratosthenes(10000000)); 63 | printf("The maximum prime between 1 ~ 100000000 is %d\n", Eratosthenes(100000000)); 64 | 65 | printf("The number of prime between 1 ~ 100000 is %d\n", Euler(100000)); 66 | printf("The number of prime between 1 ~ 1000000 is %d\n", Euler(1000000)); 67 | printf("The number of prime between 1 ~ 10000000 is %d\n", Euler(10000000)); 68 | printf("The number of prime between 1 ~ 100000000 is %d\n", Euler(100000000)); 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /test/basic/recursive.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct state_t 5 | { 6 | __int64_t count1; 7 | __int64_t count2; 8 | __int64_t count3; 9 | }; 10 | 11 | void search(struct state_t *state, int depth) 12 | { 13 | __int64_t tmp = ++state->count1; 14 | state->count1 += state->count2; 15 | state->count2 += state->count3; 16 | state->count3 += tmp; 17 | 18 | if (depth == 12) 19 | return; 20 | for (int i = 0; i <= depth; ++i) 21 | search(state, depth + 1); 22 | } 23 | 24 | int main() 25 | { 26 | struct state_t *a = (struct state_t *) malloc(sizeof(struct state_t)); 27 | struct state_t *b = (struct state_t *) malloc(sizeof(struct state_t)); 28 | struct state_t *c = (struct state_t *) malloc(sizeof(struct state_t)); 29 | 30 | a->count1 = 0; 31 | a->count2 = 0; 32 | a->count3 = 0; 33 | 34 | b->count1 = 0; 35 | b->count2 = 0; 36 | b->count3 = 0; 37 | 38 | c->count1 = 0; 39 | c->count2 = 0; 40 | c->count3 = 0; 41 | 42 | search(a, 0); 43 | search(b, 0); 44 | search(c, 0); 45 | 46 | printf("1: %ld\n", a->count1); 47 | printf("2: %ld\n", b->count2); 48 | printf("3: %ld\n", c->count3); 49 | } -------------------------------------------------------------------------------- /test/basic/safe.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | unsigned int random() 5 | { 6 | static unsigned int a = 2, b = 3, c = 5, x = 7; 7 | return x = a * x * x + b * x + c; 8 | } 9 | 10 | int main() 11 | { 12 | unsigned int a[5]; 13 | unsigned int *b = new unsigned int[5]; 14 | 15 | a[4] = 12; 16 | a[random() & 3] ^= random(); 17 | a[1] = 13; 18 | a[random() & 3] ^= random(); 19 | a[2] = 14; 20 | a[random() & 3] ^= random(); 21 | a[3] = 15; 22 | a[random() & 3] ^= random(); 23 | 24 | b[4] = 16; 25 | b[random() & 3] ^= random(); 26 | b[1] = 17; 27 | b[random() & 3] ^= random(); 28 | b[2] = 18; 29 | b[random() & 3] ^= random(); 30 | b[3] = 19; 31 | a[random() & 3] ^= random(); 32 | 33 | printf("0x%x\n", a[4] ^ a[1] ^ a[2] ^ a[3]); 34 | printf("0x%x\n", b[4] ^ b[1] ^ b[2] ^ b[3]); 35 | 36 | int n = 0xfff; 37 | int *c = new int[n]; 38 | 39 | memset(c, 0, sizeof(int) * n); 40 | for (int i = 0; i < n; ++i) 41 | { 42 | int v = random() & 0xffff; 43 | if (v < n) 44 | c[v] = random(); 45 | } 46 | 47 | int x = 0; 48 | for (int i = 0; i < n; ++i) 49 | x ^= c[i]; 50 | 51 | printf("0x%x\n", x); 52 | } -------------------------------------------------------------------------------- /test/basic/uaf_ex.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | char *srcGrid; 4 | void start(char **ptr){ 5 | // first escape 6 | *ptr = malloc(0x64b54000); 7 | 8 | // second escape 9 | // generate a false escape 10 | *ptr += 0x186a00; 11 | 12 | } 13 | 14 | void end(char **ptr){ 15 | free(*ptr - 0x186a00); 16 | } 17 | int main(){ 18 | 19 | start( &srcGrid ); 20 | end( &srcGrid ); 21 | return 0; 22 | } -------------------------------------------------------------------------------- /test/basic/unsafe.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | unsigned int random() 5 | { 6 | static unsigned int a = 2, b = 3, c = 5, x = 7; 7 | return x = a * x * x + b * x + c; 8 | } 9 | 10 | int main() 11 | { 12 | int a[1000]; 13 | for (int i = 0; i < 1000; ++i) 14 | { 15 | int v = random() % 1001; 16 | if (v >= 1000) 17 | printf("ERROR(%d)\n", v); 18 | a[v] = random(); 19 | } 20 | 21 | int x = 0; 22 | for (int i = 0; i < 1000; ++i) 23 | x ^= a[i]; 24 | 25 | printf("0x%x\n", x); 26 | } -------------------------------------------------------------------------------- /test/cpu2006/native.cfg: -------------------------------------------------------------------------------- 1 | ignore_errors = yes 2 | tune = base 3 | basepeak = yes 4 | ext = native 5 | output_format = asc,csv,html 6 | flagsurl0 = $[top]/config/flags/Example-gcc4x-flags-revA.xml 7 | flagsurl1 = $[top]/config/flags/Example-linux-platform-revA.xml 8 | reportable = yes 9 | teeout = yes 10 | teerunout = yes 11 | license_num = 0 12 | 13 | default=default=default=default: 14 | CC = %{enter your compiler path here}clang -std=gnu89 15 | CXX = %{enter your compiler path here}clang++ -std=c++03 16 | 17 | ##################################################################### 18 | # Notes 19 | ##################################################################### 20 | notes_submit_000 ='numactl' was used to bind copies to the cores. 21 | notes_submit_005 =See the configuration file for details. 22 | 23 | notes_os_000 ='ulimit -s unlimited' was used to set environment stack size 24 | 25 | ##################################################################### 26 | # Optimization 27 | ##################################################################### 28 | 29 | default=base=default=default: 30 | COPTIMIZE = -O1 31 | CXXOPTIMIZE = -O1 32 | FOPTIMIZE = -O1 33 | 34 | ##################################################################### 35 | # 32/64 bit Portability Flags - all 36 | ##################################################################### 37 | 38 | default=base=default=default: 39 | PORTABILITY = -DSPEC_CPU_LP64 40 | 41 | ##################################################################### 42 | # Portability Flags 43 | ##################################################################### 44 | 45 | 400.perlbench=default=default=default: 46 | CPORTABILITY = -DSPEC_CPU_LINUX_X64 47 | 48 | 462.libquantum=default=default=default: 49 | CPORTABILITY = -DSPEC_CPU_LINUX 50 | 51 | 483.xalancbmk=default=default=default: 52 | CXXPORTABILITY = -DSPEC_CPU_LINUX 53 | 54 | 481.wrf=default=default=default: 55 | wrf_data_header_size = 8 56 | CPORTABILITY = -DSPEC_CPU_CASE_FLAG -DSPEC_CPU_LINUX 57 | -------------------------------------------------------------------------------- /test/cpu2006/violet.cfg: -------------------------------------------------------------------------------- 1 | ignore_errors = yes 2 | tune = base 3 | basepeak = yes 4 | ext = violet 5 | output_format = asc,csv,html 6 | flagsurl0 = $[top]/config/flags/Example-gcc4x-flags-revA.xml 7 | flagsurl1 = $[top]/config/flags/Example-linux-platform-revA.xml 8 | reportable = yes 9 | teeout = yes 10 | teerunout = yes 11 | license_num = 0 12 | 13 | default=default=default=default: 14 | CC = %{enter your compiler path here}vcc -std=gnu89 15 | CXX = %{enter your compiler path here}v++ -std=c++03 16 | 17 | ##################################################################### 18 | # Notes 19 | ##################################################################### 20 | notes_submit_000 ='numactl' was used to bind copies to the cores. 21 | notes_submit_005 =See the configuration file for details. 22 | 23 | notes_os_000 ='ulimit -s unlimited' was used to set environment stack size 24 | 25 | ##################################################################### 26 | # Optimization 27 | ##################################################################### 28 | 29 | default=base=default=default: 30 | COPTIMIZE = -O1 31 | CXXOPTIMIZE = -O1 32 | FOPTIMIZE = -O1 33 | 34 | ##################################################################### 35 | # 32/64 bit Portability Flags - all 36 | ##################################################################### 37 | 38 | default=base=default=default: 39 | PORTABILITY = -DSPEC_CPU_LP64 40 | 41 | ##################################################################### 42 | # Portability Flags 43 | ##################################################################### 44 | 45 | 400.perlbench=default=default=default: 46 | CPORTABILITY = -DSPEC_CPU_LINUX_X64 47 | 48 | 462.libquantum=default=default=default: 49 | CPORTABILITY = -DSPEC_CPU_LINUX 50 | 51 | 483.xalancbmk=default=default=default: 52 | CXXPORTABILITY = -DSPEC_CPU_LINUX 53 | 54 | 481.wrf=default=default=default: 55 | wrf_data_header_size = 8 56 | CPORTABILITY = -DSPEC_CPU_CASE_FLAG -DSPEC_CPU_LINUX 57 | -------------------------------------------------------------------------------- /test/cpu2017/native.cfg: -------------------------------------------------------------------------------- 1 | %ifndef %{label} 2 | % define label "native" 3 | %endif 4 | 5 | %ifndef %{build_ncpus} 6 | % define build_ncpus 8 7 | %endif 8 | 9 | command_add_redirect = 1 10 | flagsurl = $[top]/config/flags/clang.xml 11 | ignore_errors = 1 12 | iterations = 1 13 | label = %{label} 14 | line_width = 1020 15 | log_line_width = 1020 16 | makeflags = --jobs=%{build_ncpus} 17 | mean_anyway = 1 18 | output_format = txt,html,cfg,pdf,csv 19 | preenv = 1 20 | reportable = 0 21 | tune = base 22 | 23 | intrate,fprate: 24 | copies = 1 25 | intspeed,fpspeed: 26 | threads = 1 27 | 28 | default: 29 | CC = %{enter your compiler path here}clang -std=c99 30 | CXX = %{enter your compiler path here}clang++ -std=c++03 31 | 32 | CC_VERSION_OPTION = --version 33 | CXX_VERSION_OPTION = --version 34 | 35 | default: 36 | sw_base_ptrsize = 64-bit 37 | sw_peak_ptrsize = 64-bit 38 | 39 | any_fortran: 40 | fail_build = 1 41 | 42 | default: 43 | EXTRA_PORTABILITY = -DSPEC_LP64 44 | 45 | 500.perlbench_r,600.perlbench_s: 46 | %if %{bits} == 32 47 | % define suffix IA32 48 | %else 49 | % define suffix X64 50 | %endif 51 | PORTABILITY = -DSPEC_LINUX_%{suffix} 52 | 53 | 502.gcc_r,602.gcc_s: 54 | EXTRA_CFLAGS = -fno-strict-aliasing -fgnu89-inline 55 | 56 | 510.parest_r: 57 | CXXPORTABILITY = -DSPEC_PAREST_STD_FLUSH_WORKAROUND=1 58 | 59 | 523.xalancbmk_r,623.xalancbmk_s: 60 | CXXPORTABILITY = -DSPEC_LINUX 61 | 62 | 525.x264_r,625.x264_s: 63 | PORTABILITY = -fcommon 64 | 65 | 526.blender_r: 66 | PORTABILITY = -funsigned-char -DSPEC_LINUX 67 | CXXPORTABILITY = -D__BOOL_DEFINED 68 | 69 | default=base: 70 | OPTIMIZE = -O1 71 | 72 | default: 73 | sw_compiler001 = Clang 12 74 | -------------------------------------------------------------------------------- /test/cpu2017/runall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | source shrc 4 | 5 | runcpu --rebuild --action=build --config=native intspeed_no_fortran 6 | runcpu --rebuild --action=build --config=native fpspeed_no_fortran 7 | runcpu --rebuild --action=build --config=violet intspeed_no_fortran 8 | runcpu --rebuild --action=build --config=violet fpspeed_no_fortran 9 | 10 | runcpu --config=native intspeed_no_fortran 11 | runcpu --config=native fpspeed_no_fortran 12 | 13 | export LD_LIBRARY_PATH={your path}violet/build/src/safe_tcmalloc/tcmalloc 14 | runcpu --config=violet intspeed_no_fortran 15 | runcpu --config=violet fpspeed_no_fortran 16 | -------------------------------------------------------------------------------- /test/cpu2017/violet.cfg: -------------------------------------------------------------------------------- 1 | %ifndef %{label} 2 | % define label "violet" 3 | %endif 4 | 5 | %ifndef %{build_ncpus} 6 | % define build_ncpus 8 7 | %endif 8 | 9 | command_add_redirect = 1 10 | flagsurl = $[top]/config/flags/clang.xml 11 | ignore_errors = 1 12 | iterations = 1 13 | label = %{label} 14 | line_width = 1020 15 | log_line_width = 1020 16 | makeflags = --jobs=%{build_ncpus} 17 | mean_anyway = 1 18 | output_format = txt,html,cfg,pdf,csv 19 | preenv = 1 20 | reportable = 0 21 | tune = base 22 | 23 | intrate,fprate: 24 | copies = 1 25 | intspeed,fpspeed: 26 | threads = 1 27 | 28 | default: 29 | CC = %{enter your compiler path here}vcc -std=c99 30 | CXX = %{enter your compiler path here}v++ -std=c++03 31 | 32 | CC_VERSION_OPTION = --version 33 | CXX_VERSION_OPTION = --version 34 | 35 | default: 36 | sw_base_ptrsize = 64-bit 37 | sw_peak_ptrsize = 64-bit 38 | 39 | any_fortran: 40 | fail_build = 1 41 | 42 | default: 43 | EXTRA_PORTABILITY = -DSPEC_LP64 44 | 45 | 500.perlbench_r,600.perlbench_s: 46 | %if %{bits} == 32 47 | % define suffix IA32 48 | %else 49 | % define suffix X64 50 | %endif 51 | PORTABILITY = -DSPEC_LINUX_%{suffix} 52 | 53 | 502.gcc_r,602.gcc_s: 54 | EXTRA_CFLAGS = -fno-strict-aliasing -fgnu89-inline 55 | 56 | 510.parest_r: 57 | CXXPORTABILITY = -DSPEC_PAREST_STD_FLUSH_WORKAROUND=1 58 | 59 | 523.xalancbmk_r,623.xalancbmk_s: 60 | CXXPORTABILITY = -DSPEC_LINUX 61 | 62 | 525.x264_r,625.x264_s: 63 | PORTABILITY = -fcommon 64 | 65 | 526.blender_r: 66 | PORTABILITY = -funsigned-char -DSPEC_LINUX 67 | CXXPORTABILITY = -D__BOOL_DEFINED 68 | 69 | default=base: 70 | OPTIMIZE = -O1 71 | 72 | default: 73 | sw_compiler001 = Clang 12 74 | -------------------------------------------------------------------------------- /test/juliet/test.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def main(): 4 | executables = [] 5 | badthings = [] 6 | 7 | with open("dump", 'w') as f: 8 | f.write('100 ' * 0x1000) 9 | 10 | for path, dirs, files in os.walk('testcases'): 11 | for file in files: 12 | if file.endswith('.out'): 13 | executables.append(os.path.join(path, file)) 14 | 15 | for idx, executable in enumerate(sorted(executables)): 16 | print(f"Running {idx}.{executable}") 17 | exit_code = os.system(f"LD_LIBRARY_PATH=~/violet/build/src/safe_tcmalloc/tcmalloc {executable} < dump > res.err 2>&1") 18 | 19 | if exit_code != 0: 20 | with open('res.err') as f: 21 | if 'OOB detected' not in f.read(): 22 | badthings.append(executable) 23 | print(f"ERROR: {executable}") 24 | 25 | for badthing in badthings: 26 | print(f"ERROR: {badthing}") 27 | 28 | print(f"BAD/SKIP/ALL {len(badthings)}/{len(skipthings)}/{len(executables)}") 29 | 30 | if __name__ == "__main__": 31 | main() 32 | 33 | # make CC=/home/moe/violet/tools/vcc CPP=/home/moe/violet/tools/v++ individuals -j16 34 | # find . | grep ".out" | xargs rm -------------------------------------------------------------------------------- /test/juliet/test_uaf.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import socket 4 | import subprocess 5 | 6 | def main(): 7 | executables = [] 8 | badthings = [] 9 | 10 | with open("dump", 'w') as f: 11 | f.write('100 ' * 0x1000) 12 | 13 | for path, dirs, files in os.walk('testcases'): 14 | for file in files: 15 | if file.endswith('.out'): 16 | executables.append(os.path.join(path, file)) 17 | 18 | for idx, executable in enumerate(sorted(executables)): 19 | print(f"Running {idx}.{executable}") 20 | 21 | with open('dump') as f: 22 | p = subprocess.Popen( 23 | [f'{executable}'], 24 | env={'LD_LIBRARY_PATH': '/home/moe/violet/build/src/safe_tcmalloc/tcmalloc'}, 25 | stdin=f, 26 | stdout=subprocess.PIPE, 27 | stderr=subprocess.PIPE) 28 | 29 | p.wait() 30 | 31 | stdout, stderr = p.communicate() 32 | 33 | # print(stdout) 34 | # print(stderr) 35 | 36 | if b'Calling good' in stdout and b'Finished good' not in stdout: 37 | print (f"FN: {executable}") 38 | badthings.append(executable) 39 | elif b'Calling bad' in stdout and b'Finished bad' not in stdout and b'detected' not in stderr: 40 | print (f"ERR: {executable}") 41 | badthings.append(executable) 42 | 43 | for badthing in badthings: 44 | print(f"ERROR: {badthing}") 45 | 46 | print(f"BAD/ALL {len(badthings)}/{len(executables)}") 47 | 48 | if __name__ == "__main__": 49 | main() 50 | 51 | # make CC=/home/moe/violet/tools/vcc CPP=/home/moe/violet/tools/v++ individuals -j16 52 | # find . | grep "\.out$" | xargs rm -------------------------------------------------------------------------------- /tools/v++: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../" 6 | 7 | if [ $# -eq 0 ] 8 | then 9 | echo "USAGE: $0 [options] file..." 10 | exit 0 11 | fi 12 | 13 | source ${BASE}/src/safe_tcmalloc/.config 14 | 15 | if [ "$ENABLE_GPROF" = "y" ] 16 | then 17 | FLAGS="${BASE}/build/src/safe_tcmalloc/tcmalloc/static/libtcmalloc.a -g -pg -pthread" 18 | else 19 | FLAGS="-L${BASE}/build/src/safe_tcmalloc/tcmalloc -ltcmalloc_tcmalloc" 20 | fi 21 | 22 | # The optimization level must be greater than -O0, 23 | # otherwise some analysis methods cannot be enabled. 24 | # But over-optimization (O2 or higher) can lead to changes in semantics. 25 | exec clang++ -g -O1 -Xclang -load -Xclang ${BASE}/build/src/compiler_pass/libProtectionPass.so \ 26 | "$@" \ 27 | ${FLAGS} \ 28 | -Wl,-rpath,${BASE}/build/src/safe_tcmalloc/tcmalloc \ 29 | -Qunused-arguments \ 30 | -Wpointer-arith -Wpointer-to-int-cast \ 31 | -------------------------------------------------------------------------------- /tools/vcc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../" 6 | 7 | if [ $# -eq 0 ] 8 | then 9 | echo "USAGE: $0 [options] file..." 10 | exit 0 11 | fi 12 | 13 | # The optimization level must be greater than -O0, 14 | # otherwise some analysis methods cannot be enabled. 15 | # But over-optimization (O2 or higher) can lead to changes in semantics. 16 | exec clang -g -O1 -Xclang -load -Xclang ${BASE}/build/src/compiler_pass/libProtectionPass.so \ 17 | "$@" \ 18 | -L${BASE}/build/src/safe_tcmalloc/tcmalloc -ltcmalloc_tcmalloc \ 19 | -Wl,--rpath=${BASE}/build/src/safe_tcmalloc/tcmalloc \ 20 | -Qunused-arguments \ 21 | -Wpointer-arith -Wpointer-to-int-cast 22 | -------------------------------------------------------------------------------- /tools/vcc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import subprocess 5 | import sys 6 | 7 | def keep_slience(argv): 8 | p = subprocess.Popen(['clang++'] + argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 9 | stdout, _ = p.communicate() 10 | print(stdout.decode(), end='') 11 | return p.returncode 12 | 13 | def violet(argv): 14 | base = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') 15 | prefix = ['-g', '-O1', 16 | '-Xclang', '-load', 17 | '-Xclang', f'{base}/build/src/compiler_pass/libProtectionPass.so'] 18 | 19 | suffix = [f'-L{base}/build/src/safe_tcmalloc/tcmalloc', 20 | '-ltcmalloc_tcmalloc', 21 | '-Qunused-arguments', 22 | '-Wpointer-arith', 23 | '-Wpointer-to-int-cast'] 24 | 25 | p = subprocess.Popen(['clang++'] + prefix + argv + suffix, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 26 | stdout, _ = p.communicate() 27 | print(stdout.decode(), end='') 28 | return p.returncode 29 | 30 | def main(): 31 | argv = sys.argv[1:] 32 | 33 | exts = ['.c', '.cc', '.cpp', '.cxx', '.C'] 34 | srcs = [a for a in argv if os.path.splitext(a)[1] in exts] 35 | 36 | if any(a in argv for a in ['-E', '-M', '-MM']): 37 | return keep_slience(argv) 38 | 39 | elif "-o" not in argv and not srcs: 40 | return keep_slience(argv) 41 | 42 | else: 43 | return violet(argv) 44 | 45 | if __name__ == '__main__': 46 | sys.exit(main()) --------------------------------------------------------------------------------