Skip to content

Fix undefined behavior in StringView trimming and validate positive number parsing - #471

Open
jdymitarai wants to merge 1 commit into
google:mainfrom
jdymitarai:fix-stringview-trim-and-hex-parse
Open

Fix undefined behavior in StringView trimming and validate positive number parsing#471
jdymitarai wants to merge 1 commit into
google:mainfrom
jdymitarai:fix-stringview-trim-and-hex-parse

Conversation

@jdymitarai

Copy link
Copy Markdown

Summary of Changes

  1. Fix undefined behavior in StringView trimming:

    • In standard C (C99 7.4 / C11 7.4), the argument to <ctype.h> functions like isspace() must be representable as unsigned char or equal to EOF.
    • When char is signed (default on x86/x64 MSVC and GCC/Clang), non-ASCII characters (>= 0x80) produce negative integer values when passed to isspace(), causing undefined behavior or debug assertions (e.g. _ASSERTE((unsigned)(c + 1) <= 256) on MSVC).
    • Cast characters to (unsigned char) before invoking isspace().
  2. Reject empty views in ParsePositiveNumberWithBase:

    • Previously, parsing "0x" stripped the "0x" prefix leaving an empty remainder view (size == 0). The loop in ParsePositiveNumberWithBase never iterated and returned result = 0. As a result, the malformed literal "0x" was incorrectly treated as valid integer 0 instead of returning -1.
    • Returning -1 if view.size == 0 ensures incomplete hex literals without digits properly fail.
  3. Prevent signed integer overflow in ParsePositiveNumberWithBase:

    • Added bounds check (result > (INT_MAX - value) / base) before result = (result * base) + value to guard against signed integer overflow on oversized strings.
  4. Unit Tests:

    • Added test cases in test/string_view_test.cc for non-ASCII whitespace trimming, "0", "0x0", "0x", malformed hex suffixes, and overflow inputs.

Verification

All 17 unit tests in string_view_test and all CMake test suites pass cleanly on MSVC.

…umber parsing

1. Cast char to (unsigned char) in CpuFeatures_StringView_TrimWhitespace before calling isspace() to prevent undefined behavior with negative char values on platforms with signed char.
2. Reject empty views in ParsePositiveNumberWithBase, ensuring incomplete hex prefixes such as '0x' return -1 instead of erroneously returning 0.
3. Check for signed integer overflow in ParsePositiveNumberWithBase before multiplication.
4. Add comprehensive unit tests in string_view_test.cc covering non-ASCII whitespace trimming, hex validation, and integer overflow.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant