native_heap.py revision 0529e5d033099cbfc42635f6f6183833b09dff6e
1# Copyright 2014 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
5from memory_inspector.core import stacktrace
6from memory_inspector.core import symbol
7
8
9class NativeHeap(object):
10  """A snapshot of outstanding (i.e. not freed) native allocations.
11
12  This is typically obtained by calling |backends.Process|.DumpNativeHeap()
13  """
14
15  def __init__(self):
16    self.allocations = []
17    self.stack_frames = {}  # absolute_address (int) -> |stacktrace.Frame|.
18
19  def Add(self, allocation):
20    assert(isinstance(allocation, Allocation))
21    self.allocations += [allocation]
22
23  def GetStackFrame(self, absolute_addr):
24    assert(isinstance(absolute_addr, int))
25    stack_frame = self.stack_frames.get(absolute_addr)
26    if not stack_frame:
27      stack_frame = stacktrace.Frame(absolute_addr)
28      self.stack_frames[absolute_addr] = stack_frame
29    return stack_frame
30
31  def SymbolizeUsingSymbolDB(self, symbols):
32    assert(isinstance(symbols, symbol.Symbols))
33    for stack_frame in self.stack_frames.itervalues():
34      sym = symbols.Lookup(stack_frame.exec_file_rel_path, stack_frame.offset)
35      if sym:
36        stack_frame.SetSymbolInfo(sym)
37
38
39class Allocation(object):
40  """A Native allocation, modeled in a size*count fashion.
41
42  |count| is the number of identical stack_traces which performed the allocation
43  of |size| bytes.
44  """
45
46  def __init__(self, size, count, stack_trace):
47    assert(isinstance(stack_trace, stacktrace.Stacktrace))
48    self.size = size  # in bytes.
49    self.count = count
50    self.stack_trace = stack_trace
51
52  @property
53  def total_size(self):
54    return self.size * self.count
55
56  def __str__(self):
57    return '%d x %d : %s' % (self.count, self.size, self.stack_trace)
58