Fix begin iterator for empty arrays.

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
pull/15252/head
Protobuf Team Bot 1 year ago committed by Copybara-Service
parent df57e5474b
commit 670e0c2a0d
  1. 8
      protos/repeated_field.h
  2. 14
      protos_generator/tests/test_generated.cc

@ -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()); }

@ -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>
@ -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);

Loading…
Cancel
Save