wireshark/wsutil/safe-math.h
John Thacker 9883652f96 ftypes: Use C23 compatible checked arithmetic
Add a header-only library for C23 checked integer arithmetic from
https://github.com/jart/jtckdint

Use it in the ftypes handling instead of the implementations in
safe-math. Note that the return value is opposite (true means
overflow occurred).

C23 stdckdint.h (and jtckdint.h) do not include implementations
for div, mod, and unary negation, where division by zero and,
for signed integers, cases like INT_MIN / -1 which overflow from
INT_MAX + 1 for 2's complement. Those cases have to be handled
separately. Note that the divide by zero case, unlike the others,
can't really have a "this is what the answer is if you just want
the result to wrap around," though that doesn't matter for the
ftypes/dfilter.

Ping #20144
2025-05-01 20:09:59 -04:00

23 lines
719 B
C

/* Overflow-safe math helper macros
*
* To the extent possible under law, the authors have waived all
* copyright and related or neighboring rights to this code. For
* details, see the Creative Commons Zero 1.0 Universal license at
* https://creativecommons.org/publicdomain/zero/1.0/
*/
#pragma once
#include <setjmp.h>
#define ws_safe_op_jmp(op, res, a, b, env) \
do { \
if(ckd_##op(res, a, b)) { \
longjmp(env, 1); \
} \
} while (0)
#define ws_safe_add_jmp(res, a, b, env) ws_safe_op_jmp(add, res, a, b, env)
#define ws_safe_sub_jmp(res, a, b, env) ws_safe_op_jmp(sub, res, a, b, env)
#define ws_safe_mul_jmp(res, a, b, env) ws_safe_op_jmp(mul, res, a, b, env)