-
Notifications
You must be signed in to change notification settings - Fork 1
/
MemoryLeakDetector.swift
277 lines (202 loc) · 6.78 KB
/
MemoryLeakDetector.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import UIKitTestable
public func detectLeaks<T>(by build: () -> T) -> Set<Reference.Path> {
let releasedWeakMap = autoreleasepool { () -> [Reference.ID: Reference] in
return createWeakMap(from: build())
}
let leaked = releasedWeakMap.values
.filter { (reference) in !reference.isReleased }
.flatMap { (reference) -> [Reference.Path] in reference.paths }
.filter { path in path.isCircularAtEnd }
return Set(leaked)
}
public func detectLeaks<T>(by build: (@escaping (T) -> Void) -> Void, _ callback: @escaping (Set<Reference.Path>) -> Void) {
build { target in
let releasedWeakMap = autoreleasepool { () -> [Reference.ID: Reference] in
return createWeakMap(from: target)
}
let leaked = releasedWeakMap
.values
.filter { reference in !reference.isReleased }
.flatMap { (reference) -> [Reference.Path] in reference.paths }
.filter { path in path.isCircularAtEnd }
callback(Set(leaked))
}
}
internal func createWeakMap<T>(from target: T) -> [Reference.ID: Reference] {
var result: [Reference.ID: Reference] = [:]
traverseObjectWithPath(
target,
onEnter: { (label, value, path) in
let childReferenceID = Reference.ID.from(value)
if let visitedReference = result[childReferenceID] {
visitedReference.append(path: .from(path))
}
else {
result[childReferenceID] = Reference.from(value, paths: [.from(path)])
}
},
onLeave: nil
)
return result
}
internal func traverseObjectWithPath(
_ target: Any,
onEnter: ((String?, Any, [(label: String?, value: Any)]) -> Void)?,
onLeave: ((String?, Any, [(label: String?, value: Any)]) -> Void)?
) {
var currentPath: [(label: String?, value: Any)] = []
traverseObject(
target,
onEnter: { (label, value) in
currentPath.append((label: label, value: value))
onEnter?(label, value, currentPath)
},
onLeave: { (label, value) in
onLeave?(label, value, currentPath)
currentPath.removeLast()
}
)
}
internal func traverseObject(
_ target: Any,
onEnter: ((String?, Any) -> Void)?,
onLeave: ((String?, Any) -> Void)?
) {
var footprint = Set<Reference.ID>()
traverseObjectRecursive(
label: nil,
target,
footprint: &footprint,
onEnter: onEnter,
onLeave: onLeave
)
}
private func traverseObjectRecursive(
label: String?,
_ target: Any,
footprint: inout Set<Reference.ID>,
onEnter: ((String?, Any) -> Void)?,
onLeave: ((String?, Any) -> Void)?
) {
onEnter?(label, target)
// NOTE: Avoid infinite recursions caused by circular references.
let id = Reference.ID.from(target)
if !footprint.contains(id) {
footprint.insert(id)
let mirror = Mirror(reflecting: target)
mirror.children.enumerated().forEach { indexAndChild in
let (index, (label: label, value: value)) = indexAndChild
traverseObjectRecursive(
// NOTE: Use the index as the label instead of nil only if the target is a collection.
label: mirror.displayStyle == .collection ? "\(index)" : label,
value,
footprint: &footprint,
onEnter: onEnter,
onLeave: onLeave
)
}
}
onLeave?(label, target)
}
public class Reference {
private let value: WeakOrNotReference
public let id: ID
public let typeName: String
public let description: String
public var paths: [Path]
internal init(value: WeakOrNotReference, id: ID, typeName: String, description: String, paths: [Path]) {
self.value = value
self.id = id
self.typeName = typeName
self.description = description
self.paths = paths
}
public var isReleased: Bool {
guard let weak = self.value.weak else {
return true
}
return weak.isReleased
}
public func append(path: Path) {
self.paths.append(path)
}
public static func from<T>(_ target: T, paths: [Path]) -> Reference {
return Reference(
value: .from(target),
id: .from(target),
typeName: "\(type(of: target))",
description: "\(target)",
paths: paths
)
}
public struct Path: Hashable {
public let componentsWithRoot: [Component]
public var components: [Component] {
return Array(self.componentsWithRoot.dropFirst())
}
public var labels: [String?] {
return self.components.map { $0.label }
}
public var isCircularAtEnd: Bool {
let ids = self.componentsWithRoot.map { $0.id }
guard let lastID = ids.last else {
return false
}
let idsWithoutLast = ids.dropLast()
return idsWithoutLast.contains(lastID)
}
public static func from<T, Seq>(
_ path: Seq
) -> Path where Seq: Sequence, Seq.Element == (label: String?, value: T) {
return Path(componentsWithRoot: path.map { Component(label: $0.label, id: .from($0.value)) })
}
public struct Component: Hashable {
public let label: String?
public let id: ID
}
}
public enum ID {
case anyReference(objectIdentifier: ObjectIdentifier)
case anyValue
case unknown
public static func from<T>(_ target: T) -> ID {
switch Mirror(reflecting: target).displayStyle {
case .some(.class):
let objectIdentifier = ObjectIdentifier(target as AnyObject)
return .anyReference(objectIdentifier: objectIdentifier)
case .some:
return .anyValue
case .none:
return .unknown
}
}
}
}
extension Reference: Hashable {
public var hashValue: Int {
return self.id.hashValue
}
public static func ==(lhs: Reference, rhs: Reference) -> Bool {
return lhs.id == rhs.id
}
}
extension Reference.ID: Hashable {
public var hashValue: Int {
switch self {
case .anyReference(objectIdentifier: let objectIdentifier):
return objectIdentifier.hashValue
case .anyValue:
return 0
case .unknown:
return 1
}
}
public static func ==(lhs: Reference.ID, rhs: Reference.ID) -> Bool {
switch (lhs, rhs) {
case (.anyReference(objectIdentifier: let l), .anyReference(objectIdentifier: let r)):
return l == r
default:
return false
}
}
}