Files
libakerror/tests/err_name_bounds.c
Andrew Kesterson 4212ff0b28
All checks were successful
libakerror CI Build / cmake_build (push) Successful in 2m48s
libakerror CI Build / mutation_test (push) Successful in 7m40s
Fix format-string use of __FILE__/__func__ and name_for_status lower bound
Two hardening fixes flagged by the earlier review:

1. FAIL passed __FILE__ and __func__ directly as the snprintf format string.
   __FILE__ expands to a string literal that could contain a '%' (a build path
   under a directory with a percent sign), and __func__ is not a literal at all;
   either way snprintf would read nonexistent varargs. Pass them as "%s"
   arguments instead.

2. akerr_name_for_status guarded the upper bound but not the lower one, so a
   negative status indexed __AKERR_ERROR_NAMES[negative] -- an out-of-bounds
   read, or an out-of-bounds write when a name was supplied. Reject status < 0.

Regression tests err_format_string (uses #line to put a conversion specifier in
__FILE__) and err_name_bounds fail against the old code (verified) and pass now.
Full suite: 23/23, no warnings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-28 10:52:29 -04:00

32 lines
1.0 KiB
C

#include "akerror.h"
#include "err_capture.h"
#include <string.h>
/*
* akerr_name_for_status must reject out-of-range status codes at BOTH ends.
* It already guarded the upper bound, but a negative status indexed
* __AKERR_ERROR_NAMES[negative] -- an out-of-bounds read (and an out-of-bounds
* write when a name is supplied). Every out-of-range status must return the
* "Unknown Error" sentinel instead.
*/
int main(void)
{
akerr_init();
/* Below range. */
AKERR_CHECK(strcmp(akerr_name_for_status(-1, NULL), "Unknown Error") == 0);
AKERR_CHECK(strcmp(akerr_name_for_status(-9999, NULL), "Unknown Error") == 0);
/* Above range (already handled; kept as a guard against regressions). */
AKERR_CHECK(strcmp(akerr_name_for_status(AKERR_MAX_ERR_VALUE + 1, NULL),
"Unknown Error") == 0);
/* A valid code must still resolve to its real name. */
AKERR_CHECK(strcmp(akerr_name_for_status(AKERR_NULLPOINTER, NULL),
"Null Pointer Error") == 0);
fprintf(stderr, "err_name_bounds ok\n");
return 0;
}