in extra/protobuf/protobuf-24.4/src/google/protobuf/descriptor.cc [3887:9640]
bool FieldDescriptor::is_packed() const {
if (!is_packable()) return false;
#ifdef PROTOBUF_FUTURE_EDITIONS
if (features().repeated_field_encoding() != FeatureSet::PACKED) {
#else // PROTOBUF_FUTURE_EDITIONS
if (FileDescriptorLegacy(file_).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO2) {
#endif // PROTOBUF_FUTURE_EDITIONS
return (options_ != nullptr) && options_->packed();
} else {
return options_ == nullptr || !options_->has_packed() || options_->packed();
}
}
static bool IsStrictUtf8(const FieldDescriptor* field) {
#ifdef PROTOBUF_FUTURE_EDITIONS
return internal::InternalFeatureHelper::GetFeatures(*field)
.string_field_validation() == FeatureSet::MANDATORY;
#else // PROTOBUF_FUTURE_EDITIONS
return FileDescriptorLegacy(field->file()).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO3;
#endif // PROTOBUF_FUTURE_EDITIONS
}
bool FieldDescriptor::requires_utf8_validation() const {
return type() == TYPE_STRING && IsStrictUtf8(this);
}
bool FieldDescriptor::has_presence() const {
if (is_repeated()) return false;
return cpp_type() == CPPTYPE_MESSAGE || containing_oneof() ||
#ifdef PROTOBUF_FUTURE_EDITIONS
features().field_presence() != FeatureSet::IMPLICIT;
#else // PROTOBUF_FUTURE_EDITIONS
FileDescriptorLegacy(file_).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO2;
#endif // PROTOBUF_FUTURE_EDITIONS
}
bool FieldDescriptor::legacy_enum_field_treated_as_closed() const {
#ifdef PROTOBUF_FUTURE_EDITIONS
return type() == TYPE_ENUM &&
(features().GetExtension(pb::cpp).legacy_closed_enum() ||
enum_type()->is_closed());
#else // PROTOBUF_FUTURE_EDITIONS
return type() == TYPE_ENUM &&
(FileDescriptorLegacy(file_).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO2 ||
enum_type()->is_closed());
#endif // PROTOBUF_FUTURE_EDITIONS
}
// Location methods ===============================================
bool FileDescriptor::GetSourceLocation(const std::vector<int>& path,
SourceLocation* out_location) const {
ABSL_CHECK(out_location != nullptr);
if (source_code_info_) {
if (const SourceCodeInfo_Location* loc =
tables_->GetSourceLocation(path, source_code_info_)) {
const RepeatedField<int32_t>& span = loc->span();
if (span.size() == 3 || span.size() == 4) {
out_location->start_line = span.Get(0);
out_location->start_column = span.Get(1);
out_location->end_line = span.Get(span.size() == 3 ? 0 : 2);
out_location->end_column = span.Get(span.size() - 1);
out_location->leading_comments = loc->leading_comments();
out_location->trailing_comments = loc->trailing_comments();
out_location->leading_detached_comments.assign(
loc->leading_detached_comments().begin(),
loc->leading_detached_comments().end());
return true;
}
}
}
return false;
}
bool FileDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path; // empty path for root FileDescriptor
return GetSourceLocation(path, out_location);
}
bool Descriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return file()->GetSourceLocation(path, out_location);
}
bool FieldDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return file()->GetSourceLocation(path, out_location);
}
bool OneofDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return containing_type()->file()->GetSourceLocation(path, out_location);
}
bool EnumDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return file()->GetSourceLocation(path, out_location);
}
bool MethodDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return service()->file()->GetSourceLocation(path, out_location);
}
bool ServiceDescriptor::GetSourceLocation(SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return file()->GetSourceLocation(path, out_location);
}
bool EnumValueDescriptor::GetSourceLocation(
SourceLocation* out_location) const {
std::vector<int> path;
GetLocationPath(&path);
return type()->file()->GetSourceLocation(path, out_location);
}
void Descriptor::GetLocationPath(std::vector<int>* output) const {
if (containing_type()) {
containing_type()->GetLocationPath(output);
output->push_back(DescriptorProto::kNestedTypeFieldNumber);
output->push_back(index());
} else {
output->push_back(FileDescriptorProto::kMessageTypeFieldNumber);
output->push_back(index());
}
}
void FieldDescriptor::GetLocationPath(std::vector<int>* output) const {
if (is_extension()) {
if (extension_scope() == nullptr) {
output->push_back(FileDescriptorProto::kExtensionFieldNumber);
output->push_back(index());
} else {
extension_scope()->GetLocationPath(output);
output->push_back(DescriptorProto::kExtensionFieldNumber);
output->push_back(index());
}
} else {
containing_type()->GetLocationPath(output);
output->push_back(DescriptorProto::kFieldFieldNumber);
output->push_back(index());
}
}
void OneofDescriptor::GetLocationPath(std::vector<int>* output) const {
containing_type()->GetLocationPath(output);
output->push_back(DescriptorProto::kOneofDeclFieldNumber);
output->push_back(index());
}
void Descriptor::ExtensionRange::GetLocationPath(
std::vector<int>* output) const {
containing_type()->GetLocationPath(output);
output->push_back(DescriptorProto::kExtensionRangeFieldNumber);
output->push_back(index());
}
void EnumDescriptor::GetLocationPath(std::vector<int>* output) const {
if (containing_type()) {
containing_type()->GetLocationPath(output);
output->push_back(DescriptorProto::kEnumTypeFieldNumber);
output->push_back(index());
} else {
output->push_back(FileDescriptorProto::kEnumTypeFieldNumber);
output->push_back(index());
}
}
void EnumValueDescriptor::GetLocationPath(std::vector<int>* output) const {
type()->GetLocationPath(output);
output->push_back(EnumDescriptorProto::kValueFieldNumber);
output->push_back(index());
}
void ServiceDescriptor::GetLocationPath(std::vector<int>* output) const {
output->push_back(FileDescriptorProto::kServiceFieldNumber);
output->push_back(index());
}
void MethodDescriptor::GetLocationPath(std::vector<int>* output) const {
service()->GetLocationPath(output);
output->push_back(ServiceDescriptorProto::kMethodFieldNumber);
output->push_back(index());
}
// ===================================================================
namespace {
// Represents an options message to interpret. Extension names in the option
// name are resolved relative to name_scope. element_name and orig_opt are
// used only for error reporting (since the parser records locations against
// pointers in the original options, not the mutable copy). The Message must be
// one of the Options messages in descriptor.proto.
struct OptionsToInterpret {
OptionsToInterpret(absl::string_view ns, absl::string_view el,
absl::Span<const int> path, const Message* orig_opt,
Message* opt)
: name_scope(ns),
element_name(el),
element_path(path.begin(), path.end()),
original_options(orig_opt),
options(opt) {}
std::string name_scope;
std::string element_name;
std::vector<int> element_path;
const Message* original_options;
Message* options;
};
} // namespace
class DescriptorBuilder {
public:
static std::unique_ptr<DescriptorBuilder> New(
const DescriptorPool* pool, DescriptorPool::Tables* tables,
DescriptorPool::ErrorCollector* error_collector) {
return std::unique_ptr<DescriptorBuilder>(
new DescriptorBuilder(pool, tables, error_collector));
}
~DescriptorBuilder();
const FileDescriptor* BuildFile(const FileDescriptorProto& original_proto);
private:
DescriptorBuilder(const DescriptorPool* pool, DescriptorPool::Tables* tables,
DescriptorPool::ErrorCollector* error_collector);
friend class OptionInterpreter;
// Non-recursive part of BuildFile functionality.
FileDescriptor* BuildFileImpl(const FileDescriptorProto& proto,
internal::FlatAllocator& alloc);
const DescriptorPool* pool_;
DescriptorPool::Tables* tables_; // for convenience
DescriptorPool::ErrorCollector* error_collector_;
#ifdef PROTOBUF_FUTURE_EDITIONS
absl::optional<FeatureResolver> feature_resolver_ = absl::nullopt;
#endif // PROTOBUF_FUTURE_EDITIONS
// As we build descriptors we store copies of the options messages in
// them. We put pointers to those copies in this vector, as we build, so we
// can later (after cross-linking) interpret those options.
std::vector<OptionsToInterpret> options_to_interpret_;
bool had_errors_;
std::string filename_;
FileDescriptor* file_;
FileDescriptorTables* file_tables_;
absl::flat_hash_set<const FileDescriptor*> dependencies_;
struct MessageHints {
int fields_to_suggest = 0;
const Message* first_reason = nullptr;
DescriptorPool::ErrorCollector::ErrorLocation first_reason_location =
DescriptorPool::ErrorCollector::ErrorLocation::OTHER;
void RequestHintOnFieldNumbers(
const Message& reason,
DescriptorPool::ErrorCollector::ErrorLocation reason_location,
int range_start = 0, int range_end = 1) {
auto fit = [](int value) {
return std::min(std::max(value, 0), FieldDescriptor::kMaxNumber);
};
fields_to_suggest =
fit(fields_to_suggest + fit(fit(range_end) - fit(range_start)));
if (first_reason) return;
first_reason = &reason;
first_reason_location = reason_location;
}
};
absl::flat_hash_map<const Descriptor*, MessageHints> message_hints_;
// unused_dependency_ is used to record the unused imported files.
// Note: public import is not considered.
absl::flat_hash_set<const FileDescriptor*> unused_dependency_;
// If LookupSymbol() finds a symbol that is in a file which is not a declared
// dependency of this file, it will fail, but will set
// possible_undeclared_dependency_ to point at that file. This is only used
// by AddNotDefinedError() to report a more useful error message.
// possible_undeclared_dependency_name_ is the name of the symbol that was
// actually found in possible_undeclared_dependency_, which may be a parent
// of the symbol actually looked for.
const FileDescriptor* possible_undeclared_dependency_;
std::string possible_undeclared_dependency_name_;
// If LookupSymbol() could resolve a symbol which is not defined,
// record the resolved name. This is only used by AddNotDefinedError()
// to report a more useful error message.
std::string undefine_resolved_name_;
// Tracker for current recursion depth to implement recursion protection.
//
// Counts down to 0 when there is no depth remaining.
//
// Maximum recursion depth corresponds to 32 nested message declarations.
int recursion_depth_ = 32;
// Note: Both AddError and AddWarning functions are extremely sensitive to
// the *caller* stack space used. We call these functions many times in
// complex code paths that are hot and likely to be inlined heavily. However,
// these calls themselves are cold error paths. But stack space used by the
// code that sets up the call in many cases is paid for even when the call
// isn't reached. To optimize this, we use `const std::string &` to reuse
// string objects where possible for the inputs and for the error message
// itself we use a closure to build the error message inside these routines.
// The routines themselves are marked to prevent inlining and this lets us
// move the large code sometimes required to produce a useful error message
// entirely into a helper closure rather than the immediate caller.
//
// The `const char*` overload should only be used for string literal messages
// where this is a frustrating amount of overhead and there is no harm in
// directly using the literal.
void AddError(const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
absl::FunctionRef<std::string()> make_error);
void AddError(const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
const char* error);
void AddRecursiveImportError(const FileDescriptorProto& proto, int from_here);
void AddTwiceListedError(const FileDescriptorProto& proto, int index);
void AddImportError(const FileDescriptorProto& proto, int index);
// Adds an error indicating that undefined_symbol was not defined. Must
// only be called after LookupSymbol() fails.
void AddNotDefinedError(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
const std::string& undefined_symbol);
void AddWarning(const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
absl::FunctionRef<std::string()> make_error);
void AddWarning(const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
const char* error);
// Silly helper which determines if the given file is in the given package.
// I.e., either file->package() == package_name or file->package() is a
// nested package within package_name.
bool IsInPackage(const FileDescriptor* file, absl::string_view package_name);
// Helper function which finds all public dependencies of the given file, and
// stores the them in the dependencies_ set in the builder.
void RecordPublicDependencies(const FileDescriptor* file);
// Like tables_->FindSymbol(), but additionally:
// - Search the pool's underlay if not found in tables_.
// - Insure that the resulting Symbol is from one of the file's declared
// dependencies.
Symbol FindSymbol(const std::string& name, bool build_it = true);
// Like FindSymbol() but does not require that the symbol is in one of the
// file's declared dependencies.
Symbol FindSymbolNotEnforcingDeps(const std::string& name,
bool build_it = true);
// This implements the body of FindSymbolNotEnforcingDeps().
Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool,
const std::string& name,
bool build_it = true);
// Like FindSymbol(), but looks up the name relative to some other symbol
// name. This first searches siblings of relative_to, then siblings of its
// parents, etc. For example, LookupSymbol("foo.bar", "baz.moo.corge") makes
// the following calls, returning the first non-null result:
// FindSymbol("baz.moo.foo.bar"), FindSymbol("baz.foo.bar"),
// FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called
// on the DescriptorPool, this will generate a placeholder type if
// the name is not found (unless the name itself is malformed). The
// placeholder_type parameter indicates what kind of placeholder should be
// constructed in this case. The resolve_mode parameter determines whether
// any symbol is returned, or only symbols that are types. Note, however,
// that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode,
// if it believes that's all it could refer to. The caller should always
// check that it receives the type of symbol it was expecting.
enum ResolveMode { LOOKUP_ALL, LOOKUP_TYPES };
Symbol LookupSymbol(const std::string& name, const std::string& relative_to,
DescriptorPool::PlaceholderType placeholder_type =
DescriptorPool::PLACEHOLDER_MESSAGE,
ResolveMode resolve_mode = LOOKUP_ALL,
bool build_it = true);
// Like LookupSymbol() but will not return a placeholder even if
// AllowUnknownDependencies() has been used.
Symbol LookupSymbolNoPlaceholder(const std::string& name,
const std::string& relative_to,
ResolveMode resolve_mode = LOOKUP_ALL,
bool build_it = true);
// Calls tables_->AddSymbol() and records an error if it fails. Returns
// true if successful or false if failed, though most callers can ignore
// the return value since an error has already been recorded.
bool AddSymbol(const std::string& full_name, const void* parent,
const std::string& name, const Message& proto, Symbol symbol);
// Like AddSymbol(), but succeeds if the symbol is already defined as long
// as the existing definition is also a package (because it's OK to define
// the same package in two different files). Also adds all parents of the
// package to the symbol table (e.g. AddPackage("foo.bar", ...) will add
// "foo.bar" and "foo" to the table).
void AddPackage(const std::string& name, const Message& proto,
FileDescriptor* file);
// Checks that the symbol name contains only alphanumeric characters and
// underscores. Records an error otherwise.
void ValidateSymbolName(const std::string& name, const std::string& full_name,
const Message& proto);
// Allocates a copy of orig_options in tables_ and stores it in the
// descriptor. Remembers its uninterpreted options, to be interpreted
// later. DescriptorT must be one of the Descriptor messages from
// descriptor.proto.
template <class DescriptorT>
void AllocateOptions(const typename DescriptorT::Proto& proto,
DescriptorT* descriptor, int options_field_tag,
absl::string_view option_name,
internal::FlatAllocator& alloc);
// Specialization for FileOptions.
void AllocateOptions(const FileDescriptorProto& proto,
FileDescriptor* descriptor,
internal::FlatAllocator& alloc);
// Implementation for AllocateOptions(). Don't call this directly.
template <class DescriptorT>
typename DescriptorT::OptionsType* AllocateOptionsImpl(
absl::string_view name_scope, absl::string_view element_name,
const typename DescriptorT::Proto& proto,
absl::Span<const int> options_path, absl::string_view option_name,
internal::FlatAllocator& alloc);
#ifdef PROTOBUF_FUTURE_EDITIONS
// Allocates and resolves any feature sets that need to be owned by a given
// descriptor. This also strips features out of the mutable options message to
// prevent leaking of unresolved features.
// Note: This must be used during a pre-order traversal of the
// descriptor tree, so that each descriptor's parent has a fully resolved
// feature set already.
template <class DescriptorT>
void ResolveFeatures(const typename DescriptorT::Proto& proto,
DescriptorT* descriptor,
typename DescriptorT::OptionsType* options,
internal::FlatAllocator& alloc);
void ResolveFeatures(const FileDescriptorProto& proto,
FileDescriptor* descriptor, FileOptions* options,
internal::FlatAllocator& alloc);
template <class DescriptorT>
void ResolveFeaturesImpl(
const typename DescriptorT::Proto& proto, DescriptorT* descriptor,
typename DescriptorT::OptionsType* options,
internal::FlatAllocator& alloc,
DescriptorPool::ErrorCollector::ErrorLocation error_location,
bool force_merge = false);
// Performs descriptor-specific overrides of proto2/proto3 defaults for
// descriptors outside editions.
template <class DescriptorT>
const FeatureSet* GetLegacyFeatureOverride(const FeatureSet* parent_features,
const DescriptorT* descriptor);
void PostProcessFieldFeatures(FieldDescriptor& field);
#endif // PROTOBUF_FUTURE_EDITIONS
// Allocates an array of two strings, the first one is a copy of
// `proto_name`, and the second one is the full name. Full proto name is
// "scope.proto_name" if scope is non-empty and "proto_name" otherwise.
const std::string* AllocateNameStrings(const std::string& scope,
const std::string& proto_name,
internal::FlatAllocator& alloc);
// These methods all have the same signature for the sake of the BUILD_ARRAY
// macro, below.
void BuildMessage(const DescriptorProto& proto, const Descriptor* parent,
Descriptor* result, internal::FlatAllocator& alloc);
void BuildFieldOrExtension(const FieldDescriptorProto& proto,
Descriptor* parent, FieldDescriptor* result,
bool is_extension, internal::FlatAllocator& alloc);
void BuildField(const FieldDescriptorProto& proto, Descriptor* parent,
FieldDescriptor* result, internal::FlatAllocator& alloc) {
BuildFieldOrExtension(proto, parent, result, false, alloc);
}
void BuildExtension(const FieldDescriptorProto& proto, Descriptor* parent,
FieldDescriptor* result, internal::FlatAllocator& alloc) {
BuildFieldOrExtension(proto, parent, result, true, alloc);
}
void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto,
const Descriptor* parent,
Descriptor::ExtensionRange* result,
internal::FlatAllocator& alloc);
void BuildReservedRange(const DescriptorProto::ReservedRange& proto,
const Descriptor* parent,
Descriptor::ReservedRange* result,
internal::FlatAllocator& alloc);
void BuildReservedRange(const EnumDescriptorProto::EnumReservedRange& proto,
const EnumDescriptor* parent,
EnumDescriptor::ReservedRange* result,
internal::FlatAllocator& alloc);
void BuildOneof(const OneofDescriptorProto& proto, Descriptor* parent,
OneofDescriptor* result, internal::FlatAllocator& alloc);
void BuildEnum(const EnumDescriptorProto& proto, const Descriptor* parent,
EnumDescriptor* result, internal::FlatAllocator& alloc);
void BuildEnumValue(const EnumValueDescriptorProto& proto,
const EnumDescriptor* parent, EnumValueDescriptor* result,
internal::FlatAllocator& alloc);
void BuildService(const ServiceDescriptorProto& proto, const void* dummy,
ServiceDescriptor* result, internal::FlatAllocator& alloc);
void BuildMethod(const MethodDescriptorProto& proto,
const ServiceDescriptor* parent, MethodDescriptor* result,
internal::FlatAllocator& alloc);
void CheckFieldJsonNameUniqueness(const DescriptorProto& proto,
const Descriptor* result);
void CheckFieldJsonNameUniqueness(const std::string& message_name,
const DescriptorProto& message,
const Descriptor* descriptor,
FileDescriptorLegacy::Syntax syntax,
bool use_custom_names);
void CheckEnumValueUniqueness(const EnumDescriptorProto& proto,
const EnumDescriptor* result);
void LogUnusedDependency(const FileDescriptorProto& proto,
const FileDescriptor* result);
// Must be run only after building.
//
// NOTE: Options will not be available during cross-linking, as they
// have not yet been interpreted. Defer any handling of options to the
// Validate*Options methods.
void CrossLinkFile(FileDescriptor* file, const FileDescriptorProto& proto);
void CrossLinkMessage(Descriptor* message, const DescriptorProto& proto);
void CrossLinkField(FieldDescriptor* field,
const FieldDescriptorProto& proto);
void CrossLinkExtensionRange(Descriptor::ExtensionRange* range,
const DescriptorProto::ExtensionRange& proto);
void CrossLinkEnum(EnumDescriptor* enum_type,
const EnumDescriptorProto& proto);
void CrossLinkEnumValue(EnumValueDescriptor* enum_value,
const EnumValueDescriptorProto& proto);
void CrossLinkService(ServiceDescriptor* service,
const ServiceDescriptorProto& proto);
void CrossLinkMethod(MethodDescriptor* method,
const MethodDescriptorProto& proto);
void SuggestFieldNumbers(FileDescriptor* file,
const FileDescriptorProto& proto);
// Checks that the extension field matches what is declared.
void CheckExtensionDeclaration(const FieldDescriptor& field,
const FieldDescriptorProto& proto,
absl::string_view declared_full_name,
absl::string_view declared_type_name,
bool is_repeated);
// A helper class for interpreting options.
class OptionInterpreter {
public:
// Creates an interpreter that operates in the context of the pool of the
// specified builder, which must not be nullptr. We don't take ownership of
// the builder.
explicit OptionInterpreter(DescriptorBuilder* builder);
OptionInterpreter(const OptionInterpreter&) = delete;
OptionInterpreter& operator=(const OptionInterpreter&) = delete;
~OptionInterpreter();
// Interprets the uninterpreted options in the specified Options message.
// On error, calls AddError() on the underlying builder and returns false.
// Otherwise returns true.
bool InterpretOptions(OptionsToInterpret* options_to_interpret);
#ifdef PROTOBUF_FUTURE_EDITIONS
// Interprets the uninterpreted feature options in the specified Options
// message. On error, calls AddError() on the underlying builder and returns
// false. Otherwise returns true.
bool InterpretFeatures(OptionsToInterpret* options_to_interpret);
#endif // PROTOBUF_FUTURE_EDITIONS
// Updates the given source code info by re-writing uninterpreted option
// locations to refer to the corresponding interpreted option.
void UpdateSourceCodeInfo(SourceCodeInfo* info);
class AggregateOptionFinder;
private:
bool InterpretOptionsImpl(OptionsToInterpret* options_to_interpret,
bool features);
// Interprets uninterpreted_option_ on the specified message, which
// must be the mutable copy of the original options message to which
// uninterpreted_option_ belongs. The given src_path is the source
// location path to the uninterpreted option, and options_path is the
// source location path to the options message. The location paths are
// recorded and then used in UpdateSourceCodeInfo.
// The features boolean controls whether or not we should only interpret
// feature options or skip them entirely.
bool InterpretSingleOption(Message* options,
const std::vector<int>& src_path,
const std::vector<int>& options_path,
bool features);
// Adds the uninterpreted_option to the given options message verbatim.
// Used when AllowUnknownDependencies() is in effect and we can't find
// the option's definition.
void AddWithoutInterpreting(const UninterpretedOption& uninterpreted_option,
Message* options);
// A recursive helper function that drills into the intermediate fields
// in unknown_fields to check if field innermost_field is set on the
// innermost message. Returns false and sets an error if so.
bool ExamineIfOptionIsSet(
std::vector<const FieldDescriptor*>::const_iterator
intermediate_fields_iter,
std::vector<const FieldDescriptor*>::const_iterator
intermediate_fields_end,
const FieldDescriptor* innermost_field,
const std::string& debug_msg_name,
const UnknownFieldSet& unknown_fields);
// Validates the value for the option field of the currently interpreted
// option and then sets it on the unknown_field.
bool SetOptionValue(const FieldDescriptor* option_field,
UnknownFieldSet* unknown_fields);
// Parses an aggregate value for a CPPTYPE_MESSAGE option and
// saves it into *unknown_fields.
bool SetAggregateOption(const FieldDescriptor* option_field,
UnknownFieldSet* unknown_fields);
// Convenience functions to set an int field the right way, depending on
// its wire type (a single int CppType can represent multiple wire types).
void SetInt32(int number, int32_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields);
void SetInt64(int number, int64_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields);
void SetUInt32(int number, uint32_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields);
void SetUInt64(int number, uint64_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields);
// A helper function that adds an error at the specified location of the
// option we're currently interpreting, and returns false.
bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location,
absl::FunctionRef<std::string()> make_error) {
builder_->AddError(options_to_interpret_->element_name,
*uninterpreted_option_, location, make_error);
return false;
}
// A helper function that adds an error at the location of the option name
// and returns false.
bool AddNameError(absl::FunctionRef<std::string()> make_error) {
#ifdef PROTOBUF_INTERNAL_IGNORE_FIELD_NAME_ERRORS_
return true;
#else // PROTOBUF_INTERNAL_IGNORE_FIELD_NAME_ERRORS_
return AddOptionError(DescriptorPool::ErrorCollector::OPTION_NAME,
make_error);
#endif // PROTOBUF_INTERNAL_IGNORE_FIELD_NAME_ERRORS_
}
// A helper function that adds an error at the location of the option name
// and returns false.
bool AddValueError(absl::FunctionRef<std::string()> make_error) {
return AddOptionError(DescriptorPool::ErrorCollector::OPTION_VALUE,
make_error);
}
// We interpret against this builder's pool. Is never nullptr. We don't own
// this pointer.
DescriptorBuilder* builder_;
// The options we're currently interpreting, or nullptr if we're not in a
// call to InterpretOptions.
const OptionsToInterpret* options_to_interpret_;
// The option we're currently interpreting within options_to_interpret_, or
// nullptr if we're not in a call to InterpretOptions(). This points to a
// submessage of the original option, not the mutable copy. Therefore we
// can use it to find locations recorded by the parser.
const UninterpretedOption* uninterpreted_option_;
// This maps the element path of uninterpreted options to the element path
// of the resulting interpreted option. This is used to modify a file's
// source code info to account for option interpretation.
absl::flat_hash_map<std::vector<int>, std::vector<int>> interpreted_paths_;
// This maps the path to a repeated option field to the known number of
// elements the field contains. This is used to track the compute the
// index portion of the element path when interpreting a single option.
absl::flat_hash_map<std::vector<int>, int> repeated_option_counts_;
// Factory used to create the dynamic messages we need to parse
// any aggregate option values we encounter.
DynamicMessageFactory dynamic_factory_;
};
// Work-around for broken compilers: According to the C++ standard,
// OptionInterpreter should have access to the private members of any class
// which has declared DescriptorBuilder as a friend. Unfortunately some old
// versions of GCC and other compilers do not implement this correctly. So,
// we have to have these intermediate methods to provide access. We also
// redundantly declare OptionInterpreter a friend just to make things extra
// clear for these bad compilers.
friend class OptionInterpreter;
friend class OptionInterpreter::AggregateOptionFinder;
static inline bool get_allow_unknown(const DescriptorPool* pool) {
return pool->allow_unknown_;
}
static inline bool get_enforce_weak(const DescriptorPool* pool) {
return pool->enforce_weak_;
}
static inline bool get_is_placeholder(const Descriptor* descriptor) {
return descriptor != nullptr && descriptor->is_placeholder_;
}
static inline void assert_mutex_held(const DescriptorPool* pool) {
if (pool->mutex_ != nullptr) {
pool->mutex_->AssertHeld();
}
}
// Must be run only after options have been interpreted.
//
// NOTE: Validation code must only reference the options in the mutable
// descriptors, which are the ones that have been interpreted. The const
// proto references are passed in only so they can be provided to calls to
// AddError(). Do not look at their options, which have not been interpreted.
void ValidateOptions(const FileDescriptor* file,
const FileDescriptorProto& proto);
void ValidateOptions(const Descriptor* message, const DescriptorProto& proto);
void ValidateOptions(const OneofDescriptor* oneof,
const OneofDescriptorProto& proto);
void ValidateOptions(const FieldDescriptor* field,
const FieldDescriptorProto& proto);
void ValidateFieldFeatures(const FieldDescriptor* field,
const FieldDescriptorProto& proto);
void ValidateOptions(const EnumDescriptor* enm,
const EnumDescriptorProto& proto);
void ValidateOptions(const EnumValueDescriptor* enum_value,
const EnumValueDescriptorProto& proto);
void ValidateOptions(const Descriptor::ExtensionRange* range,
const DescriptorProto::ExtensionRange& proto) {}
void ValidateExtensionRangeOptions(const DescriptorProto& proto,
const Descriptor& message);
void ValidateExtensionDeclaration(
const std::string& full_name,
const RepeatedPtrField<ExtensionRangeOptions_Declaration>& declarations,
const DescriptorProto_ExtensionRange& proto,
absl::flat_hash_set<absl::string_view>& full_name_set);
void ValidateOptions(const ServiceDescriptor* service,
const ServiceDescriptorProto& proto);
void ValidateOptions(const MethodDescriptor* method,
const MethodDescriptorProto& proto);
void ValidateProto3(const FileDescriptor* file,
const FileDescriptorProto& proto);
void ValidateProto3Message(const Descriptor* message,
const DescriptorProto& proto);
void ValidateProto3Field(const FieldDescriptor* field,
const FieldDescriptorProto& proto);
// Returns true if the map entry message is compatible with the
// auto-generated entry message from map fields syntax.
bool ValidateMapEntry(const FieldDescriptor* field,
const FieldDescriptorProto& proto);
// Recursively detects naming conflicts with map entry types for a
// better error message.
void DetectMapConflicts(const Descriptor* message,
const DescriptorProto& proto);
void ValidateJSType(const FieldDescriptor* field,
const FieldDescriptorProto& proto);
};
const FileDescriptor* DescriptorPool::BuildFile(
const FileDescriptorProto& proto) {
ABSL_CHECK(fallback_database_ == nullptr)
<< "Cannot call BuildFile on a DescriptorPool that uses a "
"DescriptorDatabase. You must instead find a way to get your file "
"into the underlying database.";
ABSL_CHECK(mutex_ == nullptr); // Implied by the above ABSL_CHECK.
tables_->known_bad_symbols_.clear();
tables_->known_bad_files_.clear();
return DescriptorBuilder::New(this, tables_.get(), nullptr)->BuildFile(proto);
}
const FileDescriptor* DescriptorPool::BuildFileCollectingErrors(
const FileDescriptorProto& proto, ErrorCollector* error_collector) {
ABSL_CHECK(fallback_database_ == nullptr)
<< "Cannot call BuildFile on a DescriptorPool that uses a "
"DescriptorDatabase. You must instead find a way to get your file "
"into the underlying database.";
ABSL_CHECK(mutex_ == nullptr); // Implied by the above ABSL_CHECK.
tables_->known_bad_symbols_.clear();
tables_->known_bad_files_.clear();
return DescriptorBuilder::New(this, tables_.get(), error_collector)
->BuildFile(proto);
}
const FileDescriptor* DescriptorPool::BuildFileFromDatabase(
const FileDescriptorProto& proto) const {
mutex_->AssertHeld();
if (tables_->known_bad_files_.contains(proto.name())) {
return nullptr;
}
const FileDescriptor* result =
DescriptorBuilder::New(this, tables_.get(), default_error_collector_)
->BuildFile(proto);
if (result == nullptr) {
tables_->known_bad_files_.insert(proto.name());
}
return result;
}
DescriptorBuilder::DescriptorBuilder(
const DescriptorPool* pool, DescriptorPool::Tables* tables,
DescriptorPool::ErrorCollector* error_collector)
: pool_(pool),
tables_(tables),
error_collector_(error_collector),
had_errors_(false),
possible_undeclared_dependency_(nullptr),
undefine_resolved_name_("") {
#ifdef PROTOBUF_FUTURE_EDITIONS
// Ensure that any lazily loaded static initializers from the generated pool
// (e.g. from bootstrapped protos) are run before building any descriptors. We
// have to avoid registering these pre-main, because we need to ensure that
// the linker --gc-sections step can strip out the full runtime if it is
// unused.
pb::cpp.LazyRegister();
#endif // PROTOBUF_FUTURE_EDITIONS
}
DescriptorBuilder::~DescriptorBuilder() {}
PROTOBUF_NOINLINE void DescriptorBuilder::AddError(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
absl::FunctionRef<std::string()> make_error) {
std::string error = make_error();
if (error_collector_ == nullptr) {
if (!had_errors_) {
ABSL_LOG(ERROR) << "Invalid proto descriptor for file \"" << filename_
<< "\":";
}
ABSL_LOG(ERROR) << " " << element_name << ": " << error;
} else {
error_collector_->RecordError(filename_, element_name, &descriptor,
location, error);
}
had_errors_ = true;
}
PROTOBUF_NOINLINE void DescriptorBuilder::AddError(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location, const char* error) {
AddError(element_name, descriptor, location, [error] { return error; });
}
PROTOBUF_NOINLINE void DescriptorBuilder::AddNotDefinedError(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
const std::string& undefined_symbol) {
if (possible_undeclared_dependency_ == nullptr &&
undefine_resolved_name_.empty()) {
AddError(element_name, descriptor, location, [&] {
return absl::StrCat("\"", undefined_symbol, "\" is not defined.");
});
} else {
if (possible_undeclared_dependency_ != nullptr) {
AddError(element_name, descriptor, location, [&] {
return absl::StrCat("\"", possible_undeclared_dependency_name_,
"\" seems to be defined in \"",
possible_undeclared_dependency_->name(),
"\", which is not "
"imported by \"",
filename_,
"\". To use it here, please "
"add the necessary import.");
});
}
if (!undefine_resolved_name_.empty()) {
AddError(element_name, descriptor, location, [&] {
return absl::StrCat(
"\"", undefined_symbol, "\" is resolved to \"",
undefine_resolved_name_,
"\", which is not defined. "
"The innermost scope is searched first in name resolution. "
"Consider using a leading '.'(i.e., \".",
undefined_symbol, "\") to start from the outermost scope.");
});
}
}
}
PROTOBUF_NOINLINE void DescriptorBuilder::AddWarning(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
absl::FunctionRef<std::string()> make_error) {
std::string error = make_error();
if (error_collector_ == nullptr) {
ABSL_LOG(WARNING) << filename_ << " " << element_name << ": " << error;
} else {
error_collector_->RecordWarning(filename_, element_name, &descriptor,
location, error);
}
}
PROTOBUF_NOINLINE void DescriptorBuilder::AddWarning(
const std::string& element_name, const Message& descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location, const char* error) {
AddWarning(element_name, descriptor, location,
[error]() -> std::string { return error; });
}
bool DescriptorBuilder::IsInPackage(const FileDescriptor* file,
absl::string_view package_name) {
return absl::StartsWith(file->package(), package_name) &&
(file->package().size() == package_name.size() ||
file->package()[package_name.size()] == '.');
}
void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) {
if (file == nullptr || !dependencies_.insert(file).second) return;
for (int i = 0; file != nullptr && i < file->public_dependency_count(); i++) {
RecordPublicDependencies(file->public_dependency(i));
}
}
Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper(
const DescriptorPool* pool, const std::string& name, bool build_it) {
// If we are looking at an underlay, we must lock its mutex_, since we are
// accessing the underlay's tables_ directly.
absl::MutexLockMaybe lock((pool == pool_) ? nullptr : pool->mutex_);
Symbol result = pool->tables_->FindSymbol(name);
if (result.IsNull() && pool->underlay_ != nullptr) {
// Symbol not found; check the underlay.
result = FindSymbolNotEnforcingDepsHelper(pool->underlay_, name);
}
if (result.IsNull()) {
// With lazily_build_dependencies_, a symbol lookup at cross link time is
// not guaranteed to be successful. In most cases, build_it will be false,
// which intentionally prevents us from building an import until it's
// actually needed. In some cases, like registering an extension, we want
// to build the file containing the symbol, and build_it will be set.
// Also, build_it will be true when !lazily_build_dependencies_, to provide
// better error reporting of missing dependencies.
if (build_it && pool->TryFindSymbolInFallbackDatabase(name)) {
result = pool->tables_->FindSymbol(name);
}
}
return result;
}
Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const std::string& name,
bool build_it) {
Symbol result = FindSymbolNotEnforcingDepsHelper(pool_, name, build_it);
// Only find symbols which were defined in this file or one of its
// dependencies.
const FileDescriptor* file = result.GetFile();
if ((file == file_ || dependencies_.contains(file)) && !result.IsPackage()) {
unused_dependency_.erase(file);
}
return result;
}
Symbol DescriptorBuilder::FindSymbol(const std::string& name, bool build_it) {
Symbol result = FindSymbolNotEnforcingDeps(name, build_it);
if (result.IsNull()) return result;
if (!pool_->enforce_dependencies_) {
// Hack for CompilerUpgrader, and also used for lazily_build_dependencies_
return result;
}
// Only find symbols which were defined in this file or one of its
// dependencies.
const FileDescriptor* file = result.GetFile();
if (file == file_ || dependencies_.contains(file)) {
return result;
}
if (result.IsPackage()) {
// Arg, this is overcomplicated. The symbol is a package name. It could
// be that the package was defined in multiple files. result.GetFile()
// returns the first file we saw that used this package. We've determined
// that that file is not a direct dependency of the file we are currently
// building, but it could be that some other file which *is* a direct
// dependency also defines the same package. We can't really rule out this
// symbol unless none of the dependencies define it.
if (IsInPackage(file_, name)) return result;
for (const auto* dep : dependencies_) {
// Note: A dependency may be nullptr if it was not found or had errors.
if (dep != nullptr && IsInPackage(dep, name)) return result;
}
}
possible_undeclared_dependency_ = file;
possible_undeclared_dependency_name_ = name;
return Symbol();
}
Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
const std::string& name, const std::string& relative_to,
ResolveMode resolve_mode, bool build_it) {
possible_undeclared_dependency_ = nullptr;
undefine_resolved_name_.clear();
if (!name.empty() && name[0] == '.') {
// Fully-qualified name.
return FindSymbol(name.substr(1), build_it);
}
// If name is something like "Foo.Bar.baz", and symbols named "Foo" are
// defined in multiple parent scopes, we only want to find "Bar.baz" in the
// innermost one. E.g., the following should produce an error:
// message Bar { message Baz {} }
// message Foo {
// message Bar {
// }
// optional Bar.Baz baz = 1;
// }
// So, we look for just "Foo" first, then look for "Bar.baz" within it if
// found.
std::string::size_type name_dot_pos = name.find_first_of('.');
std::string first_part_of_name;
if (name_dot_pos == std::string::npos) {
first_part_of_name = name;
} else {
first_part_of_name = name.substr(0, name_dot_pos);
}
std::string scope_to_try(relative_to);
while (true) {
// Chop off the last component of the scope.
std::string::size_type dot_pos = scope_to_try.find_last_of('.');
if (dot_pos == std::string::npos) {
return FindSymbol(name, build_it);
} else {
scope_to_try.erase(dot_pos);
}
// Append ".first_part_of_name" and try to find.
std::string::size_type old_size = scope_to_try.size();
scope_to_try.append(1, '.');
scope_to_try.append(first_part_of_name);
Symbol result = FindSymbol(scope_to_try, build_it);
if (!result.IsNull()) {
if (first_part_of_name.size() < name.size()) {
// name is a compound symbol, of which we only found the first part.
// Now try to look up the rest of it.
if (result.IsAggregate()) {
scope_to_try.append(name, first_part_of_name.size(),
name.size() - first_part_of_name.size());
result = FindSymbol(scope_to_try, build_it);
if (result.IsNull()) {
undefine_resolved_name_ = scope_to_try;
}
return result;
} else {
// We found a symbol but it's not an aggregate. Continue the loop.
}
} else {
if (resolve_mode == LOOKUP_TYPES && !result.IsType()) {
// We found a symbol but it's not a type. Continue the loop.
} else {
return result;
}
}
}
// Not found. Remove the name so we can try again.
scope_to_try.erase(old_size);
}
}
Symbol DescriptorBuilder::LookupSymbol(
const std::string& name, const std::string& relative_to,
DescriptorPool::PlaceholderType placeholder_type, ResolveMode resolve_mode,
bool build_it) {
Symbol result =
LookupSymbolNoPlaceholder(name, relative_to, resolve_mode, build_it);
if (result.IsNull() && pool_->allow_unknown_) {
// Not found, but AllowUnknownDependencies() is enabled. Return a
// placeholder instead.
result = pool_->NewPlaceholderWithMutexHeld(name, placeholder_type);
}
return result;
}
static bool ValidateQualifiedName(absl::string_view name) {
bool last_was_period = false;
for (char character : name) {
// I don't trust isalnum() due to locales. :(
if (('a' <= character && character <= 'z') ||
('A' <= character && character <= 'Z') ||
('0' <= character && character <= '9') || (character == '_')) {
last_was_period = false;
} else if (character == '.') {
if (last_was_period) return false;
last_was_period = true;
} else {
return false;
}
}
return !name.empty() && !last_was_period;
}
Symbol DescriptorPool::NewPlaceholder(absl::string_view name,
PlaceholderType placeholder_type) const {
absl::MutexLockMaybe lock(mutex_);
return NewPlaceholderWithMutexHeld(name, placeholder_type);
}
Symbol DescriptorPool::NewPlaceholderWithMutexHeld(
absl::string_view name, PlaceholderType placeholder_type) const {
if (mutex_) {
mutex_->AssertHeld();
}
// Compute names.
absl::string_view placeholder_full_name;
absl::string_view placeholder_name;
const std::string* placeholder_package;
if (!ValidateQualifiedName(name)) return Symbol();
if (name[0] == '.') {
// Fully-qualified.
placeholder_full_name = name.substr(1);
} else {
placeholder_full_name = name;
}
// Create the placeholders.
internal::FlatAllocator alloc;
alloc.PlanArray<FileDescriptor>(1);
alloc.PlanArray<std::string>(2);
if (placeholder_type == PLACEHOLDER_ENUM) {
alloc.PlanArray<EnumDescriptor>(1);
alloc.PlanArray<EnumValueDescriptor>(1);
alloc.PlanArray<std::string>(2); // names for the descriptor.
alloc.PlanArray<std::string>(2); // names for the value.
} else {
alloc.PlanArray<Descriptor>(1);
alloc.PlanArray<std::string>(2); // names for the descriptor.
if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) {
alloc.PlanArray<Descriptor::ExtensionRange>(1);
}
}
alloc.FinalizePlanning(tables_);
const std::string::size_type dotpos = placeholder_full_name.find_last_of('.');
if (dotpos != std::string::npos) {
placeholder_package =
alloc.AllocateStrings(placeholder_full_name.substr(0, dotpos));
placeholder_name = placeholder_full_name.substr(dotpos + 1);
} else {
placeholder_package = alloc.AllocateStrings("");
placeholder_name = placeholder_full_name;
}
FileDescriptor* placeholder_file = NewPlaceholderFileWithMutexHeld(
absl::StrCat(placeholder_full_name, ".placeholder.proto"), alloc);
placeholder_file->package_ = placeholder_package;
if (placeholder_type == PLACEHOLDER_ENUM) {
placeholder_file->enum_type_count_ = 1;
placeholder_file->enum_types_ = alloc.AllocateArray<EnumDescriptor>(1);
EnumDescriptor* placeholder_enum = &placeholder_file->enum_types_[0];
memset(static_cast<void*>(placeholder_enum), 0, sizeof(*placeholder_enum));
placeholder_enum->all_names_ =
alloc.AllocateStrings(placeholder_name, placeholder_full_name);
placeholder_enum->file_ = placeholder_file;
placeholder_enum->options_ = &EnumOptions::default_instance();
#ifdef PROTOBUF_FUTURE_EDITIONS
placeholder_enum->proto_features_ = &FeatureSet::default_instance();
placeholder_enum->merged_features_ = &FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
placeholder_enum->is_placeholder_ = true;
placeholder_enum->is_unqualified_placeholder_ = (name[0] != '.');
// Enums must have at least one value.
placeholder_enum->value_count_ = 1;
placeholder_enum->values_ = alloc.AllocateArray<EnumValueDescriptor>(1);
// Disable fast-path lookup for this enum.
placeholder_enum->sequential_value_limit_ = -1;
EnumValueDescriptor* placeholder_value = &placeholder_enum->values_[0];
memset(static_cast<void*>(placeholder_value), 0,
sizeof(*placeholder_value));
// Note that enum value names are siblings of their type, not children.
placeholder_value->all_names_ = alloc.AllocateStrings(
"PLACEHOLDER_VALUE",
placeholder_package->empty()
? "PLACEHOLDER_VALUE"
: absl::StrCat(*placeholder_package, ".PLACEHOLDER_VALUE"));
placeholder_value->number_ = 0;
placeholder_value->type_ = placeholder_enum;
placeholder_value->options_ = &EnumValueOptions::default_instance();
return Symbol(placeholder_enum);
} else {
placeholder_file->message_type_count_ = 1;
placeholder_file->message_types_ = alloc.AllocateArray<Descriptor>(1);
Descriptor* placeholder_message = &placeholder_file->message_types_[0];
memset(static_cast<void*>(placeholder_message), 0,
sizeof(*placeholder_message));
placeholder_message->all_names_ =
alloc.AllocateStrings(placeholder_name, placeholder_full_name);
placeholder_message->file_ = placeholder_file;
placeholder_message->options_ = &MessageOptions::default_instance();
#ifdef PROTOBUF_FUTURE_EDITIONS
placeholder_message->proto_features_ = &FeatureSet::default_instance();
placeholder_message->merged_features_ = &FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
placeholder_message->is_placeholder_ = true;
placeholder_message->is_unqualified_placeholder_ = (name[0] != '.');
if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) {
placeholder_message->extension_range_count_ = 1;
placeholder_message->extension_ranges_ =
alloc.AllocateArray<Descriptor::ExtensionRange>(1);
placeholder_message->extension_ranges_[0].start_ = 1;
// kMaxNumber + 1 because ExtensionRange::end is exclusive.
placeholder_message->extension_ranges_[0].end_ =
FieldDescriptor::kMaxNumber + 1;
placeholder_message->extension_ranges_[0].options_ = nullptr;
#ifdef PROTOBUF_FUTURE_EDITIONS
placeholder_message->extension_ranges_[0].proto_features_ =
&FeatureSet::default_instance();
placeholder_message->extension_ranges_[0].merged_features_ =
&FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
}
return Symbol(placeholder_message);
}
}
FileDescriptor* DescriptorPool::NewPlaceholderFile(
absl::string_view name) const {
absl::MutexLockMaybe lock(mutex_);
internal::FlatAllocator alloc;
alloc.PlanArray<FileDescriptor>(1);
alloc.PlanArray<std::string>(1);
alloc.FinalizePlanning(tables_);
return NewPlaceholderFileWithMutexHeld(name, alloc);
}
FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld(
absl::string_view name, internal::FlatAllocator& alloc) const {
if (mutex_) {
mutex_->AssertHeld();
}
FileDescriptor* placeholder = alloc.AllocateArray<FileDescriptor>(1);
memset(static_cast<void*>(placeholder), 0, sizeof(*placeholder));
placeholder->name_ = alloc.AllocateStrings(name);
placeholder->package_ = &internal::GetEmptyString();
placeholder->pool_ = this;
placeholder->options_ = &FileOptions::default_instance();
#ifdef PROTOBUF_FUTURE_EDITIONS
placeholder->proto_features_ = &FeatureSet::default_instance();
placeholder->merged_features_ = &FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
placeholder->tables_ = &FileDescriptorTables::GetEmptyInstance();
placeholder->source_code_info_ = &SourceCodeInfo::default_instance();
placeholder->is_placeholder_ = true;
placeholder->syntax_ = FileDescriptorLegacy::SYNTAX_UNKNOWN;
placeholder->finished_building_ = true;
// All other fields are zero or nullptr.
return placeholder;
}
bool DescriptorBuilder::AddSymbol(const std::string& full_name,
const void* parent, const std::string& name,
const Message& proto, Symbol symbol) {
// If the caller passed nullptr for the parent, the symbol is at file scope.
// Use its file as the parent instead.
if (parent == nullptr) parent = file_;
if (absl::StrContains(full_name, '\0')) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", full_name, "\" contains null character.");
});
return false;
}
if (tables_->AddSymbol(full_name, symbol)) {
if (!file_tables_->AddAliasUnderParent(parent, name, symbol)) {
// This is only possible if there was already an error adding something of
// the same name.
if (!had_errors_) {
ABSL_DLOG(FATAL) << "\"" << full_name
<< "\" not previously defined in "
"symbols_by_name_, but was defined in "
"symbols_by_parent_; this shouldn't be possible.";
}
return false;
}
return true;
} else {
const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile();
if (other_file == file_) {
std::string::size_type dot_pos = full_name.find_last_of('.');
if (dot_pos == std::string::npos) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", full_name, "\" is already defined.");
});
} else {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", full_name.substr(dot_pos + 1),
"\" is already defined in \"",
full_name.substr(0, dot_pos), "\".");
});
}
} else {
// Symbol seems to have been defined in a different file.
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat(
"\"", full_name, "\" is already defined in file \"",
(other_file == nullptr ? "null" : other_file->name()), "\".");
});
}
return false;
}
}
void DescriptorBuilder::AddPackage(const std::string& name,
const Message& proto, FileDescriptor* file) {
if (name.find('\0') != std::string::npos) {
AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", name, "\" contains null character.");
});
return;
}
Symbol existing_symbol = tables_->FindSymbol(name);
// It's OK to redefine a package.
if (existing_symbol.IsNull()) {
if (name.data() == file->package().data()) {
// It is the toplevel package name, so insert the descriptor directly.
tables_->AddSymbol(file->package(), Symbol(file));
} else {
auto* package = tables_->Allocate<Symbol::Subpackage>();
// If the name is the package name, then it is already in the arena.
// If not, copy it there. It came from the call to AddPackage below.
package->name_size = static_cast<int>(name.size());
package->file = file;
tables_->AddSymbol(name, Symbol(package));
}
// Also add parent package, if any.
std::string::size_type dot_pos = name.find_last_of('.');
if (dot_pos == std::string::npos) {
// No parents.
ValidateSymbolName(name, name, proto);
} else {
// Has parent.
AddPackage(name.substr(0, dot_pos), proto, file);
ValidateSymbolName(name.substr(dot_pos + 1), name, proto);
}
} else if (!existing_symbol.IsPackage()) {
// Symbol seems to have been defined in a different file.
const FileDescriptor* other_file = existing_symbol.GetFile();
AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", name,
"\" is already defined (as something other than "
"a package) in file \"",
(other_file == nullptr ? "null" : other_file->name()),
"\".");
});
}
}
void DescriptorBuilder::ValidateSymbolName(const std::string& name,
const std::string& full_name,
const Message& proto) {
if (name.empty()) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
"Missing name.");
} else {
for (char character : name) {
// I don't trust isalnum() due to locales. :(
if ((character < 'a' || 'z' < character) &&
(character < 'A' || 'Z' < character) &&
(character < '0' || '9' < character) && (character != '_')) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", name, "\" is not a valid identifier.");
});
return;
}
}
}
}
// -------------------------------------------------------------------
// This generic implementation is good for all descriptors except
// FileDescriptor.
template <class DescriptorT>
void DescriptorBuilder::AllocateOptions(
const typename DescriptorT::Proto& proto, DescriptorT* descriptor,
int options_field_tag, absl::string_view option_name,
internal::FlatAllocator& alloc) {
std::vector<int> options_path;
descriptor->GetLocationPath(&options_path);
options_path.push_back(options_field_tag);
auto options = AllocateOptionsImpl<DescriptorT>(
descriptor->full_name(), descriptor->full_name(), proto, options_path,
option_name, alloc);
descriptor->options_ = options;
#ifdef PROTOBUF_FUTURE_EDITIONS
descriptor->proto_features_ = &FeatureSet::default_instance();
descriptor->merged_features_ = &FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
}
// We specialize for FileDescriptor.
void DescriptorBuilder::AllocateOptions(const FileDescriptorProto& proto,
FileDescriptor* descriptor,
internal::FlatAllocator& alloc) {
std::vector<int> options_path;
options_path.push_back(FileDescriptorProto::kOptionsFieldNumber);
// We add the dummy token so that LookupSymbol does the right thing.
auto options = AllocateOptionsImpl<FileDescriptor>(
absl::StrCat(descriptor->package(), ".dummy"), descriptor->name(), proto,
options_path, "google.protobuf.FileOptions", alloc);
descriptor->options_ = options;
#ifdef PROTOBUF_FUTURE_EDITIONS
descriptor->proto_features_ = &FeatureSet::default_instance();
descriptor->merged_features_ = &FeatureSet::default_instance();
#endif // PROTOBUF_FUTURE_EDITIONS
}
template <class DescriptorT>
typename DescriptorT::OptionsType* DescriptorBuilder::AllocateOptionsImpl(
absl::string_view name_scope, absl::string_view element_name,
const typename DescriptorT::Proto& proto,
absl::Span<const int> options_path, absl::string_view option_name,
internal::FlatAllocator& alloc) {
if (!proto.has_options()) {
// Set to default_instance later if necessary.
return nullptr;
}
const typename DescriptorT::OptionsType& orig_options = proto.options();
auto* options = alloc.AllocateArray<typename DescriptorT::OptionsType>(1);
if (!orig_options.IsInitialized()) {
AddError(absl::StrCat(name_scope, ".", element_name), orig_options,
DescriptorPool::ErrorCollector::OPTION_NAME,
"Uninterpreted option is missing name or value.");
return nullptr;
}
// Avoid using MergeFrom()/CopyFrom() in this class to make it -fno-rtti
// friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback to the
// reflection based method, which requires the Descriptor. However, we are in
// the middle of building the descriptors, thus the deadlock.
options->ParseFromString(orig_options.SerializeAsString());
// Don't add to options_to_interpret_ unless there were uninterpreted
// options. This not only avoids unnecessary work, but prevents a
// bootstrapping problem when building descriptors for descriptor.proto.
// descriptor.proto does not contain any uninterpreted options, but
// attempting to interpret options anyway will cause
// OptionsType::GetDescriptor() to be called which may then deadlock since
// we're still trying to build it.
if (options->uninterpreted_option_size() > 0) {
options_to_interpret_.push_back(OptionsToInterpret(
name_scope, element_name, options_path, &orig_options, options));
}
// If the custom option is in unknown fields, no need to interpret it.
// Remove the dependency file from unused_dependency.
const UnknownFieldSet& unknown_fields = orig_options.unknown_fields();
if (!unknown_fields.empty()) {
// Can not use options->GetDescriptor() which may case deadlock.
Symbol msg_symbol = tables_->FindSymbol(option_name);
if (msg_symbol.type() == Symbol::MESSAGE) {
for (int i = 0; i < unknown_fields.field_count(); ++i) {
assert_mutex_held(pool_);
const FieldDescriptor* field =
pool_->InternalFindExtensionByNumberNoLock(
msg_symbol.descriptor(), unknown_fields.field(i).number());
if (field) {
unused_dependency_.erase(field->file());
}
}
}
}
return options;
}
#ifdef PROTOBUF_FUTURE_EDITIONS
template <class DescriptorT>
void DescriptorBuilder::ResolveFeaturesImpl(
const typename DescriptorT::Proto& proto, DescriptorT* descriptor,
typename DescriptorT::OptionsType* options, internal::FlatAllocator& alloc,
DescriptorPool::ErrorCollector::ErrorLocation error_location,
bool force_merge) {
const FeatureSet& parent_features = GetParentFeatures(descriptor);
descriptor->merged_features_ =
GetLegacyFeatureOverride(&parent_features, descriptor);
descriptor->proto_features_ = &FeatureSet::default_instance();
if (!feature_resolver_.has_value()) {
if (options != nullptr && options->has_features()) {
AddError(descriptor->name(), proto, error_location,
"Features are only valid under editions.");
}
return;
}
if (options != nullptr && options->has_features()) {
// Remove the features from the child's options proto to avoid leaking
// internal details.
FeatureSet* mutable_features = alloc.AllocateArray<FeatureSet>(1);
descriptor->proto_features_ = mutable_features;
if (options->features().has_raw_features()) {
// If the raw features are specified, use those and recalculate the
// resolved features.
options->mutable_features()->mutable_raw_features()->Swap(
mutable_features);
} else {
options->mutable_features()->Swap(mutable_features);
}
options->clear_features();
} else if (!force_merge) {
// Nothing to merge, and we aren't forcing it.
return;
}
FeatureSet* merged_features = alloc.AllocateArray<FeatureSet>(1);
// Calculate the merged features for this target.
absl::StatusOr<FeatureSet> merged = feature_resolver_->MergeFeatures(
parent_features, *descriptor->proto_features_);
if (!merged.ok()) {
AddError(descriptor->name(), proto, error_location,
[&] { return std::string(merged.status().message()); });
return;
}
merged_features->Swap(&merged.value());
descriptor->merged_features_ = merged_features;
}
template <class DescriptorT>
void DescriptorBuilder::ResolveFeatures(
const typename DescriptorT::Proto& proto, DescriptorT* descriptor,
typename DescriptorT::OptionsType* options,
internal::FlatAllocator& alloc) {
ResolveFeaturesImpl(proto, descriptor, options, alloc,
DescriptorPool::ErrorCollector::NAME);
}
void DescriptorBuilder::ResolveFeatures(const FileDescriptorProto& proto,
FileDescriptor* descriptor,
FileOptions* options,
internal::FlatAllocator& alloc) {
// File descriptors always need their own merged feature set, even without
// any explicit features.
ResolveFeaturesImpl(proto, descriptor, options, alloc,
DescriptorPool::ErrorCollector::EDITIONS,
/*force_merge=*/true);
}
template <typename DescriptorT>
const FeatureSet* DescriptorBuilder::GetLegacyFeatureOverride(
const FeatureSet* parent_features, const DescriptorT* descriptor) {
return parent_features;
}
template <>
const FeatureSet* DescriptorBuilder::GetLegacyFeatureOverride(
const FeatureSet* parent_features, const FieldDescriptor* descriptor) {
// Groups use delimited message encoding.
if (parent_features == &GetProto2Features() &&
descriptor->type_ == FieldDescriptor::TYPE_GROUP) {
return &GetProto2GroupFeatures();
}
return parent_features;
}
void DescriptorBuilder::PostProcessFieldFeatures(FieldDescriptor& field) {
// TODO(b/285013359) This can be replace by a runtime check in `is_required`
// once the `label` getter is hidden.
if (field.features().field_presence() == FeatureSet::LEGACY_REQUIRED &&
field.label_ == FieldDescriptor::LABEL_OPTIONAL) {
field.label_ = FieldDescriptor::LABEL_REQUIRED;
}
// TODO(b/285024320) This can be replace by a runtime check of `is_delimited`
// once the `TYPE_GROUP` value is removed.
if (field.type_ == FieldDescriptor::TYPE_MESSAGE &&
field.features().message_encoding() == FeatureSet::DELIMITED) {
field.type_ = FieldDescriptor::TYPE_GROUP;
}
}
#endif // PROTOBUF_FUTURE_EDITIONS
// A common pattern: We want to convert a repeated field in the descriptor
// to an array of values, calling some method to build each value.
#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \
OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \
OUTPUT->NAME##s_ = alloc.AllocateArray< \
typename std::remove_pointer<decltype(OUTPUT->NAME##s_)>::type>( \
INPUT.NAME##_size()); \
for (int i = 0; i < INPUT.NAME##_size(); i++) { \
METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i, alloc); \
}
PROTOBUF_NOINLINE void DescriptorBuilder::AddRecursiveImportError(
const FileDescriptorProto& proto, int from_here) {
auto make_error = [&] {
std::string error_message("File recursively imports itself: ");
for (size_t i = from_here; i < tables_->pending_files_.size(); i++) {
error_message.append(tables_->pending_files_[i]);
error_message.append(" -> ");
}
error_message.append(proto.name());
return error_message;
};
if (static_cast<size_t>(from_here) < tables_->pending_files_.size() - 1) {
AddError(tables_->pending_files_[from_here + 1], proto,
DescriptorPool::ErrorCollector::IMPORT, make_error);
} else {
AddError(proto.name(), proto, DescriptorPool::ErrorCollector::IMPORT,
make_error);
}
}
void DescriptorBuilder::AddTwiceListedError(const FileDescriptorProto& proto,
int index) {
AddError(proto.dependency(index), proto,
DescriptorPool::ErrorCollector::IMPORT, [&] {
return absl::StrCat("Import \"", proto.dependency(index),
"\" was listed twice.");
});
}
void DescriptorBuilder::AddImportError(const FileDescriptorProto& proto,
int index) {
auto make_error = [&] {
if (pool_->fallback_database_ == nullptr) {
return absl::StrCat("Import \"", proto.dependency(index),
"\" has not been loaded.");
}
return absl::StrCat("Import \"", proto.dependency(index),
"\" was not found or had errors.");
};
AddError(proto.dependency(index), proto,
DescriptorPool::ErrorCollector::IMPORT, make_error);
}
PROTOBUF_NOINLINE static bool ExistingFileMatchesProto(
const FileDescriptor* existing_file, const FileDescriptorProto& proto) {
FileDescriptorProto existing_proto;
existing_file->CopyTo(&existing_proto);
// TODO(liujisi): Remove it when CopyTo supports copying syntax params when
// syntax="proto2".
if (FileDescriptorLegacy(existing_file).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO2 &&
proto.has_syntax()) {
existing_proto.set_syntax(FileDescriptorLegacy::SyntaxName(
FileDescriptorLegacy(existing_file).syntax()));
}
return existing_proto.SerializeAsString() == proto.SerializeAsString();
}
// These PlanAllocationSize functions will gather into the FlatAllocator all the
// necessary memory allocations that BuildXXX functions below will do on the
// Tables object.
// They *must* be kept in sync. If we miss some PlanArray call we won't have
// enough memory and will ABSL_CHECK-fail.
static void PlanAllocationSize(
const RepeatedPtrField<EnumValueDescriptorProto>& values,
internal::FlatAllocator& alloc) {
alloc.PlanArray<EnumValueDescriptor>(values.size());
alloc.PlanArray<std::string>(2 * values.size()); // name + full_name
for (const auto& v : values) {
if (v.has_options()) alloc.PlanArray<EnumValueOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(v.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
}
}
static void PlanAllocationSize(
const RepeatedPtrField<EnumDescriptorProto>& enums,
internal::FlatAllocator& alloc) {
alloc.PlanArray<EnumDescriptor>(enums.size());
alloc.PlanArray<std::string>(2 * enums.size()); // name + full_name
for (const auto& e : enums) {
if (e.has_options()) alloc.PlanArray<EnumOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(e.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
PlanAllocationSize(e.value(), alloc);
alloc.PlanArray<EnumDescriptor::ReservedRange>(e.reserved_range_size());
alloc.PlanArray<const std::string*>(e.reserved_name_size());
alloc.PlanArray<std::string>(e.reserved_name_size());
}
}
static void PlanAllocationSize(
const RepeatedPtrField<OneofDescriptorProto>& oneofs,
internal::FlatAllocator& alloc) {
alloc.PlanArray<OneofDescriptor>(oneofs.size());
alloc.PlanArray<std::string>(2 * oneofs.size()); // name + full_name
for (const auto& oneof : oneofs) {
if (oneof.has_options()) alloc.PlanArray<OneofOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(oneof.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
}
}
static void PlanAllocationSize(
const RepeatedPtrField<FieldDescriptorProto>& fields,
internal::FlatAllocator& alloc) {
alloc.PlanArray<FieldDescriptor>(fields.size());
for (const auto& field : fields) {
if (field.has_options()) alloc.PlanArray<FieldOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(field.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
alloc.PlanFieldNames(field.name(),
field.has_json_name() ? &field.json_name() : nullptr);
if (field.has_default_value() && field.has_type() &&
(field.type() == FieldDescriptorProto::TYPE_STRING ||
field.type() == FieldDescriptorProto::TYPE_BYTES)) {
// For the default string value.
alloc.PlanArray<std::string>(1);
}
}
}
static void PlanAllocationSize(
const RepeatedPtrField<DescriptorProto::ExtensionRange>& ranges,
internal::FlatAllocator& alloc) {
alloc.PlanArray<Descriptor::ExtensionRange>(ranges.size());
for (const auto& r : ranges) {
if (r.has_options()) alloc.PlanArray<ExtensionRangeOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(r.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
}
}
static void PlanAllocationSize(
const RepeatedPtrField<DescriptorProto>& messages,
internal::FlatAllocator& alloc) {
alloc.PlanArray<Descriptor>(messages.size());
alloc.PlanArray<std::string>(2 * messages.size()); // name + full_name
for (const auto& message : messages) {
if (message.has_options()) alloc.PlanArray<MessageOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(message.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
PlanAllocationSize(message.nested_type(), alloc);
PlanAllocationSize(message.field(), alloc);
PlanAllocationSize(message.extension(), alloc);
PlanAllocationSize(message.extension_range(), alloc);
alloc.PlanArray<Descriptor::ReservedRange>(message.reserved_range_size());
alloc.PlanArray<const std::string*>(message.reserved_name_size());
alloc.PlanArray<std::string>(message.reserved_name_size());
PlanAllocationSize(message.enum_type(), alloc);
PlanAllocationSize(message.oneof_decl(), alloc);
}
}
static void PlanAllocationSize(
const RepeatedPtrField<MethodDescriptorProto>& methods,
internal::FlatAllocator& alloc) {
alloc.PlanArray<MethodDescriptor>(methods.size());
alloc.PlanArray<std::string>(2 * methods.size()); // name + full_name
for (const auto& m : methods) {
if (m.has_options()) alloc.PlanArray<MethodOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(m.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
}
}
static void PlanAllocationSize(
const RepeatedPtrField<ServiceDescriptorProto>& services,
internal::FlatAllocator& alloc) {
alloc.PlanArray<ServiceDescriptor>(services.size());
alloc.PlanArray<std::string>(2 * services.size()); // name + full_name
for (const auto& service : services) {
if (service.has_options()) alloc.PlanArray<ServiceOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (HasFeatures(service.options())) alloc.PlanArray<FeatureSet>(2);
#endif // !PROTOBUF_FUTURE_EDITIONS
PlanAllocationSize(service.method(), alloc);
}
}
static void PlanAllocationSize(const FileDescriptorProto& proto,
internal::FlatAllocator& alloc) {
alloc.PlanArray<FileDescriptor>(1);
alloc.PlanArray<FileDescriptorTables>(1);
alloc.PlanArray<std::string>(2
#ifdef PROTOBUF_FUTURE_EDITIONS
+ (proto.has_edition() ? 1 : 0)
#endif // !PROTOBUF_FUTURE_EDITIONS
); // name + package
if (proto.has_options()) alloc.PlanArray<FileOptions>(1);
#ifdef PROTOBUF_FUTURE_EDITIONS
if (proto.has_edition()) {
alloc.PlanArray<FeatureSet>(1);
if (HasFeatures(proto.options())) {
alloc.PlanArray<FeatureSet>(1);
}
}
#endif // !PROTOBUF_FUTURE_EDITIONS
if (proto.has_source_code_info()) alloc.PlanArray<SourceCodeInfo>(1);
PlanAllocationSize(proto.service(), alloc);
PlanAllocationSize(proto.message_type(), alloc);
PlanAllocationSize(proto.enum_type(), alloc);
PlanAllocationSize(proto.extension(), alloc);
alloc.PlanArray<int>(proto.weak_dependency_size());
alloc.PlanArray<int>(proto.public_dependency_size());
alloc.PlanArray<const FileDescriptor*>(proto.dependency_size());
}
const FileDescriptor* DescriptorBuilder::BuildFile(
const FileDescriptorProto& original_proto) {
filename_ = original_proto.name();
const FileDescriptorProto& proto = original_proto;
// Check if the file already exists and is identical to the one being built.
// Note: This only works if the input is canonical -- that is, it
// fully-qualifies all type names, has no UninterpretedOptions, etc.
// This is fine, because this idempotency "feature" really only exists to
// accommodate one hack in the proto1->proto2 migration layer.
const FileDescriptor* existing_file = tables_->FindFile(filename_);
if (existing_file != nullptr) {
// File already in pool. Compare the existing one to the input.
if (ExistingFileMatchesProto(existing_file, proto)) {
// They're identical. Return the existing descriptor.
return existing_file;
}
// Not a match. The error will be detected and handled later.
}
// Check to see if this file is already on the pending files list.
// TODO(kenton): Allow recursive imports? It may not work with some
// (most?) programming languages. E.g., in C++, a forward declaration
// of a type is not sufficient to allow it to be used even in a
// generated header file due to inlining. This could perhaps be
// worked around using tricks involving inserting #include statements
// mid-file, but that's pretty ugly, and I'm pretty sure there are
// some languages out there that do not allow recursive dependencies
// at all.
for (size_t i = 0; i < tables_->pending_files_.size(); i++) {
if (tables_->pending_files_[i] == proto.name()) {
AddRecursiveImportError(proto, i);
return nullptr;
}
}
static const int kMaximumPackageLength = 511;
if (proto.package().size() > kMaximumPackageLength) {
AddError(proto.package(), proto, DescriptorPool::ErrorCollector::NAME,
"Package name is too long");
return nullptr;
}
// If we have a fallback_database_, and we aren't doing lazy import building,
// attempt to load all dependencies now, before checkpointing tables_. This
// avoids confusion with recursive checkpoints.
if (!pool_->lazily_build_dependencies_) {
if (pool_->fallback_database_ != nullptr) {
tables_->pending_files_.push_back(proto.name());
for (int i = 0; i < proto.dependency_size(); i++) {
if (tables_->FindFile(proto.dependency(i)) == nullptr &&
(pool_->underlay_ == nullptr ||
pool_->underlay_->FindFileByName(proto.dependency(i)) ==
nullptr)) {
// We don't care what this returns since we'll find out below anyway.
pool_->TryFindFileInFallbackDatabase(proto.dependency(i));
}
}
tables_->pending_files_.pop_back();
}
}
// Checkpoint the tables so that we can roll back if something goes wrong.
tables_->AddCheckpoint();
auto alloc = absl::make_unique<internal::FlatAllocator>();
PlanAllocationSize(proto, *alloc);
alloc->FinalizePlanning(tables_);
FileDescriptor* result = BuildFileImpl(proto, *alloc);
file_tables_->FinalizeTables();
if (result) {
tables_->ClearLastCheckpoint();
result->finished_building_ = true;
alloc->ExpectConsumed();
} else {
tables_->RollbackToLastCheckpoint();
}
return result;
}
FileDescriptor* DescriptorBuilder::BuildFileImpl(
const FileDescriptorProto& proto, internal::FlatAllocator& alloc) {
FileDescriptor* result = alloc.AllocateArray<FileDescriptor>(1);
file_ = result;
#ifdef PROTOBUF_FUTURE_EDITIONS
if (proto.has_edition()) {
Symbol symbol = FindSymbolNotEnforcingDeps("google.protobuf.FeatureSet");
const Descriptor* descriptor = symbol.descriptor();
if (descriptor == nullptr) {
// descriptor.proto is not in the pool. This means no custom features are
// used so we are safe to proceed with the compiled FeatureSet message
// type.
descriptor = FeatureSet::descriptor();
}
ABSL_CHECK(descriptor);
absl::StatusOr<FeatureResolver> feature_resolver =
FeatureResolver::Create(proto.edition(), descriptor);
if (!feature_resolver.ok()) {
AddError(
proto.name(), proto, DescriptorPool::ErrorCollector::EDITIONS,
[&] { return std::string(feature_resolver.status().message()); });
} else {
feature_resolver_.emplace(std::move(feature_resolver).value());
}
}
#endif // PROTOBUF_FUTURE_EDITIONS
result->is_placeholder_ = false;
result->finished_building_ = false;
SourceCodeInfo* info = nullptr;
if (proto.has_source_code_info()) {
info = alloc.AllocateArray<SourceCodeInfo>(1);
info->CopyFrom(proto.source_code_info());
result->source_code_info_ = info;
} else {
result->source_code_info_ = &SourceCodeInfo::default_instance();
}
file_tables_ = alloc.AllocateArray<FileDescriptorTables>(1);
file_->tables_ = file_tables_;
if (!proto.has_name()) {
AddError("", proto, DescriptorPool::ErrorCollector::OTHER,
"Missing field: FileDescriptorProto.name.");
}
// TODO(liujisi): Report error when the syntax is empty after all the protos
// have added the syntax statement.
if (proto.syntax().empty() || proto.syntax() == "proto2") {
file_->syntax_ = FileDescriptorLegacy::SYNTAX_PROTO2;
} else if (proto.syntax() == "proto3") {
file_->syntax_ = FileDescriptorLegacy::SYNTAX_PROTO3;
#ifdef PROTOBUF_FUTURE_EDITIONS
} else if (proto.syntax() == "editions") {
file_->syntax_ = FileDescriptorLegacy::SYNTAX_EDITIONS;
#endif // !PROTOBUF_FUTURE_EDITIONS
} else {
file_->syntax_ = FileDescriptorLegacy::SYNTAX_UNKNOWN;
AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, [&] {
return absl::StrCat("Unrecognized syntax: ", proto.syntax());
});
}
#ifdef PROTOBUF_FUTURE_EDITIONS
if (proto.has_edition()) {
file_->edition_ = alloc.AllocateStrings(proto.edition());
}
#endif // !PROTOBUF_FUTURE_EDITIONS
result->name_ = alloc.AllocateStrings(proto.name());
if (proto.has_package()) {
result->package_ = alloc.AllocateStrings(proto.package());
} else {
// We cannot rely on proto.package() returning a valid string if
// proto.has_package() is false, because we might be running at static
// initialization time, in which case default values have not yet been
// initialized.
result->package_ = alloc.AllocateStrings("");
}
result->pool_ = pool_;
if (result->name().find('\0') != std::string::npos) {
AddError(result->name(), proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("\"", result->name(), "\" contains null character.");
});
return nullptr;
}
// Add to tables.
if (!tables_->AddFile(result)) {
AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
"A file with this name is already in the pool.");
// Bail out early so that if this is actually the exact same file, we
// don't end up reporting that every single symbol is already defined.
return nullptr;
}
if (!result->package().empty()) {
if (std::count(result->package().begin(), result->package().end(), '.') >
kPackageLimit) {
AddError(result->package(), proto, DescriptorPool::ErrorCollector::NAME,
"Exceeds Maximum Package Depth");
return nullptr;
}
AddPackage(result->package(), proto, result);
}
// Make sure all dependencies are loaded.
absl::flat_hash_set<absl::string_view> seen_dependencies;
result->dependency_count_ = proto.dependency_size();
result->dependencies_ =
alloc.AllocateArray<const FileDescriptor*>(proto.dependency_size());
result->dependencies_once_ = nullptr;
unused_dependency_.clear();
absl::flat_hash_set<int> weak_deps;
for (int i = 0; i < proto.weak_dependency_size(); ++i) {
weak_deps.insert(proto.weak_dependency(i));
}
bool need_lazy_deps = false;
for (int i = 0; i < proto.dependency_size(); i++) {
if (!seen_dependencies.insert(proto.dependency(i)).second) {
AddTwiceListedError(proto, i);
}
const FileDescriptor* dependency = tables_->FindFile(proto.dependency(i));
if (dependency == nullptr && pool_->underlay_ != nullptr) {
dependency = pool_->underlay_->FindFileByName(proto.dependency(i));
}
if (dependency == result) {
// Recursive import. dependency/result is not fully initialized, and it's
// dangerous to try to do anything with it. The recursive import error
// will be detected and reported in DescriptorBuilder::BuildFile().
return nullptr;
}
#ifdef PROTOBUF_FUTURE_EDITIONS
// Look for feature extensions in regular imports.
if (feature_resolver_.has_value() && dependency != nullptr) {
absl::Status status = feature_resolver_->RegisterExtensions(*dependency);
if (!status.ok()) {
AddError(dependency->name(), proto,
DescriptorPool::ErrorCollector::EDITIONS,
[&] { return std::string(status.message()); });
}
}
#endif // PROTOBUF_FUTURE_EDITIONS
if (dependency == nullptr) {
if (!pool_->lazily_build_dependencies_) {
if (pool_->allow_unknown_ ||
(!pool_->enforce_weak_ && weak_deps.contains(i))) {
internal::FlatAllocator lazy_dep_alloc;
lazy_dep_alloc.PlanArray<FileDescriptor>(1);
lazy_dep_alloc.PlanArray<std::string>(1);
lazy_dep_alloc.FinalizePlanning(tables_);
dependency = pool_->NewPlaceholderFileWithMutexHeld(
proto.dependency(i), lazy_dep_alloc);
} else {
AddImportError(proto, i);
}
}
} else {
// Add to unused_dependency_ to track unused imported files.
// Note: do not track unused imported files for public import.
if (pool_->enforce_dependencies_ &&
(pool_->unused_import_track_files_.find(proto.name()) !=
pool_->unused_import_track_files_.end()) &&
(dependency->public_dependency_count() == 0)) {
unused_dependency_.insert(dependency);
}
}
result->dependencies_[i] = dependency;
if (pool_->lazily_build_dependencies_ && !dependency) {
need_lazy_deps = true;
}
}
if (need_lazy_deps) {
int total_char_size = 0;
for (int i = 0; i < proto.dependency_size(); i++) {
if (result->dependencies_[i] == nullptr) {
total_char_size += static_cast<int>(proto.dependency(i).size());
}
++total_char_size; // For NUL char
}
void* data = tables_->AllocateBytes(
static_cast<int>(sizeof(absl::once_flag)) + total_char_size);
result->dependencies_once_ = ::new (data) absl::once_flag{};
char* name_data = reinterpret_cast<char*>(result->dependencies_once_ + 1);
for (int i = 0; i < proto.dependency_size(); i++) {
if (result->dependencies_[i] == nullptr) {
memcpy(name_data, proto.dependency(i).c_str(),
proto.dependency(i).size());
name_data += proto.dependency(i).size();
}
*name_data++ = '\0';
}
}
// Check public dependencies.
int public_dependency_count = 0;
result->public_dependencies_ =
alloc.AllocateArray<int>(proto.public_dependency_size());
for (int i = 0; i < proto.public_dependency_size(); i++) {
// Only put valid public dependency indexes.
int index = proto.public_dependency(i);
if (index >= 0 && index < proto.dependency_size()) {
result->public_dependencies_[public_dependency_count++] = index;
// Do not track unused imported files for public import.
// Calling dependency(i) builds that file when doing lazy imports,
// need to avoid doing this. Unused dependency detection isn't done
// when building lazily, anyways.
if (!pool_->lazily_build_dependencies_) {
unused_dependency_.erase(result->dependency(index));
}
} else {
AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
"Invalid public dependency index.");
}
}
result->public_dependency_count_ = public_dependency_count;
// Build dependency set
dependencies_.clear();
// We don't/can't do proper dependency error checking when
// lazily_build_dependencies_, and calling dependency(i) will force
// a dependency to be built, which we don't want.
if (!pool_->lazily_build_dependencies_) {
for (int i = 0; i < result->dependency_count(); i++) {
RecordPublicDependencies(result->dependency(i));
}
}
// Check weak dependencies.
int weak_dependency_count = 0;
result->weak_dependencies_ =
alloc.AllocateArray<int>(proto.weak_dependency_size());
for (int i = 0; i < proto.weak_dependency_size(); i++) {
int index = proto.weak_dependency(i);
if (index >= 0 && index < proto.dependency_size()) {
result->weak_dependencies_[weak_dependency_count++] = index;
} else {
AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
"Invalid weak dependency index.");
}
}
result->weak_dependency_count_ = weak_dependency_count;
// Convert children.
BUILD_ARRAY(proto, result, message_type, BuildMessage, nullptr);
BUILD_ARRAY(proto, result, enum_type, BuildEnum, nullptr);
BUILD_ARRAY(proto, result, service, BuildService, nullptr);
BUILD_ARRAY(proto, result, extension, BuildExtension, nullptr);
// Copy options.
AllocateOptions(proto, result, alloc);
// Note that the following steps must occur in exactly the specified order.
// Cross-link.
CrossLinkFile(result, proto);
if (!message_hints_.empty()) {
SuggestFieldNumbers(result, proto);
}
#ifdef PROTOBUF_FUTURE_EDITIONS
// Interpret only the feature options first. This has to be done in two
// passes, since options defined in this file may have features attached
// to them.
if (!had_errors_) {
OptionInterpreter option_interpreter(this);
for (std::vector<OptionsToInterpret>::iterator iter =
options_to_interpret_.begin();
iter != options_to_interpret_.end(); ++iter) {
option_interpreter.InterpretFeatures(&(*iter));
}
}
// Handle feature resolution. This must occur after option interpretation,
// but before validation.
internal::VisitDescriptors(
*result, proto, [&](const auto& descriptor, const auto& proto) {
using OptionsT =
typename std::remove_const<typename std::remove_pointer<
decltype(descriptor.options_)>::type>::type;
using DescriptorT = typename std::remove_const<
typename std::remove_reference<decltype(descriptor)>::type>::type;
ResolveFeatures(
proto, const_cast<DescriptorT*>(&descriptor),
const_cast<OptionsT*>( // NOLINT(google3-runtime-proto-const-cast)
descriptor.options_),
alloc);
});
// Post-process cleanup for field features.
internal::VisitDescriptors(*result, [&](const FieldDescriptor& field) {
PostProcessFieldFeatures(const_cast<FieldDescriptor&>(field));
});
#endif // PROTOBUF_FUTURE_EDITIONS
// Interpret any remaining uninterpreted options gathered into
// options_to_interpret_ during descriptor building. Cross-linking has made
// extension options known, so all interpretations should now succeed.
if (!had_errors_) {
OptionInterpreter option_interpreter(this);
for (std::vector<OptionsToInterpret>::iterator iter =
options_to_interpret_.begin();
iter != options_to_interpret_.end(); ++iter) {
option_interpreter.InterpretOptions(&(*iter));
}
options_to_interpret_.clear();
if (info != nullptr) {
option_interpreter.UpdateSourceCodeInfo(info);
}
}
// Validate options. See comments at InternalSetLazilyBuildDependencies about
// error checking and lazy import building.
if (!had_errors_ && !pool_->lazily_build_dependencies_) {
internal::VisitDescriptors(*result, proto,
[&](const auto& descriptor, const auto& proto) {
ValidateOptions(&descriptor, proto);
});
}
// Additional naming conflict check for map entry types. Only need to check
// this if there are already errors.
if (had_errors_) {
for (int i = 0; i < proto.message_type_size(); ++i) {
DetectMapConflicts(result->message_type(i), proto.message_type(i));
}
}
// Again, see comments at InternalSetLazilyBuildDependencies about error
// checking. Also, don't log unused dependencies if there were previous
// errors, since the results might be inaccurate.
if (!had_errors_ && !unused_dependency_.empty() &&
!pool_->lazily_build_dependencies_) {
LogUnusedDependency(proto, result);
}
if (had_errors_) {
return nullptr;
} else {
return result;
}
}
const std::string* DescriptorBuilder::AllocateNameStrings(
const std::string& scope, const std::string& proto_name,
internal::FlatAllocator& alloc) {
if (scope.empty()) {
return alloc.AllocateStrings(proto_name, proto_name);
} else {
return alloc.AllocateStrings(proto_name,
absl::StrCat(scope, ".", proto_name));
}
}
namespace {
// Helper for BuildMessage below.
struct IncrementWhenDestroyed {
~IncrementWhenDestroyed() { ++to_increment; }
int& to_increment;
};
} // namespace
namespace {
bool IsNonMessageType(absl::string_view type) {
static const auto* non_message_types =
new absl::flat_hash_set<absl::string_view>(
{"double", "float", "int64", "uint64", "int32", "fixed32", "fixed64",
"bool", "string", "bytes", "uint32", "enum", "sfixed32", "sfixed64",
"sint32", "sint64"});
return non_message_types->contains(type);
}
} // namespace
void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
const Descriptor* parent,
Descriptor* result,
internal::FlatAllocator& alloc) {
const std::string& scope =
(parent == nullptr) ? file_->package() : parent->full_name();
result->all_names_ = AllocateNameStrings(scope, proto.name(), alloc);
ValidateSymbolName(proto.name(), result->full_name(), proto);
result->file_ = file_;
result->containing_type_ = parent;
result->is_placeholder_ = false;
result->is_unqualified_placeholder_ = false;
result->well_known_type_ = Descriptor::WELLKNOWNTYPE_UNSPECIFIED;
result->options_ = nullptr; // Set to default_instance later if necessary.
auto it = pool_->tables_->well_known_types_.find(result->full_name());
if (it != pool_->tables_->well_known_types_.end()) {
result->well_known_type_ = it->second;
}
// Calculate the continuous sequence of fields.
// These can be fast-path'd during lookup and don't need to be added to the
// tables.
// We use uint16_t to save space for sequential_field_limit_, so stop before
// overflowing it. Worst case, we are not taking full advantage on huge
// messages, but it is unlikely.
result->sequential_field_limit_ = 0;
for (int i = 0; i < std::numeric_limits<uint16_t>::max() &&
i < proto.field_size() && proto.field(i).number() == i + 1;
++i) {
result->sequential_field_limit_ = i + 1;
}
// Build oneofs first so that fields and extension ranges can refer to them.
BUILD_ARRAY(proto, result, oneof_decl, BuildOneof, result);
BUILD_ARRAY(proto, result, field, BuildField, result);
BUILD_ARRAY(proto, result, enum_type, BuildEnum, result);
BUILD_ARRAY(proto, result, extension_range, BuildExtensionRange, result);
BUILD_ARRAY(proto, result, extension, BuildExtension, result);
BUILD_ARRAY(proto, result, reserved_range, BuildReservedRange, result);
// Before building submessages, check recursion limit.
--recursion_depth_;
IncrementWhenDestroyed revert{recursion_depth_};
if (recursion_depth_ <= 0) {
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::OTHER,
"Reached maximum recursion limit for nested messages.");
result->nested_types_ = nullptr;
result->nested_type_count_ = 0;
return;
}
BUILD_ARRAY(proto, result, nested_type, BuildMessage, result);
// Copy reserved names.
int reserved_name_count = proto.reserved_name_size();
result->reserved_name_count_ = reserved_name_count;
result->reserved_names_ =
alloc.AllocateArray<const std::string*>(reserved_name_count);
for (int i = 0; i < reserved_name_count; ++i) {
result->reserved_names_[i] =
alloc.AllocateStrings(proto.reserved_name(i));
}
// Copy options.
AllocateOptions(proto, result, DescriptorProto::kOptionsFieldNumber,
"google.protobuf.MessageOptions", alloc);
AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result));
for (int i = 0; i < proto.reserved_range_size(); i++) {
const DescriptorProto_ReservedRange& range1 = proto.reserved_range(i);
for (int j = i + 1; j < proto.reserved_range_size(); j++) {
const DescriptorProto_ReservedRange& range2 = proto.reserved_range(j);
if (range1.end() > range2.start() && range2.end() > range1.start()) {
AddError(result->full_name(), proto.reserved_range(i),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Reserved range $0 to $1 overlaps with "
"already-defined range $2 to $3.",
range2.start(), range2.end() - 1, range1.start(),
range1.end() - 1);
});
}
}
}
absl::flat_hash_set<absl::string_view> reserved_name_set;
for (const std::string& name : proto.reserved_name()) {
if (!reserved_name_set.insert(name).second) {
AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::Substitute("Field name \"$0\" is reserved multiple times.",
name);
});
}
}
// Check that fields aren't using reserved names or numbers and that they
// aren't using extension numbers.
for (int i = 0; i < result->field_count(); i++) {
const FieldDescriptor* field = result->field(i);
for (int j = 0; j < result->extension_range_count(); j++) {
const Descriptor::ExtensionRange* range = result->extension_range(j);
if (range->start_number() <= field->number() &&
field->number() < range->end_number()) {
message_hints_[result].RequestHintOnFieldNumbers(
proto.extension_range(j), DescriptorPool::ErrorCollector::NUMBER);
AddError(field->full_name(), proto.extension_range(j),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension range $0 to $1 includes field \"$2\" ($3).",
range->start_number(), range->end_number() - 1,
field->name(), field->number());
});
}
}
for (int j = 0; j < result->reserved_range_count(); j++) {
const Descriptor::ReservedRange* range = result->reserved_range(j);
if (range->start <= field->number() && field->number() < range->end) {
message_hints_[result].RequestHintOnFieldNumbers(
proto.reserved_range(j), DescriptorPool::ErrorCollector::NUMBER);
AddError(field->full_name(), proto.reserved_range(j),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Field \"$0\" uses reserved number $1.", field->name(),
field->number());
});
}
}
if (reserved_name_set.contains(field->name())) {
AddError(field->full_name(), proto.field(i),
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::Substitute("Field name \"$0\" is reserved.",
field->name());
});
}
}
// Check that extension ranges don't overlap and don't include
// reserved field numbers or names.
for (int i = 0; i < result->extension_range_count(); i++) {
const Descriptor::ExtensionRange* range1 = result->extension_range(i);
for (int j = 0; j < result->reserved_range_count(); j++) {
const Descriptor::ReservedRange* range2 = result->reserved_range(j);
if (range1->end_number() > range2->start &&
range2->end > range1->start_number()) {
AddError(result->full_name(), proto.extension_range(i),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension range $0 to $1 overlaps with "
"reserved range $2 to $3.",
range1->start_number(), range1->end_number() - 1,
range2->start, range2->end - 1);
});
}
}
for (int j = i + 1; j < result->extension_range_count(); j++) {
const Descriptor::ExtensionRange* range2 = result->extension_range(j);
if (range1->end_number() > range2->start_number() &&
range2->end_number() > range1->start_number()) {
AddError(result->full_name(), proto.extension_range(i),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension range $0 to $1 overlaps with "
"already-defined range $2 to $3.",
range2->start_number(), range2->end_number() - 1,
range1->start_number(), range1->end_number() - 1);
});
}
}
}
}
void DescriptorBuilder::CheckFieldJsonNameUniqueness(
const DescriptorProto& proto, const Descriptor* result) {
FileDescriptorLegacy::Syntax syntax =
FileDescriptorLegacy(result->file()).syntax();
std::string message_name = result->full_name();
if (pool_->deprecated_legacy_json_field_conflicts_ ||
IsLegacyJsonFieldConflictEnabled(result->options())) {
if (syntax == FileDescriptorLegacy::Syntax::SYNTAX_PROTO3) {
// Only check default JSON names for conflicts in proto3. This is legacy
// behavior that will be removed in a later version.
CheckFieldJsonNameUniqueness(message_name, proto, result, syntax, false);
}
} else {
// Check both with and without taking json_name into consideration. This is
// needed for field masks, which don't use json_name.
CheckFieldJsonNameUniqueness(message_name, proto, result, syntax, false);
CheckFieldJsonNameUniqueness(message_name, proto, result, syntax, true);
}
}
namespace {
// Helpers for function below
struct JsonNameDetails {
const FieldDescriptorProto* field;
std::string orig_name;
bool is_custom;
};
JsonNameDetails GetJsonNameDetails(const FieldDescriptorProto* field,
bool use_custom) {
std::string default_json_name = ToJsonName(field->name());
if (use_custom && field->has_json_name() &&
field->json_name() != default_json_name) {
return {field, field->json_name(), true};
}
return {field, default_json_name, false};
}
bool JsonNameLooksLikeExtension(std::string name) {
return !name.empty() && name.front() == '[' && name.back() == ']';
}
} // namespace
void DescriptorBuilder::CheckFieldJsonNameUniqueness(
const std::string& message_name, const DescriptorProto& message,
const Descriptor* descriptor, FileDescriptorLegacy::Syntax syntax,
bool use_custom_names) {
absl::flat_hash_map<std::string, JsonNameDetails> name_to_field;
for (const FieldDescriptorProto& field : message.field()) {
JsonNameDetails details = GetJsonNameDetails(&field, use_custom_names);
if (details.is_custom && JsonNameLooksLikeExtension(details.orig_name)) {
auto make_error = [&] {
return absl::StrFormat(
"The custom JSON name of field \"%s\" (\"%s\") is invalid: "
"JSON names may not start with '[' and end with ']'.",
field.name(), details.orig_name);
};
AddError(message_name, field, DescriptorPool::ErrorCollector::NAME,
make_error);
continue;
}
auto it_inserted = name_to_field.try_emplace(details.orig_name, details);
if (it_inserted.second) {
continue;
}
JsonNameDetails& match = it_inserted.first->second;
if (use_custom_names && !details.is_custom && !match.is_custom) {
// if this pass is considering custom JSON names, but neither of the
// names involved in the conflict are custom, don't bother with a
// message. That will have been reported from other pass (non-custom
// JSON names).
continue;
}
auto make_error = [&] {
absl::string_view this_type = details.is_custom ? "custom" : "default";
absl::string_view existing_type = match.is_custom ? "custom" : "default";
// If the matched name differs (which it can only differ in case), include
// it in the error message, for maximum clarity to user.
std::string name_suffix = "";
if (details.orig_name != match.orig_name) {
name_suffix = absl::StrCat(" (\"", match.orig_name, "\")");
}
return absl::StrFormat(
"The %s JSON name of field \"%s\" (\"%s\") conflicts "
"with the %s JSON name of field \"%s\"%s.",
this_type, field.name(), details.orig_name, existing_type,
match.field->name(), name_suffix);
};
bool involves_default = !details.is_custom || !match.is_custom;
#ifdef PROTOBUF_FUTURE_EDITIONS
if (descriptor->features().json_format() ==
FeatureSet::LEGACY_BEST_EFFORT &&
involves_default) {
#else // PROTOBUF_FUTURE_EDITIONS
if (syntax == FileDescriptorLegacy::SYNTAX_PROTO2 && involves_default) {
#endif // PROTOBUF_FUTURE_EDITIONS
// TODO(b/261750676) Upgrade this to an error once downstream protos have
// been fixed.
AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME,
make_error);
} else {
AddError(message_name, field, DescriptorPool::ErrorCollector::NAME,
make_error);
}
}
}
void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
Descriptor* parent,
FieldDescriptor* result,
bool is_extension,
internal::FlatAllocator& alloc) {
const std::string& scope =
(parent == nullptr) ? file_->package() : parent->full_name();
// We allocate all names in a single array, and dedup them.
// We remember the indices for the potentially deduped values.
auto all_names = alloc.AllocateFieldNames(
proto.name(), scope,
proto.has_json_name() ? &proto.json_name() : nullptr);
result->all_names_ = all_names.array;
result->lowercase_name_index_ = all_names.lowercase_index;
result->camelcase_name_index_ = all_names.camelcase_index;
result->json_name_index_ = all_names.json_index;
ValidateSymbolName(proto.name(), result->full_name(), proto);
result->file_ = file_;
result->number_ = proto.number();
result->is_extension_ = is_extension;
result->is_oneof_ = false;
result->proto3_optional_ = proto.proto3_optional();
if (proto.proto3_optional() &&
FileDescriptorLegacy(file_).syntax() !=
FileDescriptorLegacy::Syntax::SYNTAX_PROTO3) {
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
[&] {
return absl::StrCat(
"The [proto3_optional=true] option may only be set on proto3"
"fields, not ",
result->full_name());
});
}
result->has_json_name_ = proto.has_json_name();
// Some compilers do not allow static_cast directly between two enum types,
// so we must cast to int first.
result->type_ = static_cast<FieldDescriptor::Type>(
absl::implicit_cast<int>(proto.type()));
result->label_ = static_cast<FieldDescriptor::Label>(
absl::implicit_cast<int>(proto.label()));
if (result->is_required()) {
// An extension cannot have a required field (b/13365836).
if (result->is_extension_) {
AddError(result->full_name(), proto,
// Error location `TYPE`: we would really like to indicate
// `LABEL`, but the `ErrorLocation` enum has no entry for this,
// and we don't necessarily know about all implementations of the
// `ErrorCollector` interface to extend them to handle the new
// error location type properly.
DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::StrCat("The extension ", result->full_name(),
" cannot be required.");
});
}
}
// Some of these may be filled in when cross-linking.
result->containing_type_ = nullptr;
result->type_once_ = nullptr;
result->default_value_enum_ = nullptr;
result->has_default_value_ = proto.has_default_value();
if (proto.has_default_value() && result->is_repeated()) {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Repeated fields can't have default values.");
}
if (proto.has_type()) {
if (proto.has_default_value()) {
char* end_pos = nullptr;
switch (result->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
result->default_value_int32_t_ =
std::strtol(proto.default_value().c_str(), &end_pos, 0);
break;
case FieldDescriptor::CPPTYPE_INT64:
static_assert(sizeof(int64_t) == sizeof(long long),
"sizeof int64_t is not sizeof long long");
result->default_value_int64_t_ =
std::strtoll(proto.default_value().c_str(), &end_pos, 0);
break;
case FieldDescriptor::CPPTYPE_UINT32:
result->default_value_uint32_t_ =
std::strtoul(proto.default_value().c_str(), &end_pos, 0);
break;
case FieldDescriptor::CPPTYPE_UINT64:
static_assert(sizeof(uint64_t) == sizeof(unsigned long long),
"sizeof uint64_t is not sizeof unsigned long long");
result->default_value_uint64_t_ =
std::strtoull(proto.default_value().c_str(), &end_pos, 0);
break;
case FieldDescriptor::CPPTYPE_FLOAT:
if (proto.default_value() == "inf") {
result->default_value_float_ =
std::numeric_limits<float>::infinity();
} else if (proto.default_value() == "-inf") {
result->default_value_float_ =
-std::numeric_limits<float>::infinity();
} else if (proto.default_value() == "nan") {
result->default_value_float_ =
std::numeric_limits<float>::quiet_NaN();
} else {
result->default_value_float_ = io::SafeDoubleToFloat(
io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos));
}
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
if (proto.default_value() == "inf") {
result->default_value_double_ =
std::numeric_limits<double>::infinity();
} else if (proto.default_value() == "-inf") {
result->default_value_double_ =
-std::numeric_limits<double>::infinity();
} else if (proto.default_value() == "nan") {
result->default_value_double_ =
std::numeric_limits<double>::quiet_NaN();
} else {
result->default_value_double_ =
io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos);
}
break;
case FieldDescriptor::CPPTYPE_BOOL:
if (proto.default_value() == "true") {
result->default_value_bool_ = true;
} else if (proto.default_value() == "false") {
result->default_value_bool_ = false;
} else {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Boolean default must be true or false.");
}
break;
case FieldDescriptor::CPPTYPE_ENUM:
// This will be filled in when cross-linking.
result->default_value_enum_ = nullptr;
break;
case FieldDescriptor::CPPTYPE_STRING:
if (result->type() == FieldDescriptor::TYPE_BYTES) {
std::string value;
if (absl::CUnescape(proto.default_value(), &value)) {
result->default_value_string_ = alloc.AllocateStrings(value);
} else {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Invalid escaping in default value.");
}
} else {
result->default_value_string_ =
alloc.AllocateStrings(proto.default_value());
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Messages can't have default values.");
result->has_default_value_ = false;
result->default_generated_instance_ = nullptr;
break;
}
if (end_pos != nullptr) {
// end_pos is only set non-null by the parsers for numeric types,
// above. This checks that the default was non-empty and had no extra
// junk after the end of the number.
if (proto.default_value().empty() || *end_pos != '\0') {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE, [&] {
return absl::StrCat("Couldn't parse default value \"",
proto.default_value(), "\".");
});
}
}
} else {
// No explicit default value
switch (result->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
result->default_value_int32_t_ = 0;
break;
case FieldDescriptor::CPPTYPE_INT64:
result->default_value_int64_t_ = 0;
break;
case FieldDescriptor::CPPTYPE_UINT32:
result->default_value_uint32_t_ = 0;
break;
case FieldDescriptor::CPPTYPE_UINT64:
result->default_value_uint64_t_ = 0;
break;
case FieldDescriptor::CPPTYPE_FLOAT:
result->default_value_float_ = 0.0f;
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
result->default_value_double_ = 0.0;
break;
case FieldDescriptor::CPPTYPE_BOOL:
result->default_value_bool_ = false;
break;
case FieldDescriptor::CPPTYPE_ENUM:
// This will be filled in when cross-linking.
result->default_value_enum_ = nullptr;
break;
case FieldDescriptor::CPPTYPE_STRING:
result->default_value_string_ = &internal::GetEmptyString();
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
result->default_generated_instance_ = nullptr;
break;
}
}
}
if (result->number() <= 0) {
message_hints_[parent].RequestHintOnFieldNumbers(
proto, DescriptorPool::ErrorCollector::NUMBER);
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
"Field numbers must be positive integers.");
} else if (!is_extension && result->number() > FieldDescriptor::kMaxNumber) {
// Only validate that the number is within the valid field range if it is
// not an extension. Since extension numbers are validated with the
// extendee's valid set of extension numbers, and those are in turn
// validated against the max allowed number, the check is unnecessary for
// extension fields.
// This avoids cross-linking issues that arise when attempting to check if
// the extendee is a message_set_wire_format message, which has a higher max
// on extension numbers.
message_hints_[parent].RequestHintOnFieldNumbers(
proto, DescriptorPool::ErrorCollector::NUMBER);
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
[&] {
return absl::Substitute(
"Field numbers cannot be greater than $0.",
FieldDescriptor::kMaxNumber);
});
}
if (is_extension) {
if (!proto.has_extendee()) {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
"FieldDescriptorProto.extendee not set for extension field.");
}
result->scope_.extension_scope = parent;
if (proto.has_oneof_index()) {
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"FieldDescriptorProto.oneof_index should not be set for "
"extensions.");
}
} else {
if (proto.has_extendee()) {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
"FieldDescriptorProto.extendee set for non-extension field.");
}
result->containing_type_ = parent;
if (proto.has_oneof_index()) {
if (proto.oneof_index() < 0 ||
proto.oneof_index() >= parent->oneof_decl_count()) {
AddError(result->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::Substitute(
"FieldDescriptorProto.oneof_index $0 is "
"out of range for type \"$1\".",
proto.oneof_index(), parent->name());
});
} else {
result->is_oneof_ = true;
result->scope_.containing_oneof =
parent->oneof_decl(proto.oneof_index());
}
}
}
// Copy options.
AllocateOptions(proto, result, FieldDescriptorProto::kOptionsFieldNumber,
"google.protobuf.FieldOptions", alloc);
AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result));
}
void DescriptorBuilder::BuildExtensionRange(
const DescriptorProto::ExtensionRange& proto, const Descriptor* parent,
Descriptor::ExtensionRange* result, internal::FlatAllocator& alloc) {
result->start_ = proto.start();
result->end_ = proto.end();
result->containing_type_ = parent;
if (result->start_number() <= 0) {
message_hints_[parent].RequestHintOnFieldNumbers(
proto, DescriptorPool::ErrorCollector::NUMBER, result->start_number(),
result->end_number());
AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
"Extension numbers must be positive integers.");
}
// Checking of the upper bound of the extension range is deferred until after
// options interpreting. This allows messages with message_set_wire_format to
// have extensions beyond FieldDescriptor::kMaxNumber, since the extension
// numbers are actually used as int32s in the message_set_wire_format.
if (result->start_number() >= result->end_number()) {
AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
"Extension range end number must be greater than start number.");
}
// Copy options
AllocateOptions(proto, result,
DescriptorProto_ExtensionRange::kOptionsFieldNumber,
"google.protobuf.ExtensionRangeOptions", alloc);
}
void DescriptorBuilder::BuildReservedRange(
const DescriptorProto::ReservedRange& proto, const Descriptor* parent,
Descriptor::ReservedRange* result, internal::FlatAllocator&) {
result->start = proto.start();
result->end = proto.end();
if (result->start <= 0) {
message_hints_[parent].RequestHintOnFieldNumbers(
proto, DescriptorPool::ErrorCollector::NUMBER, result->start,
result->end);
AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
"Reserved numbers must be positive integers.");
}
}
void DescriptorBuilder::BuildReservedRange(
const EnumDescriptorProto::EnumReservedRange& proto,
const EnumDescriptor* parent, EnumDescriptor::ReservedRange* result,
internal::FlatAllocator&) {
result->start = proto.start();
result->end = proto.end();
if (result->start > result->end) {
AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
"Reserved range end number must be greater than start number.");
}
}
void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
Descriptor* parent, OneofDescriptor* result,
internal::FlatAllocator& alloc) {
result->all_names_ =
AllocateNameStrings(parent->full_name(), proto.name(), alloc);
ValidateSymbolName(proto.name(), result->full_name(), proto);
result->containing_type_ = parent;
// We need to fill these in later.
result->field_count_ = 0;
result->fields_ = nullptr;
// Copy options.
AllocateOptions(proto, result, OneofDescriptorProto::kOptionsFieldNumber,
"google.protobuf.OneofOptions", alloc);
AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result));
}
void DescriptorBuilder::CheckEnumValueUniqueness(
const EnumDescriptorProto& proto, const EnumDescriptor* result) {
// Check that enum labels are still unique when we remove the enum prefix from
// values that have it.
//
// This will fail for something like:
//
// enum MyEnum {
// MY_ENUM_FOO = 0;
// FOO = 1;
// }
//
// By enforcing this reasonable constraint, we allow code generators to strip
// the prefix and/or PascalCase it without creating conflicts. This can lead
// to much nicer language-specific enums like:
//
// enum NameType {
// FirstName = 1,
// LastName = 2,
// }
//
// Instead of:
//
// enum NameType {
// NAME_TYPE_FIRST_NAME = 1,
// NAME_TYPE_LAST_NAME = 2,
// }
PrefixRemover remover(result->name());
absl::flat_hash_map<std::string, const EnumValueDescriptor*> values;
for (int i = 0; i < result->value_count(); i++) {
const EnumValueDescriptor* value = result->value(i);
std::string stripped =
EnumValueToPascalCase(remover.MaybeRemove(value->name()));
auto insert_result = values.try_emplace(stripped, value);
bool inserted = insert_result.second;
// We don't throw the error if the two conflicting symbols are identical, or
// if they map to the same number. In the former case, the normal symbol
// duplication error will fire so we don't need to (and its error message
// will make more sense). We allow the latter case so users can create
// aliases which add or remove the prefix (code generators that do prefix
// stripping should de-dup the labels in this case).
if (!inserted && insert_result.first->second->name() != value->name() &&
insert_result.first->second->number() != value->number()) {
auto make_error = [&] {
return absl::StrFormat(
"Enum name %s has the same name as %s if you ignore case and strip "
"out the enum name prefix (if any). (If you are using allow_alias, "
"please assign the same numeric value to both enums.)",
value->name(), insert_result.first->second->name());
};
// There are proto2 enums out there with conflicting names, so to preserve
// compatibility we issue only a warning for proto2.
if ((pool_->deprecated_legacy_json_field_conflicts_ ||
IsLegacyJsonFieldConflictEnabled(result->options())) &&
FileDescriptorLegacy(result->file()).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO2) {
AddWarning(value->full_name(), proto.value(i),
DescriptorPool::ErrorCollector::NAME, make_error);
continue;
}
AddError(value->full_name(), proto.value(i),
DescriptorPool::ErrorCollector::NAME, make_error);
}
}
}
void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
const Descriptor* parent,
EnumDescriptor* result,
internal::FlatAllocator& alloc) {
const std::string& scope =
(parent == nullptr) ? file_->package() : parent->full_name();
result->all_names_ = AllocateNameStrings(scope, proto.name(), alloc);
ValidateSymbolName(proto.name(), result->full_name(), proto);
result->file_ = file_;
result->containing_type_ = parent;
result->is_placeholder_ = false;
result->is_unqualified_placeholder_ = false;
if (proto.value_size() == 0) {
// We cannot allow enums with no values because this would mean there
// would be no valid default value for fields of this type.
AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Enums must contain at least one value.");
}
// Calculate the continuous sequence of the labels.
// These can be fast-path'd during lookup and don't need to be added to the
// tables.
// We use uint16_t to save space for sequential_value_limit_, so stop before
// overflowing it. Worst case, we are not taking full advantage on huge
// enums, but it is unlikely.
for (int i = 0;
i < std::numeric_limits<uint16_t>::max() && i < proto.value_size() &&
// We do the math in int64_t to avoid overflows.
proto.value(i).number() ==
static_cast<int64_t>(i) + proto.value(0).number();
++i) {
result->sequential_value_limit_ = i;
}
BUILD_ARRAY(proto, result, value, BuildEnumValue, result);
BUILD_ARRAY(proto, result, reserved_range, BuildReservedRange, result);
// Copy reserved names.
int reserved_name_count = proto.reserved_name_size();
result->reserved_name_count_ = reserved_name_count;
result->reserved_names_ =
alloc.AllocateArray<const std::string*>(reserved_name_count);
for (int i = 0; i < reserved_name_count; ++i) {
result->reserved_names_[i] =
alloc.AllocateStrings(proto.reserved_name(i));
}
// Copy options.
AllocateOptions(proto, result, EnumDescriptorProto::kOptionsFieldNumber,
"google.protobuf.EnumOptions", alloc);
AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result));
for (int i = 0; i < proto.reserved_range_size(); i++) {
const EnumDescriptorProto_EnumReservedRange& range1 =
proto.reserved_range(i);
for (int j = i + 1; j < proto.reserved_range_size(); j++) {
const EnumDescriptorProto_EnumReservedRange& range2 =
proto.reserved_range(j);
if (range1.end() >= range2.start() && range2.end() >= range1.start()) {
AddError(result->full_name(), proto.reserved_range(i),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Reserved range $0 to $1 overlaps with "
"already-defined range $2 to $3.",
range2.start(), range2.end(), range1.start(),
range1.end());
});
}
}
}
absl::flat_hash_set<absl::string_view> reserved_name_set;
for (const std::string& name : proto.reserved_name()) {
if (!reserved_name_set.insert(name).second) {
AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::Substitute("Enum value \"$0\" is reserved multiple times.",
name);
});
}
}
for (int i = 0; i < result->value_count(); i++) {
const EnumValueDescriptor* value = result->value(i);
for (int j = 0; j < result->reserved_range_count(); j++) {
const EnumDescriptor::ReservedRange* range = result->reserved_range(j);
if (range->start <= value->number() && value->number() <= range->end) {
AddError(value->full_name(), proto.reserved_range(j),
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Enum value \"$0\" uses reserved number $1.",
value->name(), value->number());
});
}
}
if (reserved_name_set.contains(value->name())) {
AddError(value->full_name(), proto.value(i),
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::Substitute("Enum value \"$0\" is reserved.",
value->name());
});
}
}
}
void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto,
const EnumDescriptor* parent,
EnumValueDescriptor* result,
internal::FlatAllocator& alloc) {
// Note: full_name for enum values is a sibling to the parent's name, not a
// child of it.
std::string full_name;
size_t scope_len = parent->full_name().size() - parent->name().size();
full_name.reserve(scope_len + proto.name().size());
full_name.append(parent->full_name().data(), scope_len);
full_name.append(proto.name());
result->all_names_ =
alloc.AllocateStrings(proto.name(), std::move(full_name));
result->number_ = proto.number();
result->type_ = parent;
ValidateSymbolName(proto.name(), result->full_name(), proto);
// Copy options.
AllocateOptions(proto, result, EnumValueDescriptorProto::kOptionsFieldNumber,
"google.protobuf.EnumValueOptions", alloc);
// Again, enum values are weird because we makes them appear as siblings
// of the enum type instead of children of it. So, we use
// parent->containing_type() as the value's parent.
bool added_to_outer_scope =
AddSymbol(result->full_name(), parent->containing_type(), result->name(),
proto, Symbol::EnumValue(result, 0));
// However, we also want to be able to search for values within a single
// enum type, so we add it as a child of the enum type itself, too.
// Note: This could fail, but if it does, the error has already been
// reported by the above AddSymbol() call, so we ignore the return code.
bool added_to_inner_scope = file_tables_->AddAliasUnderParent(
parent, result->name(), Symbol::EnumValue(result, 1));
if (added_to_inner_scope && !added_to_outer_scope) {
// This value did not conflict with any values defined in the same enum,
// but it did conflict with some other symbol defined in the enum type's
// scope. Let's print an additional error to explain this.
std::string outer_scope;
if (parent->containing_type() == nullptr) {
outer_scope = file_->package();
} else {
outer_scope = parent->containing_type()->full_name();
}
if (outer_scope.empty()) {
outer_scope = "the global scope";
} else {
outer_scope = absl::StrCat("\"", outer_scope, "\"");
}
AddError(
result->full_name(), proto, DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat(
"Note that enum values use C++ scoping rules, meaning that "
"enum values are siblings of their type, not children of it. "
"Therefore, \"",
result->name(), "\" must be unique within ", outer_scope,
", not just within \"", parent->name(), "\".");
});
}
// An enum is allowed to define two numbers that refer to the same value.
// FindValueByNumber() should return the first such value, so we simply
// ignore AddEnumValueByNumber()'s return code.
file_tables_->AddEnumValueByNumber(result);
}
void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto,
const void* /* dummy */,
ServiceDescriptor* result,
internal::FlatAllocator& alloc) {
result->all_names_ =
AllocateNameStrings(file_->package(), proto.name(), alloc);
result->file_ = file_;
ValidateSymbolName(proto.name(), result->full_name(), proto);
BUILD_ARRAY(proto, result, method, BuildMethod, result);
// Copy options.
AllocateOptions(proto, result, ServiceDescriptorProto::kOptionsFieldNumber,
"google.protobuf.ServiceOptions", alloc);
AddSymbol(result->full_name(), nullptr, result->name(), proto,
Symbol(result));
}
void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto,
const ServiceDescriptor* parent,
MethodDescriptor* result,
internal::FlatAllocator& alloc) {
result->service_ = parent;
result->all_names_ =
AllocateNameStrings(parent->full_name(), proto.name(), alloc);
ValidateSymbolName(proto.name(), result->full_name(), proto);
// These will be filled in when cross-linking.
result->input_type_.Init();
result->output_type_.Init();
// Copy options.
AllocateOptions(proto, result, MethodDescriptorProto::kOptionsFieldNumber,
"google.protobuf.MethodOptions", alloc);
result->client_streaming_ = proto.client_streaming();
result->server_streaming_ = proto.server_streaming();
AddSymbol(result->full_name(), parent, result->name(), proto, Symbol(result));
}
#undef BUILD_ARRAY
// -------------------------------------------------------------------
void DescriptorBuilder::CrossLinkFile(FileDescriptor* file,
const FileDescriptorProto& proto) {
if (file->options_ == nullptr) {
file->options_ = &FileOptions::default_instance();
}
for (int i = 0; i < file->message_type_count(); i++) {
CrossLinkMessage(&file->message_types_[i], proto.message_type(i));
}
for (int i = 0; i < file->extension_count(); i++) {
CrossLinkField(&file->extensions_[i], proto.extension(i));
}
for (int i = 0; i < file->enum_type_count(); i++) {
CrossLinkEnum(&file->enum_types_[i], proto.enum_type(i));
}
for (int i = 0; i < file->service_count(); i++) {
CrossLinkService(&file->services_[i], proto.service(i));
}
}
void DescriptorBuilder::CrossLinkMessage(Descriptor* message,
const DescriptorProto& proto) {
if (message->options_ == nullptr) {
message->options_ = &MessageOptions::default_instance();
}
for (int i = 0; i < message->nested_type_count(); i++) {
CrossLinkMessage(&message->nested_types_[i], proto.nested_type(i));
}
for (int i = 0; i < message->enum_type_count(); i++) {
CrossLinkEnum(&message->enum_types_[i], proto.enum_type(i));
}
for (int i = 0; i < message->field_count(); i++) {
CrossLinkField(&message->fields_[i], proto.field(i));
}
for (int i = 0; i < message->extension_count(); i++) {
CrossLinkField(&message->extensions_[i], proto.extension(i));
}
for (int i = 0; i < message->extension_range_count(); i++) {
CrossLinkExtensionRange(&message->extension_ranges_[i],
proto.extension_range(i));
}
// Set up field array for each oneof.
// First count the number of fields per oneof.
for (int i = 0; i < message->field_count(); i++) {
const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof();
if (oneof_decl != nullptr) {
// Make sure fields belonging to the same oneof are defined consecutively.
// This enables optimizations in codegens and reflection libraries to
// skip fields in the oneof group, as only one of the field can be set.
// Note that field_count() returns how many fields in this oneof we have
// seen so far. field_count() > 0 guarantees that i > 0, so field(i-1) is
// safe.
if (oneof_decl->field_count() > 0 &&
message->field(i - 1)->containing_oneof() != oneof_decl) {
AddError(
absl::StrCat(message->full_name(), ".",
message->field(i - 1)->name()),
proto.field(i - 1), DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::Substitute(
"Fields in the same oneof must be defined consecutively. "
"\"$0\" cannot be defined before the completion of the "
"\"$1\" oneof definition.",
message->field(i - 1)->name(), oneof_decl->name());
});
}
// Must go through oneof_decls_ array to get a non-const version of the
// OneofDescriptor.
auto& out_oneof_decl = message->oneof_decls_[oneof_decl->index()];
if (out_oneof_decl.field_count_ == 0) {
out_oneof_decl.fields_ = message->field(i);
}
if (!had_errors_) {
// Verify that they are contiguous.
// This is assumed by OneofDescriptor::field(i).
// But only if there are no errors.
ABSL_CHECK_EQ(out_oneof_decl.fields_ + out_oneof_decl.field_count_,
message->field(i));
}
++out_oneof_decl.field_count_;
}
}
// Then verify the sizes.
for (int i = 0; i < message->oneof_decl_count(); i++) {
OneofDescriptor* oneof_decl = &message->oneof_decls_[i];
if (oneof_decl->field_count() == 0) {
AddError(absl::StrCat(message->full_name(), ".", oneof_decl->name()),
proto.oneof_decl(i), DescriptorPool::ErrorCollector::NAME,
"Oneof must have at least one field.");
}
if (oneof_decl->options_ == nullptr) {
oneof_decl->options_ = &OneofOptions::default_instance();
}
}
for (int i = 0; i < message->field_count(); i++) {
const FieldDescriptor* field = message->field(i);
if (field->proto3_optional_) {
if (!field->containing_oneof() ||
!OneofDescriptorLegacy(field->containing_oneof()).is_synthetic()) {
AddError(message->full_name(), proto.field(i),
DescriptorPool::ErrorCollector::OTHER,
"Fields with proto3_optional set must be "
"a member of a one-field oneof");
}
}
}
// Synthetic oneofs must be last.
int first_synthetic = -1;
for (int i = 0; i < message->oneof_decl_count(); i++) {
const OneofDescriptor* oneof = message->oneof_decl(i);
if (OneofDescriptorLegacy(oneof).is_synthetic()) {
if (first_synthetic == -1) {
first_synthetic = i;
}
} else {
if (first_synthetic != -1) {
AddError(message->full_name(), proto.oneof_decl(i),
DescriptorPool::ErrorCollector::OTHER,
"Synthetic oneofs must be after all other oneofs");
}
}
}
if (first_synthetic == -1) {
message->real_oneof_decl_count_ = message->oneof_decl_count_;
} else {
message->real_oneof_decl_count_ = first_synthetic;
}
}
void DescriptorBuilder::CrossLinkExtensionRange(
Descriptor::ExtensionRange* range,
const DescriptorProto::ExtensionRange& /*proto*/) {
if (range->options_ == nullptr) {
range->options_ = &ExtensionRangeOptions::default_instance();
}
}
void DescriptorBuilder::CheckExtensionDeclaration(
const FieldDescriptor& field, const FieldDescriptorProto& proto,
absl::string_view declared_full_name, absl::string_view declared_type_name,
bool is_repeated) {
if (!declared_full_name.empty()) {
std::string actual_full_name = absl::StrCat(".", field.full_name());
if (declared_full_name != actual_full_name) {
AddError(field.full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE, [&] {
return absl::Substitute(
"\"$0\" extension field $1 is expected to have field name "
"\"$2\", not \"$3\".",
field.containing_type()->full_name(), field.number(),
declared_full_name, actual_full_name);
});
}
}
if (is_repeated != field.is_repeated()) {
AddError(field.full_name(), proto, DescriptorPool::ErrorCollector::EXTENDEE,
[&] {
return absl::Substitute(
"\"$0\" extension field $1 is expected to be $2.",
field.containing_type()->full_name(), field.number(),
is_repeated ? "repeated" : "optional");
});
}
}
void DescriptorBuilder::CrossLinkField(FieldDescriptor* field,
const FieldDescriptorProto& proto) {
if (field->options_ == nullptr) {
field->options_ = &FieldOptions::default_instance();
}
if (proto.has_extendee()) {
Symbol extendee =
LookupSymbol(proto.extendee(), field->full_name(),
DescriptorPool::PLACEHOLDER_EXTENDABLE_MESSAGE);
if (extendee.IsNull()) {
AddNotDefinedError(field->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
proto.extendee());
return;
} else if (extendee.type() != Symbol::MESSAGE) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE, [&] {
return absl::StrCat("\"", proto.extendee(),
"\" is not a message type.");
});
return;
}
field->containing_type_ = extendee.descriptor();
const Descriptor::ExtensionRange* extension_range =
field->containing_type()->FindExtensionRangeContainingNumber(
field->number());
if (extension_range == nullptr) {
// Set of valid extension numbers for MessageSet is different (< 2^32)
// from other extendees (< 2^29). If unknown deps are allowed, we may not
// have that information, and wrongly deem the extension as invalid.
auto skip_check = get_allow_unknown(pool_) &&
proto.extendee() == "google.protobuf.bridge.MessageSet";
if (!skip_check) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"\"$0\" does not declare $1 as an "
"extension number.",
field->containing_type()->full_name(), field->number());
});
}
}
}
if (field->containing_oneof() != nullptr) {
if (field->label() != FieldDescriptor::LABEL_OPTIONAL) {
// Note that this error will never happen when parsing .proto files.
// It can only happen if you manually construct a FileDescriptorProto
// that is incorrect.
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Fields of oneofs must themselves have label LABEL_OPTIONAL.");
}
}
if (proto.has_type_name()) {
// Assume we are expecting a message type unless the proto contains some
// evidence that it expects an enum type. This only makes a difference if
// we end up creating a placeholder.
bool expecting_enum = (proto.type() == FieldDescriptorProto::TYPE_ENUM) ||
proto.has_default_value();
// In case of weak fields we force building the dependency. We need to know
// if the type exist or not. If it doesn't exist we substitute Empty which
// should only be done if the type can't be found in the generated pool.
// TODO(gerbens) Ideally we should query the database directly to check
// if weak fields exist or not so that we don't need to force building
// weak dependencies. However the name lookup rules for symbols are
// somewhat complicated, so I defer it too another CL.
bool is_weak = !pool_->enforce_weak_ && proto.options().weak();
bool is_lazy = pool_->lazily_build_dependencies_ && !is_weak;
Symbol type =
LookupSymbol(proto.type_name(), field->full_name(),
expecting_enum ? DescriptorPool::PLACEHOLDER_ENUM
: DescriptorPool::PLACEHOLDER_MESSAGE,
LOOKUP_TYPES, !is_lazy);
if (type.IsNull()) {
if (is_lazy) {
// Save the symbol names for later for lookup, and allocate the once
// object needed for the accessors.
const std::string& name = proto.type_name();
int name_sizes = static_cast<int>(name.size() + 1 +
proto.default_value().size() + 1);
field->type_once_ = ::new (tables_->AllocateBytes(
static_cast<int>(sizeof(absl::once_flag)) + name_sizes))
absl::once_flag{};
char* names = reinterpret_cast<char*>(field->type_once_ + 1);
memcpy(names, name.c_str(), name.size() + 1);
memcpy(names + name.size() + 1, proto.default_value().c_str(),
proto.default_value().size() + 1);
// AddFieldByNumber and AddExtension are done later in this function,
// and can/must be done if the field type was not found. The related
// error checking is not necessary when in lazily_build_dependencies_
// mode, and can't be done without building the type's descriptor,
// which we don't want to do.
file_tables_->AddFieldByNumber(field);
if (field->is_extension()) {
tables_->AddExtension(field);
}
return;
} else {
// If the type is a weak type, we change the type to a google.protobuf.Empty
// field.
if (is_weak) {
type = FindSymbol(kNonLinkedWeakMessageReplacementName);
}
if (type.IsNull()) {
AddNotDefinedError(field->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE,
proto.type_name());
return;
}
}
}
if (!proto.has_type()) {
// Choose field type based on symbol.
if (type.type() == Symbol::MESSAGE) {
field->type_ = FieldDescriptor::TYPE_MESSAGE;
} else if (type.type() == Symbol::ENUM) {
field->type_ = FieldDescriptor::TYPE_ENUM;
} else {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::StrCat("\"", proto.type_name(),
"\" is not a type.");
});
return;
}
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
field->type_descriptor_.message_type = type.descriptor();
if (field->type_descriptor_.message_type == nullptr) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::StrCat("\"", proto.type_name(),
"\" is not a message type.");
});
return;
}
if (field->has_default_value()) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Messages can't have default values.");
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
field->type_descriptor_.enum_type = type.enum_descriptor();
if (field->type_descriptor_.enum_type == nullptr) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::StrCat("\"", proto.type_name(),
"\" is not an enum type.");
});
return;
}
if (field->enum_type()->is_placeholder_) {
// We can't look up default values for placeholder types. We'll have
// to just drop them.
field->has_default_value_ = false;
}
if (field->has_default_value()) {
// Ensure that the default value is an identifier. Parser cannot always
// verify this because it does not have complete type information.
// N.B. that this check yields better error messages but is not
// necessary for correctness (an enum symbol must be a valid identifier
// anyway), only for better errors.
if (!io::Tokenizer::IsIdentifier(proto.default_value())) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Default value for an enum field must be an identifier.");
} else {
// We can't just use field->enum_type()->FindValueByName() here
// because that locks the pool's mutex, which we have already locked
// at this point.
const EnumValueDescriptor* default_value =
LookupSymbolNoPlaceholder(proto.default_value(),
field->enum_type()->full_name())
.enum_value_descriptor();
if (default_value != nullptr &&
default_value->type() == field->enum_type()) {
field->default_value_enum_ = default_value;
} else {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE, [&] {
return absl::StrCat("Enum type \"",
field->enum_type()->full_name(),
"\" has no value named \"",
proto.default_value(), "\".");
});
}
}
} else if (field->enum_type()->value_count() > 0) {
// All enums must have at least one value, or we would have reported
// an error elsewhere. We use the first defined value as the default
// if a default is not explicitly defined.
field->default_value_enum_ = field->enum_type()->value(0);
}
} else {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Field with primitive type has type_name.");
}
} else {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Field with message or enum type missing type_name.");
}
}
// Add the field to the fields-by-number table.
// Note: We have to do this *after* cross-linking because extensions do not
// know their containing type until now. If we're in
// lazily_build_dependencies_ mode, we're guaranteed there's no errors, so no
// risk to calling containing_type() or other accessors that will build
// dependencies.
if (!file_tables_->AddFieldByNumber(field)) {
const FieldDescriptor* conflicting_field = file_tables_->FindFieldByNumber(
field->containing_type(), field->number());
std::string containing_type_name =
field->containing_type() == nullptr
? "unknown"
: field->containing_type()->full_name();
if (field->is_extension()) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension number $0 has already been used "
"in \"$1\" by extension \"$2\".",
field->number(), containing_type_name,
conflicting_field->full_name());
});
} else {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Field number $0 has already been used in "
"\"$1\" by field \"$2\".",
field->number(), containing_type_name,
conflicting_field->name());
});
}
} else {
if (field->is_extension()) {
if (!tables_->AddExtension(field)) {
auto make_error = [&] {
const FieldDescriptor* conflicting_field =
tables_->FindExtension(field->containing_type(), field->number());
std::string containing_type_name =
field->containing_type() == nullptr
? "unknown"
: field->containing_type()->full_name();
return absl::Substitute(
"Extension number $0 has already been used in \"$1\" by "
"extension "
"\"$2\" defined in $3.",
field->number(), containing_type_name,
conflicting_field->full_name(),
conflicting_field->file()->name());
};
// Conflicting extension numbers should be an error. However, before
// turning this into an error we need to fix all existing broken
// protos first.
// TODO(xiaofeng): Change this to an error.
AddWarning(field->full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER, make_error);
}
}
}
}
void DescriptorBuilder::CrossLinkEnum(EnumDescriptor* enum_type,
const EnumDescriptorProto& proto) {
if (enum_type->options_ == nullptr) {
enum_type->options_ = &EnumOptions::default_instance();
}
for (int i = 0; i < enum_type->value_count(); i++) {
CrossLinkEnumValue(&enum_type->values_[i], proto.value(i));
}
}
void DescriptorBuilder::CrossLinkEnumValue(
EnumValueDescriptor* enum_value,
const EnumValueDescriptorProto& /* proto */) {
if (enum_value->options_ == nullptr) {
enum_value->options_ = &EnumValueOptions::default_instance();
}
}
void DescriptorBuilder::CrossLinkService(ServiceDescriptor* service,
const ServiceDescriptorProto& proto) {
if (service->options_ == nullptr) {
service->options_ = &ServiceOptions::default_instance();
}
for (int i = 0; i < service->method_count(); i++) {
CrossLinkMethod(&service->methods_[i], proto.method(i));
}
}
void DescriptorBuilder::CrossLinkMethod(MethodDescriptor* method,
const MethodDescriptorProto& proto) {
if (method->options_ == nullptr) {
method->options_ = &MethodOptions::default_instance();
}
Symbol input_type =
LookupSymbol(proto.input_type(), method->full_name(),
DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL,
!pool_->lazily_build_dependencies_);
if (input_type.IsNull()) {
if (!pool_->lazily_build_dependencies_) {
AddNotDefinedError(method->full_name(), proto,
DescriptorPool::ErrorCollector::INPUT_TYPE,
proto.input_type());
} else {
method->input_type_.SetLazy(proto.input_type(), file_);
}
} else if (input_type.type() != Symbol::MESSAGE) {
AddError(method->full_name(), proto,
DescriptorPool::ErrorCollector::INPUT_TYPE, [&] {
return absl::StrCat("\"", proto.input_type(),
"\" is not a message type.");
});
} else {
method->input_type_.Set(input_type.descriptor());
}
Symbol output_type =
LookupSymbol(proto.output_type(), method->full_name(),
DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL,
!pool_->lazily_build_dependencies_);
if (output_type.IsNull()) {
if (!pool_->lazily_build_dependencies_) {
AddNotDefinedError(method->full_name(), proto,
DescriptorPool::ErrorCollector::OUTPUT_TYPE,
proto.output_type());
} else {
method->output_type_.SetLazy(proto.output_type(), file_);
}
} else if (output_type.type() != Symbol::MESSAGE) {
AddError(method->full_name(), proto,
DescriptorPool::ErrorCollector::OUTPUT_TYPE, [&] {
return absl::StrCat("\"", proto.output_type(),
"\" is not a message type.");
});
} else {
method->output_type_.Set(output_type.descriptor());
}
}
void DescriptorBuilder::SuggestFieldNumbers(FileDescriptor* file,
const FileDescriptorProto& proto) {
for (int message_index = 0; message_index < file->message_type_count();
message_index++) {
const Descriptor* message = &file->message_types_[message_index];
auto hints_it = message_hints_.find(message);
if (hints_it == message_hints_.end()) continue;
auto* hints = &hints_it->second;
constexpr int kMaxSuggestions = 3;
int fields_to_suggest = std::min(kMaxSuggestions, hints->fields_to_suggest);
if (fields_to_suggest <= 0) continue;
struct Range {
int from;
int to;
};
std::vector<Range> used_ordinals;
auto add_ordinal = [&](int ordinal) {
if (ordinal <= 0 || ordinal > FieldDescriptor::kMaxNumber) return;
if (!used_ordinals.empty() &&
ordinal == used_ordinals.back().to) {
used_ordinals.back().to = ordinal + 1;
} else {
used_ordinals.push_back({ordinal, ordinal + 1});
}
};
auto add_range = [&](int from, int to) {
from = std::max(0, std::min(FieldDescriptor::kMaxNumber + 1, from));
to = std::max(0, std::min(FieldDescriptor::kMaxNumber + 1, to));
if (from >= to) return;
used_ordinals.push_back({from, to});
};
for (int i = 0; i < message->field_count(); i++) {
add_ordinal(message->field(i)->number());
}
for (int i = 0; i < message->extension_count(); i++) {
add_ordinal(message->extension(i)->number());
}
for (int i = 0; i < message->reserved_range_count(); i++) {
auto range = message->reserved_range(i);
add_range(range->start, range->end);
}
for (int i = 0; i < message->extension_range_count(); i++) {
auto range = message->extension_range(i);
add_range(range->start_number(), range->end_number());
}
used_ordinals.push_back(
{FieldDescriptor::kMaxNumber, FieldDescriptor::kMaxNumber + 1});
used_ordinals.push_back({FieldDescriptor::kFirstReservedNumber,
FieldDescriptor::kLastReservedNumber});
std::sort(used_ordinals.begin(), used_ordinals.end(),
[](Range lhs, Range rhs) {
return std::tie(lhs.from, lhs.to) < std::tie(rhs.from, rhs.to);
});
int current_ordinal = 1;
if (hints->first_reason) {
auto make_error = [&] {
std::stringstream id_list;
id_list << "Suggested field numbers for " << message->full_name()
<< ": ";
const char* separator = "";
for (auto& current_range : used_ordinals) {
while (current_ordinal < current_range.from &&
fields_to_suggest > 0) {
id_list << separator << current_ordinal++;
separator = ", ";
fields_to_suggest--;
}
if (fields_to_suggest == 0) break;
current_ordinal = std::max(current_ordinal, current_range.to);
}
return id_list.str();
};
AddError(message->full_name(), *hints->first_reason,
hints->first_reason_location, make_error);
}
}
}
// -------------------------------------------------------------------
// Determine if the file uses optimize_for = LITE_RUNTIME, being careful to
// avoid problems that exist at init time.
static bool IsLite(const FileDescriptor* file) {
// TODO(kenton): I don't even remember how many of these conditions are
// actually possible. I'm just being super-safe.
return file != nullptr &&
&file->options() != &FileOptions::default_instance() &&
file->options().optimize_for() == FileOptions::LITE_RUNTIME;
}
void DescriptorBuilder::ValidateOptions(const FileDescriptor* file,
const FileDescriptorProto& proto) {
// Lite files can only be imported by other Lite files.
if (!IsLite(file)) {
for (int i = 0; i < file->dependency_count(); i++) {
if (IsLite(file->dependency(i))) {
AddError(file->dependency(i)->name(), proto,
DescriptorPool::ErrorCollector::IMPORT, [&] {
return absl::StrCat(
"Files that do not use optimize_for = LITE_RUNTIME "
"cannot import files which do use this option. This "
"file is not lite, but it imports \"",
file->dependency(i)->name(), "\" which is.");
});
break;
}
}
}
if (FileDescriptorLegacy(file).syntax() ==
FileDescriptorLegacy::Syntax::SYNTAX_PROTO3) {
ValidateProto3(file, proto);
}
}
void DescriptorBuilder::ValidateProto3(const FileDescriptor* file,
const FileDescriptorProto& proto) {
for (int i = 0; i < file->extension_count(); ++i) {
ValidateProto3Field(file->extensions_ + i, proto.extension(i));
}
for (int i = 0; i < file->message_type_count(); ++i) {
ValidateProto3Message(file->message_types_ + i, proto.message_type(i));
}
}
void DescriptorBuilder::ValidateProto3Message(const Descriptor* message,
const DescriptorProto& proto) {
for (int i = 0; i < message->nested_type_count(); ++i) {
ValidateProto3Message(message->nested_types_ + i, proto.nested_type(i));
}
for (int i = 0; i < message->field_count(); ++i) {
ValidateProto3Field(message->fields_ + i, proto.field(i));
}
for (int i = 0; i < message->extension_count(); ++i) {
ValidateProto3Field(message->extensions_ + i, proto.extension(i));
}
if (message->extension_range_count() > 0) {
AddError(message->full_name(), proto.extension_range(0),
DescriptorPool::ErrorCollector::NUMBER,
"Extension ranges are not allowed in proto3.");
}
if (message->options().message_set_wire_format()) {
// Using MessageSet doesn't make sense since we disallow extensions.
AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"MessageSet is not supported in proto3.");
}
}
void DescriptorBuilder::ValidateProto3Field(const FieldDescriptor* field,
const FieldDescriptorProto& proto) {
if (field->is_extension() &&
!AllowedExtendeeInProto3(field->containing_type()->full_name())) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
"Extensions in proto3 are only allowed for defining options.");
}
if (field->is_required()) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Required fields are not allowed in proto3.");
}
if (field->has_default_value()) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::DEFAULT_VALUE,
"Explicit default values are not allowed in proto3.");
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
field->enum_type() &&
FileDescriptorLegacy(field->enum_type()->file()).syntax() !=
FileDescriptorLegacy::Syntax::SYNTAX_PROTO3 &&
FileDescriptorLegacy(field->enum_type()->file()).syntax() !=
FileDescriptorLegacy::Syntax::SYNTAX_UNKNOWN) {
// Proto3 messages can only use Proto3 enum types; otherwise we can't
// guarantee that the default value is zero.
AddError(
field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, [&] {
return absl::StrCat("Enum type \"", field->enum_type()->full_name(),
"\" is not a proto3 enum, but is used in \"",
field->containing_type()->full_name(),
"\" which is a proto3 message type.");
});
}
if (field->type() == FieldDescriptor::TYPE_GROUP) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Groups are not supported in proto3 syntax.");
}
}
void DescriptorBuilder::ValidateOptions(const Descriptor* message,
const DescriptorProto& proto) {
CheckFieldJsonNameUniqueness(proto, message);
ValidateExtensionRangeOptions(proto, *message);
}
void DescriptorBuilder::ValidateOptions(const OneofDescriptor* /*oneof*/,
const OneofDescriptorProto& /*proto*/) {
}
void DescriptorBuilder::ValidateOptions(const FieldDescriptor* field,
const FieldDescriptorProto& proto) {
if (pool_->lazily_build_dependencies_ && (!field || !field->message_type())) {
return;
}
ValidateFieldFeatures(field, proto);
// Only message type fields may be lazy.
if (field->options().lazy() || field->options().unverified_lazy()) {
if (field->type() != FieldDescriptor::TYPE_MESSAGE) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"[lazy = true] can only be specified for submessage fields.");
}
}
// Only repeated primitive fields may be packed.
if (field->options().packed() && !field->is_packable()) {
AddError(
field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"[packed = true] can only be specified for repeated primitive fields.");
}
// Note: Default instance may not yet be initialized here, so we have to
// avoid reading from it.
if (field->containing_type_ != nullptr &&
&field->containing_type()->options() !=
&MessageOptions::default_instance() &&
field->containing_type()->options().message_set_wire_format()) {
if (field->is_extension()) {
if (!field->is_optional() ||
field->type() != FieldDescriptor::TYPE_MESSAGE) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::TYPE,
"Extensions of MessageSets must be optional messages.");
}
} else {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"MessageSets cannot have fields, only extensions.");
}
}
// Lite extensions can only be of Lite types.
if (IsLite(field->file()) && field->containing_type_ != nullptr &&
!IsLite(field->containing_type()->file())) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::EXTENDEE,
"Extensions to non-lite types can only be declared in non-lite "
"files. Note that you cannot extend a non-lite type to contain "
"a lite type, but the reverse is allowed.");
}
// Validate map types.
if (field->is_map()) {
if (!ValidateMapEntry(field, proto)) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"map_entry should not be set explicitly. Use map<KeyType, "
"ValueType> instead.");
}
}
ValidateJSType(field, proto);
// json_name option is not allowed on extension fields. Note that the
// json_name field in FieldDescriptorProto is always populated by protoc
// when it sends descriptor data to plugins (calculated from field name if
// the option is not explicitly set) so we can't rely on its presence to
// determine whether the json_name option is set on the field. Here we
// compare it against the default calculated json_name value and consider
// the option set if they are different. This won't catch the case when
// a user explicitly sets json_name to the default value, but should be
// good enough to catch common misuses.
if (field->is_extension() &&
(field->has_json_name() &&
field->json_name() != ToJsonName(field->name()))) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::OPTION_NAME,
"option json_name is not allowed on extension fields.");
}
if (absl::StrContains(field->json_name(), '\0')) {
AddError(field->full_name(), proto,
DescriptorPool::ErrorCollector::OPTION_NAME,
"json_name cannot have embedded null characters.");
}
}
static bool IsStringMapType(const FieldDescriptor* field) {
if (!field->is_map()) return false;
for (int i = 0; i < field->message_type()->field_count(); ++i) {
if (field->message_type()->field(i)->type() ==
FieldDescriptor::TYPE_STRING) {
return true;
}
}
return false;
}
void DescriptorBuilder::ValidateFieldFeatures(
const FieldDescriptor* field, const FieldDescriptorProto& proto) {
#ifdef PROTOBUF_FUTURE_EDITIONS
// Rely on our legacy validation for proto2/proto3 files.
if (IsLegacyFeatureSet(field->features())) return;
// Validate fully resolved features.
if (field->has_default_value() &&
field->features().field_presence() == FeatureSet::IMPLICIT) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Implicit presence fields can't specify defaults.");
}
if (field->enum_type() != nullptr &&
field->enum_type()->features().enum_type() != FeatureSet::OPEN &&
field->features().field_presence() == FeatureSet::IMPLICIT) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Implicit presence enum fields must always be open.");
}
if (field->is_extension() &&
field->features().field_presence() == FeatureSet::LEGACY_REQUIRED) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Extensions can't be required.");
}
if (field->containing_type() != nullptr &&
field->containing_type()->options().map_entry()) {
// Skip validation of explicit features on generated map fields. These will
// be blindly propagated from the original map field, and may violate a lot
// of these conditions. Note: we do still validate the user-specified map
// field.
return;
}
// Validate explicitly specified features on the field proto.
if ((field->containing_oneof() != nullptr || field->is_repeated() ||
field->message_type() != nullptr) &&
field->proto_features_->field_presence() == FeatureSet::IMPLICIT) {
AddError(
field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Only singular scalar fields can specify implicit field presence.");
}
if ((field->containing_oneof() != nullptr || field->is_repeated()) &&
field->proto_features_->field_presence() == FeatureSet::LEGACY_REQUIRED) {
AddError(
field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Only singular scalar fields can specify required field presence.");
}
if (field->type() != FieldDescriptor::TYPE_STRING &&
!IsStringMapType(field) &&
field->proto_features_->has_string_field_validation()) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Only string fields can specify `string_field_validation`.");
}
if (!field->is_repeated() &&
field->proto_features_->has_repeated_field_encoding()) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Only repeated fields can specify `repeated_field_encoding`.");
}
#endif // PROTOBUF_FUTURE_EDITIONS
}
void DescriptorBuilder::ValidateOptions(const EnumDescriptor* enm,
const EnumDescriptorProto& proto) {
CheckEnumValueUniqueness(proto, enm);
if (!enm->is_closed() && enm->value_count() > 0 &&
enm->value(0)->number() != 0) {
AddError(enm->full_name(), proto.value(0),
DescriptorPool::ErrorCollector::NUMBER,
"The first enum value must be zero for open enums.");
}
if (!enm->options().has_allow_alias() || !enm->options().allow_alias()) {
absl::flat_hash_map<int, std::string> used_values;
for (int i = 0; i < enm->value_count(); ++i) {
const EnumValueDescriptor* enum_value = enm->value(i);
auto insert_result =
used_values.emplace(enum_value->number(), enum_value->full_name());
bool inserted = insert_result.second;
if (!inserted) {
if (!enm->options().allow_alias()) {
// Generate error if duplicated enum values are explicitly disallowed.
auto make_error = [&] {
// Find the next free number.
absl::flat_hash_set<int64_t> used;
for (int j = 0; j < enm->value_count(); ++j) {
used.insert(enm->value(j)->number());
}
int64_t next_value = static_cast<int64_t>(enum_value->number()) + 1;
while (used.contains(next_value)) ++next_value;
std::string error = absl::StrCat(
"\"", enum_value->full_name(),
"\" uses the same enum value as \"",
insert_result.first->second,
"\". If this is intended, set "
"'option allow_alias = true;' to the enum definition.");
if (next_value < std::numeric_limits<int32_t>::max()) {
absl::StrAppend(&error, " The next available enum value is ",
next_value, ".");
}
return error;
};
AddError(enm->full_name(), proto.value(i),
DescriptorPool::ErrorCollector::NUMBER, make_error);
}
}
}
}
}
void DescriptorBuilder::ValidateOptions(
const EnumValueDescriptor* /* enum_value */,
const EnumValueDescriptorProto& /* proto */) {
// Nothing to do so far.
}
namespace {
// Validates that a fully-qualified symbol for extension declaration must
// have a leading dot and valid identifiers.
absl::optional<std::string> ValidateSymbolForDeclaration(
absl::string_view symbol) {
if (!absl::StartsWith(symbol, ".")) {
return absl::StrCat("\"", symbol,
"\" must have a leading dot to indicate the "
"fully-qualified scope.");
}
if (!ValidateQualifiedName(symbol)) {
return absl::StrCat("\"", symbol, "\" contains invalid identifiers.");
}
return absl::nullopt;
}
} // namespace
void DescriptorBuilder::ValidateExtensionDeclaration(
const std::string& full_name,
const RepeatedPtrField<ExtensionRangeOptions_Declaration>& declarations,
const DescriptorProto_ExtensionRange& proto,
absl::flat_hash_set<absl::string_view>& full_name_set) {
absl::flat_hash_set<int> extension_number_set;
for (const auto& declaration : declarations) {
if (declaration.number() < proto.start() ||
declaration.number() >= proto.end()) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension declaration number $0 is not in the "
"extension range.",
declaration.number());
});
}
if (!extension_number_set.insert(declaration.number()).second) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension declaration number $0 is declared multiple times.",
declaration.number());
});
}
// Both full_name and type should be present. If none of them is set,
// add an error unless reserved is set to true. If only one of them is set,
// add an error whether or not reserved is set to true.
if (!declaration.has_full_name() || !declaration.has_type()) {
if (declaration.has_full_name() != declaration.has_type() ||
!declaration.reserved()) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::EXTENDEE,
[&] {
return absl::StrCat(
"Extension declaration #", declaration.number(),
" should have both \"full_name\" and \"type\" set.");
});
}
} else {
if (!full_name_set.insert(declaration.full_name()).second) {
AddError(
declaration.full_name(), proto,
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::Substitute(
"Extension field name \"$0\" is declared multiple times.",
declaration.full_name());
});
return;
}
absl::optional<std::string> err =
ValidateSymbolForDeclaration(declaration.full_name());
if (err.has_value()) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
[err] { return *err; });
}
if (!IsNonMessageType(declaration.type())) {
err = ValidateSymbolForDeclaration(declaration.type());
if (err.has_value()) {
AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
[err] { return *err; });
}
}
}
}
}
void DescriptorBuilder::ValidateExtensionRangeOptions(
const DescriptorProto& proto, const Descriptor& message) {
const int64_t max_extension_range =
static_cast<int64_t>(message.options().message_set_wire_format()
? std::numeric_limits<int32_t>::max()
: FieldDescriptor::kMaxNumber);
size_t num_declarations = 0;
for (int i = 0; i < message.extension_range_count(); i++) {
if (message.extension_range(i)->options_ == nullptr) continue;
num_declarations +=
message.extension_range(i)->options_->declaration_size();
}
// Contains the full names from both "declaration" and "metadata".
absl::flat_hash_set<absl::string_view> declaration_full_name_set;
declaration_full_name_set.reserve(num_declarations);
for (int i = 0; i < message.extension_range_count(); i++) {
const auto& range = *message.extension_range(i);
if (range.end_number() > max_extension_range + 1) {
AddError(message.full_name(), proto,
DescriptorPool::ErrorCollector::NUMBER, [&] {
return absl::Substitute(
"Extension numbers cannot be greater than $0.",
max_extension_range);
});
}
const auto& range_options = *range.options_;
if (!range_options.declaration().empty()) {
// TODO(b/278783756): remove the "has_verification" check once the default
// is flipped to DECLARATION.
if (range_options.has_verification() &&
range_options.verification() == ExtensionRangeOptions::UNVERIFIED) {
AddError(message.full_name(), proto.extension_range(i),
DescriptorPool::ErrorCollector::EXTENDEE, [&] {
return "Cannot mark the extension range as UNVERIFIED when "
"it has extension(s) declared.";
});
return;
}
ValidateExtensionDeclaration(
message.full_name(), range_options.declaration(),
proto.extension_range(i), declaration_full_name_set);
}
}
}
void DescriptorBuilder::ValidateOptions(const ServiceDescriptor* service,
const ServiceDescriptorProto& proto) {
if (IsLite(service->file()) &&
(service->file()->options().cc_generic_services() ||
service->file()->options().java_generic_services())) {
AddError(service->full_name(), proto, DescriptorPool::ErrorCollector::NAME,
"Files with optimize_for = LITE_RUNTIME cannot define services "
"unless you set both options cc_generic_services and "
"java_generic_services to false.");
}
}
void DescriptorBuilder::ValidateOptions(
const MethodDescriptor* /* method */,
const MethodDescriptorProto& /* proto */) {
// Nothing to do so far.
}
bool DescriptorBuilder::ValidateMapEntry(const FieldDescriptor* field,
const FieldDescriptorProto& proto) {
const Descriptor* message = field->message_type();
if ( // Must not contain extensions, extension range or nested message or
// enums
message->extension_count() != 0 ||
field->label() != FieldDescriptor::LABEL_REPEATED ||
message->extension_range_count() != 0 ||
message->nested_type_count() != 0 || message->enum_type_count() != 0 ||
// Must contain exactly two fields
message->field_count() != 2 ||
// Field name and message name must match
message->name() !=
absl::StrCat(ToCamelCase(field->name(), false), "Entry") ||
// Entry message must be in the same containing type of the field.
field->containing_type() != message->containing_type()) {
return false;
}
const FieldDescriptor* key = message->map_key();
const FieldDescriptor* value = message->map_value();
if (key->label() != FieldDescriptor::LABEL_OPTIONAL || key->number() != 1 ||
key->name() != "key") {
return false;
}
if (value->label() != FieldDescriptor::LABEL_OPTIONAL ||
value->number() != 2 || value->name() != "value") {
return false;
}
// Check key types are legal.
switch (key->type()) {
case FieldDescriptor::TYPE_ENUM:
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Key in map fields cannot be enum types.");
break;
case FieldDescriptor::TYPE_FLOAT:
case FieldDescriptor::TYPE_DOUBLE:
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_GROUP:
case FieldDescriptor::TYPE_BYTES:
AddError(
field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Key in map fields cannot be float/double, bytes or message types.");
break;
case FieldDescriptor::TYPE_BOOL:
case FieldDescriptor::TYPE_INT32:
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_SINT32:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_STRING:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_SFIXED64:
// Legal cases
break;
// Do not add a default, so that the compiler will complain when new types
// are added.
}
if (value->type() == FieldDescriptor::TYPE_ENUM) {
if (value->enum_type()->value(0)->number() != 0) {
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"Enum value in map must define 0 as the first value.");
}
}
return true;
}
void DescriptorBuilder::DetectMapConflicts(const Descriptor* message,
const DescriptorProto& proto) {
DescriptorsByNameSet<Descriptor> seen_types;
for (int i = 0; i < message->nested_type_count(); ++i) {
const Descriptor* nested = message->nested_type(i);
auto insert_result = seen_types.insert(nested);
bool inserted = insert_result.second;
if (!inserted) {
if ((*insert_result.first)->options().map_entry() ||
nested->options().map_entry()) {
AddError(message->full_name(), proto,
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat(
"Expanded map entry type ", nested->name(),
" conflicts with an existing nested message type.");
});
break;
}
}
// Recursively test on the nested types.
DetectMapConflicts(message->nested_type(i), proto.nested_type(i));
}
// Check for conflicted field names.
for (int i = 0; i < message->field_count(); ++i) {
const FieldDescriptor* field = message->field(i);
auto iter = seen_types.find(field->name());
if (iter != seen_types.end() && (*iter)->options().map_entry()) {
AddError(message->full_name(), proto,
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("Expanded map entry type ",
(*iter)->name(),
" conflicts with an existing field.");
});
}
}
// Check for conflicted enum names.
for (int i = 0; i < message->enum_type_count(); ++i) {
const EnumDescriptor* enum_desc = message->enum_type(i);
auto iter = seen_types.find(enum_desc->name());
if (iter != seen_types.end() && (*iter)->options().map_entry()) {
AddError(message->full_name(), proto,
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("Expanded map entry type ",
(*iter)->name(),
" conflicts with an existing enum type.");
});
}
}
// Check for conflicted oneof names.
for (int i = 0; i < message->oneof_decl_count(); ++i) {
const OneofDescriptor* oneof_desc = message->oneof_decl(i);
auto iter = seen_types.find(oneof_desc->name());
if (iter != seen_types.end() && (*iter)->options().map_entry()) {
AddError(message->full_name(), proto,
DescriptorPool::ErrorCollector::NAME, [&] {
return absl::StrCat("Expanded map entry type ",
(*iter)->name(),
" conflicts with an existing oneof type.");
});
}
}
}
void DescriptorBuilder::ValidateJSType(const FieldDescriptor* field,
const FieldDescriptorProto& proto) {
FieldOptions::JSType jstype = field->options().jstype();
// The default is always acceptable.
if (jstype == FieldOptions::JS_NORMAL) {
return;
}
switch (field->type()) {
// Integral 64-bit types may be represented as JavaScript numbers or
// strings.
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
case FieldDescriptor::TYPE_SINT64:
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
if (jstype == FieldOptions::JS_STRING ||
jstype == FieldOptions::JS_NUMBER) {
return;
}
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
[&] {
return absl::StrCat(
"Illegal jstype for int64, uint64, sint64, fixed64 "
"or sfixed64 field: ",
FieldOptions_JSType_descriptor()->value(jstype)->name());
});
break;
// No other types permit a jstype option.
default:
AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
"jstype is only allowed on int64, uint64, sint64, fixed64 "
"or sfixed64 fields.");
break;
}
}
// -------------------------------------------------------------------
DescriptorBuilder::OptionInterpreter::OptionInterpreter(
DescriptorBuilder* builder)
: builder_(builder) {
ABSL_CHECK(builder_);
}
DescriptorBuilder::OptionInterpreter::~OptionInterpreter() {}
bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
OptionsToInterpret* options_to_interpret) {
return InterpretOptionsImpl(options_to_interpret, /*features=*/false);
}
#ifdef PROTOBUF_FUTURE_EDITIONS
bool DescriptorBuilder::OptionInterpreter::InterpretFeatures(
OptionsToInterpret* options_to_interpret) {
return InterpretOptionsImpl(options_to_interpret, /*features=*/true);
}
#endif // PROTOBUF_FUTURE_EDITIONS
bool DescriptorBuilder::OptionInterpreter::InterpretOptionsImpl(
OptionsToInterpret* options_to_interpret, bool features) {
// Note that these may be in different pools, so we can't use the same
// descriptor and reflection objects on both.
Message* options = options_to_interpret->options;
const Message* original_options = options_to_interpret->original_options;
bool failed = false;
options_to_interpret_ = options_to_interpret;
// Find the uninterpreted_option field in the mutable copy of the options
// and clear them, since we're about to interpret them.
const FieldDescriptor* uninterpreted_options_field =
options->GetDescriptor()->FindFieldByName("uninterpreted_option");
ABSL_CHECK(uninterpreted_options_field != nullptr)
<< "No field named \"uninterpreted_option\" in the Options proto.";
options->GetReflection()->ClearField(options, uninterpreted_options_field);
std::vector<int> src_path = options_to_interpret->element_path;
src_path.push_back(uninterpreted_options_field->number());
// Find the uninterpreted_option field in the original options.
const FieldDescriptor* original_uninterpreted_options_field =
original_options->GetDescriptor()->FindFieldByName(
"uninterpreted_option");
ABSL_CHECK(original_uninterpreted_options_field != nullptr)
<< "No field named \"uninterpreted_option\" in the Options proto.";
const int num_uninterpreted_options =
original_options->GetReflection()->FieldSize(
*original_options, original_uninterpreted_options_field);
for (int i = 0; i < num_uninterpreted_options; ++i) {
src_path.push_back(i);
uninterpreted_option_ = DownCast<const UninterpretedOption*>(
&original_options->GetReflection()->GetRepeatedMessage(
*original_options, original_uninterpreted_options_field, i));
if (!InterpretSingleOption(options, src_path,
options_to_interpret->element_path, features)) {
// Error already added by InterpretSingleOption().
failed = true;
break;
}
src_path.pop_back();
}
// Reset these, so we don't have any dangling pointers.
uninterpreted_option_ = nullptr;
options_to_interpret_ = nullptr;
if (!failed) {
// InterpretSingleOption() added the interpreted options in the
// UnknownFieldSet, in case the option isn't yet known to us. Now we
// serialize the options message and deserialize it back. That way, any
// option fields that we do happen to know about will get moved from the
// UnknownFieldSet into the real fields, and thus be available right away.
// If they are not known, that's OK too. They will get reparsed into the
// UnknownFieldSet and wait there until the message is parsed by something
// that does know about the options.
// Keep the unparsed options around in case the reparsing fails.
std::unique_ptr<Message> unparsed_options(options->New());
options->GetReflection()->Swap(unparsed_options.get(), options);
std::string buf;
if (!unparsed_options->AppendToString(&buf) ||
!options->ParseFromString(buf)) {
builder_->AddError(
options_to_interpret->element_name, *original_options,
DescriptorPool::ErrorCollector::OTHER, [&] {
return absl::StrCat(
"Some options could not be correctly parsed using the proto "
"descriptors compiled into this binary.\n"
"Unparsed options: ",
unparsed_options->ShortDebugString(),
"\n"
"Parsing attempt: ",
options->ShortDebugString());
});
// Restore the unparsed options.
options->GetReflection()->Swap(unparsed_options.get(), options);
}
}
return !failed;
}
bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
Message* options, const std::vector<int>& src_path,
const std::vector<int>& options_path, bool features) {
// First do some basic validation.
if (uninterpreted_option_->name_size() == 0) {
// This should never happen unless the parser has gone seriously awry or
// someone has manually created the uninterpreted option badly.
return AddNameError(
[]() -> std::string { return "Option must have a name."; });
}
if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") {
return AddNameError([]() -> std::string {
return "Option must not use reserved name \"uninterpreted_option\".";
});
}
if (features != (uninterpreted_option_->name(0).name_part() == "features")) {
// Allow feature and option interpretation to occur in two phases. This is
// necessary because features *are* options and need to be interpreted
// before resolving them. However, options can also *have* features
// attached to them.
return true;
}
const Descriptor* options_descriptor = nullptr;
// Get the options message's descriptor from the builder's pool, so that we
// get the version that knows about any extension options declared in the file
// we're currently building. The descriptor should be there as long as the
// file we're building imported descriptor.proto.
// Note that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not
// DescriptorPool::FindMessageTypeByName() because we're already holding the
// pool's mutex, and the latter method locks it again. We don't use
// FindSymbol() because files that use custom options only need to depend on
// the file that defines the option, not descriptor.proto itself.
Symbol symbol = builder_->FindSymbolNotEnforcingDeps(
options->GetDescriptor()->full_name());
options_descriptor = symbol.descriptor();
if (options_descriptor == nullptr) {
// The options message's descriptor was not in the builder's pool, so use
// the standard version from the generated pool. We're not holding the
// generated pool's mutex, so we can search it the straightforward way.
options_descriptor = options->GetDescriptor();
}
ABSL_CHECK(options_descriptor);
// We iterate over the name parts to drill into the submessages until we find
// the leaf field for the option. As we drill down we remember the current
// submessage's descriptor in |descriptor| and the next field in that
// submessage in |field|. We also track the fields we're drilling down
// through in |intermediate_fields|. As we go, we reconstruct the full option
// name in |debug_msg_name|, for use in error messages.
const Descriptor* descriptor = options_descriptor;
const FieldDescriptor* field = nullptr;
std::vector<const FieldDescriptor*> intermediate_fields;
std::string debug_msg_name = "";
std::vector<int> dest_path = options_path;
for (int i = 0; i < uninterpreted_option_->name_size(); ++i) {
builder_->undefine_resolved_name_.clear();
const std::string& name_part = uninterpreted_option_->name(i).name_part();
if (!debug_msg_name.empty()) {
absl::StrAppend(&debug_msg_name, ".");
}
if (uninterpreted_option_->name(i).is_extension()) {
absl::StrAppend(&debug_msg_name, "(", name_part, ")");
// Search for the extension's descriptor as an extension in the builder's
// pool. Note that we use DescriptorBuilder::LookupSymbol(), not
// DescriptorPool::FindExtensionByName(), for two reasons: 1) It allows
// relative lookups, and 2) because we're already holding the pool's
// mutex, and the latter method locks it again.
symbol =
builder_->LookupSymbol(name_part, options_to_interpret_->name_scope);
field = symbol.field_descriptor();
// If we don't find the field then the field's descriptor was not in the
// builder's pool, but there's no point in looking in the generated
// pool. We require that you import the file that defines any extensions
// you use, so they must be present in the builder's pool.
} else {
absl::StrAppend(&debug_msg_name, name_part);
// Search for the field's descriptor as a regular field.
field = descriptor->FindFieldByName(name_part);
}
if (field == nullptr) {
if (get_allow_unknown(builder_->pool_)) {
// We can't find the option, but AllowUnknownDependencies() is enabled,
// so we will just leave it as uninterpreted.
AddWithoutInterpreting(*uninterpreted_option_, options);
return true;
} else if (!(builder_->undefine_resolved_name_).empty()) {
// Option is resolved to a name which is not defined.
return AddNameError([&] {
return absl::StrCat(
"Option \"", debug_msg_name, "\" is resolved to \"(",
builder_->undefine_resolved_name_,
")\", which is not defined. The innermost scope is searched "
"first "
"in name resolution. Consider using a leading '.'(i.e., \"(.",
debug_msg_name.substr(1),
"\") to start from the outermost scope.");
});
} else {
return AddNameError([&] {
return absl::StrCat(
"Option \"", debug_msg_name, "\" unknown. Ensure that your proto",
" definition file imports the proto which defines the option.");
});
}
} else if (field->containing_type() != descriptor) {
if (get_is_placeholder(field->containing_type())) {
// The field is an extension of a placeholder type, so we can't
// reliably verify whether it is a valid extension to use here (e.g.
// we don't know if it is an extension of the correct *Options message,
// or if it has a valid field number, etc.). Just leave it as
// uninterpreted instead.
AddWithoutInterpreting(*uninterpreted_option_, options);
return true;
} else {
// This can only happen if, due to some insane misconfiguration of the
// pools, we find the options message in one pool but the field in
// another. This would probably imply a hefty bug somewhere.
return AddNameError([&] {
return absl::StrCat("Option field \"", debug_msg_name,
"\" is not a field or extension of message \"",
descriptor->name(), "\".");
});
}
} else {
// accumulate field numbers to form path to interpreted option
dest_path.push_back(field->number());
if (i < uninterpreted_option_->name_size() - 1) {
if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
return AddNameError([&] {
return absl::StrCat("Option \"", debug_msg_name,
"\" is an atomic type, not a message.");
});
} else if (field->is_repeated()) {
return AddNameError([&] {
return absl::StrCat("Option field \"", debug_msg_name,
"\" is a repeated message. Repeated message "
"options must be initialized using an "
"aggregate value.");
});
} else {
// Drill down into the submessage.
intermediate_fields.push_back(field);
descriptor = field->message_type();
}
}
}
}
// We've found the leaf field. Now we use UnknownFieldSets to set its value
// on the options message. We do so because the message may not yet know
// about its extension fields, so we may not be able to set the fields
// directly. But the UnknownFieldSets will serialize to the same wire-format
// message, so reading that message back in once the extension fields are
// known will populate them correctly.
// First see if the option is already set.
if (!field->is_repeated() &&
!ExamineIfOptionIsSet(
intermediate_fields.begin(), intermediate_fields.end(), field,
debug_msg_name,
options->GetReflection()->GetUnknownFields(*options))) {
return false; // ExamineIfOptionIsSet() already added the error.
}
// First set the value on the UnknownFieldSet corresponding to the
// innermost message.
std::unique_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet());
if (!SetOptionValue(field, unknown_fields.get())) {
return false; // SetOptionValue() already added the error.
}
// Now wrap the UnknownFieldSet with UnknownFieldSets corresponding to all
// the intermediate messages.
for (std::vector<const FieldDescriptor*>::reverse_iterator iter =
intermediate_fields.rbegin();
iter != intermediate_fields.rend(); ++iter) {
std::unique_ptr<UnknownFieldSet> parent_unknown_fields(
new UnknownFieldSet());
switch ((*iter)->type()) {
case FieldDescriptor::TYPE_MESSAGE: {
std::string* outstr =
parent_unknown_fields->AddLengthDelimited((*iter)->number());
ABSL_CHECK(unknown_fields->SerializeToString(outstr))
<< "Unexpected failure while serializing option submessage "
<< debug_msg_name << "\".";
break;
}
case FieldDescriptor::TYPE_GROUP: {
parent_unknown_fields->AddGroup((*iter)->number())
->MergeFrom(*unknown_fields);
break;
}
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: "
<< (*iter)->type();
return false;
}
unknown_fields.reset(parent_unknown_fields.release());
}
// Now merge the UnknownFieldSet corresponding to the top-level message into
// the options message.
options->GetReflection()->MutableUnknownFields(options)->MergeFrom(
*unknown_fields);
// record the element path of the interpreted option
if (field->is_repeated()) {
int index = repeated_option_counts_[dest_path]++;
dest_path.push_back(index);
}
interpreted_paths_[src_path] = dest_path;
return true;
}
void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo(
SourceCodeInfo* info) {
if (interpreted_paths_.empty()) {
// nothing to do!
return;
}
// We find locations that match keys in interpreted_paths_ and
// 1) replace the path with the corresponding value in interpreted_paths_
// 2) remove any subsequent sub-locations (sub-location is one whose path
// has the parent path as a prefix)
//
// To avoid quadratic behavior of removing interior rows as we go,
// we keep a copy. But we don't actually copy anything until we've
// found the first match (so if the source code info has no locations
// that need to be changed, there is zero copy overhead).
RepeatedPtrField<SourceCodeInfo_Location>* locs = info->mutable_location();
RepeatedPtrField<SourceCodeInfo_Location> new_locs;
bool copying = false;
std::vector<int> pathv;
bool matched = false;
for (RepeatedPtrField<SourceCodeInfo_Location>::iterator loc = locs->begin();
loc != locs->end(); loc++) {
if (matched) {
// see if this location is in the range to remove
bool loc_matches = true;
if (loc->path_size() < static_cast<int64_t>(pathv.size())) {
loc_matches = false;
} else {
for (size_t j = 0; j < pathv.size(); j++) {
if (loc->path(j) != pathv[j]) {
loc_matches = false;
break;
}
}
}
if (loc_matches) {
// don't copy this row since it is a sub-location that we're removing
continue;
}
matched = false;
}
pathv.clear();
for (int j = 0; j < loc->path_size(); j++) {
pathv.push_back(loc->path(j));
}
auto entry = interpreted_paths_.find(pathv);
if (entry == interpreted_paths_.end()) {
// not a match
if (copying) {
*new_locs.Add() = *loc;
}
continue;
}
matched = true;
if (!copying) {
// initialize the copy we are building
copying = true;
new_locs.Reserve(locs->size());
for (RepeatedPtrField<SourceCodeInfo_Location>::iterator it =
locs->begin();
it != loc; it++) {
*new_locs.Add() = *it;
}
}
// add replacement and update its path
SourceCodeInfo_Location* replacement = new_locs.Add();
*replacement = *loc;
replacement->clear_path();
for (std::vector<int>::iterator rit = entry->second.begin();
rit != entry->second.end(); rit++) {
replacement->add_path(*rit);
}
}
// if we made a changed copy, put it in place
if (copying) {
*locs = new_locs;
}
}
void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting(
const UninterpretedOption& uninterpreted_option, Message* options) {
const FieldDescriptor* field =
options->GetDescriptor()->FindFieldByName("uninterpreted_option");
ABSL_CHECK(field != nullptr);
options->GetReflection()
->AddMessage(options, field)
->CopyFrom(uninterpreted_option);
}
bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet(
std::vector<const FieldDescriptor*>::const_iterator
intermediate_fields_iter,
std::vector<const FieldDescriptor*>::const_iterator intermediate_fields_end,
const FieldDescriptor* innermost_field, const std::string& debug_msg_name,
const UnknownFieldSet& unknown_fields) {
// We do linear searches of the UnknownFieldSet and its sub-groups. This
// should be fine since it's unlikely that any one options structure will
// contain more than a handful of options.
if (intermediate_fields_iter == intermediate_fields_end) {
// We're at the innermost submessage.
for (int i = 0; i < unknown_fields.field_count(); i++) {
if (unknown_fields.field(i).number() == innermost_field->number()) {
return AddNameError([&] {
return absl::StrCat("Option \"", debug_msg_name,
"\" was already set.");
});
}
}
return true;
}
for (int i = 0; i < unknown_fields.field_count(); i++) {
if (unknown_fields.field(i).number() ==
(*intermediate_fields_iter)->number()) {
const UnknownField* unknown_field = &unknown_fields.field(i);
FieldDescriptor::Type type = (*intermediate_fields_iter)->type();
// Recurse into the next submessage.
switch (type) {
case FieldDescriptor::TYPE_MESSAGE:
if (unknown_field->type() == UnknownField::TYPE_LENGTH_DELIMITED) {
UnknownFieldSet intermediate_unknown_fields;
if (intermediate_unknown_fields.ParseFromString(
unknown_field->length_delimited()) &&
!ExamineIfOptionIsSet(intermediate_fields_iter + 1,
intermediate_fields_end, innermost_field,
debug_msg_name,
intermediate_unknown_fields)) {
return false; // Error already added.
}
}
break;
case FieldDescriptor::TYPE_GROUP:
if (unknown_field->type() == UnknownField::TYPE_GROUP) {
if (!ExamineIfOptionIsSet(intermediate_fields_iter + 1,
intermediate_fields_end, innermost_field,
debug_msg_name, unknown_field->group())) {
return false; // Error already added.
}
}
break;
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " << type;
return false;
}
}
}
return true;
}
namespace {
// Helpers for method below
template <typename T> std::string ValueOutOfRange(
absl::string_view type_name, absl::string_view option_name) {
return absl::StrFormat(
"Value out of range, %d to %d, for %s option \"%s\".", \
std::numeric_limits<T>::min(), std::numeric_limits<T>::max(),
type_name, option_name);
}
template <typename T> std::string ValueMustBeInt(
absl::string_view type_name, absl::string_view option_name) {
return absl::StrFormat(
"Value must be integer, from %d to %d, for %s option \"%s\".", \
std::numeric_limits<T>::min(), std::numeric_limits<T>::max(),
type_name, option_name);
}
} // namespace
bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) {
// We switch on the CppType to validate.
switch (option_field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
if (uninterpreted_option_->has_positive_int_value()) {
if (uninterpreted_option_->positive_int_value() >
static_cast<uint64_t>(std::numeric_limits<int32_t>::max())) {
return AddValueError([&] {
return ValueOutOfRange<int32_t>("int32", option_field->full_name());
});
} else {
SetInt32(option_field->number(),
uninterpreted_option_->positive_int_value(),
option_field->type(), unknown_fields);
}
} else if (uninterpreted_option_->has_negative_int_value()) {
if (uninterpreted_option_->negative_int_value() <
static_cast<int64_t>(std::numeric_limits<int32_t>::min())) {
return AddValueError([&] {
return ValueOutOfRange<int32_t>("int32", option_field->full_name());
});
} else {
SetInt32(option_field->number(),
uninterpreted_option_->negative_int_value(),
option_field->type(), unknown_fields);
}
} else {
return AddValueError([&] {
return ValueMustBeInt<int32_t>("int32", option_field->full_name());
});
}
break;
case FieldDescriptor::CPPTYPE_INT64:
if (uninterpreted_option_->has_positive_int_value()) {
if (uninterpreted_option_->positive_int_value() >
static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
return AddValueError([&] {
return ValueOutOfRange<int64_t>("int64", option_field->full_name());
});
} else {
SetInt64(option_field->number(),
uninterpreted_option_->positive_int_value(),
option_field->type(), unknown_fields);
}
} else if (uninterpreted_option_->has_negative_int_value()) {
SetInt64(option_field->number(),
uninterpreted_option_->negative_int_value(),
option_field->type(), unknown_fields);
} else {
return AddValueError([&] {
return ValueMustBeInt<int64_t>("int64", option_field->full_name());
});
}
break;
case FieldDescriptor::CPPTYPE_UINT32:
if (uninterpreted_option_->has_positive_int_value()) {
if (uninterpreted_option_->positive_int_value() >
std::numeric_limits<uint32_t>::max()) {
return AddValueError([&] {
return ValueOutOfRange<uint32_t>("uint32",
option_field->full_name());
});
} else {
SetUInt32(option_field->number(),
uninterpreted_option_->positive_int_value(),
option_field->type(), unknown_fields);
}
} else {
return AddValueError([&] {
return ValueMustBeInt<uint32_t>("uint32", option_field->full_name());
});
}
break;
case FieldDescriptor::CPPTYPE_UINT64:
if (uninterpreted_option_->has_positive_int_value()) {
SetUInt64(option_field->number(),
uninterpreted_option_->positive_int_value(),
option_field->type(), unknown_fields);
} else {
return AddValueError([&] {
return ValueMustBeInt<uint64_t>("uint64", option_field->full_name());
});
}
break;
case FieldDescriptor::CPPTYPE_FLOAT: {
float value;
if (uninterpreted_option_->has_double_value()) {
value = uninterpreted_option_->double_value();
} else if (uninterpreted_option_->has_positive_int_value()) {
value = uninterpreted_option_->positive_int_value();
} else if (uninterpreted_option_->has_negative_int_value()) {
value = uninterpreted_option_->negative_int_value();
} else {
return AddValueError([&] {
return absl::StrCat("Value must be number for float option \"",
option_field->full_name(), "\".");
});
}
unknown_fields->AddFixed32(option_field->number(),
internal::WireFormatLite::EncodeFloat(value));
break;
}
case FieldDescriptor::CPPTYPE_DOUBLE: {
double value;
if (uninterpreted_option_->has_double_value()) {
value = uninterpreted_option_->double_value();
} else if (uninterpreted_option_->has_positive_int_value()) {
value = uninterpreted_option_->positive_int_value();
} else if (uninterpreted_option_->has_negative_int_value()) {
value = uninterpreted_option_->negative_int_value();
} else {
return AddValueError([&] {
return absl::StrCat("Value must be number for double option \"",
option_field->full_name(), "\".");
});
}
unknown_fields->AddFixed64(option_field->number(),
internal::WireFormatLite::EncodeDouble(value));
break;
}
case FieldDescriptor::CPPTYPE_BOOL:
uint64_t value;
if (!uninterpreted_option_->has_identifier_value()) {
return AddValueError([&] {
return absl::StrCat("Value must be identifier for boolean option \"",
option_field->full_name(), "\".");
});
}
if (uninterpreted_option_->identifier_value() == "true") {
value = 1;
} else if (uninterpreted_option_->identifier_value() == "false") {
value = 0;
} else {
return AddValueError([&] {
return absl::StrCat(
"Value must be \"true\" or \"false\" for boolean option \"",
option_field->full_name(), "\".");
});
}
unknown_fields->AddVarint(option_field->number(), value);
break;
case FieldDescriptor::CPPTYPE_ENUM: {
if (!uninterpreted_option_->has_identifier_value()) {
return AddValueError([&] {
return absl::StrCat(
"Value must be identifier for enum-valued option \"",
option_field->full_name(), "\".");
});
}
const EnumDescriptor* enum_type = option_field->enum_type();
const std::string& value_name = uninterpreted_option_->identifier_value();
const EnumValueDescriptor* enum_value = nullptr;
if (enum_type->file()->pool() != DescriptorPool::generated_pool()) {
// Note that the enum value's fully-qualified name is a sibling of the
// enum's name, not a child of it.
std::string fully_qualified_name = enum_type->full_name();
fully_qualified_name.resize(fully_qualified_name.size() -
enum_type->name().size());
fully_qualified_name += value_name;
// Search for the enum value's descriptor in the builder's pool. Note
// that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not
// DescriptorPool::FindEnumValueByName() because we're already holding
// the pool's mutex, and the latter method locks it again.
Symbol symbol =
builder_->FindSymbolNotEnforcingDeps(fully_qualified_name);
if (auto* candicate_descriptor = symbol.enum_value_descriptor()) {
if (candicate_descriptor->type() != enum_type) {
return AddValueError([&] {
return absl::StrCat(
"Enum type \"", enum_type->full_name(),
"\" has no value named \"", value_name, "\" for option \"",
option_field->full_name(),
"\". This appears to be a value from a sibling type.");
});
} else {
enum_value = candicate_descriptor;
}
}
} else {
// The enum type is in the generated pool, so we can search for the
// value there.
enum_value = enum_type->FindValueByName(value_name);
}
if (enum_value == nullptr) {
return AddValueError([&] {
return absl::StrCat(
"Enum type \"", option_field->enum_type()->full_name(),
"\" has no value named \"", value_name, "\" for option \"",
option_field->full_name(), "\".");
});
} else {
// Sign-extension is not a problem, since we cast directly from int32_t
// to uint64_t, without first going through uint32_t.
unknown_fields->AddVarint(
option_field->number(),
static_cast<uint64_t>(static_cast<int64_t>(enum_value->number())));
}
break;
}
case FieldDescriptor::CPPTYPE_STRING:
if (!uninterpreted_option_->has_string_value()) {
return AddValueError([&] {
return absl::StrCat(
"Value must be quoted string for string option \"",
option_field->full_name(), "\".");
});
}
// The string has already been unquoted and unescaped by the parser.
unknown_fields->AddLengthDelimited(option_field->number(),
uninterpreted_option_->string_value());
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (!SetAggregateOption(option_field, unknown_fields)) {
return false;
}
break;
}
return true;
}
class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder
: public TextFormat::Finder {
public:
DescriptorBuilder* builder_;
const Descriptor* FindAnyType(const Message& /*message*/,
const std::string& prefix,
const std::string& name) const override {
if (prefix != internal::kTypeGoogleApisComPrefix &&
prefix != internal::kTypeGoogleProdComPrefix) {
return nullptr;
}
assert_mutex_held(builder_->pool_);
return builder_->FindSymbol(name).descriptor();
}
const FieldDescriptor* FindExtension(Message* message,
const std::string& name) const override {
assert_mutex_held(builder_->pool_);
const Descriptor* descriptor = message->GetDescriptor();
Symbol result =
builder_->LookupSymbolNoPlaceholder(name, descriptor->full_name());
if (auto* field = result.field_descriptor()) {
return field;
} else if (result.type() == Symbol::MESSAGE &&
descriptor->options().message_set_wire_format()) {
const Descriptor* foreign_type = result.descriptor();
// The text format allows MessageSet items to be specified using
// the type name, rather than the extension identifier. If the symbol
// lookup returned a Message, and the enclosing Message has
// message_set_wire_format = true, then return the message set
// extension, if one exists.
for (int i = 0; i < foreign_type->extension_count(); i++) {
const FieldDescriptor* extension = foreign_type->extension(i);
if (extension->containing_type() == descriptor &&
extension->type() == FieldDescriptor::TYPE_MESSAGE &&
extension->is_optional() &&
extension->message_type() == foreign_type) {
// Found it.
return extension;
}
}
}
return nullptr;
}
};
// A custom error collector to record any text-format parsing errors
namespace {
class AggregateErrorCollector : public io::ErrorCollector {
public:
std::string error_;
void RecordError(int /* line */, int /* column */,
const absl::string_view message) override {
if (!error_.empty()) {
absl::StrAppend(&error_, "; ");
}
absl::StrAppend(&error_, message);
}
void RecordWarning(int /* line */, int /* column */,
const absl::string_view /* message */) override {
// Ignore warnings
}
};
} // namespace
// We construct a dynamic message of the type corresponding to
// option_field, parse the supplied text-format string into this
// message, and serialize the resulting message to produce the value.
bool DescriptorBuilder::OptionInterpreter::SetAggregateOption(
const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) {
if (!uninterpreted_option_->has_aggregate_value()) {
return AddValueError([&] {
return absl::StrCat("Option \"", option_field->full_name(),
"\" is a message. "
"To set the entire message, use syntax like \"",
option_field->name(),
" = { <proto text format> }\". "
"To set fields within it, use syntax like \"",
option_field->name(), ".foo = value\".");
});
}
const Descriptor* type = option_field->message_type();
std::unique_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New());
ABSL_CHECK(dynamic.get() != nullptr)
<< "Could not create an instance of " << option_field->DebugString();
AggregateErrorCollector collector;
AggregateOptionFinder finder;
finder.builder_ = builder_;
TextFormat::Parser parser;
parser.RecordErrorsTo(&collector);
parser.SetFinder(&finder);
if (!parser.ParseFromString(uninterpreted_option_->aggregate_value(),
dynamic.get())) {
AddValueError([&] {
return absl::StrCat("Error while parsing option value for \"",
option_field->name(), "\": ", collector.error_);
});
return false;
} else {
std::string serial;
dynamic->SerializeToString(&serial); // Never fails
if (option_field->type() == FieldDescriptor::TYPE_MESSAGE) {
unknown_fields->AddLengthDelimited(option_field->number(), serial);
} else {
ABSL_CHECK_EQ(option_field->type(), FieldDescriptor::TYPE_GROUP);
UnknownFieldSet* group = unknown_fields->AddGroup(option_field->number());
group->ParseFromString(serial);
}
return true;
}
}
void DescriptorBuilder::OptionInterpreter::SetInt32(
int number, int32_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields) {
switch (type) {
case FieldDescriptor::TYPE_INT32:
unknown_fields->AddVarint(
number, static_cast<uint64_t>(static_cast<int64_t>(value)));
break;
case FieldDescriptor::TYPE_SFIXED32:
unknown_fields->AddFixed32(number, static_cast<uint32_t>(value));
break;
case FieldDescriptor::TYPE_SINT32:
unknown_fields->AddVarint(
number, internal::WireFormatLite::ZigZagEncode32(value));
break;
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT32: " << type;
break;
}
}
void DescriptorBuilder::OptionInterpreter::SetInt64(
int number, int64_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields) {
switch (type) {
case FieldDescriptor::TYPE_INT64:
unknown_fields->AddVarint(number, static_cast<uint64_t>(value));
break;
case FieldDescriptor::TYPE_SFIXED64:
unknown_fields->AddFixed64(number, static_cast<uint64_t>(value));
break;
case FieldDescriptor::TYPE_SINT64:
unknown_fields->AddVarint(
number, internal::WireFormatLite::ZigZagEncode64(value));
break;
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT64: " << type;
break;
}
}
void DescriptorBuilder::OptionInterpreter::SetUInt32(
int number, uint32_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields) {
switch (type) {
case FieldDescriptor::TYPE_UINT32:
unknown_fields->AddVarint(number, static_cast<uint64_t>(value));
break;
case FieldDescriptor::TYPE_FIXED32:
unknown_fields->AddFixed32(number, static_cast<uint32_t>(value));
break;
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT32: " << type;
break;
}
}
void DescriptorBuilder::OptionInterpreter::SetUInt64(
int number, uint64_t value, FieldDescriptor::Type type,
UnknownFieldSet* unknown_fields) {
switch (type) {
case FieldDescriptor::TYPE_UINT64:
unknown_fields->AddVarint(number, value);
break;
case FieldDescriptor::TYPE_FIXED64:
unknown_fields->AddFixed64(number, value);
break;
default:
ABSL_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT64: " << type;
break;
}
}
void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto,
const FileDescriptor* result) {
(void)result; // Parameter is used by Google-internal code.
if (!unused_dependency_.empty()) {
auto itr = pool_->unused_import_track_files_.find(proto.name());
bool is_error =
itr != pool_->unused_import_track_files_.end() && itr->second;
for (const auto* unused : unused_dependency_) {
auto make_error = [&] {
return absl::StrCat("Import ", unused->name(), " is unused.");
};
if (is_error) {
AddError(unused->name(), proto, DescriptorPool::ErrorCollector::IMPORT,
make_error);
} else {
AddWarning(unused->name(), proto,
DescriptorPool::ErrorCollector::IMPORT, make_error);
}
}
}
}
Symbol DescriptorPool::CrossLinkOnDemandHelper(absl::string_view name,
bool expecting_enum) const {
(void)expecting_enum; // Parameter is used by Google-internal code.
auto lookup_name = std::string(name);
if (!lookup_name.empty() && lookup_name[0] == '.') {
lookup_name = lookup_name.substr(1);
}
Symbol result = tables_->FindByNameHelper(this, lookup_name);
return result;
}
// Handle the lazy import building for a message field whose type wasn't built
// at cross link time. If that was the case, we saved the name of the type to
// be looked up when the accessor for the type was called. Set type_,
// enum_type_, message_type_, and default_value_enum_ appropriately.
void FieldDescriptor::InternalTypeOnceInit() const {
ABSL_CHECK(file()->finished_building_ == true);
const EnumDescriptor* enum_type = nullptr;
const char* lazy_type_name = reinterpret_cast<const char*>(type_once_ + 1);
const char* lazy_default_value_enum_name =
lazy_type_name + strlen(lazy_type_name) + 1;
Symbol result = file()->pool()->CrossLinkOnDemandHelper(
lazy_type_name, type_ == FieldDescriptor::TYPE_ENUM);
if (result.type() == Symbol::MESSAGE) {
type_ = FieldDescriptor::TYPE_MESSAGE;
type_descriptor_.message_type = result.descriptor();
} else if (result.type() == Symbol::ENUM) {
type_ = FieldDescriptor::TYPE_ENUM;
enum_type = type_descriptor_.enum_type = result.enum_descriptor();
}
if (enum_type) {
if (lazy_default_value_enum_name[0] != '\0') {
// Have to build the full name now instead of at CrossLink time,
// because enum_type may not be known at the time.
std::string name = enum_type->full_name();
// Enum values reside in the same scope as the enum type.
std::string::size_type last_dot = name.find_last_of('.');
if (last_dot != std::string::npos) {
name = absl::StrCat(name.substr(0, last_dot), ".",
lazy_default_value_enum_name);
} else {
name = lazy_default_value_enum_name;
}
Symbol result = file()->pool()->CrossLinkOnDemandHelper(name, true);
default_value_enum_ = result.enum_value_descriptor();
} else {
default_value_enum_ = nullptr;
}
if (!default_value_enum_) {
// We use the first defined value as the default
// if a default is not explicitly defined.
ABSL_CHECK(enum_type->value_count());
default_value_enum_ = enum_type->value(0);
}
}
}
void FieldDescriptor::TypeOnceInit(const FieldDescriptor* to_init) {
to_init->InternalTypeOnceInit();
}
// message_type(), enum_type(), default_value_enum(), and type()
// all share the same absl::call_once init path to do lazy
// import building and cross linking of a field of a message.
const Descriptor* FieldDescriptor::message_type() const {
if (type_once_) {
absl::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return type_ == TYPE_MESSAGE || type_ == TYPE_GROUP
? type_descriptor_.message_type
: nullptr;
}
const EnumDescriptor* FieldDescriptor::enum_type() const {
if (type_once_) {
absl::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return type_ == TYPE_ENUM ? type_descriptor_.enum_type : nullptr;
}
const EnumValueDescriptor* FieldDescriptor::default_value_enum() const {
if (type_once_) {
absl::call_once(*type_once_, FieldDescriptor::TypeOnceInit, this);
}
return default_value_enum_;
}
const std::string& FieldDescriptor::PrintableNameForExtension() const {
const bool is_message_set_extension =
is_extension() &&
containing_type()->options().message_set_wire_format() &&
type() == FieldDescriptor::TYPE_MESSAGE && is_optional() &&
extension_scope() == message_type();
return is_message_set_extension ? message_type()->full_name() : full_name();
}
void FileDescriptor::InternalDependenciesOnceInit() const {
ABSL_CHECK(finished_building_ == true);
const char* names_ptr = reinterpret_cast<const char*>(dependencies_once_ + 1);
for (int i = 0; i < dependency_count(); i++) {
const char* name = names_ptr;
names_ptr += strlen(name) + 1;
if (name[0] != '\0') {
dependencies_[i] = pool_->FindFileByName(name);
}
}
}
void FileDescriptor::DependenciesOnceInit(const FileDescriptor* to_init) {
to_init->InternalDependenciesOnceInit();
}
const FileDescriptor* FileDescriptor::dependency(int index) const {
if (dependencies_once_) {
// Do once init for all indices, as it's unlikely only a single index would
// be called, and saves on absl::call_once allocations.
absl::call_once(*dependencies_once_, FileDescriptor::DependenciesOnceInit,
this);
}
return dependencies_[index];
}
const Descriptor* MethodDescriptor::input_type() const {
return input_type_.Get(service());
}
const Descriptor* MethodDescriptor::output_type() const {
return output_type_.Get(service());
}
namespace internal {
void LazyDescriptor::Set(const Descriptor* descriptor) {
ABSL_CHECK(!once_);
descriptor_ = descriptor;
}
void LazyDescriptor::SetLazy(absl::string_view name,
const FileDescriptor* file) {
// verify Init() has been called and Set hasn't been called yet.
ABSL_CHECK(!descriptor_);
ABSL_CHECK(!once_);
ABSL_CHECK(file && file->pool_);
ABSL_CHECK(file->pool_->lazily_build_dependencies_);
ABSL_CHECK(!file->finished_building_);
once_ = ::new (file->pool_->tables_->AllocateBytes(static_cast<int>(
sizeof(absl::once_flag) + name.size() + 1))) absl::once_flag{};
char* lazy_name = reinterpret_cast<char*>(once_ + 1);
memcpy(lazy_name, name.data(), name.size());
lazy_name[name.size()] = 0;
}
void LazyDescriptor::Once(const ServiceDescriptor* service) {
if (once_) {
absl::call_once(*once_, [&] {
auto* file = service->file();
ABSL_CHECK(file->finished_building_);
const char* lazy_name = reinterpret_cast<const char*>(once_ + 1);
descriptor_ =
file->pool_->CrossLinkOnDemandHelper(lazy_name, false).descriptor();
});
}
}
namespace cpp {
bool HasPreservingUnknownEnumSemantics(const FieldDescriptor* field) {
if (field->legacy_enum_field_treated_as_closed()) {
return false;
}
return field->enum_type() != nullptr && !field->enum_type()->is_closed();
}
bool HasHasbit(const FieldDescriptor* field) {
return field->has_presence() && !field->real_containing_oneof() &&
!field->options().weak();
}
static bool IsVerifyUtf8(const FieldDescriptor* field, bool is_lite) {
if (is_lite) return false;
return true;
}
// Which level of UTF-8 enforcemant is placed on this file.
Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field, bool is_lite) {
if (IsStrictUtf8(field)) {
return Utf8CheckMode::kStrict;
} else if (IsVerifyUtf8(field, is_lite)) {
return Utf8CheckMode::kVerify;
} else {
return Utf8CheckMode::kNone;
}
}
bool IsLazilyInitializedFile(absl::string_view filename) {
#ifdef PROTOBUF_FUTURE_EDITIONS
if (filename == "third_party/protobuf/cpp_features.proto" ||
filename == "google/protobuf/cpp_features.proto") {
return true;
}
#endif // PROTOBUF_FUTURE_EDITIONS
return filename == "net/proto2/proto/descriptor.proto" ||
filename == "google/protobuf/descriptor.proto";
}
} // namespace cpp
} // namespace internal
#ifdef PROTOBUF_FUTURE_EDITIONS
absl::string_view FileDescriptor::edition() const {
// ASLR will help give this a random value across processes.
static const void* kAntiHyrumText = &kAntiHyrumText;
absl::string_view anti_hyrum_string(
reinterpret_cast<const char*>(kAntiHyrumText),
(reinterpret_cast<size_t>(kAntiHyrumText) >> 3) % sizeof(void*));
return edition_ == nullptr ? anti_hyrum_string : *edition_;
}
#endif // !PROTOBUF_FUTURE_EDITIONS
} // namespace protobuf
} // namespace google