Skip to content

fix: correct operator precedence in ForAllFields reverse iteration#8991

Open
Tulgaaaaaaaa wants to merge 2 commits intogoogle:masterfrom
Tulgaaaaaaaa:fix/oob-read-forallfields-reverse
Open

fix: correct operator precedence in ForAllFields reverse iteration#8991
Tulgaaaaaaaa wants to merge 2 commits intogoogle:masterfrom
Tulgaaaaaaaa:fix/oob-read-forallfields-reverse

Conversation

@Tulgaaaaaaaa
Copy link
Copy Markdown

@Tulgaaaaaaaa Tulgaaaaaaaa commented Mar 23, 2026

Problem

ForAllFields() in src/reflection.cpp:392 has an operator precedence bug when iterating fields in reverse order. The expression size() - i + 1 evaluates as (size() - i) + 1 due to C++ left-to-right associativity, instead of the intended size() - (i + 1).

For a 3-field object at i=0, this produces index 3 + 1 = 4, which is 2 past the last valid index (0, 1, 2). This causes an out-of-bounds read on every call to ForAllFields with reverse=true.

The correct expression size() - (i + 1) is already used in the parallel implementation at bfbs_gen.h:192.

Fix

Changed field_to_id_map.size() - i + 1 to field_to_id_map.size() - (i + 1) to match bfbs_gen.h.

i Before (buggy) After (fixed)
0 size()+1 (OOB) size()-1 (last)
1 size() (OOB) size()-2
2 size()-1 size()-3 (first)

Tests added

  • ForAllFieldsReverseTest in tests/reflection_test.cpp
  • Tests both Stat (3 fields) and Monster (many fields, non-sequential IDs) tables
  • Verifies correct forward and reverse ID ordering

The expression `size() - i + 1` evaluates as `(size() - i) + 1` due to
left-to-right associativity, producing an out-of-bounds index when
reverse=true. For a vector of size N, the first iteration (i=0) accesses
index N+1, which is 2 past the last valid index.

Changed to `size() - (i + 1)` to match the correct implementation
already present in bfbs_gen.h:192.

Bug: CWE-125 (Out-of-bounds Read), CWE-783 (Operator Precedence Error)
@google-cla
Copy link
Copy Markdown

google-cla bot commented Mar 23, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@github-actions github-actions bot added c++ codegen Involving generating code from schema labels Mar 23, 2026
Verify that ForAllFields with reverse=true iterates fields in
descending ID order. Tests both Stat (3 fields) and Monster
(many fields with non-sequential definition order) tables.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

c++ codegen Involving generating code from schema

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants