google / flatbuffers

FlatBuffers: Memory Efficient Serialization Library

Home Page:https://flatbuffers.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[C++] Verification of size prefixed flatbuffers with reflection fails in VerifyAlignment

stefan301 opened this issue · comments

We use reflection to Verify size prefixed flatbuffers quite a while. Because there is no VerifySizePrefixed we initialized the Verifier with the address after the size prefix and the buffer size - sizeof(uoffset_t). This worked until we upgraded from 2.0.0 to 2.0.6.
Now this fails in VerifyAlignment.

We had some generated Code using the same pattern - VerifyXxxBuffer and a Verifier initialized without the size prefix instead of VerifySizePrefixedXxxBuffer and the full buffer. This code also failed in VerifyAlignment.
Changing this code to VerifySizePrefixedXxxBuffer fixed the problem here.
So I think this code was never correct.

I added a VerifySizePrefixed and a GetAnySizePrefixedRoot to solve the reflection problem.

inline Table *GetAnySizePrefixedRoot(uint8_t *flatbuf) {
  return GetMutableSizePrefixedRoot<Table>(flatbuf);
}

inline const Table *GetAnySizePrefixedRoot(const uint8_t *flatbuf) {
  return GetSizePrefixedRoot<Table>(flatbuf);
}

bool VerifySizePrefixed(const reflection::Schema &schema,
                        const reflection::Object &root, const uint8_t *buf,
                        size_t length, uoffset_t max_depth /*= 64*/,
                        uoffset_t max_tables /*= 1000000*/) {
  Verifier v(buf, length, max_depth, max_tables);
  return VerifyObject(v, schema, root, flatbuffers::GetAnySizePrefixedRoot(buf),
                      true);
}

If there is interest, I could make a PR