From 418685e4ffb4ff0cf64f9172d8d25dc126b3b1b2 Mon Sep 17 00:00:00 2001 From: Juan Cruz Viotti Date: Wed, 14 Oct 2026 19:46:45 -0300 Subject: [PATCH 1/3] Achieve 100% line coverage on the `json` module Signed-off-by: Juan Cruz Viotti --- src/core/json/construct.h | 45 ++- .../json/include/sourcemeta/core/json_auto.h | 9 +- .../include/sourcemeta/core/json_object.h | 88 +---- .../json/include/sourcemeta/core/json_value.h | 19 +- src/core/json/json.cc | 15 +- src/core/json/json_value.cc | 308 +++++++++--------- src/core/json/parser.h | 11 + test/json/json_parse_error_test.cc | 29 +- 8 files changed, 258 insertions(+), 266 deletions(-) diff --git a/src/core/json/construct.h b/src/core/json/construct.h index e70b1869b2..4208376fb9 100644 --- a/src/core/json/construct.h +++ b/src/core/json/construct.h @@ -15,7 +15,7 @@ #include // std::uint64_t, std::uint32_t, std::uint8_t #include // std::reference_wrapper #include // std::string_view -#include // std::move, std::unreachable +#include // std::move #include // std::vector namespace sourcemeta::core { @@ -34,6 +34,23 @@ inline auto parse_hex4(const char *&position) -> unsigned long { return value; } +// The code point a `\u` escape names, read from the four digits the position +// is on and leaving it on whatever follows them. A high surrogate is joined +// with the low one the scan has already made sure comes after it +inline auto parse_escaped_code_point(const char *&position, + [[maybe_unused]] const char *const end) + -> char32_t { + auto code_point{parse_hex4(position)}; + if (code_point >= 0xD800 && code_point <= 0xDBFF) { + assert(position + 6 <= end); + position += 2; + const auto low{parse_hex4(position)}; + code_point = 0x10000 + ((code_point - 0xD800) << 10) + (low - 0xDC00); + } + + return static_cast(code_point); +} + inline auto unescape_string(const char *data, const std::uint32_t length, const bool has_escape) -> JSON::String { JSON::String result; @@ -65,7 +82,8 @@ inline auto unescape_string(const char *data, const std::uint32_t length, cursor++; assert(cursor < string_end); - switch (*cursor++) { + const auto escape{*cursor++}; + switch (escape) { case '"': result.push_back('"'); break; @@ -90,23 +108,14 @@ inline auto unescape_string(const char *data, const std::uint32_t length, case 't': result.push_back('\t'); break; - case 'u': { - auto code_point{parse_hex4(cursor)}; - if (code_point >= 0xD800 && code_point <= 0xDBFF) { - assert(cursor + 6 <= string_end); - cursor += 2; - const auto low{parse_hex4(cursor)}; - code_point = 0x10000 + ((code_point - 0xD800) << 10) + (low - 0xDC00); - } - - sourcemeta::core::codepoint_to_utf8(static_cast(code_point), - result); - break; - } - // The scan accepted the escape, so what stands after the reverse solidus - // is one of the characters the grammar names + // The scan accepted the escape, so what stands after the reverse + // solidus is one of the characters the grammar names, and every one + // but the code point escape is spelled out above default: - std::unreachable(); + assert(escape == 'u'); + sourcemeta::core::codepoint_to_utf8( + parse_escaped_code_point(cursor, string_end), result); + break; } } diff --git a/src/core/json/include/sourcemeta/core/json_auto.h b/src/core/json/include/sourcemeta/core/json_auto.h index 64e28bf668..757b2df928 100644 --- a/src/core/json/include/sourcemeta/core/json_auto.h +++ b/src/core/json/include/sourcemeta/core/json_auto.h @@ -699,11 +699,10 @@ auto from_json(const JSON &value) -> std::optional { return std::nullopt; } - const auto index{static_cast(value.at(0).to_integer())}; - if (index >= std::variant_size_v) { - return std::nullopt; - } - return from_json_variant_impl(value.at(1), index); + // An index past the alternatives is turned down where the walk over them + // runs out, rather than being judged twice + return from_json_variant_impl( + value.at(1), static_cast(value.at(0).to_integer())); } } // namespace sourcemeta::core diff --git a/src/core/json/include/sourcemeta/core/json_object.h b/src/core/json/include/sourcemeta/core/json_object.h index 955b5bf805..5c9ef79c48 100644 --- a/src/core/json/include/sourcemeta/core/json_object.h +++ b/src/core/json/include/sourcemeta/core/json_object.h @@ -9,7 +9,7 @@ #include // std::advance #include // std::basic_string_view #include // std::remove_cvref_t -#include // std::pair, std::move, std::unreachable +#include // std::pair, std::move #include // std::vector namespace sourcemeta::core { @@ -320,24 +320,11 @@ template class JSONObject { /// Access an object entry by its key name [[nodiscard]] auto at(const Key &key, const hash_type key_hash) const -> const mapped_type & { - assert(this->hash(key) == key_hash); - - // Move the perfect hash condition out of the loop for extra performance - if (this->HASHER.is_perfect(key_hash)) { - for (const auto &entry : *this) { - if (entry.hash == key_hash && entry.first.size() == key.size()) { - return entry.second; - } - } - } else { - for (const auto &entry : *this) { - if (entry.hash == key_hash && entry.first == key) { - return entry.second; - } - } - } - - std::unreachable(); + const auto *const result{this->try_at(key, key_hash)}; + // The caller states the entry is there, which is what tells this apart + // from the lookup that answers whether it is + assert(result != nullptr); + return *result; } /// Access an object entry by its key name @@ -345,70 +332,25 @@ template class JSONObject { requires std::same_as, KeyView> [[nodiscard]] auto at(T key, const hash_type key_hash) const -> const mapped_type & { - assert(this->hash(key) == key_hash); - - // Move the perfect hash condition out of the loop for extra performance - if (this->HASHER.is_perfect(key_hash)) { - for (const auto &entry : *this) { - if (entry.hash == key_hash && entry.first.size() == key.size()) { - return entry.second; - } - } - } else { - for (const auto &entry : *this) { - if (entry.hash == key_hash && entry.first == key) { - return entry.second; - } - } - } - - std::unreachable(); + const auto *const result{this->try_at(key, key_hash)}; + assert(result != nullptr); + return *result; } /// Access an object entry by its key name auto at(const Key &key, const hash_type key_hash) -> mapped_type & { - assert(this->hash(key) == key_hash); - - // Move the perfect hash condition out of the loop for extra performance - if (this->HASHER.is_perfect(key_hash)) { - for (auto &entry : this->data_) { - if (entry.hash == key_hash && entry.first.size() == key.size()) { - return entry.second; - } - } - } else { - for (auto &entry : this->data_) { - if (entry.hash == key_hash && entry.first == key) { - return entry.second; - } - } - } - - std::unreachable(); + auto *const result{this->try_at(key, key_hash)}; + assert(result != nullptr); + return *result; } /// Access an object entry by its key name template requires std::same_as, KeyView> auto at(T key, const hash_type key_hash) -> mapped_type & { - assert(this->hash(key) == key_hash); - - // Move the perfect hash condition out of the loop for extra performance - if (this->HASHER.is_perfect(key_hash)) { - for (auto &entry : this->data_) { - if (entry.hash == key_hash && entry.first.size() == key.size()) { - return entry.second; - } - } - } else { - for (auto &entry : this->data_) { - if (entry.hash == key_hash && entry.first == key) { - return entry.second; - } - } - } - - std::unreachable(); + auto *const result{this->try_at(key, key_hash)}; + assert(result != nullptr); + return *result; } /// Try to access an object entry by its key name diff --git a/src/core/json/include/sourcemeta/core/json_value.h b/src/core/json/include/sourcemeta/core/json_value.h index 712db24c81..f1e2b2dfaa 100644 --- a/src/core/json/include/sourcemeta/core/json_value.h +++ b/src/core/json/include/sourcemeta/core/json_value.h @@ -15,7 +15,7 @@ #include // std::any_of #include // std::bitset #include // assert -#include // std::modf, std::trunc, std::isinf, std::isnan +#include // std::trunc, std::isinf, std::isnan #include // std::same_as #include // std::size_t #include // std::int64_t, std::uint8_t @@ -263,7 +263,7 @@ class SOURCEMETA_CORE_JSON_EXPORT JSON { auto operator=(JSON &&other) noexcept -> JSON &; /// Destructor - ~JSON(); + ~JSON() noexcept; /// This function creates an empty JSON array. For example: /// @@ -490,10 +490,8 @@ class SOURCEMETA_CORE_JSON_EXPORT JSON { switch (this->type()) { case Type::Integer: return true; - case Type::Real: { - Real integral_part = 0.0; - return std::modf(this->to_real(), &integral_part) == 0.0; - } + case Type::Real: + return std::trunc(this->to_real()) == this->to_real(); case Type::Decimal: return this->to_decimal().is_integral(); default: @@ -2588,6 +2586,15 @@ class SOURCEMETA_CORE_JSON_EXPORT JSON { #pragma warning(pop) #endif auto maybe_destruct_union() -> void; + + // Tear this value down and take the scalar given in its place. The scalar + // arrives by value, which is what copies it out of a source that may be + // living inside what is torn down + auto replace_with(const bool value) -> void; + auto replace_with(const Integer value) -> void; + auto replace_with(const Real value) -> void; + auto replace_with(String value) -> void; + auto replace_with(Decimal value) -> void; }; } // namespace sourcemeta::core diff --git a/src/core/json/json.cc b/src/core/json/json.cc index 37f32513dc..b56607cb0e 100644 --- a/src/core/json/json.cc +++ b/src/core/json/json.cc @@ -11,11 +11,10 @@ #include // std::uint64_t #include // std::filesystem #include // std::basic_istream -#include // std::numeric_limits #include // std::optional, std::nullopt #include // std::basic_ostream #include // std::conditional_t -#include // std::cmp_greater, std::move, std::unreachable +#include // std::move, std::unreachable #include // std::vector namespace sourcemeta::core { @@ -27,19 +26,7 @@ internal_parse_json(const char *&cursor, const char *end, std::uint64_t &line, [[maybe_unused]] const bool track_positions, JSON &output) -> std::conditional_t { const char *buffer_start{cursor}; - // Tape entries address the input with 32-bit offsets and lengths, so a larger - // input cannot be represented without truncation - if (std::cmp_greater(end - cursor, - std::numeric_limits::max())) { - if constexpr (ShouldThrow) { - throw JSONParseError(line, column); - } else { - return false; - } - } - std::vector tape; - tape.reserve(static_cast(end - cursor) / 8); if constexpr (ShouldThrow) { if (callback || track_positions) { diff --git a/src/core/json/json_value.cc b/src/core/json/json_value.cc index 7670c8a722..6fe8d784c5 100644 --- a/src/core/json/json_value.cc +++ b/src/core/json/json_value.cc @@ -7,7 +7,6 @@ #include // std::strong_ordering, std::is_eq, std::is_lt #include // std::size_t #include // std::int64_t -#include // std::terminate #include // std::reference_wrapper #include // std::initializer_list #include // std::numeric_limits @@ -216,6 +215,40 @@ auto cross_numeric_ordering(const JSON &left, const JSON &right) : std::strong_ordering::greater; } +// One source value and the place its copy is written to +struct CopyTask { + const JSON *source; + JSON *destination; +}; + +// Give every child of the source a null placeholder in the destination, which +// fixes the address its copy goes to, and queue each pair for the walk +auto queue_children(const JSON::Array::Container &source, + JSON::Array::Container &destination, + std::vector &tasks) -> void { + destination.reserve(source.size()); + for (std::size_t index = 0; index < source.size(); ++index) { + destination.emplace_back(nullptr); + } + for (std::size_t index = 0; index < source.size(); ++index) { + tasks.push_back( + {.source = &source[index], .destination = &destination[index]}); + } +} + +auto queue_children(const JSON::Object::underlying_type &source, + JSON::Object::underlying_type &destination, + std::vector &tasks) -> void { + destination.reserve(source.size()); + for (const auto &entry : source) { + destination.emplace_back(entry.first, JSON{nullptr}, entry.hash); + } + for (std::size_t index = 0; index < source.size(); ++index) { + tasks.push_back({.source = &source[index].second, + .destination = &destination[index].second}); + } +} + } // namespace JSON::JSON(const std::int64_t value) : current_type_{Type::Integer} { @@ -295,7 +328,11 @@ JSON::JSON(Decimal &&value) : current_type_{Type::Decimal} { std::construct_at(&this->data_decimal, std::move(value)); } -JSON::JSON(const JSON &other) { +// The copy starts out as a value of its own, so that whatever it has built by +// the time something throws is torn down by the destructor. A constructor that +// never finished does not get one of its own, which is why it is reached for +// here rather than left to the caller +JSON::JSON(const JSON &other) : JSON{nullptr} { // Fast path for non-container sources avoids the work-list allocation that // would otherwise dominate the cost of copying a scalar value switch (other.current_type_) { @@ -329,87 +366,54 @@ JSON::JSON(const JSON &other) { // Build the container copy iteratively to avoid unbounded recursion on // deeply nested values, which would otherwise overflow the call stack. Each // task copies a single source-destination pair shallowly and queues - // children for containers. Pre-filling destination containers with Null - // placeholders gives stable addresses to queue child tasks against. - // current_type is set only after the matching union member is fully - // constructed, so a throw from the catch handler can safely destroy - // whatever state is present - struct CopyTask { - const JSON *source; - JSON *destination; - }; + // children for containers. current_type is set only after the matching + // union member is fully constructed, so the destructor that runs when + // something throws can safely destroy whatever state is present std::vector tasks; tasks.reserve(16); tasks.push_back({.source = &other, .destination = this}); - try { - while (!tasks.empty()) { - const auto task{tasks.back()}; - tasks.pop_back(); - const JSON &source{*task.source}; - JSON &destination{*task.destination}; - switch (source.current_type_) { - case Type::Null: - break; - case Type::Boolean: - destination.data_boolean = source.data_boolean; - destination.current_type_ = Type::Boolean; - break; - case Type::Integer: - destination.data_integer = source.data_integer; - destination.current_type_ = Type::Integer; - break; - case Type::Real: - destination.data_real = source.data_real; - destination.current_type_ = Type::Real; - break; - case Type::String: - std::construct_at(&destination.data_string, source.data_string); - destination.current_type_ = Type::String; - break; - case Type::Decimal: - std::construct_at(&destination.data_decimal, source.data_decimal); - destination.current_type_ = Type::Decimal; - break; - case Type::Array: { - std::construct_at(&destination.data_array, Array{}); - destination.current_type_ = Type::Array; - const auto &source_data{source.data_array.data_}; - auto &destination_data{destination.data_array.data_}; - destination_data.reserve(source_data.size()); - for (std::size_t index = 0; index < source_data.size(); ++index) { - destination_data.emplace_back(nullptr); - } - for (std::size_t index = 0; index < source_data.size(); ++index) { - tasks.push_back({.source = &source_data[index], - .destination = &destination_data[index]}); - } - break; - } - case Type::Object: { - std::construct_at(&destination.data_object, Object{}); - destination.current_type_ = Type::Object; - const auto &source_data{source.data_object.data_}; - auto &destination_data{destination.data_object.data_}; - destination_data.reserve(source_data.size()); - for (const auto &entry : source_data) { - destination_data.emplace_back(entry.first, JSON{nullptr}, - entry.hash); - } - for (std::size_t index = 0; index < source_data.size(); ++index) { - tasks.push_back({.source = &source_data[index].second, - .destination = &destination_data[index].second}); - } - break; - } - } + while (!tasks.empty()) { + const auto task{tasks.back()}; + tasks.pop_back(); + const JSON &source{*task.source}; + JSON &destination{*task.destination}; + switch (source.current_type_) { + case Type::Null: + break; + case Type::Boolean: + destination.data_boolean = source.data_boolean; + destination.current_type_ = Type::Boolean; + break; + case Type::Integer: + destination.data_integer = source.data_integer; + destination.current_type_ = Type::Integer; + break; + case Type::Real: + destination.data_real = source.data_real; + destination.current_type_ = Type::Real; + break; + case Type::String: + std::construct_at(&destination.data_string, source.data_string); + destination.current_type_ = Type::String; + break; + case Type::Decimal: + std::construct_at(&destination.data_decimal, source.data_decimal); + destination.current_type_ = Type::Decimal; + break; + case Type::Array: + std::construct_at(&destination.data_array, Array{}); + destination.current_type_ = Type::Array; + queue_children(source.data_array.data_, destination.data_array.data_, + tasks); + break; + case Type::Object: + std::construct_at(&destination.data_object, Object{}); + destination.current_type_ = Type::Object; + queue_children(source.data_object.data_, destination.data_object.data_, + tasks); + break; } - } catch (...) { - // Tear down the partially-built tree before unwinding. *this's lifetime - // never began, so ~JSON would not have run otherwise. The vector dtor - // dispatches to each child's iterative ~JSON for any depth of subtree - this->maybe_destruct_union(); - throw; } } @@ -450,6 +454,36 @@ JSON::JSON(JSON &&other) noexcept : current_type_{other.current_type_} { } } +auto JSON::replace_with(const bool value) -> void { + this->~JSON(); + this->data_boolean = value; + this->current_type_ = Type::Boolean; +} + +auto JSON::replace_with(const Integer value) -> void { + this->~JSON(); + this->data_integer = value; + this->current_type_ = Type::Integer; +} + +auto JSON::replace_with(const Real value) -> void { + this->~JSON(); + this->data_real = value; + this->current_type_ = Type::Real; +} + +auto JSON::replace_with(String value) -> void { + this->~JSON(); + std::construct_at(&this->data_string, std::move(value)); + this->current_type_ = Type::String; +} + +auto JSON::replace_with(Decimal value) -> void { + this->~JSON(); + std::construct_at(&this->data_decimal, std::move(value)); + this->current_type_ = Type::Decimal; +} + auto JSON::operator=(const JSON &other) -> JSON & { if (this == &other) { return *this; @@ -457,49 +491,29 @@ auto JSON::operator=(const JSON &other) -> JSON & { // Fast path for scalar sources: tear this value down iteratively, which is // safe for any depth, then assign the scalar directly. Each scalar is - // buffered into a local first, because the source may be nested inside this - // value, and tearing this value down would otherwise free the storage still - // being read from + // handed over by value, because the source may be nested inside this value, + // and tearing this value down would otherwise free the storage still being + // read from switch (other.current_type_) { case Type::Null: this->~JSON(); this->current_type_ = Type::Null; return *this; - case Type::Boolean: { - const auto value{other.data_boolean}; - this->~JSON(); - this->data_boolean = value; - this->current_type_ = Type::Boolean; + case Type::Boolean: + this->replace_with(other.data_boolean); return *this; - } - case Type::Integer: { - const auto value{other.data_integer}; - this->~JSON(); - this->data_integer = value; - this->current_type_ = Type::Integer; + case Type::Integer: + this->replace_with(other.data_integer); return *this; - } - case Type::Real: { - const auto value{other.data_real}; - this->~JSON(); - this->data_real = value; - this->current_type_ = Type::Real; + case Type::Real: + this->replace_with(other.data_real); return *this; - } - case Type::String: { - String value{other.data_string}; - this->~JSON(); - std::construct_at(&this->data_string, std::move(value)); - this->current_type_ = Type::String; + case Type::String: + this->replace_with(other.data_string); return *this; - } - case Type::Decimal: { - Decimal value{other.data_decimal}; - this->~JSON(); - std::construct_at(&this->data_decimal, std::move(value)); - this->current_type_ = Type::Decimal; + case Type::Decimal: + this->replace_with(other.data_decimal); return *this; - } case Type::Array: case Type::Object: break; @@ -529,60 +543,56 @@ auto JSON::operator=(JSON &&other) noexcept -> JSON & { return *this; } -JSON::~JSON() { +JSON::~JSON() noexcept { // Drain only nested container children iteratively so deeply nested values // do not overflow the call stack. Scalar and empty children are left in // place to be destroyed by maybe_destruct_union, which is non-recursive // for non-container types. pending stays empty when no descendant has its // own container children, so containers full of scalars cost no heap - // allocation. Allocation failures during destruction have no sensible - // recovery, so terminate + // allocation. An allocation failure along the way has no sensible recovery, + // and the exception specification above is what settles it if (this->current_type_ == Type::Array || this->current_type_ == Type::Object) { - try { - std::vector pending; + std::vector pending; - if (this->current_type_ == Type::Array) { - for (auto &child : this->data_array.data_) { + if (this->current_type_ == Type::Array) { + for (auto &child : this->data_array.data_) { + if (child.current_type_ == Type::Array || + child.current_type_ == Type::Object) { + pending.push_back(std::move(child)); + } + } + } else { + for (auto &entry : this->data_object.data_) { + if (entry.second.current_type_ == Type::Array || + entry.second.current_type_ == Type::Object) { + pending.push_back(std::move(entry.second)); + } + } + } + + while (!pending.empty()) { + JSON node = std::move(pending.back()); + pending.pop_back(); + if (node.current_type_ == Type::Array) { + for (auto &child : node.data_array.data_) { if (child.current_type_ == Type::Array || child.current_type_ == Type::Object) { pending.push_back(std::move(child)); } } + node.data_array.~JSONArray(); + node.current_type_ = Type::Null; } else { - for (auto &entry : this->data_object.data_) { + for (auto &entry : node.data_object.data_) { if (entry.second.current_type_ == Type::Array || entry.second.current_type_ == Type::Object) { pending.push_back(std::move(entry.second)); } } + node.data_object.~JSONObject(); + node.current_type_ = Type::Null; } - - while (!pending.empty()) { - JSON node = std::move(pending.back()); - pending.pop_back(); - if (node.current_type_ == Type::Array) { - for (auto &child : node.data_array.data_) { - if (child.current_type_ == Type::Array || - child.current_type_ == Type::Object) { - pending.push_back(std::move(child)); - } - } - node.data_array.~JSONArray(); - node.current_type_ = Type::Null; - } else { - for (auto &entry : node.data_object.data_) { - if (entry.second.current_type_ == Type::Array || - entry.second.current_type_ == Type::Object) { - pending.push_back(std::move(entry.second)); - } - } - node.data_object.~JSONObject(); - node.current_type_ = Type::Null; - } - } - } catch (...) { - std::terminate(); } } @@ -648,9 +658,13 @@ auto JSON::operator<(const JSON &other) const -> bool { return this->as_array() < other.as_array(); case Type::Object: return this->as_object() < other.as_object(); - default: - return false; } + + // Clang settles that no other value arrives, so only GCC and MSVC + // need to be told that the end of this function is never reached +#if !defined(__clang__) + std::unreachable(); +#endif } auto JSON::operator<=(const JSON &other) const -> bool { diff --git a/src/core/json/parser.h b/src/core/json/parser.h index 3a73c67eca..643856b182 100644 --- a/src/core/json/parser.h +++ b/src/core/json/parser.h @@ -12,6 +12,8 @@ #include // std::size_t #include // std::uint64_t, std::uint32_t, std::uint8_t #include // std::memcpy +#include // std::numeric_limits +#include // std::cmp_greater #include // std::vector namespace sourcemeta::core { @@ -507,6 +509,15 @@ inline auto scan_json(const char *&cursor, const char *end, std::uint64_t &column, std::vector &tape) -> void { using CharT = JSON::Char; + // A tape entry addresses the input with 32-bit offsets and lengths, so an + // input past what those carry cannot be written down without truncation + if (std::cmp_greater(end - cursor, std::numeric_limits::max())) + [[unlikely]] { + throw JSONParseError(line, column); + } + + tape.reserve(static_cast(end - cursor) / 8); + char character = 0; std::vector container_stack; container_stack.reserve(32); diff --git a/test/json/json_parse_error_test.cc b/test/json/json_parse_error_test.cc index e2dcfa8786..4e8248a055 100644 --- a/test/json/json_parse_error_test.cc +++ b/test/json/json_parse_error_test.cc @@ -2,9 +2,12 @@ #include #include -#include -#include -#include +#include // std::uint32_t, std::uintmax_t +#include // std::exception +#include // std::filesystem +#include // std::numeric_limits +#include // std::istringstream +#include // std::string #include // std::string_view using namespace std::literals::string_view_literals; @@ -845,3 +848,23 @@ TEST(number_with_an_exponent_beyond_the_decimal_range) { EXPECT_EQ(error.column(), 1); } } + +// The scanner writes what it reads onto a tape whose entries address the +// input with 32-bit offsets and lengths, so an input past what those carry is +// turned down before any of it is read. The file behind it is left sparse and +// mapped rather than filled, since nothing ever looks at what it holds +TEST(input_beyond_what_a_tape_entry_can_address) { + const sourcemeta::core::TemporaryDirectory staging{ + std::filesystem::temp_directory_path(), ".sourcemeta-core-json-"}; + const auto path{staging.path() / "oversized.json"}; + sourcemeta::core::write_file(path, ""); + std::filesystem::resize_file( + path, + static_cast(std::numeric_limits::max()) + + 1); + + const sourcemeta::core::FileView view{path}; + const std::string_view input{view.as(), view.size()}; + EXPECT_FALSE(sourcemeta::core::try_parse_json(input).has_value()); + EXPECT_PARSE_ERROR(input, 1, 0); +} From bd0b744fece860e85b0b3d8153356e8dd1467a51 Mon Sep 17 00:00:00 2001 From: Juan Cruz Viotti Date: Wed, 14 Oct 2026 20:14:14 -0300 Subject: [PATCH 2/3] More Signed-off-by: Juan Cruz Viotti --- src/core/json/include/sourcemeta/core/json.h | 25 ++++++++-- src/core/json/json.cc | 50 ++++++++++++++------ src/core/json/parser.h | 9 ---- test/json/json_parse_error_test.cc | 42 ++++++++-------- 4 files changed, 79 insertions(+), 47 deletions(-) diff --git a/src/core/json/include/sourcemeta/core/json.h b/src/core/json/include/sourcemeta/core/json.h index c1f06321ce..087e8193d3 100644 --- a/src/core/json/include/sourcemeta/core/json.h +++ b/src/core/json/include/sourcemeta/core/json.h @@ -14,12 +14,14 @@ #include -#include // std::uint64_t +#include // std::size_t +#include // std::uint64_t, std::uint32_t #include // std::filesystem #include // std::formatter, std::format_context, std::format_parse_context, std::format_to #include // std::basic_ifstream #include // std::initializer_list #include // std::basic_istream +#include // std::numeric_limits #include // std::optional #include // std::basic_ostream #include // std::ostringstream @@ -37,6 +39,13 @@ namespace sourcemeta::core { +/// @ingroup json +/// The most input bytes accepted when a caller names no bound of its own, +/// which is what the offsets the parser addresses its input through can reach, +/// so a caller may name a smaller bound but never a larger one. +inline constexpr std::size_t JSON_MAXIMUM_INPUT_BYTES{ + std::numeric_limits::max()}; + /// @ingroup json /// /// Create a JSON document from a C++ standard input stream. For example, a JSON @@ -87,9 +96,14 @@ auto parse_json(std::basic_istream &stream) /// parser produces is valid UTF-8. Rejecting it is a deliberate exercise of the /// RFC 8259 Section 9 allowance that an implementation may set limits on the /// character contents of strings. +/// +/// That same allowance covers a limit on how large a text may be, so a caller +/// holding an input it does not trust may hold the parse to a bound of its +/// own, which is answered with the error above. SOURCEMETA_CORE_JSON_EXPORT auto parse_json( - const std::basic_string_view input) -> JSON; + const std::basic_string_view input, + const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> JSON; /// @ingroup json /// @@ -105,9 +119,14 @@ auto parse_json( /// assert(document.value().is_array()); /// assert(!sourcemeta::core::try_parse_json("[ 1, 2,").has_value()); /// ``` +/// +/// RFC 8259 Section 9 allows an implementation to set limits on the size of +/// the texts it accepts, so a caller holding an input it does not trust may +/// hold the parse to a bound of its own, which is answered with no value. SOURCEMETA_CORE_JSON_EXPORT auto try_parse_json( - const std::basic_string_view input) + const std::basic_string_view input, + const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> std::optional; /// @ingroup json diff --git a/src/core/json/json.cc b/src/core/json/json.cc index b56607cb0e..821bcb3255 100644 --- a/src/core/json/json.cc +++ b/src/core/json/json.cc @@ -8,13 +8,15 @@ #include "parser.h" #include "stringify.h" +#include // std::min +#include // std::size_t #include // std::uint64_t #include // std::filesystem #include // std::basic_istream #include // std::optional, std::nullopt #include // std::basic_ostream #include // std::conditional_t -#include // std::move, std::unreachable +#include // std::cmp_greater, std::move, std::unreachable #include // std::vector namespace sourcemeta::core { @@ -23,11 +25,23 @@ template static auto internal_parse_json(const char *&cursor, const char *end, std::uint64_t &line, std::uint64_t &column, const JSON::ParseCallback &callback, - [[maybe_unused]] const bool track_positions, JSON &output) + [[maybe_unused]] const bool track_positions, + const std::size_t maximum_input_bytes, JSON &output) -> std::conditional_t { const char *buffer_start{cursor}; std::vector tape; + // A tape entry addresses the input through 32-bit offsets and lengths, so + // what a caller names only ever tightens the reach those offsets have + if (std::cmp_greater(end - cursor, std::min(maximum_input_bytes, + JSON_MAXIMUM_INPUT_BYTES))) { + if constexpr (ShouldThrow) { + throw JSONParseError(line, column); + } else { + return false; + } + } + if constexpr (ShouldThrow) { if (callback || track_positions) { scan_json(cursor, end, buffer_start, line, column, tape); @@ -75,12 +89,13 @@ internal_parse_json(const char *&cursor, const char *end, std::uint64_t &line, } } -static auto internal_parse_json(const char *&cursor, const char *end, - std::uint64_t &line, std::uint64_t &column, - const bool track_positions) -> JSON { +static auto internal_parse_json( + const char *&cursor, const char *end, std::uint64_t &line, + std::uint64_t &column, const bool track_positions, + const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> JSON { JSON output{nullptr}; internal_parse_json(cursor, end, line, column, nullptr, track_positions, - output); + maximum_input_bytes, output); return output; } @@ -160,13 +175,15 @@ auto parse_json(std::basic_istream &stream) } auto parse_json( - const std::basic_string_view input) -> JSON { + const std::basic_string_view input, + const std::size_t maximum_input_bytes) -> JSON { std::uint64_t line{1}; std::uint64_t column{0}; const char *begin{input.empty() ? "" : input.data()}; const char *cursor{begin}; const char *end{cursor + input.size()}; - auto result{internal_parse_json(cursor, end, line, column, false)}; + auto result{internal_parse_json(cursor, end, line, column, false, + maximum_input_bytes)}; const char *trailing{skip_trailing_whitespace(cursor, end)}; if (trailing != end) { position_of(begin, trailing, line, column); @@ -177,15 +194,15 @@ auto parse_json( } auto try_parse_json( - const std::basic_string_view input) - -> std::optional { + const std::basic_string_view input, + const std::size_t maximum_input_bytes) -> std::optional { std::uint64_t line{1}; std::uint64_t column{0}; const char *cursor{input.empty() ? "" : input.data()}; const char *end{cursor + input.size()}; JSON output{nullptr}; if (internal_parse_json(cursor, end, line, column, nullptr, false, - output) && + maximum_input_bytes, output) && skip_trailing_whitespace(cursor, end) == end) { return output; } @@ -210,7 +227,8 @@ auto parse_json(std::basic_istream &stream, const auto input{read_to_string(stream)}; const char *cursor{input.data()}; const char *end{input.data() + input.size()}; - internal_parse_json(cursor, end, line, column, callback, true, output); + internal_parse_json(cursor, end, line, column, callback, true, + JSON_MAXIMUM_INPUT_BYTES, output); resume_stream(stream, start_position, static_cast(cursor - input.data())); } @@ -222,7 +240,7 @@ auto parse_json( // Continuation-style overload: see the note on the non-callback variant const char *cursor{input.empty() ? "" : input.data()}; internal_parse_json(cursor, cursor + input.size(), line, column, - callback, true, output); + callback, true, JSON_MAXIMUM_INPUT_BYTES, output); } // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) @@ -234,7 +252,8 @@ auto parse_json(std::basic_istream &stream, const char *end{input.data() + input.size()}; std::uint64_t line{1}; std::uint64_t column{0}; - internal_parse_json(cursor, end, line, column, callback, false, output); + internal_parse_json(cursor, end, line, column, callback, false, + JSON_MAXIMUM_INPUT_BYTES, output); resume_stream(stream, start_position, static_cast(cursor - input.data())); } @@ -250,7 +269,8 @@ auto parse_json( // Parse into a temporary so that a trailing-content failure leaves the output // untouched, matching how a malformed value fails before ever populating it JSON result{nullptr}; - internal_parse_json(cursor, end, line, column, callback, false, result); + internal_parse_json(cursor, end, line, column, callback, false, + JSON_MAXIMUM_INPUT_BYTES, result); const char *trailing{skip_trailing_whitespace(cursor, end)}; if (trailing != end) { position_of(begin, trailing, line, column); diff --git a/src/core/json/parser.h b/src/core/json/parser.h index 643856b182..44b0b5c747 100644 --- a/src/core/json/parser.h +++ b/src/core/json/parser.h @@ -12,8 +12,6 @@ #include // std::size_t #include // std::uint64_t, std::uint32_t, std::uint8_t #include // std::memcpy -#include // std::numeric_limits -#include // std::cmp_greater #include // std::vector namespace sourcemeta::core { @@ -509,13 +507,6 @@ inline auto scan_json(const char *&cursor, const char *end, std::uint64_t &column, std::vector &tape) -> void { using CharT = JSON::Char; - // A tape entry addresses the input with 32-bit offsets and lengths, so an - // input past what those carry cannot be written down without truncation - if (std::cmp_greater(end - cursor, std::numeric_limits::max())) - [[unlikely]] { - throw JSONParseError(line, column); - } - tape.reserve(static_cast(end - cursor) / 8); char character = 0; diff --git a/test/json/json_parse_error_test.cc b/test/json/json_parse_error_test.cc index 4e8248a055..db3157a37b 100644 --- a/test/json/json_parse_error_test.cc +++ b/test/json/json_parse_error_test.cc @@ -2,10 +2,8 @@ #include #include -#include // std::uint32_t, std::uintmax_t #include // std::exception #include // std::filesystem -#include // std::numeric_limits #include // std::istringstream #include // std::string #include // std::string_view @@ -849,22 +847,26 @@ TEST(number_with_an_exponent_beyond_the_decimal_range) { } } -// The scanner writes what it reads onto a tape whose entries address the -// input with 32-bit offsets and lengths, so an input past what those carry is -// turned down before any of it is read. The file behind it is left sparse and -// mapped rather than filled, since nothing ever looks at what it holds -TEST(input_beyond_what_a_tape_entry_can_address) { - const sourcemeta::core::TemporaryDirectory staging{ - std::filesystem::temp_directory_path(), ".sourcemeta-core-json-"}; - const auto path{staging.path() / "oversized.json"}; - sourcemeta::core::write_file(path, ""); - std::filesystem::resize_file( - path, - static_cast(std::numeric_limits::max()) + - 1); - - const sourcemeta::core::FileView view{path}; - const std::string_view input{view.as(), view.size()}; - EXPECT_FALSE(sourcemeta::core::try_parse_json(input).has_value()); - EXPECT_PARSE_ERROR(input, 1, 0); +// The parser addresses its input through 32-bit offsets, which is a reach no +// caller can widen, but a caller holding an input it does not trust may hold +// the parse to a smaller one of its own +TEST(input_past_the_bound_the_caller_allows) { + try { + sourcemeta::core::parse_json("[ 1, 2, 3 ]", 8); + FAIL(); + } catch (const sourcemeta::core::JSONParseError &error) { + EXPECT_STREQ(error.what(), "Failed to parse the JSON document"); + EXPECT_EQ(error.line(), 1); + EXPECT_EQ(error.column(), 0); + } catch (const std::exception &) { + FAIL(); + } + + EXPECT_EQ(sourcemeta::core::parse_json("[ 1, 2, 3 ]", 11), + sourcemeta::core::parse_json("[ 1, 2, 3 ]")); +} + +TEST(input_past_the_bound_the_caller_allows_without_throwing) { + EXPECT_FALSE(sourcemeta::core::try_parse_json("[ 1, 2, 3 ]", 8).has_value()); + EXPECT_TRUE(sourcemeta::core::try_parse_json("[ 1, 2, 3 ]", 11).has_value()); } From 8b017bda331c67174ad95ddee3f18da60084cc71 Mon Sep 17 00:00:00 2001 From: Juan Cruz Viotti Date: Wed, 14 Oct 2026 20:27:25 -0300 Subject: [PATCH 3/3] Fix Signed-off-by: Juan Cruz Viotti --- src/core/json/include/sourcemeta/core/json.h | 11 +++++----- src/core/json/json.cc | 21 +++++++++---------- .../include/sourcemeta/core/markdown.h | 9 ++++---- src/core/markdown/markdown.cc | 12 +++++------ 4 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/core/json/include/sourcemeta/core/json.h b/src/core/json/include/sourcemeta/core/json.h index 087e8193d3..064daa8ec9 100644 --- a/src/core/json/include/sourcemeta/core/json.h +++ b/src/core/json/include/sourcemeta/core/json.h @@ -41,9 +41,10 @@ namespace sourcemeta::core { /// @ingroup json /// The most input bytes accepted when a caller names no bound of its own, -/// which is what the offsets the parser addresses its input through can reach, -/// so a caller may name a smaller bound but never a larger one. -inline constexpr std::size_t JSON_MAXIMUM_INPUT_BYTES{ +/// which is what the offsets the parser addresses its input through can +/// reach. A bound is carried in as many bits as those offsets, so a caller +/// may name a smaller one and has no way to name a larger one. +inline constexpr std::uint32_t JSON_MAXIMUM_INPUT_BYTES{ std::numeric_limits::max()}; /// @ingroup json @@ -103,7 +104,7 @@ auto parse_json(std::basic_istream &stream) SOURCEMETA_CORE_JSON_EXPORT auto parse_json( const std::basic_string_view input, - const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> JSON; + const std::uint32_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> JSON; /// @ingroup json /// @@ -126,7 +127,7 @@ auto parse_json( SOURCEMETA_CORE_JSON_EXPORT auto try_parse_json( const std::basic_string_view input, - const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) + const std::uint32_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> std::optional; /// @ingroup json diff --git a/src/core/json/json.cc b/src/core/json/json.cc index 821bcb3255..aa2368d00c 100644 --- a/src/core/json/json.cc +++ b/src/core/json/json.cc @@ -8,9 +8,7 @@ #include "parser.h" #include "stringify.h" -#include // std::min -#include // std::size_t -#include // std::uint64_t +#include // std::uint64_t, std::uint32_t #include // std::filesystem #include // std::basic_istream #include // std::optional, std::nullopt @@ -26,15 +24,15 @@ static auto internal_parse_json(const char *&cursor, const char *end, std::uint64_t &line, std::uint64_t &column, const JSON::ParseCallback &callback, [[maybe_unused]] const bool track_positions, - const std::size_t maximum_input_bytes, JSON &output) + const std::uint32_t maximum_input_bytes, JSON &output) -> std::conditional_t { const char *buffer_start{cursor}; std::vector tape; - // A tape entry addresses the input through 32-bit offsets and lengths, so - // what a caller names only ever tightens the reach those offsets have - if (std::cmp_greater(end - cursor, std::min(maximum_input_bytes, - JSON_MAXIMUM_INPUT_BYTES))) { + // A tape entry addresses the input through 32-bit offsets and lengths, + // which is as many bits as the bound is carried in, so what a caller names + // only ever tightens the reach those offsets have + if (std::cmp_greater(end - cursor, maximum_input_bytes)) { if constexpr (ShouldThrow) { throw JSONParseError(line, column); } else { @@ -92,7 +90,8 @@ internal_parse_json(const char *&cursor, const char *end, std::uint64_t &line, static auto internal_parse_json( const char *&cursor, const char *end, std::uint64_t &line, std::uint64_t &column, const bool track_positions, - const std::size_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) -> JSON { + const std::uint32_t maximum_input_bytes = JSON_MAXIMUM_INPUT_BYTES) + -> JSON { JSON output{nullptr}; internal_parse_json(cursor, end, line, column, nullptr, track_positions, maximum_input_bytes, output); @@ -176,7 +175,7 @@ auto parse_json(std::basic_istream &stream) auto parse_json( const std::basic_string_view input, - const std::size_t maximum_input_bytes) -> JSON { + const std::uint32_t maximum_input_bytes) -> JSON { std::uint64_t line{1}; std::uint64_t column{0}; const char *begin{input.empty() ? "" : input.data()}; @@ -195,7 +194,7 @@ auto parse_json( auto try_parse_json( const std::basic_string_view input, - const std::size_t maximum_input_bytes) -> std::optional { + const std::uint32_t maximum_input_bytes) -> std::optional { std::uint64_t line{1}; std::uint64_t column{0}; const char *cursor{input.empty() ? "" : input.data()}; diff --git a/src/core/markdown/include/sourcemeta/core/markdown.h b/src/core/markdown/include/sourcemeta/core/markdown.h index 2dd374aa63..2baf6a449f 100644 --- a/src/core/markdown/include/sourcemeta/core/markdown.h +++ b/src/core/markdown/include/sourcemeta/core/markdown.h @@ -29,9 +29,10 @@ namespace sourcemeta::core { /// @ingroup markdown /// The most input bytes accepted when a caller names no bound of its own, -/// which is what the offsets the parser addresses its input through can reach, -/// so a caller may name a smaller bound but never a larger one. -inline constexpr std::size_t MARKDOWN_MAXIMUM_INPUT_BYTES{ +/// which is what the offsets the parser addresses its input through can +/// reach. A bound is carried in as many bits as those offsets, so a caller +/// may name a smaller one and has no way to name a larger one. +inline constexpr std::uint32_t MARKDOWN_MAXIMUM_INPUT_BYTES{ std::numeric_limits::max()}; /// @ingroup markdown @@ -60,7 +61,7 @@ inline constexpr std::size_t MARKDOWN_MAXIMUM_INPUT_BYTES{ /// ``` SOURCEMETA_CORE_MARKDOWN_EXPORT auto markdown_to_html(const std::string_view input, const bool safe = true, - std::size_t maximum_input_bytes = + std::uint32_t maximum_input_bytes = MARKDOWN_MAXIMUM_INPUT_BYTES) -> std::string; } // namespace sourcemeta::core diff --git a/src/core/markdown/markdown.cc b/src/core/markdown/markdown.cc index 37e1340192..9ab334c233 100644 --- a/src/core/markdown/markdown.cc +++ b/src/core/markdown/markdown.cc @@ -9,8 +9,8 @@ #include "postprocess.h" #include "render.h" -#include // std::min #include // std::size_t +#include // std::uint32_t #include // std::optional #include // std::string #include // std::string_view @@ -60,7 +60,7 @@ auto replace_invalid_characters(const std::string_view input, namespace sourcemeta::core { auto markdown_to_html(const std::string_view input, const bool safe, - const std::size_t maximum_input_bytes) -> std::string { + const std::uint32_t maximum_input_bytes) -> std::string { thread_local std::optional state; if (!state.has_value()) { state.emplace(); @@ -79,10 +79,10 @@ auto markdown_to_html(const std::string_view input, const bool safe, source = converter.repaired; } - // The parser addresses the input through 32-bit offsets, so what a caller - // names only ever tightens the reach those offsets have - if (source.size() > - std::min(maximum_input_bytes, MARKDOWN_MAXIMUM_INPUT_BYTES)) { + // The parser addresses the input through 32-bit offsets, which is as many + // bits as the bound is carried in, so what a caller names only ever + // tightens the reach those offsets have + if (source.size() > maximum_input_bytes) { throw MarkdownError{"The input is larger than the supported size bound"}; }