Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 45 additions & 15 deletions common/value.cc
Original file line number Diff line number Diff line change
Expand Up @@ -935,6 +935,9 @@ void BoolRepeatedFieldAccessor(
*result = BoolValue(reflection->GetRepeatedBool(*message, field, index));
}

// If `Unsafe` is `std::true_type`, elements are borrowed rather than copied to
// `arena`, as with `Value::WrapRepeatedFieldUnsafe`.
template <typename Unsafe>
void StringRepeatedFieldAccessor(
int index, const google::protobuf::Message* absl_nonnull message,
const google::protobuf::FieldDescriptor* absl_nonnull field,
Expand Down Expand Up @@ -964,20 +967,26 @@ void StringRepeatedFieldAccessor(
string.size() == scratch.size()) {
*result = StringValue::From(std::move(scratch), arena);
} else {
if (message->GetArena() == nullptr) {
*result = StringValue::From(string, arena);
if constexpr (Unsafe::value) {
*result = StringValue::WrapUnsafe(string);
} else {
*result = StringValue::Wrap(string, message->GetArena());
if (google::protobuf::Arena* message_arena = message->GetArena();
message_arena != nullptr) {
*result = StringValue::Wrap(string, message_arena);
} else {
*result = StringValue::From(string, arena);
}
}
}
},
[&](absl::Cord&& cord) {
*result = StringValue::From(std::move(cord), arena);
}),
well_known_types::AsVariant(well_known_types::GetRepeatedStringField(
*message, field, index, scratch)));
reflection, *message, field, index, scratch)));
}

template <typename Unsafe>
void MessageRepeatedFieldAccessor(
int index, const google::protobuf::Message* absl_nonnull message,
const google::protobuf::FieldDescriptor* absl_nonnull field,
Expand All @@ -999,11 +1008,18 @@ void MessageRepeatedFieldAccessor(
ABSL_DCHECK_GE(index, 0);
ABSL_DCHECK_LT(index, reflection->FieldSize(*message, field));

*result = Value::WrapMessage(
&reflection->GetRepeatedMessage(*message, field, index), descriptor_pool,
message_factory, arena);
if constexpr (Unsafe::value) {
*result = Value::WrapMessageUnsafe(
&reflection->GetRepeatedMessage(*message, field, index),
descriptor_pool, message_factory, arena);
} else {
*result = Value::WrapMessage(
&reflection->GetRepeatedMessage(*message, field, index),
descriptor_pool, message_factory, arena);
}
}

template <typename Unsafe>
void BytesRepeatedFieldAccessor(
int index, const google::protobuf::Message* absl_nonnull message,
const google::protobuf::FieldDescriptor* absl_nonnull field,
Expand Down Expand Up @@ -1033,18 +1049,23 @@ void BytesRepeatedFieldAccessor(
string.size() == scratch.size()) {
*result = BytesValue::From(std::move(scratch), arena);
} else {
if (message->GetArena() == nullptr) {
*result = BytesValue::From(string, arena);
if constexpr (Unsafe::value) {
*result = BytesValue::WrapUnsafe(string);
} else {
*result = BytesValue::Wrap(string, message->GetArena());
if (google::protobuf::Arena* message_arena = message->GetArena();
message_arena != nullptr) {
*result = BytesValue::Wrap(string, message_arena);
} else {
*result = BytesValue::From(string, arena);
}
}
}
},
[&](absl::Cord&& cord) {
*result = BytesValue::From(std::move(cord), arena);
}),
well_known_types::AsVariant(well_known_types::GetRepeatedBytesField(
*message, field, index, scratch)));
reflection, *message, field, index, scratch)));
}

