Handle NaN in json_int() (undefined double->int cast)#541
Open
gigioneggiando wants to merge 1 commit into
Open
Handle NaN in json_int() (undefined double->int cast)#541gigioneggiando wants to merge 1 commit into
gigioneggiando wants to merge 1 commit into
Conversation
json_number() is a thin strtod() wrapper, which per C99 accepts "NaN" and "Infinity". In json_int() the clamps `v < 0` and `v > INT_MAX` are both false for NaN (every NaN comparison is false), so NaN reaches the (int)v cast, which is undefined behavior (on x86-64 it yields INT_MIN). Replace `if (v < 0)` with `if (!(v >= 0))`, which folds NaN and negatives to 0; +/-Infinity are still handled by the two clamps.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
json_number()is a thinstrtod()wrapper, which per C99 accepts"NaN"and"Infinity". Injson_int()the two clampsv < 0andv > INT_MAXare both false for NaN (every comparison against NaN is false), so a NaN value reaches the(int)vcast, which is undefined behavior for NaN (on x86-64 it yieldsINT_MIN).So a request field like
{"max_tokens": NaN}produces an out-of-range integer conversion rather than being rejected/clamped.Fix
Replace
if (v < 0) v = 0;withif (!(v >= 0)) v = 0;, which folds NaN (and negatives) to 0.+Infinity/-Infinityremain handled by the existing clamps. One-line change, no new dependency.Verification
Built under UBSan with
-fsanitize=float-cast-overflow, driving the realjson_int("NaN"):runtime error: nan is outside the range of representable values of type 'int'.0, no trap.Low severity (no memory corruption), found during a coordinated security review of ds4; a standalone offline PoC is available on request.