Skip to content

LOG_ERROR

Description

Writes an error-level log message. Format string + args follow the StrAppendFmt placeholder vocabulary; the line lands on fd 2.

…[in] : Format string and arguments.

Success

Message formatted via a stack-local HeapAllocator and written to the diagnostic channel.

Failure

Formatter / FileWrite errors are dropped silently; the caller continues regardless (LOG_ERROR is best-effort).

Usage example (Cross-references)

Usage examples (Cross-references)
        HANDLE h = CreateFileA(path, access, FILE_SHARE_READ, NULL, disposition, FILE_ATTRIBUTE_NORMAL, NULL);
        if (h == INVALID_HANDLE_VALUE) {
            LOG_ERROR("FileOpen: CreateFileA(\"{}\") failed (err {})", path, (u32)GetLastError());
            return f;
        }
        int flags;
        if (!parse_open_mode(mode, &flags)) {
            LOG_ERROR("FileOpen: invalid mode \"{}\"", mode);
            return f;
        }
            // 256-byte slot. Until that pipeline learns a default-allocator
            // fall-through, surface the errno number directly here.
            LOG_ERROR("FileOpen: open(\"{}\") failed (errno {})", path, ErrnoOf(fd));
            return f;
        }
            // caller-supplied, libc-independent), so "LOG_SYS_ERROR" would
            // be misleading. Plain error log.
            LOG_ERROR("allocator allocate failed");
            return NULL;
        }
    
                default :
                    LOG_ERROR("Invalid format specifier");
                    return false;
            }
    
        if (pos < len) {
            LOG_ERROR(
                "Parsing format specifier ended, but more characters are left for parsing. Indicates invalid format "
                "specifier."
                }
                if (brace_end >= fmt_len) {
                    LOG_ERROR("Unclosed format specifier");
                    return false;
                }
    
                if (arg_idx >= argc) {
                    LOG_ERROR("Not enough arguments for format string");
                    return false;
                }
                        var_width = 8;
                    } else {
                        LOG_ERROR(
                            "Raw data writing can only be used for u8-64, i8-64, f32, f64. Either unsupported format or "
                            "attempt to write a complex type."
    
                    if (fmt_info.width > var_width) {
                        LOG_ERROR(
                            "Number of raw bytes to be written exceeds variable width. Excess data filled with zeroes."
                        );
                        }
                        default : {
                            LOG_ERROR("Unreachable code reached");
                            return false;
                        }
                        }
                        default : {
                            LOG_ERROR("Unreachable code reached");
                            return false;
                        }
                    continue;
                }
                LOG_ERROR("Unmatched closing brace");
                return false;
            } else {
    
        if (arg_idx < argc) {
            LOG_ERROR("Too many arguments for format string");
            return false;
        }
        if (ok) {
            if (offset > StrLen(o) || StrLen(&tmp) > StrLen(o) - offset) {
                LOG_ERROR(
                    "StrPatchFmt: write of {} bytes at offset {} exceeds str length {}",
                    StrLen(&tmp),
    
        if (ok && StrLen(&out) > 0 && FileWrite(stream, StrBegin(&out), StrLen(&out)) != (i64)StrLen(&out)) {
            LOG_ERROR("Failed to write formatted output");
            ok = false;
        }
    
        if (ok && !FileFlush(stream)) {
            LOG_ERROR("Failed to flush formatted output");
            ok = false;
        }
            if (rem_p >= 2 && p[0] == '{' && p[1] == '{') {
                if (!in || *in != '{') {
                    LOG_ERROR("Expected '{' in input");
                    return NULL;
                }
            } else if (rem_p >= 2 && p[0] == '}' && p[1] == '}') {
                if (!in || *in != '}') {
                    LOG_ERROR("Expected '}' in input");
                    return NULL;
                }
    
                if (rem_p == 0 || *p != '}') {
                    LOG_ERROR("Unmatched '{' in format string");
                    return NULL;
                }
                // longer than that is malformed by construction.
                if (spec_len >= 32) {
                    LOG_ERROR("Format specifier too long");
                    return NULL;
                }
    
                if (arg_index >= argc) {
                    LOG_ERROR("More placeholders than arguments");
                    return NULL;
                }
                }
                if (!spec_ok) {
                    LOG_ERROR("Failed to parse format specifier");
                    return NULL;
                }
                TypeSpecificIO *io = &argv[arg_index++];
                if (!io->reader) {
                    LOG_ERROR("Missing reader function");
                    return NULL;
                }
                        }
                        default : {
                            LOG_ERROR("Invalid raw data read width specified. Must be one of 1, 2, 4 or 8.");
                            return NULL;
                        }
                        var_width = 8;
                    } else {
                        LOG_ERROR(
                            "Raw data reading can only be used for u8-64, i8-64, f32, f64. Either unsupported format or "
                            "attempt to read a complex type."
                        }
                        default : {
                            LOG_ERROR("Invalid raw data read width specified. Must be one of 1, 2, 4 or 8.");
                            return NULL;
                        }
    
                if (!next || next == in) {
                    LOG_ERROR("Failed to read value for placeholder {}", LVAL(arg_index - 1));
                    return NULL;
                }
            } else {
                if (!in || *in != *p) {
                    LOG_ERROR(
                        "Input '{.8}' does not match format string '{.8}'",
                        LVAL(in ? in : "(null)"),
        if (ok) {
            if (offset > BufLength(out) || StrLen(&tmp) > BufLength(out) - offset) {
                LOG_ERROR(
                    "BufPatchFmt: write of {} bytes at offset {} exceeds buf length {}",
                    StrLen(&tmp),
            i64 end_pos = FileSeek(file, 0, FILE_SEEK_END);
            if (end_pos < 0) {
                LOG_ERROR("FileSeek(END) failed during f_read_fmt");
                StrDeinit(&buffer);
                DefaultAllocatorDeinit(&scratch);
                i64 got = FileRead(file, StrBegin(&buffer), (u64)file_len);
                if (got < 0) {
                    LOG_ERROR("FileRead failed during f_read_fmt");
                    StrDeinit(&buffer);
                    DefaultAllocatorDeinit(&scratch);
                Zstr new_pos = str_read_fmt(StrBegin(&buffer), fmtstr, argv, argc);
                if (!new_pos) {
                    LOG_ERROR("Parse failed, rolling back...");
                    (void)FileSeek(file, cur_pos, FILE_SEEK_SET);
                } else {
        Zstr s = *str;
        if (*s != '\\') {
            LOG_ERROR("ZstrProcessEscape called on non-escape sequence");
            return 0;
        }
                // than letting `hex_byte` peek past the NUL terminator.
                if (s[0] == '\0' || s[1] == '\0') {
                    LOG_ERROR("Invalid hex escape sequence");
                    return 0;
                }
                i32 hex_val = hex_byte(s[0], s[1]);
                if (hex_val < 0) {
                    LOG_ERROR("Invalid hex escape sequence");
                    return 0;
                }
            }
            default :
                LOG_ERROR("Invalid escape sequence '\\{c}'", s[0]);
                return 0;
        }
    
        if (!*i || !r) {
            LOG_ERROR("Empty input string");
            return i;
        }
    
        if (quote) {
            LOG_ERROR("Unterminated quoted string");
            StrDeinit(s);
            return NULL;
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Failed to parse f64: empty input");
            DefaultAllocatorDeinit(&scratch);
            return StrIterDataAt(&si, StrIterIndex(&si));
    
        if (!is_valid_numeric_string(&temp, true)) {
            LOG_ERROR("Invalid floating point format");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
    
        if (!StrToF64(&temp, v, NULL)) {
            LOG_ERROR("Failed to parse f64");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Failed to parse u8: empty input");
            DefaultAllocatorDeinit(&scratch);
            return StrIterDataAt(&si, StrIterIndex(&si));
            (StrBegin(&temp)[1] == 'x' || StrBegin(&temp)[1] == 'X' || StrBegin(&temp)[1] == 'b' ||
             StrBegin(&temp)[1] == 'B' || StrBegin(&temp)[1] == 'o' || StrBegin(&temp)[1] == 'O')) {
            LOG_ERROR("Incomplete number format");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
    
        if (!is_valid_numeric_string(&temp, false)) {
            LOG_ERROR("Invalid numeric format");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
        u64 val;
        if (!StrToU64(&temp, &val, NULL)) {
            LOG_ERROR("Failed to parse u8");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
    
        if (val > UINT8_MAX) {
            LOG_ERROR("Value {} exceeds u8 maximum ({})", val, UINT8_MAX);
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
                                                                                                                           \
            if (!StrIterRemainingLength(&si)) {                                                                            \
                LOG_ERROR("Failed to parse " #NAME ": empty input");                                                       \
                DefaultAllocatorDeinit(&scratch);                                                                          \
                return StrIterDataAt(&si, StrIterIndex(&si));                                                              \
                (StrBegin(&temp)[1] == 'x' || StrBegin(&temp)[1] == 'X' || StrBegin(&temp)[1] == 'b' ||                    \
                 StrBegin(&temp)[1] == 'B' || StrBegin(&temp)[1] == 'o' || StrBegin(&temp)[1] == 'O')) {                   \
                LOG_ERROR("Incomplete number format");                                                                     \
                StrDeinit(&temp);                                                                                          \
                DefaultAllocatorDeinit(&scratch);                                                                          \
                                                                                                                           \
            if (!is_valid_numeric_string(&temp, false)) {                                                                  \
                LOG_ERROR("Invalid numeric format");                                                                       \
                StrDeinit(&temp);                                                                                          \
                DefaultAllocatorDeinit(&scratch);                                                                          \
            VAL_T val;                                                                                                     \
            if (!PARSER(&temp, &val, NULL)) {                                                                              \
                LOG_ERROR("Failed to parse " #NAME);                                                                       \
                StrDeinit(&temp);                                                                                          \
                DefaultAllocatorDeinit(&scratch);                                                                          \
    #define _U_BOUND(NAME, UMAX)                                                                                           \
        if (val > UMAX) {                                                                                                  \
            LOG_ERROR("Value {} exceeds " #NAME " maximum ({})", val, UMAX);                                               \
            StrDeinit(&temp);                                                                                              \
            DefaultAllocatorDeinit(&scratch);                                                                              \
    #define _I_BOUND(NAME, IMIN, IMAX)                                                                                     \
        if (val > IMAX || val < IMIN) {                                                                                    \
            LOG_ERROR("Value {} outside " #NAME " range ({} to {})", val, IMIN, IMAX);                                     \
            StrDeinit(&temp);                                                                                              \
            DefaultAllocatorDeinit(&scratch);                                                                              \
        result = (char *)ZstrDupN(StrBegin(&temp), StrLen(&temp), allocator_ptr);
        if (!result) {
            LOG_ERROR("Failed to allocate memory for string");
            StrDeinit(&temp);
            return i;
    
            if (!buffer) {
                LOG_ERROR("Failed to allocate buffer for Int character formatting");
                return false;
            }
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Empty input string");
            return StrIterDataAt(&si, StrIterIndex(&si));
        }
    
            if (StrIterIndex(&si) == StrIterIndex(&hex_saved)) {
                LOG_ERROR("Invalid hex format - no digits after 0x");
                return start;
            }
            StrParseConfig config = {.base = 16};
            if (!StrToU64(&hex_str, &value, &config)) {
                LOG_ERROR("Failed to parse hex value");
                StrDeinit(&hex_str);
                return start;
    
            if (StrIterIndex(&si) == StrIterIndex(&oct_saved)) {
                LOG_ERROR("Invalid octal format - no digits after 0o");
                return start;
            }
            StrParseConfig config = {.base = 8};
            if (!StrToU64(&oct_str, &value, &config)) {
                LOG_ERROR("Failed to parse octal value");
                StrDeinit(&oct_str);
                return start;
    
        if (StrIterIndex(&si) == StrIterIndex(&bin_saved)) {
            LOG_ERROR("Invalid binary format - expected 0s and 1s");
            return start;
        }
    
        if (fmt_info && (fmt_info->flags & FMT_FLAG_CHAR)) {
            LOG_ERROR("Character-format reads are not supported for Int");
            return i;
        }
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Failed to parse Int: empty input");
            return StrIterDataAt(&si, StrIterIndex(&si));
        }
    
        if (radix == 16 && p0 == '0' && (p1 == 'x' || p1 == 'X')) {
            LOG_ERROR("Int hex reads expect plain hex digits without a 0x prefix");
            return start;
        }
        }
        if (radix == 2 && p0 == '0' && (p1 == 'b' || p1 == 'B')) {
            LOG_ERROR("Int binary reads expect plain binary digits without a 0b prefix");
            return start;
        }
        }
        if (radix == 8 && p0 == '0' && (p1 == 'o' || p1 == 'O')) {
            LOG_ERROR("Int octal reads expect plain octal digits without a 0o prefix");
            return start;
        }
    
        if (StrIterIndex(&si) == StrIterIndex(&digits_saved)) {
            LOG_ERROR("Failed to parse Int");
            return start;
        }
        char trailing = 0;
        if (StrIterPeek(&si, &trailing) && trailing == '_') {
            LOG_ERROR("Int reads do not accept digit separators");
            return start;
        }
    
        if (float_fmt_uses_unsupported_flags(fmt_info)) {
            LOG_ERROR("Float only supports decimal and scientific reading");
            StrDeinit(&temp);
            FloatDeinit(&parsed);
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Failed to parse Float: empty input");
            StrDeinit(&temp);
            FloatDeinit(&parsed);
    
        if (token_len == 0) {
            LOG_ERROR("Failed to parse Float");
            StrDeinit(&temp);
            FloatDeinit(&parsed);
    
        if (!StrIterRemainingLength(&si)) {
            LOG_ERROR("Failed to parse f32: empty input");
            DefaultAllocatorDeinit(&scratch);
            return StrIterDataAt(&si, StrIterIndex(&si));
    
        if (!is_valid_numeric_string(&temp, true)) {
            LOG_ERROR("Invalid floating point format");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
        f64 val;
        if (!StrToF64(&temp, &val, NULL)) {
            LOG_ERROR("Failed to parse f32");
            StrDeinit(&temp);
            DefaultAllocatorDeinit(&scratch);
    ArgRun ArgParseRun(ArgParse *self, int argc, char **argv) {
        if (!self || argc < 0 || (argc > 0 && !argv)) {
            LOG_ERROR("ArgParseRun: bad arguments");
            return ARG_RUN_ERROR;
        }
                break;
            default :
                LOG_ERROR("PageProtect: unknown protection bit {}", (u32)prot);
                return false;
        }
        DWORD old_prot = 0;
        if (!VirtualProtect(ptr, (SIZE_T)bytes, win_prot, &old_prot)) {
            LOG_ERROR("PageProtect: VirtualProtect failed (error {})", (u32)GetLastError());
            return false;
        }
                break;
            default :
                LOG_ERROR("PageProtect: unknown protection bit {}", (u32)prot);
                return false;
        }
            else
                AllocatorFree(&self->heap, user_p);
            LOG_ERROR("DebugAllocator: failed to record allocation in live map");
    #if FEATURE_ALLOC_STATS
            self->base.stats.failed_allocations += 1u;
    static void debug_emit_trace(const StackFrame *frames, size count, Zstr label, Allocator *meta) {
        if (!count) {
            LOG_ERROR("    {} trace: (none captured)", label);
            return;
        }
        }
    #endif
        LOG_ERROR("    {} trace:\n{}", label, rendered);
        StrDeinit(&rendered);
    }
            const DebugFreedEntry *fe = debug_freed_find(self, ptr);
            if (fe) {
                LOG_ERROR(
                    "DebugAllocator: DOUBLE FREE of {x} (originally {} bytes); original alloc + first-free traces:",
                    (u64)ptr,
            if (!debug_check_canary(trail, self->config.canary_bytes)) {
                self->overflows += 1;
                LOG_ERROR(
                    "DebugAllocator: BUFFER OVERFLOW past {x} ({} bytes requested)",
                    (u64)ptr,
            size rounded   = (padded + page_size - 1) & ~(page_size - 1);
            if (!PageProtect(ptr, rounded, PAGE_PROT_NONE)) {
                LOG_ERROR("DebugAllocator: PageProtect(PROT_NONE) failed on {x}", (u64)ptr);
            }
        } else {
        // Report leaks for anything still in `live`.
        if (MapAllocator(&self->live) && MapPairCount(&self->live) > 0) {
            LOG_ERROR("DebugAllocator: {} live allocation(s) at deinit time:", (u64)MapPairCount(&self->live));
            MapForeachPairPtr(&self->live, key_ptr, val_ptr) {
                LOG_ERROR("  leaked {x} ({} bytes)", (u64)*key_ptr, (u64)val_ptr->requested_size);
            LOG_ERROR("DebugAllocator: {} live allocation(s) at deinit time:", (u64)MapPairCount(&self->live));
            MapForeachPairPtr(&self->live, key_ptr, val_ptr) {
                LOG_ERROR("  leaked {x} ({} bytes)", (u64)*key_ptr, (u64)val_ptr->requested_size);
                debug_emit_trace(val_ptr->alloc_trace, val_ptr->alloc_trace_n, "alloc", ALLOCATOR_OF(&self->meta));
            }
    
        if (!new_data) {
            LOG_ERROR("Failed to allocate memory for bitvec");
            return false;
        }
                // Not LOG_SYS_ERROR: allocator failures don't flow through the
                // syscall error path; the LOG_ERROR variant is the right report.
                LOG_ERROR("allocator reallocate failed");
                return false;
            }
                // Not LOG_SYS_ERROR: allocator failures don't flow through the
                // syscall error path; the LOG_ERROR variant is the right report.
                LOG_ERROR("allocator reallocate failed");
                return false;
            }
                if (saw_decimal) {
                    if (fractional == INT64_MAX) {
                        LOG_ERROR("Float fractional exponent overflow");
                        goto fail;
                    }
            if (ch == '.') {
                if (saw_decimal) {
                    LOG_ERROR("Invalid Float format");
                    goto fail;
                }
                pos++;
                if (pos >= length) {
                    LOG_ERROR("Invalid Float exponent");
                    goto fail;
                }
                parsed    = ZstrToI64(exp_start, &endptr);
                if (endptr == exp_start) {
                    LOG_ERROR("Invalid Float exponent");
                    goto fail;
                }
                exp_offset = (size)(endptr - text);
                if (exp_offset != length) {
                    LOG_ERROR("Invalid Float exponent");
                    goto fail;
                }
            }
    
            LOG_ERROR("Invalid Float format");
            goto fail;
        }
    
        if (!saw_digit) {
            LOG_ERROR("Invalid Float format");
            goto fail;
        }
    
        if (explicit_exp < INT64_MIN + fractional) {
            LOG_ERROR("Float exponent overflow");
            goto fail;
        }
    
        if (FloatIsZero(b)) {
            LOG_ERROR("Division by zero");
            return false;
        }
    
        if (!is_valid_base(config->base)) {
            LOG_ERROR("Invalid base: {}", config->base);
            return NULL;
        }
    
        if (!is_valid_base(config->base)) {
            LOG_ERROR("Invalid base: {}", config->base);
            return NULL;
        }
    
        if (config->precision > 17) {
            LOG_ERROR("Precision {} exceeds maximum (17)", config->precision);
            return NULL;
        }
        u8 base = config->base;
        if (base != 0 && !is_valid_base(base)) {
            LOG_ERROR("Invalid base: {}", base);
            return false;
        }
    
        if (pos >= str->length) {
            LOG_ERROR("Empty string");
            return false;
        }
                if (IS_SPACE(str->data[pos]))
                    break;
                LOG_ERROR("Invalid digit for base {}: {c}", base, str->data[pos]);
                return false;
            }
            // one more digit without wrapping; anything above is an overflow.
            if (result > (UINT64_MAX - digit) / base) {
                LOG_ERROR("Overflow");
                return false;
            }
    
        if (config->strict && pos < str->length) {
            LOG_ERROR("Extra characters after number");
            return false;
        }
    
        if (!have_digits) {
            LOG_ERROR("No valid digits found");
            return false;
        }
    
        if (pos >= str->length) {
            LOG_ERROR("Empty string");
            return false;
        }
        if (negative) {
            if (unsigned_value > 9223372036854775808ULL) {
                LOG_ERROR("Overflow");
                return false;
            }
        } else {
            if (unsigned_value > 9223372036854775807ULL) {
                LOG_ERROR("Overflow");
                return false;
            }
    
        if (pos >= str->length) {
            LOG_ERROR("Empty string");
            return false;
        }
    
            if (!have_exp_digits) {
                LOG_ERROR("Missing exponent digits");
                return false;
            }
    
        if (config->strict && pos < str->length) {
            LOG_ERROR("Extra characters after number");
            return false;
        }
    
        if (!have_digits) {
            LOG_ERROR("No valid digits found");
            return false;
        }
    static bool int_try_from_i64_with_allocator(Int *out, i64 value, Allocator *alloc) {
        if (value < 0) {
            LOG_ERROR("Int cannot represent negative values");
            return false;
        }
    static bool int_validate_radix(u8 radix) {
        if (radix < 2 || radix > 36) {
            LOG_ERROR("radix must be between 2 and 36");
            return false;
        }
            digit = int_radix_digit(digits[i]);
            if (digit < 0 || digit >= radix) {
                LOG_ERROR("Invalid digit for radix in Int conversion");
                IntDeinit(&result);
                return false;
    
        if (!saw_digit) {
            LOG_ERROR("No valid digits found");
            IntDeinit(&result);
            return false;
    
        if (IntIsZero(value)) {
            LOG_ERROR("log2 undefined for zero");
            return false;
        }
    
        if (!IntFitsU64(value)) {
            LOG_ERROR("Int value exceeds u64 range");
            return false;
        }
    
        if (!IntFitsU64(exponent)) {
            LOG_ERROR("Int exponent exceeds u64 range");
            return false;
        }
        }
        if (IntIsZero(divisor)) {
            LOG_ERROR("Division by zero");
            return false;
        }
    
        if (IntIsZero(divisor)) {
            LOG_ERROR("Division by zero");
            return false;
        }
    
        if (divisor == 0) {
            LOG_ERROR("Division by zero");
            return 0;
        }
    
        if (modulus == 0) {
            LOG_ERROR("modulus is zero");
            return 0;
        }
        }
        if (degree == 0) {
            LOG_ERROR("root degree is zero");
            return false;
        }
    
        if (IntIsZero(n) || IntIsEven(n)) {
            LOG_ERROR("n must be non-zero and odd");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
    
        if (IntIsZero(modulus)) {
            LOG_ERROR("modulus is zero");
            return false;
        }
        const PdbInfo        *pdb_inf = PdbInfoStream(&entry->pdb);
        if (pe_cv->age != pdb_inf->age || MemCompare(pe_cv->guid, pdb_inf->guid, 16) != 0) {
            LOG_ERROR("PdbCache: GUID/age mismatch between PE and PDB for {}", entry->module_path);
            PdbDeinit(&entry->pdb);
            return false;
        InitOnceExecuteOnce(&g_winsock_init_once, winsock_init_cb, NULL, NULL);
        if (g_winsock_init_rc != 0) {
            LOG_ERROR("ensure_winsock: WSAStartup failed: {}", (i32)g_winsock_init_rc);
            return false;
        }
            do {                                                                                                           \
                (void)(ret);                                                                                               \
                LOG_ERROR(msg " (WSAGetLastError={})", (i32)WSAGetLastError());                                            \
            } while (0)
                const struct sockaddr_in *sa = (const struct sockaddr_in *)addr->raw;
                if (!format_ipv4((const u8 *)&sa->sin_addr.s_addr, host_data, 48)) {
                    LOG_ERROR("SocketAddrFormat: format_ipv4 failed");
                    break;
                }
                const u8 *v6 = sa->sin6_addr.s6_addr;
                if (!format_ipv6(v6, host_data, 48)) {
                    LOG_ERROR("SocketAddrFormat: format_ipv6 failed");
                    break;
                }
                StrAppendFmt(&out, "[{}]:{}", (Zstr)host_data, (u32)port);
            } else {
                LOG_ERROR("SocketAddrFormat: unknown family {}", (u32)addr->family);
            }
        }
        i32 proto    = sock_kind_to_protocol(kind);
        if (af == AF_UNSPEC || socktype < 0) {
            LOG_ERROR("ListenerOpen: invalid family/kind combination");
            return false;
        }
        i32 proto    = sock_kind_to_protocol(kind);
        if (af == AF_UNSPEC || socktype < 0) {
            LOG_ERROR("SocketConnect: invalid family/kind combination");
            return false;
        }
            if (!pfds) {
                HeapAllocatorDeinit(&halloc);
                LOG_ERROR("SocketPoll: heap allocation for pollfd array failed");
                return -1;
            }
        if (!CreatePipe(&hStdinRead, &hStdinWrite, &sa, 0) || !CreatePipe(&hStdoutRead, &hStdoutWrite, &sa, 0) ||
            !CreatePipe(&hStderrRead, &hStderrWrite, &sa, 0)) {
            LOG_ERROR("CreatePipe failed (GetLastError={})", (i32)GetLastError());
            if (hStdinRead)
                CloseHandle(hStdinRead);
    
        if (!CreateProcessA(NULL, StrBegin(&cmdline), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
            LOG_ERROR("CreateProcessA() failed (GetLastError={})", (i32)GetLastError());
            StrDeinit(&cmdline);
            CloseHandle(hStdinRead);
            // Win32: WaitForSingleObject uses GetLastError, not errno. Log
            // explicitly; LOG_SYS_ERROR's first arg is unused on Windows.
            LOG_ERROR("Failed to wait for child process (GetLastError={})", (i32)GetLastError());
            return PROC_STATUS_ERROR;
        }
    #else
        if (!TerminateProcess(proc->_pi.hProcess, 1)) {
            LOG_ERROR("TerminateProcess failed (GetLastError={})", (i32)GetLastError());
            return;
        }
        // Wait for it to actually exit
        if (WAIT_FAILED == WaitForSingleObject(proc->_pi.hProcess, INFINITE)) {
            LOG_ERROR("WaitForSingleObject after TerminateProcess failed (GetLastError={})", (i32)GetLastError());
            return;
        }
    
                if (!PeekNamedPipe(rhandle, NULL, 0, NULL, &available, NULL)) {
                    LOG_ERROR("PeekNamedPipe failed (GetLastError={})", (i32)GetLastError());
                    total_read = -1;
                    break;
                DWORD bytes_read = 0;
                if (!ReadFile(rhandle, StrBegin(&tmpbuf), 1023, &bytes_read, NULL)) {
                    LOG_ERROR("ReadFile failed (GetLastError={})", (i32)GetLastError());
                    total_read = -1;
                    break;
            DWORD len = GetModuleFileNameA(NULL, StrBegin(&buffer), MAX_PATH);
            if (len == 0 || len >= MAX_PATH) {
                LOG_ERROR("Failed to get executable path or buffer too small");
                break;
            }
        File f = FileOpen("/proc/self/maps", "rb");
        if (!FileIsOpen(&f)) {
            LOG_ERROR("ProcMapsLoad: FileOpen(/proc/self/maps) failed");
            ProcMapsDeinit(out);
            return false;
            u64 grown_to = StrLen(&out->raw) + CHUNK + 1;
            if (!StrReserve(&out->raw, grown_to)) {
                LOG_ERROR("ProcMapsLoad: failed to grow buffer");
                FileClose(&f);
                ProcMapsDeinit(out);
            i64 n = FileRead(&f, StrEnd(&out->raw), CHUNK);
            if (n < 0) {
                LOG_ERROR("ProcMapsLoad: FileRead failed");
                FileClose(&f);
                ProcMapsDeinit(out);
        FileClose(&f);
        if (StrLen(&out->raw) == 0) {
            LOG_ERROR("ProcMapsLoad: /proc/self/maps was empty");
            ProcMapsDeinit(out);
            return false;
            size path_len = ZstrLen(path);
            if (path_len + 3 > MAX_PATH) {
                LOG_ERROR("dir_get_contents: path too long for MAX_PATH");
                break;
            }
        if (file == INVALID_HANDLE_VALUE) {
            // Win32 sets GetLastError, not errno. Log it explicitly.
            LOG_ERROR("CreateFileA() failed (GetLastError={})", (i32)GetLastError());
            return -1;
        }
        LARGE_INTEGER file_size;
        if (!GetFileSizeEx(file, &file_size)) {
            LOG_ERROR("GetFileSizeEx() failed (GetLastError={})", (i32)GetLastError());
            CloseHandle(file);
            return -1;
    #if PLATFORM_WINDOWS
        if (!DeleteFileA(path)) {
            LOG_ERROR("FileRemove(\"{}\"): DeleteFileA failed (GetLastError={})", path, (i32)GetLastError());
            return 0;
        }
    #if PLATFORM_WINDOWS
        if (!RemoveDirectoryA(path)) {
            LOG_ERROR("DirRemove(\"{}\"): RemoveDirectoryA failed (GetLastError={})", path, (i32)GetLastError());
            return 0;
        }
    #if PLATFORM_WINDOWS
        if (!CreateDirectoryA(path, NULL)) {
            LOG_ERROR("DirCreate(\"{}\"): CreateDirectoryA failed (GetLastError={})", path, (i32)GetLastError());
            return 0;
        }
        }
        if (n >= 4096) {
            LOG_ERROR("DirCreateAll(\"{}\"): path too long ({} bytes)", path, (u64)n);
            return 0;
        }
    
        if (!MachoHasUuid(&e->dsym) || MemCompare(MachoUuid(&e->dsym), MachoUuid(&e->main), 16) != 0) {
            LOG_ERROR("MachoCache: dSYM UUID mismatch for {}", e->module_path);
            MachoDeinit(&e->dsym);
            return false;
        // aligned with one literal.
        if (ZstrLen(hostname) >= 256) {
            LOG_ERROR("DnsResolve: hostname \"{}\" exceeds 255 bytes", hostname);
            return false;
        }
            // 2. Nameserver query path.
            if (VecLen(&self->nameservers) == 0) {
                LOG_ERROR("DnsResolve: no nameservers configured (read /etc/resolv.conf at init)");
                break;
            }
    
            if (!found) {
                LOG_ERROR("DnsResolve: no A/AAAA records found for \"{}\"", hostname);
            }
        }
        }
        if (colon_at >= spec_len) {
            LOG_ERROR("DnsResolve: spec \"{}\" has no \":port\"", spec);
            return false;
        }
        }
        if (colon_at >= 256) {
            LOG_ERROR("DnsResolve: host portion of \"{}\" exceeds 255 bytes", spec);
            return false;
        }
            char c = spec[i];
            if (c < '0' || c > '9') {
                LOG_ERROR("DnsResolve: non-numeric port in \"{}\"", spec);
                return false;
            }
            u32 next = (u32)port * 10u + (u32)(c - '0');
            if (next > 0xFFFFu) {
                LOG_ERROR("DnsResolve: port in \"{}\" out of range", spec);
                return false;
            }
        // A bare "host:" with no digits after the colon is malformed.
        if (colon_at + 1 == spec_len) {
            LOG_ERROR("DnsResolve: empty port in \"{}\"", spec);
            return false;
        }
        StrReadFmt(cursor, "{} {} {}\r\n", method, req->url, version);
        if (cursor == in) {
            LOG_ERROR("http request parse failed: invalid request line");
            StrDeinit(&method);
            StrDeinit(&version);
    
        if (0 != ZstrCompareN(StrBegin(&version), "HTTP/1.1", 8)) {
            LOG_ERROR("invalid/unsupported HTTP version");
            StrDeinit(&method);
            StrDeinit(&version);
        StrDeinit(&method);
        if (req->method == HTTP_REQUEST_METHOD_UNKNOWN) {
            LOG_ERROR("invalid http request method");
            return in;
        }
    
            if (VecLen(&req->headers) >= HTTP_REQUEST_HEADERS_MAX) {
                LOG_ERROR("http request header count exceeds {} cap", HTTP_REQUEST_HEADERS_MAX);
                return in;
            }
            StrReadFmt(cursor, "{}: {}\r\n", hh.key, hh.value);
            if (cursor == line_start) {
                LOG_ERROR("failed to parse header line");
                HttpHeaderDeinit(&hh);
                return in;
            if (!VecPushBackR(&req->headers, hh)) {
                HttpHeaderDeinit(&hh);
                LOG_ERROR("failed to push header");
                return in;
            }
        response->body = StrInit(response->allocator);
        if (FileReadAndClose(filepath, &response->body) < 0) {
            LOG_ERROR("failed to read file: {}", filepath);
            return NULL;
        }
        Zstr response_code = HttpResponseCodeToZstr(response->status_code);
        if (!response_code) {
            LOG_ERROR("HttpResponseSerialize: invalid/unknown response code {}", (u32)response->status_code);
            return out;
        }
        Zstr content_type = HttpContentTypeToZstr(response->content_type);
        if (!content_type) {
            LOG_ERROR("HttpResponseSerialize: invalid/unknown content type {}", (u32)response->content_type);
            return out;
        }
        if (StrLen(&response->body)) {
            if (!StrPushBackMany(&out, StrBegin(&response->body), StrLen(&response->body))) {
                LOG_ERROR("HttpResponseSerialize: failed to append body");
                StrDeinit(&out);
                return StrInit(alloc);
    
        if (StrLen(key) == 0) {
            LOG_ERROR("Expected config key");
            StrClear(key);
            return saved_si;
                    StrIterMustNext(&si);
                    if (!StrIterPeek(&si, &c)) {
                        LOG_ERROR("Unexpected end of quoted config value");
                        StrClear(value);
                        return saved_si;
            }
    
            LOG_ERROR("Missing closing quote in config value");
            StrClear(value);
            return saved_si;
        char c;
        if (!StrIterPeek(&si, &c) || (c != '=' && c != ':')) {
            LOG_ERROR("Expected '=' or ':' after config key");
            StrClear(key);
            StrClear(value);
            si = KvConfigSkipLine(si);
        } else if (c != '\n') {
            LOG_ERROR("Unexpected trailing characters after config value");
            StrClear(key);
            StrClear(value);
        Macho *m = ctx->out;
        if (BufLength(&m->data) < MH_HEADER_64_SIZE) {
            LOG_ERROR("MachO: file too small for header");
            return false;
        }
                reserved
            )) {
            LOG_ERROR("MachO: header truncated");
            return false;
        }
        (void)reserved;
        if (magic == FAT_MAGIC || magic == FAT_CIGAM) {
            LOG_ERROR("MachO: fat/universal binary not supported in v1 -- caller must pick a slice");
            return false;
        }
        }
        if (magic == MH_MAGIC_32 || magic == MH_CIGAM_32) {
            LOG_ERROR("MachO: 32-bit Mach-O not supported in v1");
            return false;
        }
        }
        if (magic == MH_CIGAM_64) {
            LOG_ERROR("MachO: byte-swapped 64-bit Mach-O not supported in v1");
            return false;
        }
        }
        if (magic != MH_MAGIC_64) {
            LOG_ERROR("MachO: bad magic 0x{x}", magic);
            return false;
        }
        u64 cmdsize = IterLength(cmd);
        if (cmdsize < SEG64_CMD_SIZE_MIN) {
            LOG_ERROR("MachO: LC_SEGMENT_64 truncated");
            return false;
        }
                seg.flags
            )) {
            LOG_ERROR("MachO: LC_SEGMENT_64 body truncated");
            return false;
        }
        for (u32 i = 0; i < seg.nsects; ++i) {
            if (IterIndex(cmd) + SECT64_SIZE > IterLength(cmd)) {
                LOG_ERROR("MachO: section table overruns LC_SEGMENT_64");
                return false;
            }
                    reserved3
                )) {
                LOG_ERROR("MachO: section_64 body truncated");
                return false;
            }
    static bool decode_symtab(MachoContext *ctx, BufIter *cmd) {
        if (IterLength(cmd) < SYMTAB_CMD_SIZE) {
            LOG_ERROR("MachO: LC_SYMTAB truncated");
            return false;
        }
        IterMustMove(cmd, 8); // skip cmd + cmdsize prefix
        if (!BufReadFmt(cmd, FMT_MACHO_SYMTAB_BODY_LE, ctx->symoff, ctx->nsyms, ctx->stroff, ctx->strsize)) {
            LOG_ERROR("MachO: LC_SYMTAB body truncated");
            return false;
        }
    static bool decode_uuid(MachoContext *ctx, BufIter *cmd) {
        if (IterLength(cmd) < UUID_CMD_SIZE) {
            LOG_ERROR("MachO: LC_UUID truncated");
            return false;
        }
    static bool walk_load_commands(MachoContext *ctx) {
        if ((u64)MH_HEADER_64_SIZE + ctx->sizeofcmds > BufLength(&ctx->out->data)) {
            LOG_ERROR("MachO: load commands overrun file");
            return false;
        }
            u64 remaining = IterRemainingLength(&walker);
            if (remaining < 8) {
                LOG_ERROR("MachO: load command prefix truncated at {}", i);
                return false;
            }
            u32     cmd, cmdsize;
            if (!BufReadFmt(&prefix, FMT_MACHO_LC_PREFIX_LE, cmd, cmdsize)) {
                LOG_ERROR("MachO: load command prefix truncated at {}", i);
                return false;
            }
            }
            if (cmdsize < 8 || cmdsize > remaining) {
                LOG_ERROR("MachO: bad cmdsize at load command {}", i);
                return false;
            }
        };
        if (ctx->nsyms > MACHO_MAX_SYMBOLS) {
            LOG_ERROR("MachO: nsyms {} exceeds sanity cap; refusing", (u64)ctx->nsyms);
            return false;
        }
        u64 tab_end = (u64)ctx->symoff + (u64)ctx->nsyms * NLIST64_SIZE;
        if (tab_end > BufLength(&ctx->out->data)) {
            LOG_ERROR("MachO: symtab past EOF");
            return false;
        }
        u64 str_end = (u64)ctx->stroff + ctx->strsize;
        if (str_end > BufLength(&ctx->out->data)) {
            LOG_ERROR("MachO: symbol strtab past EOF");
            return false;
        }
            u64 n_value;
            if (!BufReadFmt(&tab, FMT_MACHO_NLIST64_LE, n_strx, n_type, n_sect, n_desc, n_value)) {
                LOG_ERROR("MachO: nlist_64 truncated at index {}", i);
                return false;
            }
        Buf copy = BufInit(alloc);
        if (!VecReserve(&copy, (u64)data_size)) {
            LOG_ERROR("MachoOpenFromMemoryCopy: allocation failed ({} bytes)", (u64)data_size);
            return false;
        }
        if (FileReadAndClose(path, &data) < 0) {
            BufDeinit(&data);
            LOG_ERROR("MachoOpen: failed to read {}", path);
            return false;
        }
        char c;
        if (!StrIterPeek(&si, &c) || c != '{') {
            LOG_ERROR("Invalid object start. Expected '{'.");
            return saved_si;
        }
            if (expect_comma) {
                if (c != ',') {
                    LOG_ERROR(
                        "Expected ',' between key/value pairs in object. Invalid "
                        "JSON object."
            read_si = JReadString(si, &key);
            if (StrIterIndex(&read_si) == StrIterIndex(&si)) {
                LOG_ERROR("Failed to read string key in object. Invalid JSON");
                StrDeinit(&key);
                DefaultAllocatorDeinit(&scratch);
    
            if (!StrIterPeek(&si, &c) || c != ':') {
                LOG_ERROR("Expected ':' after key string. Failed to read JSON");
                StrDeinit(&key);
                DefaultAllocatorDeinit(&scratch);
            // if still no advancement in read position
            if (StrIterIndex(&read_si) == StrIterIndex(&si)) {
                LOG_ERROR("Failed to parse value. Invalid JSON.");
                StrDeinit(&key);
                DefaultAllocatorDeinit(&scratch);
    
        if (!StrIterPeek(&si, &c) || c != '}') {
            LOG_ERROR("Expected end of object '}' but found '{c}'", c);
            DefaultAllocatorDeinit(&scratch);
            return saved_si;
        char c;
        if (!StrIterPeek(&si, &c) || c != '[') {
            LOG_ERROR("Invalid array start. Expected '['.");
            return saved_si;
        }
            if (expect_comma) {
                if (c != ',') {
                    LOG_ERROR("Expected ',' between values in array. Invalid JSON array.");
                    return saved_si;
                }
            // if no advancement in read position
            if (StrIterIndex(&read_si) == StrIterIndex(&si)) {
                LOG_ERROR("Failed to parse value. Invalid JSON.");
                return saved_si;
            }
        // end of array
        if (!StrIterPeek(&si, &c) || c != ']') {
            LOG_ERROR("Invalid end of array. Expected ']'.");
            return saved_si;
        }
                        StrIterMustNext(&si);
                        if (!StrIterPeek(&si, &c)) {
                            LOG_ERROR("Unexpected end of string.");
                            StrClear(str);
                            return saved_si;
                                // process otherwise.
                                if (StrIterRemainingLength(&si) < 5) {
                                    LOG_ERROR("Truncated \\uXXXX escape in JSON string.");
                                    StrClear(str);
                                    return saved_si;
                                    return saved_si;
                                }
                                LOG_ERROR(
                                    "No unicode support '{.6}'. Unicode sequence will be skipped.",
                                    LVAL(StrIterDataAt(&si, StrIterIndex(&si) - 1))
    
                            default :
                                LOG_ERROR("Invalid JSON object key string.");
                                StrClear(str);
                                return saved_si;
                case 'e' :
                    if (has_exp) {
                        LOG_ERROR("Invalid number. Multiple exponent indicators.");
                        StrDeinit(&ns);
                        DefaultAllocatorDeinit(&scratch);
                case '.' :
                    if (is_flt) {
                        LOG_ERROR("Invalid number. Multiple decimal indicators.");
                        StrDeinit(&ns);
                        DefaultAllocatorDeinit(&scratch);
                    // +/- can only appear after an exponent
                    if (!has_exp) {
                        LOG_ERROR(
                            "Invalid number. Exponent sign indicators '+' or '-' "
                            "must appear after exponent 'E' or 'e' indicator."
                    }
                    if (has_exp_plus_minus) {
                        LOG_ERROR(
                            "Invalid number. Multiple '+' or '-' in Number. "
                            "Expected only once after 'e' or 'E'."
    
        if (!StrLen(&ns)) {
            LOG_ERROR("Failed to parse number. '{.8}'", LVAL(StrIterDataAt(&saved_si, StrIterIndex(&saved_si))));
            StrDeinit(&ns);
            DefaultAllocatorDeinit(&scratch);
        }
        if (end == StrBegin(&ns)) {
            LOG_ERROR("Failed to convert string to number.");
            StrDeinit(&ns);
            DefaultAllocatorDeinit(&scratch);
    
        if (StrIterIndex(&si) == StrIterIndex(&saved_si)) {
            LOG_ERROR("Failed to parse integer number.");
            return saved_si;
        }
    
        if (num.is_float) {
            LOG_ERROR("Failed to parse integer. Got floating point value.");
            return saved_si;
        }
    
        if (StrIterIndex(&si) == StrIterIndex(&saved_si)) {
            LOG_ERROR("Failed to parse floating point number");
            return saved_si;
        }
                    return si;
                }
                LOG_ERROR("Failed to read boolean value. Expected true. Invalid JSON");
                return saved_si;
            }
                        return si;
                    }
                    LOG_ERROR("Failed to read boolean value. Expected false. Invalid JSON");
                    return saved_si;
                }
            }
    
            LOG_ERROR("Failed to parse boolean value. Expected true/false. Invalid JSON");
            return saved_si;
        } else {
            return saved_si;
        } else {
            LOG_ERROR(
                "Insufficient string length to parse a boolean value. Unexpected "
                "end of input."
                    return si;
                }
                LOG_ERROR("Failed to read boolean value. Expected null. Invalid JSON");
                return saved_si;
            }
            return saved_si;
        } else {
            LOG_ERROR(
                "Insufficient string length to parse a boolean value. Unexpected "
                "end of input."
        char c;
        if (!StrIterPeek(&si, &c)) {
            LOG_ERROR("Failed to read value. Invalid JSON");
            return si;
        }
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR(
                    "Failed to read boolean value. Expected true/false. Invalid "
                    "JSON."
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR(
                    "Failed to read boolean value. Expected true/false. Invalid "
                    "JSON."
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR("Failed to read string value. Expected string. Invalid JSON.");
                return saved_si;
            }
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR("Failed to read number value. Expected a number. Invalid JSON.");
                return saved_si;
            }
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR("Failed to read object. Expected an object. Invalid JSON.");
                return saved_si;
            }
    
            if (StrIterIndex(&si) == StrIterIndex(&before_si)) {
                LOG_ERROR("Failed to read array. Expected an array. Invalid JSON.");
                return saved_si;
            }
        }
    
        LOG_ERROR("Failed to read value. Invalid JSON");
        return si;
    }
    static bool elf_decode_header(Elf *self) {
        if (BufLength(&self->data) < EI_NIDENT + EHDR64_SIZE_AFTER_IDENT) {
            LOG_ERROR("Elf: file too small for ELF64 header ({} bytes)", (u64)BufLength(&self->data));
            return false;
        }
        const u8 *id = BufData(&self->data);
        if (id[EI_MAG0] != ELF_MAG0 || id[EI_MAG1] != ELF_MAG1 || id[EI_MAG2] != ELF_MAG2 || id[EI_MAG3] != ELF_MAG3) {
            LOG_ERROR("Elf: bad magic");
            return false;
        }
    
        if (id[EI_CLASS] != (u8)ELF_CLASS_64) {
            LOG_ERROR("Elf: only ELF64 supported in v1 (got class {})", (u32)id[EI_CLASS]);
            return false;
        }
        }
        if (id[EI_DATA] != (u8)ELF_DATA_LSB) {
            LOG_ERROR("Elf: only little-endian supported in v1 (got data {})", (u32)id[EI_DATA]);
            return false;
        }
    
        if (shentsize != SHDR64_SIZE && shnum > 0) {
            LOG_ERROR("Elf: unexpected e_shentsize ({} vs {})", (u32)shentsize, (u32)SHDR64_SIZE);
            return false;
        }
        u64 needed = (u64)n * SHDR64_SIZE;
        if (!elf_range_ok(self, shoff, needed)) {
            LOG_ERROR("Elf: section header table out of range");
            return false;
        }
    
        if (self->header.shstrndx >= n) {
            LOG_ERROR("Elf: shstrndx {} out of range (shnum={})", (u32)self->header.shstrndx, (u32)n);
            return false;
        }
        }
        if (!elf_range_ok(self, shstr_off, shstr_size)) {
            LOG_ERROR("Elf: shstrtab out of range");
            return false;
        }
        }
        if (symtab->entry_size != SYM64_SIZE) {
            LOG_ERROR("Elf: unexpected symbol entry size {}", (u64)symtab->entry_size);
            return false;
        }
        }
        if (!elf_range_ok(self, symtab->offset, symtab->size)) {
            LOG_ERROR("Elf: symbol table out of range");
            return false;
        }
        u32 strtab_idx = symtab->link;
        if (strtab_idx >= VecLen(&self->sections)) {
            LOG_ERROR("Elf: symtab link {} out of range", (u32)strtab_idx);
            return false;
        }
        const ElfSection *strtab = VecPtrAt(&self->sections, strtab_idx);
        if (!elf_range_ok(self, strtab->offset, strtab->size)) {
            LOG_ERROR("Elf: strtab out of range");
            return false;
        }
        };
        if (count > ELF_MAX_SYMBOLS) {
            LOG_ERROR("Elf: symbol count {} exceeds sanity cap; refusing", count);
            return false;
        }
        Buf copy = BufInit(alloc);
        if (!VecReserve(&copy, (u64)data_size)) {
            LOG_ERROR("ElfOpenFromMemoryCopy: allocation failed ({} bytes)", (u64)data_size);
            return false;
        }
        if (FileReadAndClose(path, &data) < 0) {
            BufDeinit(&data);
            LOG_ERROR("ElfOpen: failed to read {}", path);
            return false;
        }
            return false;
        if (unit_length == 0xffffffff) {
            LOG_ERROR("DWARF: 64-bit DWARF length form not supported in v1");
            return false;
        }
                    out->opcode_base
                )) {
                LOG_ERROR("DWARF: line program header (v4) truncated");
                return false;
            }
                    out->opcode_base
                )) {
                LOG_ERROR("DWARF: line program header (v3) truncated");
                return false;
            }
        // would divide by zero. Refuse the unit.
        if (out->line_range == 0) {
            LOG_ERROR("DWARF: line program header has line_range == 0");
            return false;
        }
            }
            if (unit_length == 0xffffffff) {
                LOG_ERROR("DWARF: 64-bit length form not supported (skipping rest of section)");
                ok = false;
                break;
            u64 code;
            if (!BufReadULeb128(&cur, &code)) {
                LOG_ERROR("DWARF info: malformed abbrev table (code)");
                return false;
            }
                        return false;
                } else {
                    LOG_ERROR("DWARF info: unsupported addr_size {}", (u32)addr_size);
                    return false;
                }
            }
            default :
                LOG_ERROR("DWARF info: unsupported FORM {x}", form);
                return false;
        }
            u64 abbrev_code;
            if (!BufReadULeb128(&cu_cur, &abbrev_code)) {
                LOG_ERROR("DWARF info: truncated DIE");
                return false;
            }
            const AbbrevEntry *e = abbrev_table_find(abbrevs, abbrev_code);
            if (!e) {
                LOG_ERROR("DWARF info: unknown abbrev code {}", (u32)abbrev_code);
                return false;
            }
    
        if (!abbrev_bytes || abbrev_size == 0) {
            LOG_ERROR("DWARF info: .debug_info present but .debug_abbrev missing");
            return false;
        }
            }
            if (unit_length == 0xffffffff) {
                LOG_ERROR("DWARF info: 64-bit length form not supported");
                ok = false;
                break;
            size unit_end_pos = unit_start_pos + 4u + unit_length;
            if (unit_end_pos > IterLength(&info_cur) || unit_end_pos < unit_start_pos) {
                LOG_ERROR("DWARF info: CU overruns section");
                ok = false;
                break;
    
            if (abbrev_offset >= abbrev_size) {
                LOG_ERROR("DWARF info: abbrev_offset past .debug_abbrev end");
                ok = false;
                break;
    static bool parse_superblock(Pdb *self, u32 *out_num_dir_bytes, u32 *out_block_map_addr) {
        if (BufLength(&self->data) < SUPERBLOCK_SIZE) {
            LOG_ERROR("PDB: file too small for MSF superblock");
            return false;
        }
        }
        if (MemCompare(BufData(&self->data), MSF_MAGIC_7, sizeof(MSF_MAGIC_7)) != 0) {
            LOG_ERROR("PDB: bad MSF magic (not 7.00)");
            return false;
        }
                *out_block_map_addr
            )) {
            LOG_ERROR("PDB: superblock truncated");
            return false;
        }
    
        if (self->block_size != 512 && self->block_size != 1024 && self->block_size != 2048 && self->block_size != 4096) {
            LOG_ERROR("PDB: unsupported MSF block size {}", self->block_size);
            return false;
        }
        u32 num_dir_blocks = div_ceil_u32(num_dir_bytes, self->block_size);
        if ((u64)num_dir_blocks * sizeof(u32) > self->block_size) {
            LOG_ERROR("PDB: directory block-map exceeds one page");
            return false;
        }
        const u8 *map_page = block_ptr(self, block_map_addr);
        if (!map_page) {
            LOG_ERROR("PDB: block_map_addr out of range");
            return false;
        }
            u32     block_id;
            if (!BufReadU32LE(&blk_iter, &block_id)) {
                LOG_ERROR("PDB: directory block map truncated");
                return false;
            }
            const u8 *src = block_ptr(self, block_id);
            if (!src) {
                LOG_ERROR("PDB: directory block id {} out of range", block_id);
                return false;
            }
            if (done + want > num_dir_bytes) {
                if (done >= num_dir_bytes) {
                    LOG_ERROR("PDB: directory copy offset past stream-dir size");
                    return false;
                }
    static bool parse_directory(Pdb *self) {
        if (self->stream_dir_size < 4) {
            LOG_ERROR("PDB: directory truncated (no stream count)");
            return false;
        }
        u64 expected = 4 + (u64)self->num_streams * 4;
        if (expected > self->stream_dir_size) {
            LOG_ERROR("PDB: directory truncated in sizes table");
            return false;
        }
        };
        if (self->num_streams > PDB_MAX_STREAMS) {
            LOG_ERROR("PDB: num_streams {} exceeds sanity cap; refusing", (u64)self->num_streams);
            return false;
        }
        u64 counts_bytes = (u64)self->num_streams * sizeof(u32);
        if (sizes_bytes > (u64)((size)-1) || ptrs_bytes > (u64)((size)-1) || counts_bytes > (u64)((size)-1)) {
            LOG_ERROR("PDB: per-stream array byte size overflows size_t");
            return false;
        }
        }
        if (expected + total_block_words * 4 > self->stream_dir_size) {
            LOG_ERROR("PDB: directory truncated in block-id table");
            return false;
        }
            u64 advance = (u64)cnt * sizeof(u32);
            if (advance > (u64)(dir_end - block_cursor)) {
                LOG_ERROR("PDB: directory block-id table overruns stream-dir");
                return false;
            }
            return true;
        if (self->stream_sizes[1] < 28) {
            LOG_ERROR("PDB: info stream too small");
            return false;
        }
            BufIter bi = BufIterFromMemory(VecBegin(&buf), VecCapacity(&buf));
            if (!BufReadFmt(&bi, FMT_PDB_INFO_LE, self->info.version, self->info.signature, self->info.age)) {
                LOG_ERROR("PDB: info stream prefix truncated");
                break;
            }
        if (sz % 40 != 0) {
            // Not a clean array of IMAGE_SECTION_HEADER -- bail.
            LOG_ERROR("PDB: section-hdr stream size {} not multiple of 40", sz);
            return NULL;
        }
        Buf copy = BufInit(alloc);
        if (!BufReserve(&copy, (u64)data_size)) {
            LOG_ERROR("PdbOpenFromMemoryCopy: allocation failed ({} bytes)", (u64)data_size);
            return false;
        }
        if (FileReadAndClose(path, &data) < 0) {
            BufDeinit(&data);
            LOG_ERROR("PdbOpen: failed to read {}", path);
            return false;
        }
    
        if (len < 12) {
            LOG_ERROR("DNS response shorter than header (got {} bytes, need 12)", len);
            return false;
        }
    static bool pe_decode_dos(PeContext *ctx) {
        if (BufLength(&ctx->out->data) < 64) {
            LOG_ERROR("PE: file too small for DOS header");
            return false;
        }
        }
        if (mz != DOS_MAGIC) {
            LOG_ERROR("PE: bad DOS magic 0x{x}", (u32)mz);
            return false;
        }
            return false;
        if (e_lfanew >= BufLength(&ctx->out->data)) {
            LOG_ERROR("PE: e_lfanew past EOF");
            return false;
        }
        u32 sig;
        if (!BufReadU32LE(&c, &sig) || sig != NT_SIGNATURE) {
            LOG_ERROR("PE: bad NT signature");
            return false;
        }
        u32 timestamp, sym_ptr, num_sym;
        if (!BufReadFmt(&c, FMT_PE_FILE_HEADER_LE, machine, num_sec, timestamp, sym_ptr, num_sym, size_opt, chars)) {
            LOG_ERROR("PE: file header truncated");
            return false;
        }
    static bool pe_decode_optional(PeContext *ctx, u64 opt_offset) {
        if (opt_offset > BufLength(&ctx->out->data) || ctx->opt_hdr_size > BufLength(&ctx->out->data) - opt_offset) {
            LOG_ERROR("PE: optional header overruns file");
            return false;
        }
            return false;
        if (magic != OPTIONAL_MAGIC_PE32 && magic != OPTIONAL_MAGIC_PE32PLUS) {
            LOG_ERROR("PE: unsupported optional magic 0x{x}", (u32)magic);
            return false;
        }
                    ctx->num_dirs
                )) {
                LOG_ERROR("PE: optional (PE32+) header truncated");
                return false;
            }
                    ctx->num_dirs
                )) {
                LOG_ERROR("PE: optional (PE32) header truncated");
                return false;
            }
        for (u32 i = 0; i < ctx->num_sections; ++i) {
            if (IterRemainingLength(&c) < 40) {
                LOG_ERROR("PE: section table truncated at index {}", i);
                return false;
            }
                    s.characteristics
                )) {
                LOG_ERROR("PE: section header {} truncated", i);
                return false;
            }
        u64 dir_offset;
        if (!PeRvaToOffset(ctx->out, (u32)ctx->debug_dir_rva, &dir_offset)) {
            LOG_ERROR("PE: debug directory RVA not in any section");
            return;
        }
        u32 num_entries = ctx->debug_dir_size / DEBUG_ENTRY_SIZE;
        if (dir_offset + (u64)num_entries * DEBUG_ENTRY_SIZE > BufLength(&ctx->out->data)) {
            LOG_ERROR("PE: debug directory overruns file");
            return;
        }
                continue;
            if (rptr + (u64)sz > BufLength(&ctx->out->data)) {
                LOG_ERROR("PE: codeview record points outside file");
                continue;
            }
        Buf copy = BufInit(alloc);
        if (!BufReserve(&copy, (u64)data_size)) {
            LOG_ERROR("PeOpenFromMemoryCopy: allocation failed ({} bytes)", (u64)data_size);
            return false;
        }
        if (FileReadAndClose(path, &data) < 0) {
            BufDeinit(&data);
            LOG_ERROR("PeOpen: failed to read {}", path);
            return false;
        }
            DnsResolver r;
            if (!DnsResolverInit(&r, alloc)) {
                LOG_ERROR("failed to init resolver");
                return 1;
            }
        Socket upstream;
        if (!SocketConnect(&upstream, SOCKET_KIND_TCP, upstream_addr)) {
            LOG_ERROR("failed to dial upstream for client [{}]", peer_str);
            SocketClose(client);
            StrDeinit(&peer_str);
            DnsResolver resolver;
            if (!DnsResolverInit(&resolver, alloc)) {
                LOG_ERROR("failed to init DNS resolver");
                return 1;
            }
            SocketAddr listen_addr;
            if (!DnsResolve(&resolver, listen_spec, SOCKET_KIND_TCP, &listen_addr)) {
                LOG_ERROR("invalid --listen address: {}", listen_spec);
                DnsResolverDeinit(&resolver);
                return 1;
            SocketAddr upstream_addr;
            if (!DnsResolve(&resolver, upstream_spec, SOCKET_KIND_TCP, &upstream_addr)) {
                LOG_ERROR("invalid --upstream address: {}", upstream_spec);
                DnsResolverDeinit(&resolver);
                return 1;
            Listener listener;
            if (!ListenerOpen(&listener, SOCKET_KIND_TCP, &listen_addr, 128)) {
                LOG_ERROR("failed to open listener on {}", listen_spec);
                return 1;
            }
            char UNPL(jr_c);                                                                                               \
            if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != '{') {                                                     \
                LOG_ERROR("Invalid object start. Expected '{'.");                                                          \
                si = UNPL(saved_si);                                                                                       \
                break;                                                                                                     \
                if (UNPL(expect_comma)) {                                                                                  \
                    if (UNPL(jr_c) != ',') {                                                                               \
                        LOG_ERROR("Expected ',' after key/value pairs in object. Invalid JSON object.");                   \
                        UNPL(failed) = true;                                                                               \
                        si           = UNPL(saved_si);                                                                     \
                UNPL(read_si) = JReadString(si, &key);                                                                     \
                if (StrIterIndex(&UNPL(read_si)) == StrIterIndex(&si)) {                                                   \
                    LOG_ERROR("Failed to read string key in object. Invalid JSON");                                        \
                    StrDeinit(&key);                                                                                       \
                    UNPL(failed) = true;                                                                                   \
                si = JSkipWhitespace(si);                                                                                  \
                if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != ':') {                                                 \
                    LOG_ERROR("Expected ':' after key string. Failed to read JSON");                                       \
                    StrDeinit(&key);                                                                                       \
                    UNPL(failed) = true;                                                                                   \
                    StrIter UNPL(skip_si) = JSkipValue(si);                                                                \
                    if (StrIterIndex(&UNPL(skip_si)) == StrIterIndex(&si)) {                                               \
                        LOG_ERROR("Failed to parse value. Invalid JSON.");                                                 \
                        StrDeinit(&key);                                                                                   \
                        UNPL(failed) = true;                                                                               \
            if (!UNPL(failed)) {                                                                                           \
                if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != '}') {                                                 \
                    LOG_ERROR("Expected end of object '}' but found '{c}'", UNPL(jr_c));                                   \
                    UNPL(failed) = true;                                                                                   \
                    si           = UNPL(saved_si);                                                                         \
    
            if (iteration_count > 2) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx > 2) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx < 4) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx > 3) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx < 5) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx > VecLen(&vec)) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
    
            if (idx > 2) {
                LOG_ERROR("Should've terminated");
                VecDeinit(&vec);
                return false;
        Elf stripped;
        if (!ElfOpen(&stripped, stripped_path_arg, base)) {
            LOG_ERROR("stripped binary not openable: {}", stripped_path_arg);
            DefaultAllocatorDeinit(&alloc);
            return false;
    
            if (idx > 4) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
    
            if (idx >= 5) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
            // loop will automatically terminate
            if (idx < 10) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
    
            if (idx > 4) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
    
            if (idx < 12) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
    
            if (idx >= StrLen(&s)) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
    
            if (idx > 3) {
                LOG_ERROR("Should've terminated");
                StrDeinit(&s);
                DefaultAllocatorDeinit(&alloc);
            char UNPL(jr_c);                                                                                               \
            if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != '[') {                                                     \
                LOG_ERROR("Invalid array start. Expected '['.");                                                           \
                si = UNPL(saved_si);                                                                                       \
                break;                                                                                                     \
                if (UNPL(expect_comma)) {                                                                                  \
                    if (UNPL(jr_c) != ',') {                                                                               \
                        LOG_ERROR("Expected ',' between values in array. Invalid JSON array.");                            \
                        UNPL(failed) = true;                                                                               \
                        si           = UNPL(saved_si);                                                                     \
                    /* if still no advancement in read position */                                                         \
                    if (StrIterIndex(&UNPL(read_si)) == StrIterIndex(&si)) {                                               \
                        LOG_ERROR("Failed to parse value. Invalid JSON.");                                                 \
                        UNPL(failed) = true;                                                                               \
                        si           = UNPL(saved_si);                                                                     \
            if (!UNPL(failed)) {                                                                                           \
                if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != ']') {                                                 \
                    LOG_ERROR("Invalid end of array. Expected ']'.");                                                      \
                    UNPL(failed) = true;                                                                                   \
                    si           = UNPL(saved_si);                                                                         \
            char UNPL(jr_c);                                                                                               \
            if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != '{') {                                                     \
                LOG_ERROR("Invalid object start. Expected '{'.");                                                          \
                si = UNPL(saved_si);                                                                                       \
                break;                                                                                                     \
                if (UNPL(expect_comma)) {                                                                                  \
                    if (UNPL(jr_c) != ',') {                                                                               \
                        LOG_ERROR("Expected ',' after key/value pairs in object. Invalid JSON object.");                   \
                        UNPL(failed) = true;                                                                               \
                        si           = UNPL(saved_si);                                                                     \
                UNPL(read_si) = JReadString(si, &key);                                                                     \
                if (StrIterIndex(&UNPL(read_si)) == StrIterIndex(&si)) {                                                   \
                    LOG_ERROR("Failed to read string key in object. Invalid JSON");                                        \
                    StrDeinit(&key);                                                                                       \
                    UNPL(failed) = true;                                                                                   \
                                                                                                                           \
                if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != ':') {                                                 \
                    LOG_ERROR("Expected ':' after key string. Failed to read JSON");                                       \
                    StrDeinit(&key);                                                                                       \
                    UNPL(failed) = true;                                                                                   \
                    /* if still no advancement in read position */                                                         \
                    if (StrIterIndex(&UNPL(read_si)) == StrIterIndex(&si)) {                                               \
                        LOG_ERROR("Failed to parse value. Invalid JSON.");                                                 \
                        StrDeinit(&key);                                                                                   \
                        UNPL(failed) = true;                                                                               \
            if (!UNPL(failed)) {                                                                                           \
                if (!StrIterPeek(&si, &UNPL(jr_c)) || UNPL(jr_c) != '}') {                                                 \
                    LOG_ERROR("Expected end of object '}' but found '{c}'", UNPL(jr_c));                                   \
                    UNPL(failed) = true;                                                                                   \
                    si           = UNPL(saved_si);                                                                         \
Last updated on