From 908b70ab00fb03ea62d1c74b0dc07bc9c8df8cc0 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Fri, 6 Nov 2026 05:49:23 +0300 Subject: feat(unw): add stack unwinding --- include/unw.h | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 include/unw.h (limited to 'include/unw.h') diff --git a/include/unw.h b/include/unw.h new file mode 100644 index 0000000..21564d7 --- /dev/null +++ b/include/unw.h @@ -0,0 +1,89 @@ +// unw.h --- stack unwinding -*- C -*- +// +// Copyright (c) 2026 Martin Michalec +// +// 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 +#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 -- cgit v1.3.1