Skip to content

Commit b1c8bfc

Browse files
committed
Add Error class
1 parent 6a4742b commit b1c8bfc

3 files changed

Lines changed: 579 additions & 0 deletions

File tree

‎include/silk/util/error.h‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
#pragma once
2+
3+
#include <cstdint>
4+
#include <string>
5+
#include <string_view>
6+
#include <utility>
7+
#include <vector>
8+
9+
namespace silk
10+
{
11+
12+
/**
13+
* Rich error description that travels alongside an errno-style code returned by a function.
14+
* An Error is a stack of frames: the top frame is the most recent, the bottom is the innermost
15+
* failure that started the chain. All frame storage (headers + message bytes) lives in a single
16+
* arena owned by the Error.
17+
*
18+
* Errors are normally produced through the RETURN_ERROR / CHECK_ERROR / CHECK_BOOL macros,
19+
* which push a frame and capture the call-site file and line. Functions take an Error * error
20+
* out-parameter and the caller declares the Error on its own stack:
21+
*
22+
* Error error;
23+
* int r = doWork(&error);
24+
* if (r) {
25+
* logger->log(error.format());
26+
* }
27+
*
28+
* Callers must hand in a clean Error. The macros only push: any pre-existing frames remain
29+
* underneath the new top frame. Use clear between independent uses of the same Error
30+
* (e.g., a loop dispatching independent operations).
31+
*
32+
* To walk the stack, follow the chain from top via next:
33+
*
34+
* for (const Error::Frame * frame = error.top(); frame; frame = error.next(frame)) {
35+
* use(frame->code, frame->file, frame->line, frame->message());
36+
* }
37+
*
38+
* Frame pointers stay valid until the next push/clear/move/destroy on the owning Error.
39+
*/
40+
class Error
41+
{
42+
public:
43+
/**
44+
* One frame stored in the arena. The message bytes follow inline immediately after the header
45+
* and are always NUL-terminated (the byte one past the last message byte is '\0'), so callers
46+
* may pass message().data() to C APIs expecting a NUL-terminated string.
47+
*/
48+
struct Frame
49+
{
50+
uint32_t nextOffset; // arena offset of the next-deeper frame, or SENTINEL at the bottom
51+
uint32_t msgLen;
52+
const char * file;
53+
int code;
54+
int line;
55+
56+
/** Inline message bytes following this header (NUL-terminated; the NUL is not counted). */
57+
std::string_view message() const noexcept { return std::string_view(reinterpret_cast<const char *>(this + 1), msgLen); }
58+
};
59+
static_assert(sizeof(Frame) == 24);
60+
61+
/** Maximum length of a single frame's message in bytes; longer messages are truncated. */
62+
static constexpr size_t MAX_MESSAGE_LEN = 512;
63+
64+
/** Construct an empty Error with no frames; no heap allocation until the first push. */
65+
Error() noexcept = default;
66+
67+
// non-copyable
68+
Error(const Error &) = delete;
69+
Error & operator=(const Error &) = delete;
70+
71+
// moveable; source is left empty (no frames, freshly default-constructed state)
72+
Error(Error && other) noexcept
73+
: arena(std::move(other.arena))
74+
, topOffset(std::exchange(other.topOffset, SENTINEL))
75+
{
76+
}
77+
Error & operator=(Error && other) noexcept
78+
{
79+
arena = std::move(other.arena);
80+
topOffset = std::exchange(other.topOffset, SENTINEL);
81+
return *this;
82+
}
83+
84+
/** True if no frames have been pushed yet. */
85+
bool empty() const noexcept { return topOffset == SENTINEL; }
86+
87+
/** errno-style code of the top frame; 0 if empty. */
88+
int code() const noexcept { return topOffset == SENTINEL ? 0 : frameAt(topOffset)->code; }
89+
90+
/** Pointer to the top of the stack (most recent frame); nullptr if empty. */
91+
const Frame * top() const noexcept { return topOffset == SENTINEL ? nullptr : frameAt(topOffset); }
92+
93+
/** Pointer to the next-deeper frame; nullptr if frame is the innermost. */
94+
const Frame * next(const Frame * frame) const noexcept { return frame->nextOffset == SENTINEL ? nullptr : frameAt(frame->nextOffset); }
95+
96+
/** Push one frame on top of the existing stack with a plain message. Returns code. */
97+
int push(int code, const char * file, int line, std::string_view message) noexcept;
98+
99+
/** printf-style variant of push: vsnprintf's format + varargs into the frame's message. */
100+
int pushf(int code, const char * file, int line, const char * format, ...) noexcept __attribute__((format(printf, 5, 6)));
101+
102+
/**
103+
* Render the stack as one human-readable string. The top frame prints first; deeper frames are
104+
* prefixed with "caused by: ". Each frame is <file>:<line>: <message> (errno=<code>[:
105+
* <description>]). Best-effort: returns whatever was built so far if allocation fails partway.
106+
*/
107+
std::string format() const noexcept;
108+
109+
/** Discard all frames. */
110+
void clear() noexcept
111+
{
112+
arena.clear();
113+
topOffset = SENTINEL;
114+
}
115+
116+
private:
117+
/** Marker stored in topOffset / Frame::nextOffset to indicate "no frame". */
118+
static constexpr uint32_t SENTINEL = UINT32_MAX;
119+
120+
/** Reserve space for a new top frame; returns a pointer to the message slot, or nullptr on OOM. */
121+
char * reserve(int code, const char * file, int line, size_t msgLen) noexcept;
122+
123+
/** Interpret arena bytes at offset as a Frame. */
124+
const Frame * frameAt(uint32_t offset) const noexcept { return reinterpret_cast<const Frame *>(arena.data() + offset); }
125+
126+
//
127+
// State.
128+
//
129+
130+
std::vector<uint8_t> arena;
131+
uint32_t topOffset = SENTINEL;
132+
};
133+
134+
} // namespace silk
135+
136+
/**
137+
* Unconditional return-and-push: push a fresh frame on top of *error and return code. Captures
138+
* the call-site file and line. Use when an error condition is detected directly (not propagated
139+
* from a callee returning a code):
140+
*
141+
* if (input == nullptr) {
142+
* RETURN_ERROR(EINVAL, error, "null input: idx=%d", idx);
143+
* }
144+
*/
145+
#define RETURN_ERROR(code, error, msg, ...) return (error)->push##__VA_OPT__(f)((code), __FILE__, __LINE__, msg __VA_OPT__(, ) __VA_ARGS__)
146+
147+
/**
148+
* Failure propagation: if r is non-zero, push a new frame on top of *error and return r.
149+
* Works uniformly for callees that populate *error (the existing stack is preserved underneath)
150+
* and for callees that do not (the frame becomes the leaf). Callers must hand in a clean Error;
151+
* see the class doc.
152+
*
153+
* int r = volume->allocateLsn(&lsn);
154+
* CHECK_ERROR(r, error, "could not allocate LSN");
155+
*
156+
* int r = store->getRowBlockReference(rbn, time, rowFunctions, &reference, error);
157+
* CHECK_ERROR(r, error, "could not get row-block reference: pgId=%u", rbn.pgId);
158+
*/
159+
#define CHECK_ERROR(code, error, msg, ...) \
160+
do \
161+
{ \
162+
if ((code) != 0) [[unlikely]] \
163+
{ \
164+
return (error)->push##__VA_OPT__(f)((code), __FILE__, __LINE__, msg __VA_OPT__(, ) __VA_ARGS__); \
165+
} \
166+
} while (0)
167+
168+
/**
169+
* Boolean failure: if cond is false, push a fresh frame on top of *error and return code.
170+
*
171+
* NEVER embed a function call as cond -- capture into a bool b temp first:
172+
* bool b = record.addRow(&context, recordRow);
173+
* CHECK_BOOL(b, ENOSPC, error, "could not append row");
174+
*/
175+
#define CHECK_BOOL(cond, code, error, msg, ...) \
176+
do \
177+
{ \
178+
if (!(cond)) [[unlikely]] \
179+
{ \
180+
return (error)->push##__VA_OPT__(f)((code), __FILE__, __LINE__, msg __VA_OPT__(, ) __VA_ARGS__); \
181+
} \
182+
} while (0)

