Colin Cross | bcb4ed3 | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2016 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef LIBMEMUNREACHABLE_HEAP_WALKER_H_ |
| 18 | #define LIBMEMUNREACHABLE_HEAP_WALKER_H_ |
| 19 | |
| 20 | #include "android-base/macros.h" |
| 21 | |
| 22 | #include "Allocator.h" |
| 23 | |
| 24 | // A range [begin, end) |
| 25 | struct Range { |
| 26 | uintptr_t begin; |
| 27 | uintptr_t end; |
| 28 | }; |
| 29 | |
| 30 | // Comparator for Ranges that returns equivalence for overlapping ranges |
| 31 | struct compare_range { |
| 32 | bool operator()(const Range& a, const Range& b) const { |
| 33 | return a.end <= b.begin; |
| 34 | } |
| 35 | }; |
| 36 | |
| 37 | |
| 38 | class HeapWalker { |
| 39 | public: |
| 40 | HeapWalker(Allocator<HeapWalker> allocator) : allocator_(allocator), |
| 41 | allocations_(allocator), allocation_bytes_(0), |
| 42 | roots_(allocator), root_vals_(allocator) { |
| 43 | valid_allocations_range_.end = 0; |
| 44 | valid_allocations_range_.begin = ~valid_allocations_range_.end; |
| 45 | } |
| 46 | ~HeapWalker() {} |
| 47 | bool Allocation(uintptr_t begin, uintptr_t end); |
| 48 | void Root(uintptr_t begin, uintptr_t end); |
| 49 | void Root(const allocator::vector<uintptr_t>& vals); |
| 50 | |
| 51 | bool DetectLeaks(); |
| 52 | |
| 53 | bool Leaked(allocator::vector<Range>&, size_t limit, size_t* num_leaks, |
| 54 | size_t* leak_bytes); |
| 55 | size_t Allocations(); |
| 56 | size_t AllocationBytes(); |
| 57 | |
| 58 | private: |
| 59 | struct RangeInfo { |
| 60 | bool referenced_from_root; |
| 61 | bool referenced_from_leak; |
| 62 | }; |
| 63 | void Walk(const Range& range, bool RangeInfo::* flag); |
| 64 | DISALLOW_COPY_AND_ASSIGN(HeapWalker); |
| 65 | Allocator<HeapWalker> allocator_; |
| 66 | using RangeMap = allocator::map<RangeInfo, Range, compare_range>; |
| 67 | RangeMap allocations_; |
| 68 | size_t allocation_bytes_; |
| 69 | Range valid_allocations_range_; |
| 70 | |
| 71 | allocator::vector<Range> roots_; |
| 72 | allocator::vector<uintptr_t> root_vals_; |
| 73 | }; |
| 74 | |
| 75 | #endif |