Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(122)

Side by Side Diff: components/metrics/leak_detector/leak_detector_impl_unittest.cc

Issue 986503002: components/metrics: Add runtime memory leak detector (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Add comments about lack of thread safety Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/metrics/leak_detector/leak_detector_impl.h"
6
7 #include <math.h>
8 #include <stdint.h>
9
10 #include <complex>
11 #include <new>
12 #include <set>
13 #include <vector>
14
15 #include "base/macros.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "components/metrics/leak_detector/custom_allocator.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19
20 namespace metrics {
21 namespace leak_detector {
22
23 namespace {
24
25 // Makes working with complex numbers easier.
26 using Complex = std::complex<double>;
27
28 // The mapping location in memory for a fictional executable.
29 const uintptr_t kMappingAddr = 0x800000;
30 const size_t kMappingSize = 0x200000;
31
32 // Some call stacks within the fictional executable.
33 // * - outside the mapping range, e.g. JIT code.
34 const uintptr_t kRawStack0[] = {
35 0x800100, 0x900000, 0x880080, 0x810000,
36 };
37 const uintptr_t kRawStack1[] = {
38 0x940000, 0x980000,
39 0xdeadbeef, // *
40 0x9a0000,
41 };
42 const uintptr_t kRawStack2[] = {
43 0x8f0d00, 0x803abc, 0x9100a0,
44 };
45 const uintptr_t kRawStack3[] = {
46 0x90fcde,
47 0x900df00d, // *
48 0x801000, 0x880088,
49 0xdeadcafe, // *
50 0x9f0000, 0x8700a0, 0x96037c,
51 };
52 const uintptr_t kRawStack4[] = {
53 0x8c0000, 0x85d00d, 0x921337,
54 0x780000, // *
55 };
56 const uintptr_t kRawStack5[] = {
57 0x990000, 0x888888, 0x830ac0, 0x8e0000,
58 0xc00000, // *
59 };
60
61 // This struct makes it easier to pass call stack info to
62 // LeakDetectorImplTest::Alloc().
63 struct TestCallStack {
64 const uintptr_t* stack; // A reference to the original stack data.
65 size_t depth;
66 };
67
68 const TestCallStack kStack0 = {kRawStack0, arraysize(kRawStack0)};
69 const TestCallStack kStack1 = {kRawStack1, arraysize(kRawStack1)};
70 const TestCallStack kStack2 = {kRawStack2, arraysize(kRawStack2)};
71 const TestCallStack kStack3 = {kRawStack3, arraysize(kRawStack3)};
72 const TestCallStack kStack4 = {kRawStack4, arraysize(kRawStack4)};
73 const TestCallStack kStack5 = {kRawStack5, arraysize(kRawStack5)};
74
75 // The interval between consecutive analyses (LeakDetectorImpl::TestForLeaks),
76 // in number of bytes allocated. e.g. if |kAllocedSizeAnalysisInterval| = 1024
77 // then call TestForLeaks() every 1024 bytes of allocation that occur.
78 static const size_t kAllocedSizeAnalysisInterval = 8192;
79
80 } // namespace
81
82 // This test suite will test the ability of LeakDetectorImpl to catch leaks in
83 // a program. Individual tests can run leaky code locally.
84 //
85 // The leaky code must call Alloc() and Free() for heap memory management. It
86 // should not call See comments on those
87 // functions for more details.
88 class LeakDetectorImplTest : public ::testing::Test {
89 public:
90 LeakDetectorImplTest()
91 : total_num_allocs_(0),
92 total_num_frees_(0),
93 total_alloced_size_(0),
94 next_analysis_total_alloced_size_(kAllocedSizeAnalysisInterval) {}
95
96 void SetUp() override {
97 CustomAllocator::Initialize();
98
99 const int kSizeSuspicionThreshold = 4;
100 const int kCallStackSuspicionThreshold = 4;
101 detector_.reset(new LeakDetectorImpl(kMappingAddr, kMappingSize,
102 kSizeSuspicionThreshold,
103 kCallStackSuspicionThreshold));
104 }
105
106 void TearDown() override {
107 // Free any memory that was leaked by test cases. Do not use Free() because
108 // that will try to modify |alloced_ptrs_|.
109 for (void* ptr : alloced_ptrs_)
110 delete[] reinterpret_cast<char*>(ptr);
111 alloced_ptrs_.clear();
112
113 // Must destroy all objects that use CustomAllocator before shutting down.
114 detector_.reset();
115 stored_reports_.clear();
116
117 EXPECT_TRUE(CustomAllocator::Shutdown());
118 }
119
120 protected:
121 // Alloc and free functions that allocate and free heap memory and
122 // automatically pass alloc/free info to |detector_|. They emulate the
123 // alloc/free hook functions that would call into LeakDetectorImpl in
124 // real-life usage. They also keep track of individual allocations locally, so
125 // any leaked memory could be cleaned up.
126 //
127 // |stack| is just a nominal call stack object to identify the call site. It
128 // doesn't have to contain the stack trace of the actual call stack.
129 void* Alloc(size_t size, const TestCallStack& stack) {
130 void* ptr = new char[size];
131 detector_->RecordAlloc(ptr, size, stack.depth,
132 reinterpret_cast<const void* const*>(stack.stack));
133
134 EXPECT_TRUE(alloced_ptrs_.find(ptr) == alloced_ptrs_.end());
135 alloced_ptrs_.insert(ptr);
136
137 ++total_num_allocs_;
138 total_alloced_size_ += size;
139 if (total_alloced_size_ >= next_analysis_total_alloced_size_) {
140 InternalVector<InternalLeakReport> reports;
141 detector_->TestForLeaks(&reports);
142 for (const InternalLeakReport& report : reports)
143 stored_reports_.insert(report);
144
145 // Determine when the next leak analysis should occur.
146 while (total_alloced_size_ >= next_analysis_total_alloced_size_)
147 next_analysis_total_alloced_size_ += kAllocedSizeAnalysisInterval;
148 }
149 return ptr;
150 }
151
152 // See comment for Alloc().
153 void Free(void* ptr) {
154 auto find_ptr_iter = alloced_ptrs_.find(ptr);
155 EXPECT_FALSE(find_ptr_iter == alloced_ptrs_.end());
156 if (find_ptr_iter == alloced_ptrs_.end())
157 return;
158 alloced_ptrs_.erase(find_ptr_iter);
159 ++total_num_frees_;
160
161 detector_->RecordFree(ptr);
162
163 delete[] reinterpret_cast<char*>(ptr);
164 }
165
166 // TEST CASE: Julia set fractal computation. Pass in enable_leaks=true to
167 // trigger some memory leaks.
168 void JuliaSet(bool enable_leaks);
169
170 // Instance of the class being tested.
171 scoped_ptr<LeakDetectorImpl> detector_;
172
173 // Number of pointers allocated and freed so far.
174 size_t total_num_allocs_;
175 size_t total_num_frees_;
176
177 // Keeps count of total size allocated by Alloc().
178 size_t total_alloced_size_;
179
180 // The cumulative allocation size at which to trigger the TestForLeaks() call.
181 size_t next_analysis_total_alloced_size_;
182
183 // Stores all pointers to memory allocated by by Alloc() so we can manually
184 // free the leaked pointers at the end. This also serves as redundant
185 // bookkeepping: it stores all pointers that have been allocated but not yet
186 // freed.
187 std::set<void*> alloced_ptrs_;
188
189 // Store leak reports here. Use a set so duplicate reports are not stored.
190 std::set<InternalLeakReport> stored_reports_;
191
192 private:
193 DISALLOW_COPY_AND_ASSIGN(LeakDetectorImplTest);
194 };
195
196 void LeakDetectorImplTest::JuliaSet(bool enable_leaks) {
197 // The center region of the complex plane that is the basis for our Julia set
198 // computations is a circle of radius kRadius.
199 constexpr double kRadius = 2;
200
201 // To track points in the complex plane, we will use a rectangular grid in the
202 // range defined by [-kRadius, kRadius] along both axes.
203 constexpr double kRangeMin = -kRadius;
204 constexpr double kRangeMax = kRadius;
205
206 // Divide each axis into intervals, each of which is associated with a point
207 // on that axis at its center.
208 constexpr double kIntervalInverse = 64;
209 constexpr double kInterval = 1.0 / kIntervalInverse;
210 constexpr int kNumPoints = (kRangeMax - kRangeMin) / kInterval + 1;
211
212 // Contains some useful functions for converting between points on the complex
213 // plane and in a gridlike data structure.
214 struct ComplexPlane {
215 static int GetXGridIndex(const Complex& value) {
216 return (value.real() + kInterval / 2 - kRangeMin) / kInterval;
217 }
218 static int GetYGridIndex(const Complex& value) {
219 return (value.imag() + kInterval / 2 - kRangeMin) / kInterval;
220 }
221 static int GetArrayIndex(const Complex& value) {
222 return GetXGridIndex(value) + GetYGridIndex(value) * kNumPoints;
223 }
224 static Complex GetComplexForGridPoint(size_t x, size_t y) {
225 return Complex(kRangeMin + x * kInterval, kRangeMin + y * kInterval);
226 }
227 };
228
229 // Make sure the choice of interval doesn't result in any loss of precision.
230 ASSERT_EQ(1.0, kInterval * kIntervalInverse);
231
232 // Create a grid for part of the complex plane, with each axis within the
233 // range [kRangeMin, kRangeMax].
234 constexpr size_t width = kNumPoints;
235 constexpr size_t height = kNumPoints;
236 std::vector<Complex*> grid(width * height);
237
238 // Initialize an object for each point within the inner circle |z| < kRadius.
239 for (size_t i = 0; i < width; ++i) {
240 for (size_t j = 0; j < height; ++j) {
241 Complex point = ComplexPlane::GetComplexForGridPoint(i, j);
242 // Do not store any values outside the inner circle.
243 if (abs(point) <= kRadius) {
244 grid[i + j * width] =
245 new (Alloc(sizeof(Complex), kStack0)) Complex(point);
246 }
247 }
248 }
249 EXPECT_LE(alloced_ptrs_.size(), width * height);
250
251 // Create a new grid for the result of the transformation.
252 std::vector<Complex*> next_grid(width * height, nullptr);
253
254 const int kNumIterations = 20;
255 for (int n = 0; n < kNumIterations; ++n) {
256 for (int i = 0; i < kNumPoints; ++i) {
257 for (int j = 0; j < kNumPoints; ++j) {
258 if (!grid[i + j * width])
259 continue;
260
261 // NOTE: The below code is NOT an efficient way to compute a Julia set.
262 // This is only to test the leak detector with some nontrivial code.
263
264 // A simple polynomial function for generating Julia sets is:
265 // f(z) = z^n + c
266
267 // But in this algorithm, we need the inverse:
268 // fInv(z) = (z - c)^(1/n)
269
270 // Here, let's use n=5 and c=0.544.
271 const Complex c(0.544, 0);
272 const Complex& z = *grid[i + j * width];
273
274 // This is the principal root.
275 Complex root = pow(z - c, 0.2);
276
277 // Discard the result if it is too far out from the center of the plane.
278 if (abs(root) > kRadius)
279 continue;
280
281 // The below code only allocates Complex objects of the same size. The
282 // leak detector expects various sizes, so increase the allocation size
283 // by a different amount at each call site.
284
285 // Nth root produces N results.
286 // Place all root results on |next_grid|.
287
288 // First, place the principal root.
289 if (!next_grid[ComplexPlane::GetArrayIndex(root)]) {
290 next_grid[ComplexPlane::GetArrayIndex(root)] =
291 new (Alloc(sizeof(Complex) + 24, kStack1)) Complex(root);
292 }
293
294 double magnitude = abs(root);
295 double angle = arg(root);
296 // To generate other roots, rotate the principal root by increments of
297 // 1/N of a full circle.
298 const double kAngleIncrement = M_PI * 2 / 5;
299
300 // Second root.
301 root = std::polar(magnitude, angle + kAngleIncrement);
302 if (!next_grid[ComplexPlane::GetArrayIndex(root)]) {
303 next_grid[ComplexPlane::GetArrayIndex(root)] =
304 new (Alloc(sizeof(Complex) + 40, kStack2)) Complex(root);
305 }
306
307 // In some of the sections below, setting |enable_leaks| to true will
308 // trigger a memory leak by overwriting the old Complex pointer value
309 // without freeing it. Due to the nature of complex roots being confined
310 // to equal sections of the complex plane, each new pointer will
311 // displace an old pointer that was allocated from the same line of
312 // code.
313
314 // Third root.
315 root = std::polar(magnitude, angle + kAngleIncrement * 2);
316 // *** LEAK ***
317 if (enable_leaks || !next_grid[ComplexPlane::GetArrayIndex(root)]) {
318 next_grid[ComplexPlane::GetArrayIndex(root)] =
319 new (Alloc(sizeof(Complex) + 40, kStack3)) Complex(root);
320 }
321
322 // Fourth root.
323 root = std::polar(magnitude, angle + kAngleIncrement * 3);
324 // *** LEAK ***
325 if (enable_leaks || !next_grid[ComplexPlane::GetArrayIndex(root)]) {
326 next_grid[ComplexPlane::GetArrayIndex(root)] =
327 new (Alloc(sizeof(Complex) + 52, kStack4)) Complex(root);
328 }
329
330 // Fifth root.
331 root = std::polar(magnitude, angle + kAngleIncrement * 4);
332 if (!next_grid[ComplexPlane::GetArrayIndex(root)]) {
333 next_grid[ComplexPlane::GetArrayIndex(root)] =
334 new (Alloc(sizeof(Complex) + 52, kStack5)) Complex(root);
335 }
336 }
337 }
338
339 // Clear the previously allocated points.
340 for (Complex*& point : grid) {
341 if (point) {
342 Free(point);
343 point = nullptr;
344 }
345 }
346
347 // Now swap the two grids for the next iteration.
348 grid.swap(next_grid);
349 }
350
351 // Clear the previously allocated points.
352 for (Complex*& point : grid) {
353 if (point) {
354 Free(point);
355 point = nullptr;
356 }
357 }
358 }
359
360 TEST_F(LeakDetectorImplTest, CheckTestFramework) {
361 EXPECT_EQ(0U, total_num_allocs_);
362 EXPECT_EQ(0U, total_num_frees_);
363 EXPECT_EQ(0U, alloced_ptrs_.size());
364
365 // Allocate some memory.
366 void* ptr0 = Alloc(12, kStack0);
367 void* ptr1 = Alloc(16, kStack0);
368 void* ptr2 = Alloc(24, kStack0);
369 EXPECT_EQ(3U, total_num_allocs_);
370 EXPECT_EQ(0U, total_num_frees_);
371 EXPECT_EQ(3U, alloced_ptrs_.size());
372
373 // Free one of the pointers.
374 Free(ptr1);
375 EXPECT_EQ(3U, total_num_allocs_);
376 EXPECT_EQ(1U, total_num_frees_);
377 EXPECT_EQ(2U, alloced_ptrs_.size());
378
379 // Allocate some more memory.
380 void* ptr3 = Alloc(72, kStack1);
381 void* ptr4 = Alloc(104, kStack1);
382 void* ptr5 = Alloc(96, kStack1);
383 void* ptr6 = Alloc(24, kStack1);
384 EXPECT_EQ(7U, total_num_allocs_);
385 EXPECT_EQ(1U, total_num_frees_);
386 EXPECT_EQ(6U, alloced_ptrs_.size());
387
388 // Free more pointers.
389 Free(ptr2);
390 Free(ptr4);
391 Free(ptr6);
392 EXPECT_EQ(7U, total_num_allocs_);
393 EXPECT_EQ(4U, total_num_frees_);
394 EXPECT_EQ(3U, alloced_ptrs_.size());
395
396 // Free remaining memory.
397 Free(ptr0);
398 Free(ptr3);
399 Free(ptr5);
400 EXPECT_EQ(7U, total_num_allocs_);
401 EXPECT_EQ(7U, total_num_frees_);
402 EXPECT_EQ(0U, alloced_ptrs_.size());
403 }
404
405 TEST_F(LeakDetectorImplTest, JuliaSetNoLeak) {
406 JuliaSet(false /* enable_leaks */);
407
408 // JuliaSet() should have run cleanly without leaking.
409 EXPECT_EQ(total_num_allocs_, total_num_frees_);
410 EXPECT_EQ(0U, alloced_ptrs_.size());
411 ASSERT_EQ(0U, stored_reports_.size());
412 }
413
414 TEST_F(LeakDetectorImplTest, JuliaSetWithLeak) {
415 JuliaSet(true /* enable_leaks */);
416
417 // JuliaSet() should have leaked some memory from two call sites.
418 EXPECT_GT(total_num_allocs_, total_num_frees_);
419 EXPECT_GT(alloced_ptrs_.size(), 0U);
420
421 // There should be one unique leak report generated for each leaky call site.
422 ASSERT_EQ(2U, stored_reports_.size());
423
424 // The reports should be stored in order of size.
425
426 // |report1| comes from the call site in JuliaSet() corresponding to
427 // |kStack3|.
428 const InternalLeakReport& report1 = *stored_reports_.begin();
429 EXPECT_EQ(sizeof(Complex) + 40, report1.alloc_size_bytes);
430 EXPECT_EQ(kStack3.depth, report1.call_stack.size());
431 for (size_t i = 0; i < kStack3.depth && i < report1.call_stack.size(); ++i) {
432 // The call stack's addresses may not fall within the mapping address.
433 // Those that don't will not be converted to mapping offsets.
434 if (kStack3.stack[i] >= kMappingAddr &&
435 kStack3.stack[i] <= kMappingAddr + kMappingSize) {
436 EXPECT_EQ(kStack3.stack[i] - kMappingAddr, report1.call_stack[i]);
437 } else {
438 EXPECT_EQ(kStack3.stack[i], report1.call_stack[i]);
439 }
440 }
441
442 // |report2| comes from the call site in JuliaSet() corresponding to
443 // |kStack4|.
444 const InternalLeakReport& report2 = *(++stored_reports_.begin());
445 EXPECT_EQ(sizeof(Complex) + 52, report2.alloc_size_bytes);
446 EXPECT_EQ(kStack4.depth, report2.call_stack.size());
447 for (size_t i = 0; i < kStack4.depth && i < report2.call_stack.size(); ++i) {
448 // The call stack's addresses may not fall within the mapping address.
449 // Those that don't will not be converted to mapping offsets.
450 if (kStack4.stack[i] >= kMappingAddr &&
451 kStack4.stack[i] <= kMappingAddr + kMappingSize) {
452 EXPECT_EQ(kStack4.stack[i] - kMappingAddr, report2.call_stack[i]);
453 } else {
454 EXPECT_EQ(kStack4.stack[i], report2.call_stack[i]);
455 }
456 }
457 }
458
459 } // namespace leak_detector
460 } // namespace metrics
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698