Skip to content

Hardening: add null guards, bounds checks, and return correctness to allocators, vector iterators, and stl emulation - #9369

Open
anagnorisis2peripeteia wants to merge 1 commit into
google:masterfrom
anagnorisis2peripeteia:fix-stl-emulation-vector-and-allocator-safety
Open

anagnorisis2peripeteia wants to merge 1 commit into
google:masterfrom
anagnorisis2peripeteia:fix-stl-emulation-vector-and-allocator-safety

Conversation

@anagnorisis2peripeteia

Copy link
Copy Markdown

Description

This PR strengthens defensive engineering across FlatBuffers memory allocation, vector iterators, and STL emulation utilities:

  1. include/flatbuffers/allocator.h:

    • Check if allocate(new_size) returns nullptr before performing downward copies and deallocating in reallocate_downward.
    • In memcpy_downward, verify pointers (new_p, old_p) are non-null and copy counts (in_use_back, in_use_front) are non-zero before invoking memcpy to avoid undefined behavior.
  2. include/flatbuffers/default_allocator.h:

    • Guard against zero-byte allocation in allocate(size) (size ? new uint8_t[size] : nullptr).
    • Add null checks before calling array delete[] in deallocate, dealloc, and helper Deallocate.
  3. include/flatbuffers/stl_emulation.h:

    • Fix missing return *this; in span::operator=(const span &other) which previously fell off the end of a value-returning function (undefined behavior).
    • Change pointer const data_; in span to pointer data_; so copy assignment can actually rebind the data pointer as specified.
    • Add mutable operator*, operator->, and mutable value() overloads to Optional matching standard std::optional semantics.
  4. include/flatbuffers/vector.h:

    • In VectorIterator, avoid null pointer arithmetic (nullptr + offset) during construction and iterator offset operations.
    • In VectorIterator::operator-, check for element_stride != 0 before division to avoid division by zero.
    • In Vector::LookupByKey, return nullptr immediately if size() == 0 rather than executing binary search on empty ranges.
    • In Vector::KeyCompare, add null guards for key, data, and table before dereference.
    • Fix copy-paste issue in make_structs_span pointers overloads where make_span was invoked instead of make_structs_span.
    • In VectorCast, check for nullptr before reinterpret casting.
  5. tests/test.cpp:

    • Added unit test StlEmulationAndVectorSafetyTest() validating Optional, span assignment, VectorIterator, VectorCast, and null-safe allocator behaviors.

All tests compile cleanly under -DFLATBUFFERS_STRICT_MODE=ON and pass with flattests and flatc_cpp_tests.py.

…allocators, vector iterators, and stl emulation

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant