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
|
// unw.h --- stack unwinding -*- C -*-
//
// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
//
// SPDX-License-Identifier: MIT
//
// This file is part of COSMOS Codebase.
//
// Commentary:
//
// TODO(cmmm): keep track of DBG_LOC and or backtrace conditionally.
// This could be used for tracing unwinds.
//
// TODO(cmmm): save a msg, explaining why the specific unw happened,
// only in debug builds
//
// Code:
#ifndef INCLUDED_COSMOS_UNW_H
#define INCLUDED_COSMOS_UNW_H
#include <setjmp.h>
#include "macros.h"
#include "types.h"
#include "dbg.h"
struct unw_frame {
struct unw_frame *next;
jmp_buf jmp;
};
struct unw_reason {
const char *sym;
const char *msg;
};
#define UNW_DECLARE_REASON(sym) \
extern const struct unw_reason UNW_REASON_ ## sym
#define UNW_DEFINE_REASON(SYM, MSG) \
const struct unw_reason UNW_REASON_ ## SYM = { .sym = #SYM, .msg = (MSG) }
#define UNW_BEG() do { \
struct unw_frame _unw_frame; \
_unw_code = _unw_push_frame (&_unw_frame); \
if (unw_code == 0)
#define UNW_MATCH(sym) \
else if (_unw_reason == &UNW_REASON_ ## sym && !(_unw_reason = NULL))
#define UNW_MATCH_ANY() else if (_unw_reason && !(_unw_reason = NULL))
#define UNW_ALWAYS() // Execution continues here unconditionally
#define UNW_END() \
if (_unw_reason) \
_unw (_unw_reason, _unw_code); \
} while (0)
#define UNW(sym, code, why) _unw (&UNW_REASON_ ## sym, code)
// Expose as R-values, so that user can't modify them.
#define UNW_REASON ((const struct *unw_reason) _unw_reason)
#define UNW_CODE (( int ) _unw_code )
extern THREAD_LOCAL const struct unw_reason *_unw_reason;
extern THREAD_LOCAL int _unw_code;
extern THREAD_LOCAL struct unw_frame *_unw_top;
static inline int
unw_push_frame (struct unw_frame *frame)
{
frame->next = _unw_top;
_unw_top = frame;
return setjmp (frame->jmp);
}
static inline void
unw_pop_frame (struct unw_frame *frame)
{
DBG_ASSERT_EQ (frame, _unw_top, "%p", "%p");
_unw_top = frame->next;
}
void _unw (const struct unw_reason *, int code) NO_RETURN;
UNW_DECLARE_REASON (INVAL); // Don't overuse!
#endif // INCLUDED_COSMOS_UNW_H
// unw.h ends here
|