• sundb's avatar
    Avoid mostly harmless integer overflow in cjson (#12456) · da9c2804
    sundb authored
    This PR mainly fixes a possible integer overflow in `json_append_string()`.
    When we use `cjson.encoding()` to encode a string larger than 2GB, at specific
    compilation flags, an integer overflow may occur leading to truncation, resulting
    in the part of the string larger than 2GB not being encoded.
    On the other hand, this overflow doesn't cause any read or write out-of-range or segment fault.
    
    1) using -O0 for lua_cjson (`make LUA_DEBUG=yes`)
        In this case, `i` will overflow and leads to truncation.
        When `i` reaches `INT_MAX+1` and overflows to INT_MIN, when compared to
        len, `i` (1000000..00) is expanded to 64 bits signed integer (1111111.....000000) .
        At this point i will be greater than len and jump out of the loop, so `for (i = 0; i < len; i++)`
        will loop up to 2^31 times, and the part of larger than 2GB will be truncated.
    
    ```asm
    `i` => -0x24(%rbp)
    <+253>:   addl   $0x1,-0x24(%rbp)       ; overflow if i large than...
    da9c2804
strbuf.c 4.4 KB