Protocol Buffers - Google's data interchange format (grpc依赖) https://developers.google.com/protocol-buffers/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

319 lines
11 KiB

/*
* Copyright (c) 2009-2021, Google LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Google LLC nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "upb/mini_descriptor/internal/encode.hpp"
#include <string_view>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "google/protobuf/descriptor.h"
#include "upb/message/accessors_internal.h"
#include "upb/mini_descriptor/decode.h"
#include "upb/mini_descriptor/internal/base92.h"
#include "upb/mini_descriptor/internal/modifiers.h"
#include "upb/mini_table/enum.h"
#include "upb/upb.hpp"
#include "upb/wire/decode.h"
// begin:google_only
// #include "testing/fuzzing/fuzztest.h"
// end:google_only
namespace protobuf = ::google::protobuf;
class MiniTableTest : public testing::TestWithParam<upb_MiniTablePlatform> {};
TEST_P(MiniTableTest, Empty) {
upb::Arena arena;
upb::Status status;
upb_MiniTable* table =
_upb_MiniTable_Build(NULL, 0, GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(0, table->field_count);
EXPECT_EQ(0, table->required_count);
}
TEST_P(MiniTableTest, AllScalarTypes) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartMessage(0));
int count = 0;
3 years ago
for (int i = kUpb_FieldType_Double; i < kUpb_FieldType_SInt64; i++) {
ASSERT_TRUE(e.PutField(static_cast<upb_FieldType>(i), i, 0));
count++;
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(count, table->field_count);
absl::flat_hash_set<size_t> offsets;
for (int i = 0; i < 16; i++) {
const upb_MiniTableField* f = &table->fields[i];
EXPECT_EQ(i + 1, f->number);
EXPECT_EQ(kUpb_FieldMode_Scalar, f->mode & kUpb_FieldMode_Mask);
EXPECT_TRUE(offsets.insert(f->offset).second);
EXPECT_TRUE(f->offset < table->size);
}
EXPECT_EQ(0, table->required_count);
}
TEST_P(MiniTableTest, AllRepeatedTypes) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartMessage(0));
int count = 0;
3 years ago
for (int i = kUpb_FieldType_Double; i < kUpb_FieldType_SInt64; i++) {
ASSERT_TRUE(e.PutField(static_cast<upb_FieldType>(i), i,
kUpb_FieldModifier_IsRepeated));
count++;
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(count, table->field_count);
absl::flat_hash_set<size_t> offsets;
for (int i = 0; i < 16; i++) {
const upb_MiniTableField* f = &table->fields[i];
EXPECT_EQ(i + 1, f->number);
EXPECT_EQ(kUpb_FieldMode_Array, f->mode & kUpb_FieldMode_Mask);
EXPECT_TRUE(offsets.insert(f->offset).second);
EXPECT_TRUE(f->offset < table->size);
}
EXPECT_EQ(0, table->required_count);
}
TEST_P(MiniTableTest, Skips) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartMessage(0));
int count = 0;
std::vector<int> field_numbers;
for (int i = 0; i < 25; i++) {
int field_number = 1 << i;
field_numbers.push_back(field_number);
ASSERT_TRUE(e.PutField(kUpb_FieldType_Float, field_number, 0));
count++;
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(count, table->field_count);
absl::flat_hash_set<size_t> offsets;
for (size_t i = 0; i < field_numbers.size(); i++) {
const upb_MiniTableField* f = &table->fields[i];
EXPECT_EQ(field_numbers[i], f->number);
EXPECT_EQ(kUpb_FieldType_Float, upb_MiniTableField_Type(f));
EXPECT_EQ(kUpb_FieldMode_Scalar, f->mode & kUpb_FieldMode_Mask);
EXPECT_TRUE(offsets.insert(f->offset).second);
EXPECT_TRUE(f->offset < table->size);
}
EXPECT_EQ(0, table->required_count);
}
TEST_P(MiniTableTest, AllScalarTypesOneof) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartMessage(0));
int count = 0;
3 years ago
for (int i = kUpb_FieldType_Double; i < kUpb_FieldType_SInt64; i++) {
ASSERT_TRUE(e.PutField(static_cast<upb_FieldType>(i), i, 0));
count++;
}
ASSERT_TRUE(e.StartOneof());
3 years ago
for (int i = kUpb_FieldType_Double; i < kUpb_FieldType_SInt64; i++) {
ASSERT_TRUE(e.PutOneofField(i));
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table) << status.error_message();
EXPECT_EQ(count, table->field_count);
absl::flat_hash_set<size_t> offsets;
for (int i = 0; i < 16; i++) {
const upb_MiniTableField* f = &table->fields[i];
EXPECT_EQ(i + 1, f->number);
EXPECT_EQ(kUpb_FieldMode_Scalar, f->mode & kUpb_FieldMode_Mask);
// For a oneof all fields have the same offset.
EXPECT_EQ(table->fields[0].offset, f->offset);
// All presence fields should point to the same oneof case offset.
size_t case_ofs = _upb_oneofcase_ofs(f);
EXPECT_EQ(table->fields[0].presence, f->presence);
EXPECT_TRUE(f->offset < table->size);
EXPECT_TRUE(case_ofs < table->size);
EXPECT_TRUE(case_ofs != f->offset);
}
EXPECT_EQ(0, table->required_count);
}
TEST_P(MiniTableTest, SizeOverflow) {
upb::Arena arena;
upb::MtDataEncoder e;
// upb can only handle messages up to UINT16_MAX.
size_t max_double_fields = UINT16_MAX / (sizeof(double) + 1);
// A bit under max_double_fields is ok.
ASSERT_TRUE(e.StartMessage(0));
for (size_t i = 1; i < max_double_fields; i++) {
ASSERT_TRUE(e.PutField(kUpb_FieldType_Double, i, 0));
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table) << status.error_message();
// A bit over max_double_fields fails.
ASSERT_TRUE(e.StartMessage(0));
for (size_t i = 1; i < max_double_fields + 2; i++) {
ASSERT_TRUE(e.PutField(kUpb_FieldType_Double, i, 0));
}
upb_MiniTable* table2 = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_EQ(nullptr, table2) << status.error_message();
}
INSTANTIATE_TEST_SUITE_P(Platforms, MiniTableTest,
testing::Values(kUpb_MiniTablePlatform_32Bit,
kUpb_MiniTablePlatform_64Bit));
TEST(MiniTablePlatformIndependentTest, Base92Roundtrip) {
for (char i = 0; i < 92; i++) {
EXPECT_EQ(i, _upb_FromBase92(_upb_ToBase92(i)));
}
}
TEST(MiniTablePlatformIndependentTest, IsTypePackable) {
for (int i = 1; i <= protobuf::FieldDescriptor::MAX_TYPE; i++) {
EXPECT_EQ(upb_FieldType_IsPackable(static_cast<upb_FieldType>(i)),
protobuf::FieldDescriptor::IsTypePackable(
static_cast<protobuf::FieldDescriptor::Type>(i)));
}
}
TEST(MiniTableEnumTest, Enum) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartEnum());
absl::flat_hash_set<int32_t> values;
for (int i = 0; i < 256; i++) {
values.insert(i * 2);
e.PutEnumValue(i * 2);
}
e.EndEnum();
upb::Status status;
upb_MiniTableEnum* table = upb_MiniTableEnum_Build(
e.data().data(), e.data().size(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table) << status.error_message();
for (int i = 0; i < UINT16_MAX; i++) {
EXPECT_EQ(values.contains(i), upb_MiniTableEnum_CheckValue(table, i)) << i;
}
}
Added a new dynamic tree shaking model to upb, with the intention of removing the old model once YouTube has migrated. The `kUpb_DecodeOption_ExperimentalAllowUnlinked` flag to the decoder will enable the new behavior. When that flag is not passed, tree shaking with the old model will still be possible. "Dynamic tree shaking" in upb is a feature that allows messages to be parsed even if the MiniTables have not been fully linked. Unlinked sub-message fields can be parsed by preserving their data in the unknown fields. If the application later discovers that the message field is actually needed, the MiniTable can be patched to properly link that field, and existing message instances can "promote" the data from the unknown fields to an actual message of the correct type. Before this change, dynamic tree shaking stored unparsed message data in the unknown fields of the *parent*. In effect, we were treating the field as if it did not exist at all. This meant that parsing an unlinked field did not affect the hasbits or oneof cases of the parent, nor did it create a `upb_Array` or `upb_Map` for array/map fields. Only when a message was linked and promoted did any of these things occur. While this model had some amount of conceptual simplicity, it caused significant problems with oneofs. When multiple fields inside a single oneof are parsed from the wire, order matters, because later oneof fields must overwrite earlier ones. Dynamic tree shaking can mean that some fields in a oneof are linked while others are not. It is essential that we preserve this ordering semantic even when dynamic tree shaking is being used, but it is difficult to do if the oneof's data can be split between linked fields (which have been reified into parsed field data) and unlinked fields (whose data lives in the unknown fields of the parent). To solve this problem, this CL changes the representation for unlinked fields. Instead of being placed in the parent's unknown fields, we create an actual message instance for each unlinked message we parse, but we use a placeholder "empty message" MiniTable as the message's type. All of the message's data will therefore be placed into the "empty message's" unknown fields. But unlike before, this "empty message" is actually present according to the hasbits, oneof case, and `upb_Array`/`upb_Map` of the parent. This means that all of the oneof presence logic works as normal. Since the MiniTable can be patched at any time, we need a bit in the message instance itself to signal whether a pointer to a sub-message is an "empty message" or not. When dynamic tree shaking is in use, all users must be capable of recognizing an empty message and acting accordingly (promoting, etc) even if the MiniTable itself says that the field is linked. Because dynamic tree shaking imposes this extra requirement on users, we require that users pass an extra option to the decoder to allow parsing of unlinked sub-messages. Many existing users of upb (Ruby, PHP, Python, etc) will always have fully-linked MiniTables, so there is no reason for them to add extra logic to handle empty messages. By omitting the `kUpb_DecodeOption_ExperimentalAllowUnlinked` option, they will be relieved of the duty to check the tagged pointer that would indicate an empty, unlinked message. For existing users of dynamic tree shaking, there are three main changes: 1. The APIs in message/promote.h have changed, and users will need to update to the new interfaces. 2. The model for maps has changed slightly. Before, we required that map entries always had their values linked; for dynamic tree shaking to apply to maps, we required that the *entry* was left unlinked, not the entry's value. In the new model, that is reversed: map entries must always be linked, but a map entry's value can be unlinked. 3. The presence model for unlinked fields has changed. Unlinked fields will now register as "present" from the perspective of hasbits, oneof cases, and array/map entries. Users must test the tagged pointer to know if a message is of the correct, linked type or whether it is a placeholder "empty" message. There is a new function `upb_Message_GetTaggedMessagePtr()`, as well as a new accessor `upb_MessageValue.tagged_msg_val` that can be used to read and test the tagged pointer directly. PiperOrigin-RevId: 535288031
2 years ago
TEST_P(MiniTableTest, SubsInitializedToEmpty) {
upb::Arena arena;
upb::MtDataEncoder e;
// Create mini table with 2 message fields.
ASSERT_TRUE(e.StartMessage(0));
ASSERT_TRUE(e.PutField(kUpb_FieldType_Message, 15, 0));
ASSERT_TRUE(e.PutField(kUpb_FieldType_Message, 16, 0));
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(table->field_count, 2);
Added a new dynamic tree shaking model to upb, with the intention of removing the old model once YouTube has migrated. The `kUpb_DecodeOption_ExperimentalAllowUnlinked` flag to the decoder will enable the new behavior. When that flag is not passed, tree shaking with the old model will still be possible. "Dynamic tree shaking" in upb is a feature that allows messages to be parsed even if the MiniTables have not been fully linked. Unlinked sub-message fields can be parsed by preserving their data in the unknown fields. If the application later discovers that the message field is actually needed, the MiniTable can be patched to properly link that field, and existing message instances can "promote" the data from the unknown fields to an actual message of the correct type. Before this change, dynamic tree shaking stored unparsed message data in the unknown fields of the *parent*. In effect, we were treating the field as if it did not exist at all. This meant that parsing an unlinked field did not affect the hasbits or oneof cases of the parent, nor did it create a `upb_Array` or `upb_Map` for array/map fields. Only when a message was linked and promoted did any of these things occur. While this model had some amount of conceptual simplicity, it caused significant problems with oneofs. When multiple fields inside a single oneof are parsed from the wire, order matters, because later oneof fields must overwrite earlier ones. Dynamic tree shaking can mean that some fields in a oneof are linked while others are not. It is essential that we preserve this ordering semantic even when dynamic tree shaking is being used, but it is difficult to do if the oneof's data can be split between linked fields (which have been reified into parsed field data) and unlinked fields (whose data lives in the unknown fields of the parent). To solve this problem, this CL changes the representation for unlinked fields. Instead of being placed in the parent's unknown fields, we create an actual message instance for each unlinked message we parse, but we use a placeholder "empty message" MiniTable as the message's type. All of the message's data will therefore be placed into the "empty message's" unknown fields. But unlike before, this "empty message" is actually present according to the hasbits, oneof case, and `upb_Array`/`upb_Map` of the parent. This means that all of the oneof presence logic works as normal. Since the MiniTable can be patched at any time, we need a bit in the message instance itself to signal whether a pointer to a sub-message is an "empty message" or not. When dynamic tree shaking is in use, all users must be capable of recognizing an empty message and acting accordingly (promoting, etc) even if the MiniTable itself says that the field is linked. Because dynamic tree shaking imposes this extra requirement on users, we require that users pass an extra option to the decoder to allow parsing of unlinked sub-messages. Many existing users of upb (Ruby, PHP, Python, etc) will always have fully-linked MiniTables, so there is no reason for them to add extra logic to handle empty messages. By omitting the `kUpb_DecodeOption_ExperimentalAllowUnlinked` option, they will be relieved of the duty to check the tagged pointer that would indicate an empty, unlinked message. For existing users of dynamic tree shaking, there are three main changes: 1. The APIs in message/promote.h have changed, and users will need to update to the new interfaces. 2. The model for maps has changed slightly. Before, we required that map entries always had their values linked; for dynamic tree shaking to apply to maps, we required that the *entry* was left unlinked, not the entry's value. In the new model, that is reversed: map entries must always be linked, but a map entry's value can be unlinked. 3. The presence model for unlinked fields has changed. Unlinked fields will now register as "present" from the perspective of hasbits, oneof cases, and array/map entries. Users must test the tagged pointer to know if a message is of the correct, linked type or whether it is a placeholder "empty" message. There is a new function `upb_Message_GetTaggedMessagePtr()`, as well as a new accessor `upb_MessageValue.tagged_msg_val` that can be used to read and test the tagged pointer directly. PiperOrigin-RevId: 535288031
2 years ago
EXPECT_EQ(table->subs[0].submsg, &_kUpb_MiniTable_Empty);
EXPECT_EQ(table->subs[1].submsg, &_kUpb_MiniTable_Empty);
}
TEST(MiniTableEnumTest, PositiveAndNegative) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartEnum());
absl::flat_hash_set<int32_t> values;
for (int i = 0; i < 100; i++) {
values.insert(i);
e.PutEnumValue(i);
}
for (int i = 100; i > 0; i--) {
values.insert(-i);
e.PutEnumValue(-i);
}
e.EndEnum();
upb::Status status;
upb_MiniTableEnum* table = upb_MiniTableEnum_Build(
e.data().data(), e.data().size(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table) << status.error_message();
for (int i = -UINT16_MAX; i < UINT16_MAX; i++) {
EXPECT_EQ(values.contains(i), upb_MiniTableEnum_CheckValue(table, i)) << i;
}
}
TEST_P(MiniTableTest, Extendible) {
upb::Arena arena;
upb::MtDataEncoder e;
ASSERT_TRUE(e.StartMessage(kUpb_MessageModifier_IsExtendable));
int count = 0;
for (int i = kUpb_FieldType_Double; i < kUpb_FieldType_SInt64; i++) {
ASSERT_TRUE(e.PutField(static_cast<upb_FieldType>(i), i, 0));
count++;
}
upb::Status status;
upb_MiniTable* table = _upb_MiniTable_Build(
e.data().data(), e.data().size(), GetParam(), arena.ptr(), status.ptr());
ASSERT_NE(nullptr, table);
EXPECT_EQ(kUpb_ExtMode_Extendable, table->ext & kUpb_ExtMode_Extendable);
}
// begin:google_only
//
// static void BuildMiniTable(std::string_view s, bool is_32bit) {
// upb::Arena arena;
// upb::Status status;
// _upb_MiniTable_Build(
// s.data(), s.size(),
// is_32bit ? kUpb_MiniTablePlatform_32Bit : kUpb_MiniTablePlatform_64Bit,
// arena.ptr(), status.ptr());
// }
// FUZZ_TEST(FuzzTest, BuildMiniTable);
//
// TEST(FuzzTest, BuildMiniTableRegression) {
// BuildMiniTable("g}{v~fq{\271", false);
// }
//
// end:google_only