aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/lfalloc/alloc_profiler/stackcollect.h
blob: 80715ed7cb58f90ae398fe59a6868fc3b97cc5b1 (plain) (blame)
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
#pragma once

#include <library/cpp/containers/stack_vector/stack_vec.h>
#include <library/cpp/cache/cache.h>

#include <util/generic/noncopyable.h>
#include <util/generic/ptr.h>
#include <util/stream/output.h>

namespace NAllocProfiler {

struct TStats {
    intptr_t Allocs = 0;
    intptr_t Frees = 0;
    intptr_t CurrentSize = 0;

    void Clear()
    {
        Allocs = 0;
        Frees = 0;
        CurrentSize = 0;
    }

    void Alloc(size_t size)
    {
        AtomicIncrement(Allocs);
        AtomicAdd(CurrentSize, size);
    }

    void Free(size_t size)
    {
        AtomicIncrement(Frees);
        AtomicSub(CurrentSize, size);
    }
};

struct TAllocationInfo {
    int Tag;
    TStats Stats;
    TStackVec<void*, 64> Stack;

    void Clear() {
        Tag = 0;
        Stats.Clear();
        Stack.clear();
    }
};


class IAllocationStatsDumper {
public:
    virtual ~IAllocationStatsDumper() = default;

    // Total stats
    virtual void DumpTotal(const TStats& total) = 0;

    // Stats for individual stack
    virtual void DumpEntry(const TAllocationInfo& allocInfo) = 0;

    // App-specific tag printer
    virtual TString FormatTag(int tag);

    // Size printer (e.g. "10KB", "100MB", "over 9000")
    virtual TString FormatSize(intptr_t sz);
};

// Default implementation
class TAllocationStatsDumper: public IAllocationStatsDumper {
public:
    explicit TAllocationStatsDumper(IOutputStream& out);
    void DumpTotal(const TStats& total) override;
    void DumpEntry(const TAllocationInfo& allocInfo) override;

private:
    void FormatBackTrace(void* const* stack, size_t sz);

private:
    struct TSymbol {
        const void* Address;
        TString Name;
    };

    size_t PrintedCount;
    IOutputStream& Out;
    TLFUCache<void*, TSymbol> SymbolCache;
};

////////////////////////////////////////////////////////////////////////////////

class TAllocationStackCollector: private TNonCopyable {
private:
    class TImpl;
    THolder<TImpl> Impl;

public:
    TAllocationStackCollector();
    ~TAllocationStackCollector();

    int Alloc(void** stack, size_t frameCount, int tag, size_t size);
    void Free(int stackId, size_t size);

    void Clear();

    void Dump(int count, IAllocationStatsDumper& out) const;
};

}   // namespace NAllocProfiler