void EnumRepeatedFieldAccessor(
Expand Down Expand Up @@ -1101,7 +1122,7 @@ void NullRepeatedFieldAccessor(
} // namespace

absl::StatusOr<RepeatedFieldAccessor> RepeatedFieldAccessorFor(
const google::protobuf::FieldDescriptor* absl_nonnull field) {
const google::protobuf::FieldDescriptor* absl_nonnull field, bool unsafe) {
switch (field->type()) {
case google::protobuf::FieldDescriptor::TYPE_DOUBLE:
return &DoubleRepeatedFieldAccessor;
Expand All @@ -1126,13 +1147,22 @@ absl::StatusOr<RepeatedFieldAccessor> RepeatedFieldAccessorFor(
case google::protobuf::FieldDescriptor::TYPE_BOOL:
return &BoolRepeatedFieldAccessor;
case google::protobuf::FieldDescriptor::TYPE_STRING:
return &StringRepeatedFieldAccessor;
if (unsafe) {
return &StringRepeatedFieldAccessor<std::true_type>;
}
return &StringRepeatedFieldAccessor<std::false_type>;
case google::protobuf::FieldDescriptor::TYPE_GROUP:
ABSL_FALLTHROUGH_INTENDED;
case google::protobuf::FieldDescriptor::TYPE_MESSAGE:
return &MessageRepeatedFieldAccessor;
if (unsafe) {
return &MessageRepeatedFieldAccessor<std::true_type>;
}
return &MessageRepeatedFieldAccessor<std::false_type>;
case google::protobuf::FieldDescriptor::TYPE_BYTES:
return &BytesRepeatedFieldAccessor;
if (unsafe) {
return &BytesRepeatedFieldAccessor<std::true_type>;
}
return &BytesRepeatedFieldAccessor<std::false_type>;
case google::protobuf::FieldDescriptor::TYPE_FIXED32:
ABSL_FALLTHROUGH_INTENDED;
case google::protobuf::FieldDescriptor::TYPE_UINT32:
Expand Down
5 changes: 4 additions & 1 deletion common/value.h
Original file line number Diff line number Diff line change
Expand Up @@ -2888,8 +2888,11 @@ using RepeatedFieldAccessor =
google::protobuf::MessageFactory* absl_nonnull, google::protobuf::Arena* absl_nonnull,
Value* absl_nonnull);

// If `unsafe` is true, message, string, and bytes elements are borrowed rather
// than copied, as with `Value::WrapRepeatedFieldUnsafe`. Caller is responsible
// for ensuring the resulting values do not outlive the input message.
absl::StatusOr<RepeatedFieldAccessor> RepeatedFieldAccessorFor(
const google::protobuf::FieldDescriptor* absl_nonnull field);
const google::protobuf::FieldDescriptor* absl_nonnull field, bool unsafe = false);

} // namespace common_internal

Expand Down
12 changes: 7 additions & 5 deletions common/values/parsed_repeated_field_value.cc
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ absl::Status ParsedRepeatedFieldValue::Get(
*result = IndexOutOfBoundsError(index, arena);
return absl::OkStatus();
}
if (arena_ == nullptr) {
if (is_unsafe()) {
*result = Value::WrapRepeatedFieldUnsafe(static_cast<int>(index), message_,
field_, descriptor_pool,
message_factory, arena);
Expand All @@ -274,7 +274,8 @@ absl::Status ParsedRepeatedFieldValue::ForEach(
const int size = reflection->FieldSize(*message_, field_);
if (size > 0) {
CEL_ASSIGN_OR_RETURN(auto accessor,
common_internal::RepeatedFieldAccessorFor(field_));
common_internal::RepeatedFieldAccessorFor(
field_, /*unsafe=*/is_unsafe()));
Value scratch;
for (int i = 0; i < size; ++i) {
(*accessor)(i, message_, field_, reflection, descriptor_pool,
Expand Down Expand Up @@ -377,8 +378,8 @@ ParsedRepeatedFieldValue::NewIterator() const {
if (ABSL_PREDICT_FALSE(field_ == nullptr)) {
return NewEmptyValueIterator();
}
CEL_ASSIGN_OR_RETURN(auto accessor,
common_internal::RepeatedFieldAccessorFor(field_));
CEL_ASSIGN_OR_RETURN(auto accessor, common_internal::RepeatedFieldAccessorFor(
field_, /*unsafe=*/is_unsafe()));
return std::make_unique<ParsedRepeatedFieldValueIterator>(message_, field_,
accessor);
}
Expand All @@ -397,7 +398,8 @@ absl::Status ParsedRepeatedFieldValue::Contains(
const int size = reflection->FieldSize(*message_, field_);
if (size > 0) {
CEL_ASSIGN_OR_RETURN(auto accessor,
common_internal::RepeatedFieldAccessorFor(field_));
common_internal::RepeatedFieldAccessorFor(
field_, /*unsafe=*/is_unsafe()));
Value scratch;
for (int i = 0; i < size; ++i) {
(*accessor)(i, message_, field_, reflection, descriptor_pool,
Expand Down
7 changes: 6 additions & 1 deletion common/values/parsed_repeated_field_value.h
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class ParsedRepeatedFieldValue final

ParsedRepeatedFieldValue(const google::protobuf::Message* absl_nonnull message,
const google::protobuf::FieldDescriptor* absl_nonnull field)
: message_(message), field_(field), arena_(message->GetArena()) {
: message_(message), field_(field), arena_(nullptr) {
ABSL_DCHECK(message != nullptr);
ABSL_DCHECK(field != nullptr);
ABSL_DCHECK(field_->is_repeated() && !field_->is_map())
Expand All @@ -193,10 +193,15 @@ class ParsedRepeatedFieldValue final
return absl::OkStatus();
}

bool is_unsafe() const { return arena_ == nullptr; }

const google::protobuf::Reflection* absl_nonnull GetReflection() const;

const google::protobuf::Message* absl_nullable message_ = nullptr;
const google::protobuf::FieldDescriptor* absl_nullable field_ = nullptr;
// The arena attributed as owning this value. Null if the value is created by
// UnsafeParsedRepeatedFieldValue(), indicating an externally managed message
// whose elements should be borrowed rather than copied.
google::protobuf::Arena* absl_nullable arena_ = nullptr;
};

Expand Down
106 changes: 106 additions & 0 deletions common/values/parsed_repeated_field_value_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

#include <cstddef>
#include <optional>
#include <string>
#include <utility>
#include <vector>

Expand All @@ -23,6 +24,7 @@
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "absl/types/optional.h"
#include "cel/expr/conformance/proto3/test_all_types.pb.h"
#include "common/memory.h"
#include "common/type.h"
Expand Down Expand Up @@ -416,6 +418,110 @@ TEST_F(ParsedRepeatedFieldValueTest, NewIterator2) {
IsOkAndHolds(Eq(std::nullopt)));
}

TEST_F(ParsedRepeatedFieldValueTest, GetUnsafeDifferentArenaBorrowsMessages) {
google::protobuf::Arena source_arena;
auto* message = google::protobuf::Arena::Create<TestAllTypesProto3>(&source_arena);
message->add_repeated_nested_message()->set_bb(1);
ParsedRepeatedFieldValue value = UnsafeParsedRepeatedFieldValue(
message, TestAllTypesProto3::descriptor()->FindFieldByName(
"repeated_nested_message"));
ASSERT_OK_AND_ASSIGN(Value element, value.Get(0, descriptor_pool(),
message_factory(), arena()));
ASSERT_TRUE(element.IsParsedMessage());
EXPECT_EQ(cel::to_address(element.GetParsedMessage()),
&message->repeated_nested_message(0));
EXPECT_EQ(arena()->SpaceUsed(), 0);
}

TEST_F(ParsedRepeatedFieldValueTest, NewIteratorUnsafeBorrowsMessages) {
TestAllTypesProto3 heap_message;
heap_message.add_repeated_nested_message()->set_bb(1);
heap_message.add_repeated_nested_message()->set_bb(2);

google::protobuf::Arena source_arena;
auto* arena_message =
google::protobuf::Arena::Create<TestAllTypesProto3>(&source_arena);
arena_message->CopyFrom(heap_message);

for (const TestAllTypesProto3* message : {&heap_message, arena_message}) {
ParsedRepeatedFieldValue value = UnsafeParsedRepeatedFieldValue(
message, TestAllTypesProto3::descriptor()->FindFieldByName(
"repeated_nested_message"));
ASSERT_OK_AND_ASSIGN(auto iterator, value.NewIterator());
for (int i = 0; i < 2; ++i) {
SCOPED_TRACE(i);
ASSERT_OK_AND_ASSIGN(
auto element,
iterator->Next1(descriptor_pool(), message_factory(), arena()));
ASSERT_TRUE(element.has_value());
ASSERT_TRUE(element->IsParsedMessage());
EXPECT_EQ(cel::to_address(element->GetParsedMessage()),
&message->repeated_nested_message(i));
}
}
EXPECT_EQ(arena()->SpaceUsed(), 0);
}

TEST_F(ParsedRepeatedFieldValueTest, ForEachUnsafeBorrowsStringsAndBytes) {
TestAllTypesProto3 heap_message;
heap_message.add_repeated_string(std::string(64, 'a'));
heap_message.add_repeated_bytes(std::string(64, 'b'));

google::protobuf::Arena source_arena;
auto* arena_message =
google::protobuf::Arena::Create<TestAllTypesProto3>(&source_arena);
arena_message->CopyFrom(heap_message);

for (const TestAllTypesProto3* message : {&heap_message, arena_message}) {
std::vector<absl::optional<absl::string_view>> flat;
for (absl::string_view field_name : {"repeated_string", "repeated_bytes"}) {
ParsedRepeatedFieldValue value = UnsafeParsedRepeatedFieldValue(
message,
TestAllTypesProto3::descriptor()->FindFieldByName(field_name));
EXPECT_THAT(value.ForEach(
[&](const Value& element) -> absl::StatusOr<bool> {
if (element.IsString()) {
flat.push_back(element.GetString().TryFlat());
} else {
flat.push_back(element.GetBytes().TryFlat());
}
return true;
},
descriptor_pool(), message_factory(), arena()),
IsOk());
}
ASSERT_THAT(flat, ElementsAre(Optional(_), Optional(_)));
EXPECT_EQ(flat[0]->data(), message->repeated_string(0).data());
EXPECT_EQ(flat[1]->data(), message->repeated_bytes(0).data());
}
EXPECT_EQ(arena()->SpaceUsed(), 0);
}

TEST_F(ParsedRepeatedFieldValueTest, ContainsUnsafeBorrowsElements) {
google::protobuf::Arena source_arena;
auto* message = google::protobuf::Arena::Create<TestAllTypesProto3>(&source_arena);
message->add_repeated_string(std::string(64, 'a'));
message->add_repeated_nested_message()->set_bb(42);

ParsedRepeatedFieldValue strings = UnsafeParsedRepeatedFieldValue(
message,
TestAllTypesProto3::descriptor()->FindFieldByName("repeated_string"));
const std::string target_str(64, 'a');
EXPECT_THAT(strings.Contains(StringValue::WrapUnsafe(target_str),
descriptor_pool(), message_factory(), arena()),
IsOkAndHolds(BoolValueIs(true)));

TestAllTypesProto3::NestedMessage target_msg;
target_msg.set_bb(42);
ParsedRepeatedFieldValue messages = UnsafeParsedRepeatedFieldValue(
message, TestAllTypesProto3::descriptor()->FindFieldByName(
"repeated_nested_message"));
EXPECT_THAT(messages.Contains(UnsafeParsedMessageValue(&target_msg),
descriptor_pool(), message_factory(), arena()),
IsOkAndHolds(BoolValueIs(true)));
EXPECT_EQ(arena()->SpaceUsed(), 0);
}

TEST_F(ParsedRepeatedFieldValueTest, Contains) {
ParsedRepeatedFieldValue value(
DynamicParseTextProto<TestAllTypesProto3>(R"pb(repeated_bool: true)pb"),
Expand Down
16 changes: 15 additions & 1 deletion eval/public/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,10 @@ cc_library(
],
deps = [
":activation",
"//common:value",
"//eval/public/containers:field_access",
"//eval/public/containers:field_backed_list_impl",
"//eval/public/containers:field_backed_map_impl",
"//internal:status_macros",
"@com_google_absl//absl/status",
],
)
Expand Down Expand Up @@ -793,11 +794,24 @@ cc_test(
deps = [
":activation",
":activation_bind_helper",
":builtin_func_registrar",
":cel_expr_builder_factory",
":cel_expression",
":cel_function",
":cel_options",
":cel_value",
"//eval/testutil:test_message_cc_proto",
"//internal:status_macros",
"//internal:testing",
"//parser",
"//testutil:util",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:status_matchers",
"@com_google_absl//absl/status:statusor",
"@com_google_absl//absl/strings:string_view",
"@com_google_absl//absl/types:span",
"@com_google_cel_spec//proto/cel/expr:syntax_cc_proto",
"@com_google_protobuf//:protobuf",
],
)

Expand Down
9 changes: 6 additions & 3 deletions eval/public/activation_bind_helper.cc
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
#include "eval/public/activation_bind_helper.h"

#include "absl/status/status.h"
#include "common/legacy_value.h"
#include "common/value.h"
#include "eval/public/containers/field_access.h"
#include "eval/public/containers/field_backed_list_impl.h"
#include "eval/public/containers/field_backed_map_impl.h"
#include "internal/status_macros.h"

namespace google {
namespace api {
Expand All @@ -25,8 +27,9 @@ absl::Status CreateValueFromField(const google::protobuf::Message* msg,
arena, msg, field_desc, arena));
return absl::OkStatus();
} else if (field_desc->is_repeated()) {
*result = CelValue::CreateList(google::protobuf::Arena::Create<FieldBackedListImpl>(
arena, msg, field_desc, arena));
CEL_ASSIGN_OR_RETURN(
*result, cel::LegacyValue(arena, cel::UnsafeParsedRepeatedFieldValue(
msg, field_desc)));
return absl::OkStatus();
} else {
return CreateValueFromSingleField(msg, field_desc, arena, result);
Expand Down
Loading
Loading