danielaparker / jsoncons

A C++, header-only library for constructing JSON and JSON-like data formats, with JSON Pointer, JSON Patch, JSON Schema, JSONPath, JMESPath, CSV, MessagePack, CBOR, BSON, UBJSON
https://danielaparker.github.io/jsoncons
Other
726 stars 164 forks source link

Avoid integer overflow UB in basic_json_parser #542

Closed PragmaTwice closed 1 month ago

PragmaTwice commented 1 month ago

In Kvrocks we faced an integer overflow detected by UBSAN in basic_json_parser.

/home/runner/work/kvrocks/kvrocks/build/_deps/jsoncons-src/include/jsoncons/json_parser.hpp:180:74: runtime error: signed integer overflow: 2147483647 + 2 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /home/runner/work/kvrocks/kvrocks/build/_deps/jsoncons-src/include/jsoncons/json_parser.hpp:180:74 in 

The reason is that we set max_nesting_depth to numeric_limits::max(), so that max_nesting_depth + 2 leads to overflow.

Here I use an equivalent form to eliminate the problem.