Skip to content

Commit

Permalink
Fix begin iterator for empty arrays.
Browse files Browse the repository at this point in the history
If the underlying array for a repeated field is a nullptr (which is possible for const array access on a message field that hasn't been set) the begin iterator will currently contain garbage data, which can lead to an illegal access. This CL adds a nullptr check to `begin()`, similar to what already exists for `size()`.

PiperOrigin-RevId: 595217999
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Jan 2, 2024
1 parent df57e54 commit 670e0c2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
8 changes: 5 additions & 3 deletions protos/repeated_field.h
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,11 @@ class RepeatedFieldProxy
}

iterator begin() const {
return iterator({static_cast<upb_Message**>(
const_cast<void*>(upb_Array_DataPtr(this->arr_))),
this->arena_});
return iterator(
{static_cast<upb_Message**>(
this->arr_ ? const_cast<void*>(upb_Array_DataPtr(this->arr_))
: nullptr),
this->arena_});
}
iterator end() const { return begin() + this->size(); }
reverse_iterator rbegin() const { return reverse_iterator(end()); }
Expand Down
14 changes: 14 additions & 0 deletions protos_generator/tests/test_generated.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd

#include <iterator>
#include <limits>
#include <memory>
#include <string>
Expand Down Expand Up @@ -571,6 +572,19 @@ TEST(CppGeneratedCode, RepeatedFieldProxyForMessages) {
EXPECT_EQ(test_model.mutable_child_models()->size(), 0);
}

TEST(CppGeneratedCode, EmptyRepeatedFieldProxyForMessages) {
::protos::Arena arena;
auto test_model = ::protos::CreateMessage<TestModel>(arena);
EXPECT_EQ(0, test_model.child_models().size());
ChildModel1 child1;
child1.set_child_str1(kTestStr1);

EXPECT_EQ(test_model.child_models().size(), 0);
EXPECT_EQ(std::distance(test_model.child_models().begin(),
test_model.child_models().end()),
0);
}

TEST(CppGeneratedCode, RepeatedFieldProxyForMessagesIndexOperator) {
::protos::Arena arena;
auto test_model = ::protos::CreateMessage<TestModel>(arena);
Expand Down

0 comments on commit 670e0c2

Please sign in to comment.