aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/lfalloc/alloc_profiler/profiler.cpp
blob: b4f92fe0db42584517982eb8e986c64f48749500 (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
#include "profiler.h"
 
#include "stackcollect.h"

#include <util/generic/algorithm.h>
#include <util/generic/singleton.h>
#include <util/generic/string.h>
#include <util/generic/vector.h>
#include <util/stream/str.h>

namespace NAllocProfiler {

namespace {

static TAllocationStackCollector& AllocationStackCollector()
{
    return *Singleton<TAllocationStackCollector>();
}

int AllocationCallback(int tag, size_t size, int sizeIdx)
{
    Y_UNUSED(sizeIdx);

    static const size_t STACK_FRAMES_COUNT = 32;
    static const size_t STACK_FRAMES_SKIP = 1;

    void* frames[STACK_FRAMES_COUNT];
    size_t frameCount = BackTrace(frames, Y_ARRAY_SIZE(frames));
    if (frameCount <= STACK_FRAMES_SKIP) {
        return -1;
    }

    void** stack = &frames[STACK_FRAMES_SKIP];
    frameCount -= STACK_FRAMES_SKIP;

    auto& collector = AllocationStackCollector();
    return collector.Alloc(stack, frameCount, tag, size);
}

void DeallocationCallback(int stackId, int tag, size_t size, int sizeIdx)
{
    Y_UNUSED(tag);
    Y_UNUSED(sizeIdx);

    auto& collector = AllocationStackCollector();
    collector.Free(stackId, size);
}

}   // namespace

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

bool StartAllocationSampling(bool profileAllThreads)
{
    auto& collector = AllocationStackCollector();
    collector.Clear();

    NAllocDbg::SetProfileAllThreads(profileAllThreads);
    NAllocDbg::SetAllocationCallback(AllocationCallback);
    NAllocDbg::SetDeallocationCallback(DeallocationCallback);
    NAllocDbg::SetAllocationSamplingEnabled(true);
    return true;
}

bool StopAllocationSampling(IAllocationStatsDumper &out, int count)
{
    NAllocDbg::SetAllocationCallback(nullptr);
    NAllocDbg::SetDeallocationCallback(nullptr);
    NAllocDbg::SetAllocationSamplingEnabled(false);

    auto& collector = AllocationStackCollector();
    collector.Dump(count, out);
    return true;
}

bool StopAllocationSampling(IOutputStream& out, int count) {
    TAllocationStatsDumper dumper(out);
    return StopAllocationSampling(dumper, count);
}

}   // namespace NProfiler