aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/include/winapi/debug/call_stack.hpp
blob: 9145d6ac487339a6bcabb3a0d8a3e47c1ddac037 (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
// Copyright (c) 2020 Egor Tensin <egor@tensin.name>
// This file is part of the "winapi-debug" project.
// For details, see https://github.com/egor-tensin/winapi-debug
// Distributed under the MIT License.

#pragma once

#include "address.hpp"
#include "dbghelp.hpp"

#include <windows.h>

#include <array>
#include <cstddef>
#include <functional>
#include <ostream>
#include <string>

namespace winapi {

class CallStack {
public:
    static constexpr std::size_t frames_to_skip = 0;
    static constexpr std::size_t frames_to_capture = 62;

    // Imposed by CaptureStackBackTrace:
    static constexpr std::size_t max_length = 62;

    static_assert(
        frames_to_skip + frames_to_capture <= max_length,
        "Call stack length is too large"
    );

    static CallStack capture();

    using AddressCallback = std::function<bool(Address)>;
    bool for_each_address(const AddressCallback& callback) const;

    static std::string pretty_print_address(const DbgHelp& dbghelp, Address addr);

    void dump(std::ostream& os, const DbgHelp&) const;

    std::size_t length() const {
        return _length;
    }

    const Address* begin() const {
        return frames.data();
    }

    const Address* cbegin() const {
        return begin();
    }

    const Address* end() const {
        return begin() + _length;
    }

    const Address* cend() const {
        return end();
    }

private:
    CallStack() = default;

    CallStack(std::array<Address, max_length>&& frames, std::size_t length)
        : frames{std::move(frames)}, _length{length} {}

    std::array<Address, max_length> frames;
    std::size_t _length;
};

} // namespace winapi