‎src/util/error.cpp‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
#include <silk/util/error.h>
2+
3+
#include <silk/util/platform.h>
4+
5+
#include <algorithm>
6+
#include <cstdarg>
7+
#include <cstdio>
8+
#include <cstring>
9+
#include <memory>
10+
#include <string>
11+
#include <string_view>
12+
13+
namespace silk
14+
{
15+
16+
// std::vector<uint8_t>::data comes from ::operator new, which on hosted implementations is
17+
// aligned to __STDCPP_DEFAULT_NEW_ALIGNMENT__. We need that to be at least alignof(Frame) so that
18+
// Frames placed at offset 0 are aligned; record-padding inside reserve keeps subsequent
19+
// Frames aligned as well.
20+
static_assert(__STDCPP_DEFAULT_NEW_ALIGNMENT__ >= alignof(Error::Frame), "arena base must satisfy Frame alignment");
21+
22+
char * Error::reserve(int code, const char * file, int line, size_t msgLen) noexcept
23+
{
24+
// Record size is the Frame header + message + 1 byte reserved for vsnprintf's NUL terminator
25+
// (unused on plain-message paths). Pad to 8 bytes so consecutive Frames stay 8-aligned.
26+
size_t recordSize = sizeof(Frame) + msgLen + 1;
27+
size_t alignedRecordSize = alignUp<size_t>(recordSize, 8);
28+
29+
size_t newOffset = arena.size();
30+
if (newOffset >= SENTINEL)
31+
{
32+
return nullptr;
33+
}
34+
35+
try
36+
{
37+
arena.resize(newOffset + alignedRecordSize);
38+
}
39+
catch (...)
40+
{
41+
return nullptr;
42+
}
43+
44+
Frame * frame = std::construct_at(
45+
reinterpret_cast<Frame *>(arena.data() + newOffset), Frame{topOffset, static_cast<uint32_t>(msgLen), file, code, line});
46+
47+
topOffset = static_cast<uint32_t>(newOffset);
48+
return reinterpret_cast<char *>(frame + 1);
49+
}
50+
51+
int Error::push(int code, const char * file, int line, std::string_view message) noexcept
52+
{
53+
size_t msgLen = std::min(message.size(), MAX_MESSAGE_LEN);
54+
55+
char * dest = reserve(code, file, line, msgLen);
56+
if (dest)
57+
{
58+
std::memcpy(dest, message.data(), msgLen);
59+
dest[msgLen] = '\0';
60+
}
61+
return code;
62+
}
63+
64+
int Error::pushf(int code, const char * file, int line, const char * format, ...) noexcept
65+
{
66+
char buffer[MAX_MESSAGE_LEN + 1];
67+
68+
std::va_list args;
69+
va_start(args, format);
70+
int written = std::vsnprintf(buffer, sizeof(buffer), format, args);
71+
va_end(args);
72+
73+
if (written < 0)
74+
{
75+
written = 0;
76+
}
77+
78+
return push(code, file, line, std::string_view(buffer, static_cast<size_t>(written)));
79+
}
80+
81+
std::string Error::format() const noexcept
82+
{
83+
std::string result;
84+
try
85+
{
86+
bool first = true;
87+
for (const Frame * frame = top(); frame; frame = next(frame))
88+
{
89+
if (!first)
90+
{
91+
result += "\n caused by: ";
92+
}
93+
first = false;
94+
95+
if (frame->file)
96+
{
97+
result += frame->file;
98+
result += ':';
99+
result += std::to_string(frame->line);
100+
result += ": ";
101+
}
102+
103+
std::string_view message = frame->message();
104+
result.append(message.data(), message.size());
105+
106+
result += " (errno=";
107+
result += std::to_string(frame->code);
108+
const char * description = strerrordesc_np(frame->code);
109+
if (description)
110+
{
111+
result += ": ";
112+
result += description;
113+
}
114+
result += ')';
115+
}
116+
}
117+
catch (...)
118+
{
119+
}
120+
return result;
121+
}
122+
123+
} // namespace silk

0 commit comments

Comments
 (0)