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_LEAK_FOLDING_H_
18 #define LIBMEMUNREACHABLE_LEAK_FOLDING_H_
19 
20 #include "HeapWalker.h"
21 
22 namespace android {
23 
24 class LeakFolding {
25  public:
LeakFolding(Allocator<void> allocator,HeapWalker & heap_walker)26   LeakFolding(Allocator<void> allocator, HeapWalker& heap_walker)
27       : allocator_(allocator),
28         heap_walker_(heap_walker),
29         leak_map_(allocator),
30         leak_graph_(allocator),
31         leak_scc_(allocator) {}
32 
33   bool FoldLeaks();
34 
35   struct Leak {
36     const Range range;
37     size_t referenced_count;
38     size_t referenced_size;
39   };
40 
41   bool Leaked(allocator::vector<Leak>& leaked, size_t* num_leaks_out, size_t* leak_bytes_out);
42 
43  private:
44   DISALLOW_COPY_AND_ASSIGN(LeakFolding);
45   Allocator<void> allocator_;
46   HeapWalker& heap_walker_;
47 
48   struct SCCInfo {
49    public:
50     Node<SCCInfo> node;
51 
52     size_t count;
53     size_t size;
54 
55     size_t cuumulative_count;
56     size_t cuumulative_size;
57 
58     bool dominator;
59     SCCInfo* accumulator;
60 
SCCInfoSCCInfo61     explicit SCCInfo(Allocator<SCCInfo> allocator)
62         : node(this, allocator),
63           count(0),
64           size(0),
65           cuumulative_count(0),
66           cuumulative_size(0),
67           dominator(false),
68           accumulator(nullptr) {}
69 
70    private:
71     SCCInfo(SCCInfo&&) = delete;
72     DISALLOW_COPY_AND_ASSIGN(SCCInfo);
73   };
74 
75   struct LeakInfo {
76    public:
77     Node<LeakInfo> node;
78 
79     const Range range;
80 
81     SCCInfo* scc;
82 
LeakInfoLeakInfo83     LeakInfo(const Range& range, Allocator<LeakInfo> allocator)
84         : node(this, allocator), range(range), scc(nullptr) {}
85 
86    private:
87     DISALLOW_COPY_AND_ASSIGN(LeakInfo);
88   };
89 
90   void ComputeDAG();
91   void AccumulateLeaks(SCCInfo* dominator);
92 
93   allocator::map<Range, LeakInfo, compare_range> leak_map_;
94   Graph<LeakInfo> leak_graph_;
95   allocator::vector<Allocator<SCCInfo>::unique_ptr> leak_scc_;
96 };
97 
98 }  // namespace android
99 
100 #endif  // LIBMEMUNREACHABLE_LEAK_FOLDING_H_
101