diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 596ad0ae9..a081aa5ae 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -103,6 +103,13 @@ class BitReader { return true; } + // After align(), take up to length bytes, including the available prefix at EOF. + std::span take_aligned(std::size_t length) { + const auto bytes = in_.subspan(pos_, std::min(length, in_.size() - pos_)); + pos_ += bytes.size(); + return bytes; + } + std::size_t position() const { return pos_ - std::size_t(count_ / 8); } bool failed() const { return failed_; } @@ -285,11 +292,9 @@ inline bool zlib_inflate(std::span in, std::vector limit || length > limit - out.size()) return fail(ZlibError::limit); - for (unsigned i = 0; i < length; ++i) { - std::uint8_t x; - if (!reader.byte(x)) return fail(ZlibError::data); - out.push_back(x); - } + const auto payload = reader.take_aligned(length); + out.insert(out.end(), payload.begin(), payload.end()); + if (payload.size() != length) return fail(ZlibError::data); } else if (type == 1) { // fixed Huffman static const auto tables = [] { std::pair t; diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 55105d987..84c7baf03 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -308,6 +308,7 @@ int huffman_lut_checks() { w.write_byte(std::uint8_t(n >> 8)); w.write_byte(std::uint8_t(nlen)); w.write_byte(std::uint8_t(nlen >> 8)); + const std::size_t payload_at = w.bytes.size(); for (char c : mid) { w.write_byte(std::uint8_t(c)); expected.push_back(std::uint8_t(c)); @@ -326,7 +327,16 @@ int huffman_lut_checks() { CHECK(zlib_inflate(w.bytes, out, expected.size()) && out == expected); for (std::size_t cut = 0; cut < w.bytes.size(); ++cut) { std::vector trunc(w.bytes.begin(), w.bytes.begin() + cut); - CHECK(!zlib_inflate(trunc, out, expected.size())); + ZlibError why{}; + CHECK(!zlib_inflate(trunc, out, expected.size(), &why)); + if (cut >= payload_at && cut < payload_at + n) { + CHECK(why == ZlibError::data); + const auto prefix_end = expected.begin() + k + (cut - payload_at); + CHECK(std::equal(out.begin(), out.end(), expected.begin(), prefix_end)); + // The output limit applies to the whole declared block before consuming its payload. + CHECK(!zlib_inflate(trunc, out, k + n - 1, &why) && why == ZlibError::limit); + CHECK(std::equal(out.begin(), out.end(), expected.begin(), expected.begin() + k)); + } } } }