Skip to content

Commit 35bac3c

Browse files
authored
bugfix: fix truncation of decoded numbers outside lua_Integer's range (#116)
json_next_number_token stores the `long long` return value from `stroll` in a `lua_Integer` (which is typically a typedef for `ptrdiff_t`). On 32-bit platforms, this ends up storing an 8-byte number into a 4-byte variable, truncating the value. Instead, store the converted value in a temporary `long long` variable so we can detect the scenario and decode into a `lua_Number`. Signed-off-by: James McCoy <jamessan@jamessan.com>
1 parent cd944c1 commit 35bac3c

1 file changed

Lines changed: 9 additions & 1 deletion

File tree

lua_cjson.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1190,7 +1190,7 @@ static int json_is_invalid_number(json_parse_t *json)
11901190
static void json_next_number_token(json_parse_t *json, json_token_t *token)
11911191
{
11921192
char *endptr;
1193-
token->value.integer = strtoll(json->ptr, &endptr, 10);
1193+
long long tmpval = strtoll(json->ptr, &endptr, 10);
11941194
if (json->ptr == endptr || *endptr == '.' || *endptr == 'e' ||
11951195
*endptr == 'E' || *endptr == 'x') {
11961196
token->type = T_NUMBER;
@@ -1199,8 +1199,16 @@ static void json_next_number_token(json_parse_t *json, json_token_t *token)
11991199
json_set_token_error(token, json, "invalid number");
12001200
return;
12011201
}
1202+
} else if (tmpval > PTRDIFF_MAX || tmpval < PTRDIFF_MIN) {
1203+
/* Typical Lua builds typedef ptrdiff_t to lua_Integer. If tmpval is
1204+
* outside the range of that type, we need to use T_NUMBER to avoid
1205+
* truncation.
1206+
*/
1207+
token->type = T_NUMBER;
1208+
token->value.number = tmpval;
12021209
} else {
12031210
token->type = T_INTEGER;
1211+
token->value.integer = tmpval;
12041212
}
12051213
json->ptr = endptr; /* Skip the processed number */
12061214

0 commit comments

Comments
 (0)