ClickHouse/libs/libcommon/include/common/StackTrace.h

62 lines
1.5 KiB
C++
Raw Normal View History

2019-07-01 22:11:11 +00:00
#pragma once
#include <string>
#include <vector>
#include <array>
#include <optional>
#include <signal.h>
#ifdef __APPLE__
// ucontext is not available without _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
2019-07-01 22:11:11 +00:00
#endif
#include <ucontext.h>
struct NoCapture
{
};
/// Tries to capture current stack trace using libunwind or signal context
2019-07-24 23:11:00 +00:00
/// NOTE: StackTrace calculation is signal safe only if enablePHDRCache() was called beforehand.
2019-07-01 22:11:11 +00:00
class StackTrace
{
public:
static constexpr size_t capacity = 32;
using Frames = std::array<void *, capacity>;
/// Tries to capture stack trace
StackTrace();
/// Tries to capture stack trace. Fallbacks on parsing caller address from
/// signal context if no stack trace could be captured
StackTrace(const ucontext_t & signal_context);
/// Creates empty object for deferred initialization
StackTrace(NoCapture);
/// Fills stack trace frames with provided sequence
2019-07-05 13:48:47 +00:00
template <typename Iterator>
StackTrace(Iterator it, Iterator end)
{
while (size < capacity && it != end)
{
frames[size++] = *(it++);
}
}
2019-07-01 22:11:11 +00:00
size_t getSize() const;
const Frames & getFrames() const;
std::string toString() const;
protected:
void tryCapture();
static std::string toStringImpl(const Frames & frames, size_t size);
2019-07-03 15:23:46 +00:00
size_t size = 0;
2019-07-24 23:11:00 +00:00
Frames frames{};
2019-07-01 22:11:11 +00:00
};
std::string signalToErrorMessage(int sig, const siginfo_t & info, const ucontext_t & context);
void * getCallerAddress(const ucontext_t & context);