├── LICENSE ├── README.md ├── lib.rs ├── need_to_modify.rs └── safedrop_check ├── corner_handle.rs ├── graph.rs ├── mod.rs ├── node.rs └── tools.rs /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 | # SafeDrop 2 | 3 | ### NOTE!!!The project is obsolete!!! We have integrated the features of SafeDrop into [RAP](https://github.com/Artisan-Lab/RAP). 4 | 5 | A additional Rust compiler pass to detect memory safe bugs of Rust programs. SafeDrop performs path-sensitive and field-sensitive inter-procedural static analysis based on the mid-level IR of Rust program. It uses the tarjan algorithm to deal with the complex control flow loop and function call loop, 6 | then performs alias analysis on each execution path, detecting potential problems and reporting errors depend on our summarized rules. 7 | 8 | The associated paper titled *SafeDrop: Detecting Memory Deallocation Bugs of Rust Programs via Static Data-Flow Analysis* (TOSEM '22). 9 | 10 | 11 | 12 | ## Requirement 13 | 14 | - First, git clone the Rust compiler source code. 15 | 16 | ``` 17 | $ git clone https://github.com/rust-lang/rust.git 18 | ``` 19 | 20 | Since this implementation is based on Rust `1.63.0`, it need to switch to the corresponding tag. 21 | 22 | ```shell 23 | $ cd rust 24 | $ git checkout -b mycompiler 1.63.0 25 | ``` 26 | 27 | - Make sure you can build the Rust compiler. The specific requirements and tutorial you can find in https://github.com/rust-lang/rust. 28 | 29 | 30 | 31 | ## Usage 32 | 33 | It need to add some code snippets to make this pass work. 34 | 35 | - Modify the compiler source code according to the `need_to_modify.rs` and `lib.rs`. 36 | 37 | - put the `safedrop_check` module under the `rust/compiler/rustc_mir_transform/` 38 | 39 | - rebuild the compiler, and we can get the compiler with safedrop checking: `rust/build/(target_machine)/stage1/bin/rustc`. 40 | 41 | - You can set this compiler in rust toolchain use: 42 | 43 | ```shell 44 | # link this compiler as safedrop in rust toolchains. 45 | $ rustup toolchain link safedrop path_to_rust/build/(target_machine)/stage1 46 | # set the default toolchain as safedrop. 47 | $ rustup default safedrop 48 | ``` 49 | 50 | After that, you can use both `rustc` or `cargo` to compile rust programs with safedrop checking. 51 | 52 | - example: 53 | 54 | ```rust 55 | // a program with double-free bug 56 | use std::vec::Vec; 57 | fn main() { 58 | let mut a = vec![1,2]; 59 | let ptr = a.as_mut_ptr(); 60 | unsafe{ 61 | let mut _v = Vec::from_raw_parts(ptr, 2, 2); 62 | } 63 | } 64 | ``` 65 | 66 | We use this compiler to compile this program, and can get the following warning message: 67 | 68 | ```shell 69 | $ rustc test.rs 70 | ================================= 71 | Function:DefId(0:6 ~ test[5105]::main) 72 | Double Free Bugs Exist: 73 | occurs in test.rs:9:1: 9:2 (#0) 74 | 75 | ``` 76 | -------------------------------------------------------------------------------- /lib.rs: -------------------------------------------------------------------------------- 1 | // rust/compiler/rustc_mir_transform/lib.rs 2 | // need to modify 3 | + pub mod safedrop_check; 4 | + use safedrop_check::{SafeDropGraph, FuncMap}; 5 | ... 6 | pub fn provide(providers: &mut Providers) { 7 | ... 8 | *providers = Providers { 9 | ... 10 | optimized_mir, 11 | is_mir_available, 12 | + safedrop_check, 13 | ... 14 | }; 15 | } 16 | 17 | 18 | // add a pass function safedrop_check() 19 | fn safedrop_check<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> () { 20 | if let Some(_other) = tcx.hir().body_const_context(def_id.expect_local()){ 21 | return; 22 | } 23 | if tcx.is_mir_available(def_id) { 24 | let body = tcx.optimized_mir(def_id); 25 | let mut func_map = FuncMap::new(); 26 | let mut safedrop_graph = SafeDropGraph::new(&body, tcx, def_id); 27 | safedrop_graph.solve_scc(); 28 | safedrop_graph.safedrop_check(0, tcx, &mut func_map); 29 | if safedrop_graph.visit_times <= 10000{ 30 | safedrop_graph.output_warning(); 31 | } 32 | else{ 33 | println!("over_visited: {:?}", def_id); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /need_to_modify.rs: -------------------------------------------------------------------------------- 1 | // rust/compiler/rustc_middle/src/query/mod.rs 2 | rustc_queries! { 3 | query trigger_delay_span_bug(key: DefId) -> () { 4 | desc { "trigger a delay span bug" } 5 | } 6 | + query safedrop_check(_: DefId) -> () { 7 | + desc { "check safedrop bugs in rustc mir" } 8 | + } 9 | ... 10 | } 11 | 12 | 13 | 14 | // rust/compiler/rustc_interface/src/passes.rs 15 | fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { 16 | ... 17 | sess.time("layout_testing", || layout_test::test_layout(tcx)); 18 | 19 | + sess.time("safedrop_check", || { 20 | + tcx.hir().par_body_owners(|def_id| tcx.ensure().safedrop_check(def_id)); 21 | + }); 22 | } -------------------------------------------------------------------------------- /safedrop_check/corner_handle.rs: -------------------------------------------------------------------------------- 1 | 2 | use crate::SafeDropGraph; 3 | use rustc_data_structures::fx::FxHashSet; 4 | use rustc_span::def_id::DefId; 5 | 6 | 7 | impl<'tcx> SafeDropGraph<'tcx>{ 8 | //can also use the format to check. 9 | //these function calls are the functions whose MIRs can not be fetched. 10 | pub fn corner_handle(&mut self, _left_ssa: usize, _merge_vec: &Vec::, _move_set: &mut FxHashSet, def_id: DefId) -> bool{ 11 | // function::call_mut 12 | if def_id.index.as_usize() == 3430{ 13 | return true; 14 | } 15 | //function::iterator::next 16 | if def_id.index.as_usize() == 8476{ 17 | return true; 18 | } 19 | //intrinsic_offset 20 | if def_id.index.as_usize() == 1709{ 21 | return true; 22 | } 23 | return false; 24 | } 25 | 26 | //the dangling pointer occuring in some functions like drop() is reasonable. 27 | pub fn should_check(def_id: DefId) -> bool{ 28 | let def_str = format!("{:?}",def_id); 29 | if let Some(_) = def_str.find("drop"){ 30 | return false; 31 | } 32 | if let Some(_) = def_str.find("dealloc"){ 33 | return false; 34 | } 35 | if let Some(_) = def_str.find("release"){ 36 | return false; 37 | } 38 | if let Some(_) = def_str.find("destroy"){ 39 | return false; 40 | } 41 | return true; 42 | } 43 | } 44 | 45 | //these adt structs use the Rc-kind drop instruction, which we do not focus on. 46 | pub fn is_corner_adt(str: String) -> bool{ 47 | if let Some(_) = str.find("cell::RefMut"){ 48 | return true; 49 | } 50 | if let Some(_) = str.find("cell::Ref"){ 51 | return true; 52 | } 53 | if let Some(_) = str.find("rc::Rc"){ 54 | return true; 55 | } 56 | return false; 57 | } -------------------------------------------------------------------------------- /safedrop_check/graph.rs: -------------------------------------------------------------------------------- 1 | use std::vec::Vec; 2 | use std::cmp::min; 3 | use rustc_middle::mir::StatementKind; 4 | use rustc_middle::mir::terminator::TerminatorKind; 5 | use rustc_middle::mir::Body; 6 | use rustc_middle::mir::BasicBlock; 7 | use rustc_middle::mir::Local; 8 | use rustc_middle::mir::Terminator; 9 | use rustc_middle::mir::Place; 10 | use rustc_middle::ty::TyCtxt; 11 | use rustc_span::def_id::DefId; 12 | use rustc_data_structures::fx::FxHashSet; 13 | use rustc_data_structures::fx::FxHashMap; 14 | use rustc_middle::mir::Operand; 15 | use rustc_middle::mir::Rvalue; 16 | use rustc_span::Span; 17 | use super::BugRecords; 18 | use super::tools::*; 19 | use super::node::Node; 20 | use super::node::ReturnResults; 21 | 22 | 23 | //self-defined assignments structure. 24 | #[derive(Debug,Clone)] 25 | pub struct Assignment<'tcx>{ 26 | pub left: Place<'tcx>, 27 | pub right: Place<'tcx>, 28 | pub atype: usize, 29 | pub span: Span, 30 | } 31 | 32 | impl<'tcx> Assignment<'tcx>{ 33 | pub fn new(left: Place<'tcx>, right: Place<'tcx>, atype: usize, span: Span)->Assignment<'tcx>{ 34 | Assignment{ 35 | left: left, 36 | right: right, 37 | atype: atype, 38 | span: span, 39 | } 40 | } 41 | } 42 | 43 | //self-defined basicblock structure. 44 | #[derive(Debug,Clone)] 45 | pub struct BlockNode<'tcx>{ 46 | pub index: usize, 47 | pub is_cleanup: bool, 48 | pub next: FxHashSet, 49 | pub assignments: Vec>, 50 | pub calls: Vec>, 51 | pub drops: Vec>, 52 | //store the index of the sub-blocks as the current node is the root node of a SCC. 53 | pub sub_blocks: Vec, 54 | //store the const value defined in this block; 55 | pub const_value: Vec::<(usize, usize)>, 56 | //store switch stmts in current block for the path filtering in path-sensitive analysis. 57 | pub switch_stmts: Vec::>, 58 | } 59 | 60 | impl<'tcx> BlockNode<'tcx>{ 61 | pub fn new(index:usize, is_cleanup: bool) -> BlockNode<'tcx>{ 62 | BlockNode{ 63 | index: index, 64 | is_cleanup: is_cleanup, 65 | next: FxHashSet::::default(), 66 | assignments: Vec::>::new(), 67 | calls: Vec::>::new(), 68 | drops: Vec::>::new(), 69 | sub_blocks: Vec::::new(), 70 | const_value: Vec::<(usize, usize)>::new(), 71 | switch_stmts: Vec::>::new(), 72 | } 73 | } 74 | 75 | pub fn push(&mut self, index: usize){ 76 | self.next.insert(index); 77 | } 78 | } 79 | 80 | pub struct SafeDropGraph<'tcx>{ 81 | pub def_id: DefId, 82 | pub span: Span, 83 | // contains all varibles (including fields) as nodes. 84 | pub nodes: Vec, 85 | // contains all blocks in the CFG 86 | pub blocks: Vec>, 87 | pub arg_size: usize, 88 | // we shrink a SCC into a node and use a father node to represent the SCC. 89 | pub father_block: Vec, 90 | // record the constant value during safedrop checking. 91 | pub constant_bool: FxHashMap, 92 | // used for tarjan algorithmn. 93 | pub count: usize, 94 | // contains the return results for inter-procedure analysis. 95 | pub return_results: ReturnResults, 96 | // used for filtering duplicate alias assignments in return results. 97 | pub return_set: FxHashSet<(usize, usize)>, 98 | // record the information of bugs for the function. 99 | pub bug_records: BugRecords, 100 | // a threhold to avoid path explosion. 101 | pub visit_times: usize 102 | } 103 | 104 | impl<'tcx> SafeDropGraph<'tcx>{ 105 | pub fn new(my_body: &Body<'tcx>, tcx: TyCtxt<'tcx>, def_id: DefId) -> SafeDropGraph<'tcx>{ 106 | // handle variables 107 | let locals = &my_body.local_decls; 108 | let arg_size = my_body.arg_count; 109 | let mut nodes = Vec::::new(); 110 | let param_env = tcx.param_env(def_id); 111 | for ld in 0..locals.len() { 112 | let temp = Local::from(ld); 113 | let need_drop = locals[temp].ty.needs_drop(tcx, param_env); 114 | let so_so = so_so(locals[temp].ty); 115 | let mut node = Node::new(ld, ld, need_drop, need_drop || !so_so); 116 | node.kind = kind(locals[temp].ty); 117 | nodes.push(node); 118 | } 119 | 120 | let basicblocks = my_body.basic_blocks(); 121 | let mut blocks = Vec::>::new(); 122 | let mut father_block = Vec::::new(); 123 | 124 | // handle each basicblock 125 | for i in 0..basicblocks.len(){ 126 | father_block.push(i); 127 | let iter = BasicBlock::from(i); 128 | let terminator = basicblocks[iter].terminator.clone().unwrap(); 129 | let mut current_node = BlockNode::new(i, basicblocks[iter].is_cleanup); 130 | 131 | // handle general statements 132 | for statement in &basicblocks[iter].statements{ 133 | if let StatementKind::Assign(ref assign) = statement.kind { 134 | let left_ssa = assign.0.local.as_usize(); 135 | let left = assign.0.clone(); 136 | match assign.1 { 137 | Rvalue::Use(ref x) => { 138 | match x { 139 | Operand::Copy(ref p) => { 140 | let right_ssa = p.local.as_usize(); 141 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 142 | let right = p.clone(); 143 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 144 | current_node.assignments.push(assign); 145 | } 146 | }, 147 | Operand::Move(ref p) => { 148 | let right_ssa = p.local.as_usize(); 149 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 150 | let right = p.clone(); 151 | let assign = Assignment::new(left, right, 1, statement.source_info.span.clone()); 152 | current_node.assignments.push(assign); 153 | } 154 | }, 155 | Operand::Constant(ref constant) => { 156 | if let None = constant.literal.try_to_scalar(){ 157 | continue; 158 | } 159 | if let Err(_tmp) = constant.literal.try_to_scalar().clone().unwrap().try_to_int(){ 160 | continue; 161 | } 162 | if let Some(ans) = constant.literal.try_eval_usize(tcx, param_env){ 163 | current_node.const_value.push((left_ssa, ans as usize)); 164 | continue; 165 | } 166 | if let Some(const_bool) = constant.literal.try_to_bool() { 167 | current_node.const_value.push((left_ssa, const_bool as usize)); 168 | } 169 | continue; 170 | }, 171 | } 172 | } 173 | Rvalue::Ref(_, _, ref p) => { 174 | let right_ssa = p.local.as_usize(); 175 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 176 | let right = p.clone(); 177 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 178 | current_node.assignments.push(assign); 179 | } 180 | }, 181 | Rvalue::AddressOf(_, ref p) => { 182 | let right_ssa = p.local.as_usize(); 183 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 184 | let right = p.clone(); 185 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 186 | current_node.assignments.push(assign); 187 | } 188 | }, 189 | 190 | Rvalue::ShallowInitBox(ref x, _) => { 191 | if nodes[left_ssa].sons.contains_key(&0) == false{ 192 | let mut node = Node::new(left_ssa, nodes.len(), false, true); 193 | let mut node1 = Node::new(left_ssa, nodes.len() + 1, false, true); 194 | let mut node2 = Node::new(left_ssa, nodes.len() + 2, false, true); 195 | node.alive = nodes[left_ssa].alive; 196 | node1.alive = node.alive; 197 | node2.alive = node.alive; 198 | node.sons.insert(0, node1.local); 199 | node.field_info.push(0); 200 | node1.sons.insert(0, node2.local); 201 | node1.field_info.push(0); 202 | node1.field_info.push(0); 203 | node2.field_info.push(0); 204 | node2.field_info.push(0); 205 | node2.field_info.push(0); 206 | node2.kind = 1; 207 | nodes[left_ssa].sons.insert(0, node.local); 208 | nodes.push(node); 209 | nodes.push(node1); 210 | nodes.push(node2); 211 | } 212 | match x { 213 | Operand::Copy(ref p) => { 214 | let right_ssa = p.local.as_usize(); 215 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 216 | let right = p.clone(); 217 | let assign = Assignment::new(left, right, 2, statement.source_info.span.clone()); 218 | current_node.assignments.push(assign); 219 | } 220 | }, 221 | Operand::Move(ref p) => { 222 | let right_ssa = p.local.as_usize(); 223 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 224 | let right = p.clone(); 225 | let assign = Assignment::new(left, right, 2, statement.source_info.span.clone()); 226 | current_node.assignments.push(assign); 227 | } 228 | }, 229 | Operand::Constant(_) => {}, 230 | } 231 | }, 232 | Rvalue::Cast(_, ref x, _) => { 233 | match x { 234 | Operand::Copy(ref p) => { 235 | let right_ssa = p.local.as_usize(); 236 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 237 | let right = p.clone(); 238 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 239 | current_node.assignments.push(assign); 240 | } 241 | }, 242 | Operand::Move(ref p) => { 243 | let right_ssa = p.local.as_usize(); 244 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 245 | let right = p.clone(); 246 | let assign = Assignment::new(left, right, 1, statement.source_info.span.clone()); 247 | current_node.assignments.push(assign); 248 | } 249 | }, 250 | Operand::Constant(_) => {}, 251 | } 252 | }, 253 | Rvalue::Aggregate(_, ref x) => { 254 | for each_x in x { 255 | match each_x { 256 | Operand::Copy(ref p) => { 257 | let right_ssa = p.local.as_usize(); 258 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 259 | let right = p.clone(); 260 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 261 | current_node.assignments.push(assign); 262 | } 263 | }, 264 | Operand::Move(ref p) => { 265 | let right_ssa = p.local.as_usize(); 266 | if nodes[left_ssa].so_so() && nodes[right_ssa].so_so(){ 267 | let right = p.clone(); 268 | let assign = Assignment::new(left, right, 0, statement.source_info.span.clone()); 269 | current_node.assignments.push(assign); 270 | } 271 | }, 272 | Operand::Constant(_) => {}, 273 | } 274 | } 275 | }, 276 | Rvalue::Discriminant(ref p) => { 277 | let right = p.clone(); 278 | let assign = Assignment::new(left, right, 3, statement.source_info.span.clone()); 279 | current_node.assignments.push(assign); 280 | } 281 | _ => {} 282 | } 283 | } 284 | } 285 | 286 | // handle terminator statements 287 | match terminator.kind { 288 | TerminatorKind::Goto { ref target } => { 289 | current_node.push(target.as_usize()); 290 | }, 291 | TerminatorKind::SwitchInt{ discr: _, switch_ty: _, ref targets } => { 292 | current_node.switch_stmts.push(terminator.clone()); 293 | for (_, ref target) in targets.iter() { 294 | current_node.push(target.as_usize()); 295 | } 296 | current_node.push(targets.otherwise().as_usize()); 297 | }, 298 | TerminatorKind::Resume => {}, 299 | TerminatorKind::Return => {}, 300 | TerminatorKind::Abort 301 | | TerminatorKind::GeneratorDrop 302 | | TerminatorKind::Unreachable => {} 303 | TerminatorKind::Drop { place: _, ref target, ref unwind } => { 304 | current_node.push(target.as_usize()); 305 | current_node.drops.push(terminator.clone()); 306 | if let Some(target) = unwind { 307 | current_node.push(target.as_usize()); 308 | } 309 | }, 310 | TerminatorKind::DropAndReplace { place: _, value: _, ref target, ref unwind } => { 311 | current_node.push(target.as_usize()); 312 | if let Some(target) = unwind { 313 | current_node.push(target.as_usize()); 314 | } 315 | }, 316 | TerminatorKind::Call { func: _, args: _, destination: _, ref target, ref cleanup, from_hir_call: _, fn_span: _ } => { 317 | if let Some(tt) = target { 318 | current_node.push(tt.as_usize()); 319 | } 320 | if let Some(tt) = cleanup { 321 | current_node.push(tt.as_usize()); 322 | } 323 | current_node.calls.push(terminator.clone()); 324 | }, 325 | TerminatorKind::Assert { cond: _, expected: _, msg: _, ref target, ref cleanup } => { 326 | current_node.push(target.as_usize()); 327 | if let Some(target) = cleanup { 328 | current_node.push(target.as_usize()); 329 | } 330 | }, 331 | TerminatorKind::Yield { value: _, ref resume, resume_arg: _, ref drop } => { 332 | current_node.push(resume.as_usize()); 333 | if let Some(target) = drop { 334 | current_node.push(target.as_usize()); 335 | } 336 | }, 337 | TerminatorKind::FalseEdge { ref real_target, imaginary_target: _ } => { 338 | current_node.push(real_target.as_usize()); 339 | }, 340 | TerminatorKind::FalseUnwind { ref real_target, unwind: _ } => { 341 | current_node.push(real_target.as_usize()); 342 | }, 343 | TerminatorKind::InlineAsm { template: _, operands: _, options: _, line_spans: _, ref destination, ref cleanup} => { 344 | if let Some(target) = destination { 345 | current_node.push(target.as_usize()); 346 | } 347 | if let Some(target) = cleanup { 348 | current_node.push(target.as_usize()); 349 | } 350 | } 351 | } 352 | blocks.push(current_node); 353 | } 354 | 355 | SafeDropGraph{ 356 | def_id: def_id.clone(), 357 | span: my_body.span, 358 | blocks: blocks, 359 | nodes: nodes, 360 | arg_size: arg_size, 361 | father_block: father_block, 362 | constant_bool: FxHashMap::default(), 363 | count: 0, 364 | return_results: ReturnResults::new(arg_size), 365 | return_set: FxHashSet::default(), 366 | bug_records: BugRecords::new(), 367 | visit_times: 0, 368 | } 369 | } 370 | 371 | pub fn tarjan(&mut self, index: usize, 372 | stack: &mut Vec, 373 | instack: &mut FxHashSet, 374 | dfn: &mut Vec, 375 | low: &mut Vec){ 376 | dfn[index] = self.count; 377 | low[index] = self.count; 378 | self.count += 1; 379 | instack.insert(index); 380 | stack.push(index); 381 | let out_set = self.blocks[index].next.clone(); 382 | for i in out_set{ 383 | let target = i; 384 | if dfn[target] == 0{ 385 | self.tarjan(target, stack, instack, dfn, low); 386 | low[index] = min(low[index], low[target]); 387 | } 388 | else{ 389 | if instack.contains(&target){ 390 | low[index] = min(low[index], dfn[target]); 391 | } 392 | } 393 | } 394 | // generate SCC 395 | if dfn[index] == low[index]{ 396 | loop{ 397 | let top = stack.pop().unwrap(); 398 | self.father_block[top] = index; 399 | instack.remove(&top); 400 | if index == top{ 401 | break; 402 | } 403 | let top_node = self.blocks[top].next.clone(); 404 | for i in top_node{self.blocks[index].next.insert(i);} 405 | self.blocks[index].sub_blocks.push(top); 406 | for i in self.blocks[top].sub_blocks.clone(){ 407 | self.blocks[index].sub_blocks.push(i); 408 | } 409 | } 410 | self.blocks[index].sub_blocks.reverse(); 411 | //remove the out nodes which is in the current SCC 412 | let mut remove_list = Vec::new(); 413 | for i in self.blocks[index].next.iter(){ 414 | if self.father_block[*i] == index{ 415 | remove_list.push(*i); 416 | } 417 | } 418 | for i in remove_list{ 419 | self.blocks[index].next.remove(&i); 420 | } 421 | } 422 | } 423 | 424 | // handle SCC 425 | pub fn solve_scc(&mut self){ 426 | let mut stack = Vec::::new(); 427 | let mut instack = FxHashSet::::default(); 428 | let mut dfn = vec![0 as usize; self.blocks.len()]; 429 | let mut low = vec![0 as usize; self.blocks.len()]; 430 | self.tarjan(0, &mut stack, &mut instack, &mut dfn, &mut low); 431 | } 432 | } 433 | -------------------------------------------------------------------------------- /safedrop_check/mod.rs: -------------------------------------------------------------------------------- 1 | //This module should put under the directory: rust/compiler/rustc_mir_transform/safedrop_check 2 | 3 | use rustc_middle::ty::TyCtxt; 4 | use rustc_middle::ty; 5 | use rustc_middle::mir::Operand; 6 | use rustc_middle::mir::terminator::TerminatorKind; 7 | use rustc_data_structures::fx::FxHashSet; 8 | pub mod graph; 9 | pub mod node; 10 | pub mod tools; 11 | pub mod corner_handle; 12 | pub use graph::SafeDropGraph; 13 | pub use node::*; 14 | pub use tools::*; 15 | pub use corner_handle::*; 16 | pub use std::fmt; 17 | 18 | impl<'tcx> SafeDropGraph<'tcx>{ 19 | // alias analysis for a single block 20 | pub fn alias_check(&mut self, bb_index: usize, tcx: TyCtxt<'tcx>, move_set: &mut FxHashSet){ 21 | for stmt in self.blocks[bb_index].const_value.clone(){ 22 | self.constant_bool.insert(stmt.0, stmt.1); 23 | } 24 | let current_block = self.blocks[bb_index].clone(); 25 | for i in current_block.assignments{ 26 | let mut l_node_ref = self.handle_projection(false, i.left.local.as_usize(), tcx, i.left.clone()); 27 | let r_node_ref = self.handle_projection(true, i.right.local.as_usize(), tcx, i.right.clone()); 28 | if i.atype == 3{ 29 | self.nodes[l_node_ref].alias[0] = r_node_ref; 30 | continue; 31 | } 32 | self.uaf_check(r_node_ref, i.span, i.right.local.as_usize(), false); 33 | self.fill_alive(l_node_ref, self.father_block[bb_index] as isize); 34 | if i.atype == 2{ 35 | l_node_ref = *self.nodes[l_node_ref].sons.get(&0).unwrap() + 2; 36 | self.nodes[l_node_ref].alive = self.father_block[bb_index] as isize; 37 | self.nodes[l_node_ref-1].alive = self.father_block[bb_index] as isize; 38 | self.nodes[l_node_ref-2].alive = self.father_block[bb_index] as isize; 39 | } 40 | merge_alias(move_set, l_node_ref, r_node_ref, &mut self.nodes); 41 | } 42 | } 43 | 44 | // interprocedure alias analysis, mainly handle the function call statement 45 | pub fn call_alias_check(&mut self, bb_index: usize, tcx: TyCtxt<'tcx>, func_map: &mut FuncMap, move_set: &mut FxHashSet){ 46 | let current_block = self.blocks[bb_index].clone(); 47 | for call in current_block.calls{ 48 | if let TerminatorKind::Call { ref func, ref args, ref destination, target:_, cleanup: _, from_hir_call: _, fn_span: _ } = call.kind { 49 | if let Operand::Constant(ref constant) = func { 50 | let left_ssa = self.handle_projection(false, destination.local.as_usize(), tcx, destination.clone()); 51 | self.nodes[left_ssa].alive = self.father_block[bb_index] as isize; 52 | let mut merge_vec = Vec::new(); 53 | merge_vec.push(left_ssa); 54 | let mut so_so_flag = 0; 55 | if self.nodes[left_ssa].so_so() { 56 | so_so_flag += 1; 57 | } 58 | for arg in args { 59 | match arg { 60 | Operand::Copy(ref p) => { 61 | let right_ssa = self.handle_projection(true, p.local.as_usize(), tcx, p.clone()); 62 | self.uaf_check(right_ssa, call.source_info.span, p.local.as_usize(), true); 63 | merge_vec.push(right_ssa); 64 | if self.nodes[right_ssa].so_so() { 65 | so_so_flag += 1; 66 | } 67 | }, 68 | Operand::Move(ref p) => { 69 | let right_ssa = self.handle_projection(true, p.local.as_usize(), tcx, p.clone()); 70 | self.uaf_check(right_ssa, call.source_info.span, p.local.as_usize(), true); 71 | merge_vec.push(right_ssa); 72 | if self.nodes[right_ssa].so_so() { 73 | so_so_flag += 1; 74 | } 75 | }, 76 | Operand::Constant(_) => { 77 | merge_vec.push(0); 78 | }, 79 | } 80 | } 81 | if let ty::FnDef(ref target_id, _) = constant.literal.ty().kind() { 82 | if so_so_flag > 1 || (so_so_flag > 0 && Self::should_check(target_id.clone()) == false){ 83 | if tcx.is_mir_available(*target_id){ 84 | if func_map.map.contains_key(&target_id.index.as_usize()){ 85 | let assignments = func_map.map.get(&target_id.index.as_usize()).unwrap(); 86 | for assign in assignments.assignments.iter(){ 87 | if !assign.valuable(){ 88 | continue; 89 | } 90 | merge(move_set, &mut self.nodes, assign, &merge_vec); 91 | } 92 | for dead in assignments.dead.iter(){ 93 | let drop = merge_vec[*dead]; 94 | self.dead_node(drop, 99999, &call.source_info, false); 95 | } 96 | } 97 | else{ 98 | if func_map.set.contains(&target_id.index.as_usize()){ 99 | continue; 100 | } 101 | func_map.set.insert(target_id.index.as_usize()); 102 | let func_body = tcx.optimized_mir(*target_id); 103 | let mut safedrop_graph = SafeDropGraph::new(&func_body, tcx, *target_id); 104 | safedrop_graph.solve_scc(); 105 | safedrop_graph.safedrop_check(0, tcx, func_map); 106 | let return_results = safedrop_graph.return_results.clone(); 107 | for assign in return_results.assignments.iter(){ 108 | if !assign.valuable(){ 109 | continue; 110 | } 111 | merge(move_set, &mut self.nodes, assign, &merge_vec); 112 | } 113 | for dead in return_results.dead.iter(){ 114 | let drop = merge_vec[*dead]; 115 | self.dead_node(drop, 99999, &call.source_info, false); 116 | } 117 | func_map.map.insert(target_id.index.as_usize(), return_results); 118 | } 119 | } 120 | else{ 121 | if self.nodes[left_ssa].so_so(){ 122 | if self.corner_handle(left_ssa, &merge_vec, move_set, *target_id){ 123 | continue; 124 | } 125 | let mut right_set = Vec::new(); 126 | for right_ssa in &merge_vec{ 127 | if self.nodes[*right_ssa].so_so() && left_ssa != *right_ssa && self.nodes[left_ssa].is_ptr(){ 128 | right_set.push(*right_ssa); 129 | } 130 | } 131 | if right_set.len() == 1{ 132 | merge_alias(move_set, left_ssa, right_set[0], &mut self.nodes); 133 | } 134 | } 135 | } 136 | } 137 | } 138 | } 139 | } 140 | } 141 | } 142 | // analyze the drop statement and update the alive state for nodes. 143 | pub fn drop_check(&mut self, bb_index: usize, tcx: TyCtxt<'tcx>){ 144 | let current_block = self.blocks[bb_index].clone(); 145 | for drop in current_block.drops{ 146 | match drop.kind{ 147 | TerminatorKind::Drop{ref place, target: _, unwind: _} => { 148 | let life_begin = self.father_block[bb_index]; 149 | let drop_local = self.handle_projection(false, place.local.as_usize(), tcx, place.clone()); 150 | let info = drop.source_info.clone(); 151 | self.dead_node(drop_local, life_begin, &info, false); 152 | }, 153 | _ => {} 154 | } 155 | } 156 | } 157 | 158 | // the core function of the safedrop. 159 | pub fn safedrop_check(&mut self, bb_index: usize, tcx: TyCtxt<'tcx>, func_map: &mut FuncMap){ 160 | self.visit_times += 1; 161 | if self.visit_times > 10000{ 162 | return; 163 | } 164 | let current_block = self.blocks[self.father_block[bb_index]].clone(); 165 | let mut move_set = FxHashSet::default(); 166 | self.alias_check(self.father_block[bb_index], tcx, &mut move_set); 167 | self.call_alias_check(self.father_block[bb_index], tcx, func_map, &mut move_set); 168 | self.drop_check(self.father_block[bb_index], tcx); 169 | if current_block.sub_blocks.len() > 0{ 170 | for i in current_block.sub_blocks.clone(){ 171 | self.alias_check(i, tcx, &mut move_set); 172 | self.call_alias_check(i, tcx, func_map, &mut move_set); 173 | self.drop_check(i, tcx); 174 | } 175 | } 176 | 177 | //finish the analysis for a path 178 | if current_block.next.len() == 0{ 179 | // check the bugs. 180 | if Self::should_check(self.def_id){ 181 | self.bug_check(¤t_block); 182 | } 183 | // merge the result. 184 | let results_nodes = self.nodes.clone(); 185 | self.merge_results(results_nodes, current_block.is_cleanup); 186 | } 187 | 188 | 189 | //search for the next block to visit. 190 | let mut loop_flag = true; 191 | let mut ans_bool = 0; 192 | let mut s_target = 0; 193 | let mut discr_target = 0; 194 | let mut s_targets = None; 195 | //handle the SwitchInt statement. 196 | if current_block.switch_stmts.is_empty() == false && current_block.sub_blocks.is_empty(){ 197 | if let TerminatorKind::SwitchInt { ref discr, switch_ty: _, ref targets } = current_block.switch_stmts[0].clone().kind{ 198 | if let Some(p) = discr.place() { 199 | let place = self.handle_projection(false, p.local.as_usize(), tcx, p.clone()); 200 | if let Some(const_bool) = self.constant_bool.get(&self.nodes[place].alias[0]) { 201 | loop_flag = false; 202 | ans_bool = *const_bool; 203 | } 204 | if self.nodes[place].alias[0] != place{ 205 | discr_target = self.nodes[place].alias[0]; 206 | s_targets = Some(targets.clone()); 207 | } 208 | } else { 209 | loop{ 210 | if let None = discr.constant(){ 211 | break; 212 | } 213 | let temp = discr.constant().unwrap().literal; 214 | if let None = temp.try_to_scalar(){ 215 | break; 216 | } 217 | if let Err(_tmp) = temp.try_to_scalar().clone().unwrap().try_to_int(){ 218 | break; 219 | } 220 | let param_env = tcx.param_env(self.def_id); 221 | if let Some(const_bool) = temp.try_eval_usize(tcx, param_env){ 222 | loop_flag = false; 223 | ans_bool = const_bool as usize; 224 | break; 225 | } 226 | if let Some(const_bool) = temp.try_to_bool() { 227 | loop_flag = false; 228 | ans_bool = const_bool as usize; 229 | } 230 | break; 231 | } 232 | } 233 | if !loop_flag { 234 | for iter in targets.iter(){ 235 | if iter.0 as usize == ans_bool as usize{ 236 | s_target = iter.1.as_usize(); 237 | break; 238 | } 239 | } 240 | if s_target == 0{ 241 | let all_target = targets.all_targets(); 242 | if ans_bool as usize >= all_target.len(){ 243 | s_target = all_target[all_target.len()-1].as_usize(); 244 | } 245 | else{ 246 | s_target = all_target[ans_bool as usize].as_usize(); 247 | } 248 | } 249 | } 250 | } 251 | } 252 | // only one path 253 | if current_block.next.len() == 1{ 254 | for next_index in current_block.next{ 255 | self.safedrop_check(next_index, tcx, func_map); 256 | } 257 | } 258 | else{ 259 | // fixed path since a constant switchInt value 260 | if loop_flag == false{ 261 | self.safedrop_check(s_target, tcx, func_map); 262 | } 263 | else{ 264 | // Other cases in switchInt terminators 265 | if let Some(targets) = s_targets{ 266 | for iter in targets.iter(){ 267 | if self.visit_times > 10000{ 268 | continue; 269 | } 270 | let next_index = iter.1.as_usize(); 271 | let backup_nodes = self.nodes.clone(); 272 | let constant_record = self.constant_bool.clone(); 273 | self.constant_bool.insert(discr_target , iter.0 as usize); 274 | self.safedrop_check(next_index, tcx, func_map); 275 | self.nodes = backup_nodes; 276 | self.constant_bool = constant_record; 277 | } 278 | let all_targets = targets.all_targets(); 279 | let next_index = all_targets[all_targets.len()-1].as_usize(); 280 | let backup_nodes = self.nodes.clone(); 281 | let constant_record = self.constant_bool.clone(); 282 | self.constant_bool.insert(discr_target , 99999 as usize); 283 | self.safedrop_check(next_index, tcx, func_map); 284 | self.nodes = backup_nodes; 285 | self.constant_bool = constant_record; 286 | } 287 | else{ 288 | for i in current_block.next{ 289 | if self.visit_times > 10000{ 290 | continue; 291 | } 292 | let next_index = i; 293 | let backup_nodes = self.nodes.clone(); 294 | let constant_record = self.constant_bool.clone(); 295 | self.safedrop_check(next_index, tcx, func_map); 296 | self.nodes = backup_nodes; 297 | self.constant_bool = constant_record; 298 | } 299 | } 300 | } 301 | } 302 | } 303 | } -------------------------------------------------------------------------------- /safedrop_check/node.rs: -------------------------------------------------------------------------------- 1 | use rustc_data_structures::{fx::FxHashMap, stable_set::FxHashSet}; 2 | 3 | #[derive(Debug,Clone)] 4 | pub struct Node{ 5 | pub index: usize, 6 | pub local: usize, 7 | need_drop: bool, 8 | so_so:bool, 9 | pub kind: usize, 10 | pub father: usize, 11 | pub alias: Vec, 12 | pub alive: isize, 13 | pub sons: FxHashMap, 14 | pub field_info: Vec, 15 | } 16 | 17 | impl Node{ 18 | pub fn new(index: usize, local: usize, need_drop: bool, so_so: bool) -> Node{ 19 | let mut eq = Vec::new(); 20 | eq.push(local); 21 | Node { index: index, local: local, need_drop: need_drop, father: local, alias: eq, alive: 0, so_so: so_so, kind: 0, sons: FxHashMap::default(), field_info: Vec::::new()} 22 | } 23 | 24 | pub fn need_drop(&self) -> bool{ 25 | return self.need_drop; 26 | } 27 | 28 | pub fn so_so(&self) -> bool{ 29 | return self.so_so; 30 | } 31 | 32 | pub fn dead(&mut self){ 33 | self.alive = -1; 34 | } 35 | 36 | pub fn is_alive(&self) -> bool{ 37 | return self.alive > -1; 38 | } 39 | 40 | pub fn is_tuple(&self)-> bool{ 41 | return self.kind == 2; 42 | } 43 | 44 | pub fn is_ptr(&self)-> bool{ 45 | return self.kind == 1 || self.kind == 4; 46 | } 47 | 48 | pub fn is_ref(&self)-> bool{ 49 | return self.kind == 4; 50 | } 51 | 52 | pub fn is_corner_case(&self)-> bool{ 53 | return self.kind == 3; 54 | } 55 | } 56 | 57 | #[derive(Debug,Clone)] 58 | pub struct ReturnAssign{ 59 | pub left_index: usize, 60 | pub left: Vec, 61 | pub left_so_so: bool, 62 | pub left_need_drop: bool, 63 | pub right_index: usize, 64 | pub right: Vec, 65 | pub right_so_so: bool, 66 | pub right_need_drop: bool, 67 | pub atype: usize, 68 | } 69 | 70 | impl ReturnAssign{ 71 | pub fn new(atype: usize, left_index: usize, left_so_so: bool, left_need_drop: bool, 72 | right_index: usize, right_so_so: bool, right_need_drop: bool) -> ReturnAssign{ 73 | let left = Vec::::new(); 74 | let right = Vec::::new(); 75 | ReturnAssign{ 76 | left_index: left_index, 77 | left: left, 78 | left_so_so: left_so_so, 79 | left_need_drop: left_need_drop, 80 | right_index: right_index, 81 | right: right, 82 | right_so_so: right_so_so, 83 | right_need_drop: right_need_drop, 84 | atype: atype 85 | } 86 | } 87 | 88 | pub fn valuable(&self) -> bool{ 89 | return self.left_so_so && self.right_so_so; 90 | } 91 | } 92 | 93 | #[derive(Clone)] 94 | pub struct ReturnResults{ 95 | pub arg_size: usize, 96 | pub assignments: Vec, 97 | pub dead: FxHashSet, 98 | } 99 | 100 | impl ReturnResults { 101 | pub fn new(arg_size: usize) -> ReturnResults{ 102 | let assignments = Vec::::new(); 103 | let dead = FxHashSet::default(); 104 | ReturnResults { arg_size: arg_size, assignments: assignments, dead: dead } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /safedrop_check/tools.rs: -------------------------------------------------------------------------------- 1 | use rustc_middle::mir::SourceInfo; 2 | use rustc_middle::ty; 3 | use rustc_middle::ty::Ty; 4 | use rustc_middle::mir::Place; 5 | use rustc_middle::ty::TyCtxt; 6 | use rustc_middle::mir::ProjectionElem; 7 | use rustc_span::Span; 8 | use rustc_data_structures::fx::FxHashMap; 9 | use rustc_data_structures::fx::FxHashSet; 10 | use super::Node; 11 | use super::ReturnAssign; 12 | use super::ReturnResults; 13 | use super::SafeDropGraph; 14 | use super::corner_handle::is_corner_adt; 15 | use super::graph::BlockNode; 16 | pub use std::fmt; 17 | 18 | 19 | impl<'tcx> SafeDropGraph<'tcx>{ 20 | pub fn output_warning(&self){ 21 | if self.bug_records.is_bug_free(){ 22 | return; 23 | } 24 | println!("================================="); 25 | println!("Function:{0:?};{1:?}", self.def_id, self.def_id.index); 26 | self.bug_records.df_bugs_output(); 27 | self.bug_records.uaf_bugs_output(); 28 | self.bug_records.dp_bug_output(self.span); 29 | 30 | println!(); 31 | println!(); 32 | } 33 | 34 | // assign to the variable _x, we will set the alive of _x and its child nodes a new alive. 35 | pub fn fill_alive(&mut self, node: usize, alive: isize){ 36 | self.nodes[node].alive = alive; 37 | //TODO: check the correctness. 38 | for i in self.nodes[node].alias.clone(){ 39 | if self.nodes[i].alive == -1{ 40 | self.nodes[i].alive = alive; 41 | } 42 | } 43 | for i in self.nodes[node].sons.clone().into_iter(){ 44 | self.fill_alive(i.1, alive); 45 | } 46 | } 47 | 48 | pub fn exist_dead(&self, node: usize, record: &mut FxHashSet, dangling: bool) -> bool{ 49 | //if is a dangling pointer check, only check the pointer type varible. 50 | if self.nodes[node].is_alive() == false && (dangling && self.nodes[node].is_ptr() || !dangling){ 51 | return true; 52 | } 53 | record.insert(node); 54 | if self.nodes[node].alias[0] != node{ 55 | for i in self.nodes[node].alias.clone().into_iter(){ 56 | if i != node && record.contains(&i) == false && self.exist_dead(i, record, dangling){ 57 | return true; 58 | } 59 | } 60 | } 61 | for i in self.nodes[node].sons.clone().into_iter(){ 62 | if record.contains(&i.1) == false && self.exist_dead(i.1, record, dangling){ 63 | return true; 64 | } 65 | } 66 | return false; 67 | } 68 | 69 | pub fn df_check(&mut self, drop: usize, span: Span) -> bool{ 70 | let root = self.nodes[drop].index; 71 | if self.nodes[drop].is_alive() == false 72 | && self.bug_records.df_bugs.contains_key(&root) == false{ 73 | self.bug_records.df_bugs.insert(root, span.clone()); 74 | } 75 | return self.nodes[drop].is_alive() == false; 76 | } 77 | 78 | pub fn uaf_check(&mut self, used: usize, span: Span, origin: usize, is_func_call: bool){ 79 | let mut record = FxHashSet::default(); 80 | if self.nodes[used].so_so() && (!self.nodes[used].is_ptr() || self.nodes[used].index != origin || is_func_call) 81 | && self.exist_dead(used, &mut record, false) == true 82 | && self.bug_records.uaf_bugs.contains(&span) == false{ 83 | self.bug_records.uaf_bugs.insert(span.clone()); 84 | } 85 | } 86 | 87 | pub fn dp_check(&self, local: usize) -> bool{ 88 | let mut record = FxHashSet::default(); 89 | return self.exist_dead(local, &mut record, local != 0); 90 | } 91 | 92 | pub fn bug_check(&mut self, current_block: &BlockNode<'tcx>){ 93 | if current_block.is_cleanup == false{ 94 | if self.nodes[0].so_so() && self.dp_check(0){ 95 | self.bug_records.dp_bug = true; 96 | } 97 | else{ 98 | for i in 0..self.arg_size{ 99 | if self.nodes[i+1].is_ptr() && self.dp_check(i+1){ 100 | self.bug_records.dp_bug = true; 101 | } 102 | } 103 | } 104 | } 105 | else{ 106 | for i in 0..self.arg_size{ 107 | if self.nodes[i+1].is_ptr() && self.dp_check(i+1){ 108 | self.bug_records.dp_bug_unwind = true; 109 | } 110 | } 111 | } 112 | } 113 | 114 | pub fn dead_node(&mut self, drop: usize, life_begin: usize, info: &SourceInfo, alias: bool){ 115 | //Rc drop 116 | if self.nodes[drop].is_corner_case(){ 117 | return; 118 | } 119 | //check if there is a double free bug. 120 | if self.df_check(drop, info.span){ 121 | return; 122 | } 123 | //drop their alias 124 | if self.nodes[drop].alias[0] != drop{ 125 | for i in self.nodes[drop].alias.clone().into_iter(){ 126 | if self.nodes[i].is_ref(){ 127 | continue; 128 | } 129 | self.dead_node(i, life_begin, info, true); 130 | } 131 | } 132 | //drop the sons of the root node. 133 | //alias flag is used to avoid the sons of the alias are dropped repeatly. 134 | if alias == false{ 135 | for i in self.nodes[drop].sons.clone().into_iter(){ 136 | if self.nodes[drop].is_tuple() == true && self.nodes[i.1].need_drop() == false{ 137 | continue; 138 | } 139 | self.dead_node( i.1, life_begin, info, false); 140 | } 141 | } 142 | //SCC. 143 | if self.nodes[drop].alive < life_begin as isize && self.nodes[drop].so_so(){ 144 | self.nodes[drop].dead(); 145 | } 146 | } 147 | 148 | // field-sensitive fetch instruction for a variable. 149 | // is_right: 2 = 1.0; 0 = 2.0; => 0 = 1.0.0; 150 | pub fn handle_projection(&mut self, is_right: bool, local: usize, tcx: TyCtxt<'tcx>, place: Place<'tcx>) -> usize{ 151 | let mut init_local = local; 152 | let mut current_local = local; 153 | for projection in place.projection{ 154 | match projection{ 155 | ProjectionElem::Deref => { 156 | if current_local == self.nodes[current_local].alias[0] && self.nodes[current_local].is_ref() == false{ 157 | let need_drop = true; 158 | let so_so = true; 159 | let mut node = Node::new(self.nodes.len(), self.nodes.len(), need_drop, need_drop || !so_so); 160 | node.kind = 1; //TODO 161 | node.alive = self.nodes[current_local].alive; 162 | self.nodes[current_local].alias[0] = self.nodes.len(); 163 | self.nodes.push(node); 164 | } 165 | current_local = self.nodes[current_local].alias[0]; 166 | init_local = self.nodes[current_local].index; 167 | } 168 | ProjectionElem::Field(field, ty) =>{ 169 | let index = field.as_usize(); 170 | if is_right && self.nodes[current_local].alias[0] != current_local{ 171 | current_local = self.nodes[current_local].alias[0]; 172 | init_local = self.nodes[current_local].index; 173 | } 174 | if self.nodes[current_local].sons.contains_key(&index) == false{ 175 | let param_env = tcx.param_env(self.def_id); 176 | let need_drop = ty.needs_drop(tcx, param_env); 177 | let so_so = so_so(ty); 178 | let mut node = Node::new(init_local, self.nodes.len(), need_drop, need_drop || !so_so); 179 | node.kind = kind(ty); 180 | node.alive = self.nodes[current_local].alive; 181 | node.field_info = self.nodes[current_local].field_info.clone(); 182 | node.field_info.push(index); 183 | self.nodes[current_local].sons.insert(index, node.local); 184 | self.nodes.push(node); 185 | } 186 | current_local = *self.nodes[current_local].sons.get(&index).unwrap(); 187 | } 188 | _ => {} 189 | } 190 | } 191 | return current_local; 192 | } 193 | 194 | //merge the result of current path to the final result. 195 | pub fn merge_results(&mut self, results_nodes: Vec, is_cleanup: bool){ 196 | for node in results_nodes.iter(){ 197 | if node.index <= self.arg_size{ 198 | if node.alias[0] != node.local || node.alias.len() > 1{ 199 | for alias in node.alias.clone(){ 200 | if results_nodes[alias].index <= self.arg_size 201 | && !self.return_set.contains(&(node.local, alias)) 202 | && alias != node.local 203 | && node.index != results_nodes[alias].index{ 204 | self.return_set.insert((node.local, alias)); 205 | let left_node = node; 206 | let right_node = &results_nodes[alias]; 207 | let mut new_assign = ReturnAssign::new(0, 208 | left_node.index, left_node.so_so(), left_node.need_drop(), 209 | right_node.index, right_node.so_so(), right_node.need_drop()); 210 | new_assign.left = left_node.field_info.clone(); 211 | new_assign.right = right_node.field_info.clone(); 212 | self.return_results.assignments.push(new_assign); 213 | } 214 | } 215 | } 216 | if node.is_ptr() && is_cleanup == false && node.is_alive() == false && node.local <= self.arg_size{ 217 | self.return_results.dead.insert(node.local); 218 | } 219 | } 220 | } 221 | } 222 | } 223 | 224 | pub fn kind<'tcx>(current_ty: Ty<'tcx>) -> usize { 225 | match current_ty.kind() { 226 | ty::RawPtr(..) => 1, 227 | ty::Ref(..) => 4, 228 | ty::Tuple(..) => 2, 229 | ty::Adt(ref adt_def, _) => { 230 | if is_corner_adt(format!("{:?}", adt_def)){ 231 | return 3; 232 | } 233 | else{ 234 | return 0; 235 | } 236 | }, 237 | _ => 0, 238 | } 239 | } 240 | 241 | //type filter. 242 | pub fn so_so<'tcx>(current_ty: Ty<'tcx>) -> bool { 243 | match current_ty.kind() { 244 | ty::Bool 245 | | ty::Char 246 | | ty::Int(_) 247 | | ty::Uint(_) 248 | | ty::Float(_) => true, 249 | ty::Array(ref tys,_) => so_so(*tys), 250 | ty::Adt(_, ref substs) => { 251 | for tys in substs.types() { 252 | if !so_so(tys) { 253 | return false; 254 | } 255 | } 256 | true 257 | }, 258 | ty::Tuple(ref substs) => { 259 | for tys in substs.iter() { 260 | if !so_so(tys) { 261 | return false; 262 | } 263 | } 264 | true 265 | }, 266 | _ => false, 267 | } 268 | } 269 | 270 | //instruction to assign alias for a variable. 271 | pub fn merge_alias(move_set: &mut FxHashSet, left_ssa: usize, right_ssa: usize, nodes: &mut Vec){ 272 | if nodes[left_ssa].index == nodes[right_ssa].index{ 273 | return; 274 | } 275 | if move_set.contains(&left_ssa){ 276 | let mut alias_clone = nodes[right_ssa].alias.clone(); 277 | nodes[left_ssa].alias.append(&mut alias_clone); 278 | } 279 | else{ 280 | move_set.insert(left_ssa); 281 | nodes[left_ssa].alias = nodes[right_ssa].alias.clone(); 282 | } 283 | for son in nodes[right_ssa].sons.clone().into_iter(){ 284 | if nodes[left_ssa].sons.contains_key(&son.0) == false{ 285 | let mut node = Node::new(nodes[left_ssa].index, nodes.len(), nodes[son.1].need_drop(), nodes[son.1].so_so()); 286 | node.kind = nodes[son.1].kind; 287 | node.alive = nodes[left_ssa].alive; 288 | node.field_info = nodes[left_ssa].field_info.clone(); 289 | node.field_info.push(son.0); 290 | nodes[left_ssa].sons.insert(son.0, node.local); 291 | nodes.push(node); 292 | } 293 | let l_son = *(nodes[left_ssa].sons.get(&son.0).unwrap()); 294 | merge_alias(move_set, l_son, son.1, nodes); 295 | } 296 | } 297 | 298 | //inter-procedure instruction to merge alias. 299 | pub fn merge(move_set: &mut FxHashSet, nodes: &mut Vec, assign: &ReturnAssign, arg_vec: &Vec){ 300 | if assign.left_index >= arg_vec.len(){ 301 | println!("vector warning!"); 302 | return; 303 | } 304 | if assign.right_index >= arg_vec.len(){ 305 | println!("vector warning!"); 306 | return; 307 | } 308 | let left_init = arg_vec[assign.left_index]; 309 | let mut right_init = arg_vec[assign.right_index]; 310 | let mut left_ssa = left_init; 311 | let mut right_ssa = right_init; 312 | for index in assign.left.iter(){ 313 | if nodes[left_ssa].sons.contains_key(&index) == false{ 314 | let need_drop = assign.left_need_drop; 315 | let so_so = assign.left_so_so; 316 | let mut node = Node::new(left_init, nodes.len(), need_drop, so_so); 317 | node.kind = 1; 318 | node.alive = nodes[left_ssa].alive; 319 | node.field_info = nodes[left_ssa].field_info.clone(); 320 | node.field_info.push(*index); 321 | nodes[left_ssa].sons.insert(*index, node.local); 322 | nodes.push(node); 323 | } 324 | left_ssa = *nodes[left_ssa].sons.get(&index).unwrap(); 325 | } 326 | for index in assign.right.iter(){ 327 | if nodes[right_ssa].alias[0] != right_ssa{ 328 | right_ssa = nodes[right_ssa].alias[0]; 329 | right_init = nodes[right_ssa].index; 330 | } 331 | if nodes[right_ssa].sons.contains_key(&index) == false{ 332 | let need_drop = assign.right_need_drop; 333 | let so_so = assign.right_so_so; 334 | let mut node = Node::new(right_init, nodes.len(), need_drop, so_so); 335 | node.kind = 1; 336 | node.alive = nodes[right_ssa].alive; 337 | node.field_info = nodes[right_ssa].field_info.clone(); 338 | node.field_info.push(*index); 339 | nodes[right_ssa].sons.insert(*index, node.local); 340 | nodes.push(node); 341 | } 342 | right_ssa = *nodes[right_ssa].sons.get(&index).unwrap(); 343 | } 344 | merge_alias(move_set, left_ssa, right_ssa, nodes); 345 | } 346 | 347 | //struct to cache the results for analyzed functions. 348 | #[derive(Clone)] 349 | pub struct FuncMap { 350 | pub map: FxHashMap, 351 | pub set: FxHashSet, 352 | } 353 | 354 | impl FuncMap{ 355 | pub fn new() -> FuncMap{ 356 | FuncMap { map: FxHashMap::default(), set: FxHashSet::default()} 357 | } 358 | } 359 | 360 | //structure to record the existed bugs. 361 | pub struct BugRecords{ 362 | pub df_bugs: FxHashMap, 363 | pub df_bugs_unwind: FxHashMap, 364 | pub uaf_bugs: FxHashSet, 365 | pub dp_bug: bool, 366 | pub dp_bug_unwind: bool, 367 | } 368 | 369 | impl BugRecords{ 370 | pub fn new() -> BugRecords{ 371 | BugRecords { df_bugs: FxHashMap::default(), df_bugs_unwind: FxHashMap::default(), uaf_bugs: FxHashSet::default(), dp_bug: false, dp_bug_unwind: false} 372 | } 373 | 374 | pub fn is_bug_free(&self) -> bool{ 375 | return self.df_bugs.is_empty() && self.uaf_bugs.is_empty() && self.dp_bug == false && self.dp_bug_unwind == false; 376 | } 377 | 378 | pub fn df_bugs_output(&self){ 379 | if self.df_bugs.is_empty(){ 380 | return; 381 | } 382 | println!("Double Free Bugs Exist:"); 383 | for i in self.df_bugs.iter(){ 384 | println!("occurs in {:?}", i.1); 385 | } 386 | } 387 | 388 | pub fn uaf_bugs_output(&self){ 389 | if self.uaf_bugs.is_empty(){ 390 | return; 391 | } 392 | println!("Use After Free Bugs Exist:"); 393 | for i in self.uaf_bugs.iter(){ 394 | println!("occurs in {:?}", i); 395 | } 396 | } 397 | 398 | pub fn dp_bug_output(&self, span: Span){ 399 | if self.dp_bug{ 400 | println!("Dangling Pointer Bug Exist {:?}", span); 401 | } 402 | if self.dp_bug_unwind{ 403 | println!("Dangling Pointer Bug Exist in Unwinding {:?}", span); 404 | } 405 | } 406 | } 407 | --------------------------------------------------------------------------------