repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
opencode/test-c-skills/src/test-ub-safety.c
Raw/*
* test-ub-safety.c - Tests for C Undefined Behavior Safety patterns
*
* Demonstrates safe patterns for:
* - Type punning via memcpy
* - Integer overflow detection
* - Memory zero patterns
* - Static assertions
* - Sanitizer integration
*
* Compile with sanitizers to catch issues:
* clang -fsanitize=address,undefined -g test-ub-safety.c -o test-ub-safety
*/
#include "base.h"
// Note: log_message is provided by base.c
// ============================================================================
// Static Assertions (compile-time validation)
// ============================================================================
#define StaticAssert(c, id) global U8 static_assert_##id[(c) ? 1 : -1]
/* Verify our basic types have expected sizes */
StaticAssert(sizeof(U8) == 1, u8_is_one_byte);
StaticAssert(sizeof(U32) == 4, u32_is_four_bytes);
StaticAssert(sizeof(S64) == 8, s64_is_eight_bytes);
StaticAssert(sizeof(F32) == 4, f32_is_four_bytes);
StaticAssert(sizeof(void*) == 8, pointer_is_64_bit);
// ============================================================================
// Safe Type Punning
// ============================================================================
/*
* Float to U32 conversion via memcpy
* This is the safe, portable way to do type punning.
* Compilers optimize this to a register move.
*/
internal U32
float_bits_u32(F32 f)
{
U32 result;
memcpy(&result, &f, sizeof(result));
return result;
}
/*
* U32 to Float conversion via memcpy
*/
internal F32
u32_bits_float(U32 u)
{
F32 result;
memcpy(&result, &u, sizeof(result));
return result;
}
/*
* Union type punning (implementation-defined but widely supported)
* Use this when targeting known compilers.
*/
typedef union
{
F32 f;
U32 u;
} F32Bits;
/*
* Double to U64 conversion via memcpy
*/
internal U64
double_bits_u64(F64 d)
{
U64 result;
memcpy(&result, &d, sizeof(result));
return result;
}
/*
* U64 to Double conversion via memcpy
*/
internal F64
u64_bits_double(U64 u)
{
F64 result;
memcpy(&result, &u, sizeof(result));
return result;
}
typedef union
{
F64 d;
U64 u;
} F64Bits;
// ============================================================================
// Integer Overflow-Safe Functions
// ============================================================================
/*
* Safe 64-bit signed addition with overflow detection
* Returns 1 on success, 0 if overflow would occur
*/
internal B32
safe_add_s64(S64 a, S64 b, S64 *result)
{
/* Check for positive overflow */
if (b > 0 && a > INT64_MAX - b)
{
return 0;
}
/* Check for negative overflow (underflow) */
if (b < 0 && a < INT64_MIN - b)
{
return 0;
}
*result = a + b;
return 1;
}
/*
* Safe 64-bit signed subtraction with overflow detection
* Returns 1 on success, 0 if overflow would occur
*/
internal B32
safe_sub_s64(S64 a, S64 b, S64 *result)
{
/* Check for negative overflow: a - b when b is negative and result < INT64_MIN */
if (b < 0 && a > INT64_MAX + b)
{
return 0;
}
/* Check for positive overflow: a - b when b is positive and result > INT64_MAX */
if (b > 0 && a < INT64_MIN + b)
{
return 0;
}
*result = a - b;
return 1;
}
/*
* Safe 64-bit signed multiplication with overflow detection
* Returns 1 on success, 0 if overflow would occur
*/
internal B32
safe_mul_s64(S64 a, S64 b, S64 *result)
{
if (a > 0)
{
if (b > 0 && a > INT64_MAX / b)
{
return 0;
}
if (b < 0 && b < INT64_MIN / a)
{
return 0;
}
}
else if (a < 0)
{
if (b > 0 && a < INT64_MIN / b)
{
return 0;
}
if (b < 0 && a < INT64_MAX / b)
{
/* Overflow when both are negative and product > INT64_MAX */
return 0;
}
}
/* If a is 0, no overflow possible */
*result = a * b;
return 1;
}
/*
* Safe 32-bit signed addition with overflow detection
*/
internal B32
safe_add_s32(S32 a, S32 b, S32 *result)
{
if (b > 0 && a > INT32_MAX - b)
{
return 0;
}
if (b < 0 && a < INT32_MIN - b)
{
return 0;
}
*result = a + b;
return 1;
}
/*
* Safe 32-bit signed multiplication with overflow detection
*/
internal B32
safe_mul_s32(S32 a, S32 b, S32 *result)
{
if (a > 0)
{
if (b > 0 && a > INT32_MAX / b)
{
return 0;
}
if (b < 0 && b < INT32_MIN / a)
{
return 0;
}
}
else if (a < 0)
{
if (b > 0 && a < INT32_MIN / b)
{
return 0;
}
if (b < 0 && a < INT32_MAX / b)
{
return 0;
}
}
*result = a * b;
return 1;
}
// ============================================================================
// Unsigned Overflow (Defined Behavior - Wraps)
// ============================================================================
/*
* Unsigned addition - defined to wrap
*/
internal U64
wrap_add_u64(U64 a, U64 b)
{
return a + b;
}
/*
* Unsigned multiplication - defined to wrap
*/
internal U64
wrap_mul_u64(U64 a, U64 b)
{
return a * b;
}
// ============================================================================
// Memory Zero Patterns
// ============================================================================
/*
* Structure for testing MemoryZero
*/
typedef struct TestStruct
{
U32 a;
U64 b;
F32 c;
F64 d;
U8 e[16];
} TestStruct;
/*
* Initialize struct using zero-initializer
*/
internal TestStruct
make_test_struct_zero_init(U32 a, U64 b, F32 c, F64 d)
{
TestStruct ts = {0}; /* Zero-initializer */
ts.a = a;
ts.b = b;
ts.c = c;
ts.d = d;
return ts;
}
/*
* Zero an existing struct using MemoryZeroStruct
*/
internal void
reset_test_struct(TestStruct *ts)
{
MemoryZeroStruct(ts);
}
// ============================================================================
// Safe Pointer Arithmetic
// ============================================================================
/*
* Safe array iteration - uses pointer comparison within bounds
*/
internal void
safe_array_sum(U32 *arr, U32 count, U64 *sum)
{
*sum = 0;
U32 *end = arr + count; /* OK: one-past-end is valid */
for (U32 *p = arr; p < end; p++)
{
*sum += *p;
}
}
/*
* Check bounds before pointer arithmetic
*/
internal B32
safe_array_access(U32 *arr, U32 count, U32 index, U32 *value)
{
if (index >= count)
{
return 0; /* Out of bounds */
}
*value = arr[index];
return 1;
}
// ============================================================================
// Sequence Point Safe Patterns
// ============================================================================
/*
* Safe increment - separate statements instead of i++ + i++
*/
internal void
safe_increment_array(U32 *arr, U32 count)
{
for (U32 i = 0; i < count; i++)
{
arr[i] = arr[i] + 1;
}
}
// ============================================================================
// Sanitizer Integration
// ============================================================================
/*
* AddressSanitizer poison/unpoison macros
* When compiled with -fsanitize=address, use real ASAN functions
* Otherwise, use no-op macros for testing pattern only
*/
#if defined(__SANITIZE_ADDRESS__)
#include <sanitizer/asan_interface.h>
#define AsanPoisonMemoryRegion(addr, size) __asan_poison_memory_region((addr), (size))
#define AsanUnpoisonMemoryRegion(addr, size) __asan_unpoison_memory_region((addr), (size))
#else
#define AsanPoisonMemoryRegion(addr, size) ((void)(addr), (void)(size))
#define AsanUnpoisonMemoryRegion(addr, size) ((void)(addr), (void)(size))
#endif
/*
* Example: Poison a region of memory
* When built with -fsanitize=address, ASAN will detect invalid access
*/
internal void
example_asan_poison(U8 *buffer, U64 size)
{
/* Mark buffer as inaccessible */
AsanPoisonMemoryRegion(buffer, size);
/* Later, unpoison when done */
AsanUnpoisonMemoryRegion(buffer, size);
}
// ============================================================================
// Test Functions
// ============================================================================
internal void
test_safe_type_punning(void)
{
LOG_INFO("=== Testing Safe Type Punning ===");
/* Test float -> u32 via memcpy */
F32 f = 1.0f;
U32 bits = float_bits_u32(f);
LOG_INFO("float_bits_u32(1.0f) = 0x%08X", bits);
/* Test u32 -> float via memcpy */
F32 f2 = u32_bits_float(0x3F800000);
LOG_INFO("u32_bits_float(0x3F800000) = %f", (double)f2);
/* Test union type punning */
F32Bits u = { .f = 2.5f };
LOG_INFO("F32Bits union: .f = %f, .u = 0x%08X", (double)u.f, u.u);
/* Test double -> u64 via memcpy */
F64 d = 3.14159265358979;
U64 dbits = double_bits_u64(d);
LOG_INFO("double_bits_u64(pi) = 0x%016lX", (unsigned long)dbits);
/* Verify round-trip */
F64 d2 = u64_bits_double(dbits);
LOG_INFO("Round-trip double: %f -> 0x%016lX -> %f", d, (unsigned long)dbits, d2);
/* Special values */
F32 infinity = 1.0f / 0.0f;
U32 inf_bits = float_bits_u32(infinity);
LOG_INFO("Infinity bits: 0x%08X", inf_bits);
LOG_INFO("Safe type punning tests PASSED\n");
}
internal void
test_safe_add_s64(void)
{
LOG_INFO("=== Testing safe_add_s64 ===");
S64 result;
B32 success;
/* Normal addition */
success = safe_add_s64(10, 20, &result);
LOG_INFO("safe_add_s64(10, 20) = %lld (success=%d)", (long long)result, success);
/* Addition near limits */
success = safe_add_s64(INT64_MAX - 5, 10, &result);
LOG_INFO("safe_add_s64(INT64_MAX-5, 10) = %s (would overflow)", success ? "OK" : "OVERFLOW");
/* Addition that would overflow */
success = safe_add_s64(INT64_MAX - 5, 10, &result);
Assert(!success); /* Should detect overflow */
/* Near minimum */
success = safe_add_s64(INT64_MIN + 5, -10, &result);
LOG_INFO("safe_add_s64(INT64_MIN+5, -10) = %s", success ? "OK" : "OVERFLOW");
/* Negative overflow detection */
success = safe_add_s64(INT64_MIN + 5, -10, &result);
Assert(!success); /* Should detect underflow */
/* Zero cases */
success = safe_add_s64(0, 0, &result);
LOG_INFO("safe_add_s64(0, 0) = %lld (success=%d)", (long long)result, success);
/* Large positive + large negative = OK */
success = safe_add_s64(1000000, -999999, &result);
LOG_INFO("safe_add_s64(1000000, -999999) = %lld (success=%d)", (long long)result, success);
LOG_INFO("safe_add_s64 tests PASSED\n");
}
internal void
test_safe_mul_s64(void)
{
LOG_INFO("=== Testing safe_mul_s64 ===");
S64 result;
B32 success;
/* Normal multiplication */
success = safe_mul_s64(3, 7, &result);
LOG_INFO("safe_mul_s64(3, 7) = %lld (success=%d)", (long long)result, success);
/* Multiplication that would overflow */
success = safe_mul_s64(INT64_MAX, 2, &result);
LOG_INFO("safe_mul_s64(INT64_MAX, 2) = %s", success ? "OK" : "OVERFLOW");
Assert(!success);
/* Large numbers */
success = safe_mul_s64(1000000, 1000000, &result);
LOG_INFO("safe_mul_s64(1000000, 1000000) = %lld (success=%d)", (long long)result, success);
/* Negative * positive overflow */
success = safe_mul_s64(-(INT64_MAX / 2), 3, &result);
LOG_INFO("safe_mul_s64(-(INT64_MAX/2), 3) = %s", success ? "OK" : "OVERFLOW");
Assert(!success);
/* Negative * negative overflow */
success = safe_mul_s64(-(INT64_MAX / 2), -3, &result);
LOG_INFO("safe_mul_s64(-(INT64_MAX/2), -3) = %s", success ? "OK" : "OVERFLOW");
Assert(!success);
/* Zero multiplication (always safe) */
success = safe_mul_s64(0, INT64_MAX, &result);
LOG_INFO("safe_mul_s64(0, INT64_MAX) = %lld (success=%d)", (long long)result, success);
Assert(success);
Assert(result == 0);
/* One multiplication (always safe) */
success = safe_mul_s64(1, INT64_MIN, &result);
LOG_INFO("safe_mul_s64(1, INT64_MIN) = %lld (success=%d)", (long long)result, success);
Assert(success);
Assert(result == INT64_MIN);
LOG_INFO("safe_mul_s64 tests PASSED\n");
}
internal void
test_memory_zero_patterns(void)
{
LOG_INFO("=== Testing Memory Zero Patterns ===");
/* Test zero-initializer */
TestStruct ts1 = {0};
LOG_INFO("Zero-initialized struct: a=%u, b=%llu", ts1.a, (unsigned long long)ts1.b);
/* Test make_test_struct_zero_init */
TestStruct ts2 = make_test_struct_zero_init(42, 100, 3.14f, 2.718);
LOG_INFO("make_test_struct_zero_init: a=%u, b=%llu, c=%f, d=%f",
ts2.a, (unsigned long long)ts2.b, (double)ts2.c, ts2.d);
/* Test MemoryZeroStruct - zero out then set values */
TestStruct ts3;
MemoryZeroStruct(&ts3);
ts3.a = 99;
ts3.b = 888;
LOG_INFO("After MemoryZeroStruct + set: a=%u, b=%llu", ts3.a, (unsigned long long)ts3.b);
/* Test reset_test_struct */
reset_test_struct(&ts3);
LOG_INFO("After reset_test_struct: a=%u, b=%llu (should be 0)", ts3.a, (unsigned long long)ts3.b);
Assert(ts3.a == 0);
Assert(ts3.b == 0);
/* Test MemoryZero on array */
U8 buffer[64];
MemoryZero(buffer, sizeof(buffer));
/* Verify all bytes are zero */
B32 all_zero = 1;
for (U32 i = 0; i < 64; i++)
{
if (buffer[i] != 0)
{
all_zero = 0;
break;
}
}
Assert(all_zero);
LOG_INFO("MemoryZero on buffer: all zeros = %d", all_zero);
LOG_INFO("Memory zero patterns tests PASSED\n");
}
internal void
test_static_assert(void)
{
LOG_INFO("=== Testing Static Assertions ===");
/* These already compiled, so static asserts passed */
LOG_INFO("StaticAssert(sizeof(U8) == 1): PASSED");
LOG_INFO("StaticAssert(sizeof(U32) == 4): PASSED");
LOG_INFO("StaticAssert(sizeof(S64) == 8): PASSED");
LOG_INFO("StaticAssert(sizeof(F32) == 4): PASSED");
LOG_INFO("StaticAssert(sizeof(void*) == 8): PASSED");
/* Additional compile-time checks could be added */
LOG_INFO("Static assert tests PASSED (compiled successfully)\n");
}
internal void
test_sanitizer_info(void)
{
LOG_INFO("=== Sanitizer Information ===");
LOG_INFO("To catch UB issues, compile with sanitizers:");
LOG_INFO(" clang -fsanitize=address,undefined -g test-ub-safety.c -o test-ub-safety");
LOG_INFO("");
LOG_INFO("Sanitizers detect:");
LOG_INFO(" - AddressSanitizer (ASAN): buffer overflow, use-after-free, double-free");
LOG_INFO(" - UndefinedBehaviorSanitizer (UBSAN): signed overflow, null deref, misaligned");
LOG_INFO(" - MemorySanitizer (MSAN): uninitialized reads");
LOG_INFO("");
/* Show ASAN is not enabled (this is just informational) */
#if defined(ASAN_ENABLED)
LOG_INFO("ASAN is ENABLED in this build");
#else
LOG_INFO("ASAN is NOT enabled (this is a safe test build)");
#endif
LOG_INFO("Sanitizer info tests PASSED\n");
}
internal void
test_safe_pointer_arithmetic(void)
{
LOG_INFO("=== Testing Safe Pointer Arithmetic ===");
U32 arr[] = {1, 2, 3, 4, 5};
U32 count = ArrayCount(arr);
/* Safe array sum using one-past-end pointer */
U64 sum;
safe_array_sum(arr, count, &sum);
LOG_INFO("safe_array_sum({1,2,3,4,5}) = %llu", (unsigned long long)sum);
Assert(sum == 15);
/* Safe array access with bounds check */
U32 value;
B32 ok;
ok = safe_array_access(arr, count, 2, &value);
LOG_INFO("safe_array_access(arr, 5, 2) = %u (ok=%d)", value, ok);
Assert(ok && value == 3);
ok = safe_array_access(arr, count, 5, &value);
LOG_INFO("safe_array_access(arr, 5, 5) = out-of-bounds (ok=%d)", ok);
Assert(!ok);
ok = safe_array_access(arr, count, 100, &value);
LOG_INFO("safe_array_access(arr, 5, 100) = out-of-bounds (ok=%d)", ok);
Assert(!ok);
LOG_INFO("Safe pointer arithmetic tests PASSED\n");
}
internal void
test_sequence_point_safety(void)
{
LOG_INFO("=== Testing Sequence Point Safety ===");
/* Safe increment pattern */
U32 arr[] = {1, 2, 3, 4, 5};
safe_increment_array(arr, ArrayCount(arr));
LOG_INFO("After safe_increment_array: {%u, %u, %u, %u, %u}",
arr[0], arr[1], arr[2], arr[3], arr[4]);
Assert(arr[0] == 2);
Assert(arr[4] == 6);
/* Demonstrate what NOT to do (commented out - would be UB): */
/* int a = i++ + i++; // WRONG: unsequenced modifications */
/* arr[i] = i++; // WRONG: modification and read unsequenced */
LOG_INFO("Sequence point safety tests PASSED\n");
}
// ============================================================================
// Main
// ============================================================================
int
main(int argc, char **argv)
{
(void)argc;
(void)argv;
LOG_INFO("=================================================");
LOG_INFO("C Undefined Behavior Safety Test Suite");
LOG_INFO("=================================================\n");
test_safe_type_punning();
test_safe_add_s64();
test_safe_mul_s64();
test_memory_zero_patterns();
test_static_assert();
test_safe_pointer_arithmetic();
test_sequence_point_safety();
test_sanitizer_info();
LOG_INFO("=================================================");
LOG_INFO("ALL TESTS PASSED");
LOG_INFO("=================================================");
return 0;
}