1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // Author: kenton@google.com (Kenton Varda)
32 // Based on original Protocol Buffers design by
33 // Sanjay Ghemawat, Jeff Dean, and others.
34
35 #include <iostream>
36 #include <stack>
37 #include <unordered_map>
38
39 #include <google/protobuf/generated_message_reflection.h>
40 #include <google/protobuf/message.h>
41
42 #include <google/protobuf/stubs/casts.h>
43 #include <google/protobuf/stubs/logging.h>
44 #include <google/protobuf/stubs/common.h>
45 #include <google/protobuf/descriptor.pb.h>
46 #include <google/protobuf/parse_context.h>
47 #include <google/protobuf/reflection_internal.h>
48 #include <google/protobuf/io/coded_stream.h>
49 #include <google/protobuf/io/zero_copy_stream_impl.h>
50 #include <google/protobuf/descriptor.h>
51 #include <google/protobuf/generated_message_util.h>
52 #include <google/protobuf/map_field.h>
53 #include <google/protobuf/map_field_inl.h>
54 #include <google/protobuf/reflection_ops.h>
55 #include <google/protobuf/unknown_field_set.h>
56 #include <google/protobuf/wire_format.h>
57 #include <google/protobuf/wire_format_lite.h>
58 #include <google/protobuf/stubs/strutil.h>
59 #include <google/protobuf/stubs/map_util.h>
60 #include <google/protobuf/stubs/stl_util.h>
61 #include <google/protobuf/stubs/hash.h>
62
63 #include <google/protobuf/port_def.inc>
64
65 namespace google {
66 namespace protobuf {
67
68 namespace internal {
69
70 // TODO(gerbens) make this factorized better. This should not have to hop
71 // to reflection. Currently uses GeneratedMessageReflection and thus is
72 // defined in generated_message_reflection.cc
73 void RegisterFileLevelMetadata(const DescriptorTable* descriptor_table);
74
75 } // namespace internal
76
77 using internal::ReflectionOps;
78 using internal::WireFormat;
79 using internal::WireFormatLite;
80
MergeFrom(const Message & from)81 void Message::MergeFrom(const Message& from) {
82 const Descriptor* descriptor = GetDescriptor();
83 GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
84 << ": Tried to merge from a message with a different type. "
85 "to: "
86 << descriptor->full_name()
87 << ", "
88 "from: "
89 << from.GetDescriptor()->full_name();
90 ReflectionOps::Merge(from, this);
91 }
92
CheckTypeAndMergeFrom(const MessageLite & other)93 void Message::CheckTypeAndMergeFrom(const MessageLite& other) {
94 MergeFrom(*down_cast<const Message*>(&other));
95 }
96
CopyFrom(const Message & from)97 void Message::CopyFrom(const Message& from) {
98 const Descriptor* descriptor = GetDescriptor();
99 GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor)
100 << ": Tried to copy from a message with a different type. "
101 "to: "
102 << descriptor->full_name()
103 << ", "
104 "from: "
105 << from.GetDescriptor()->full_name();
106 ReflectionOps::Copy(from, this);
107 }
108
GetTypeName() const109 std::string Message::GetTypeName() const {
110 return GetDescriptor()->full_name();
111 }
112
Clear()113 void Message::Clear() { ReflectionOps::Clear(this); }
114
IsInitialized() const115 bool Message::IsInitialized() const {
116 return ReflectionOps::IsInitialized(*this);
117 }
118
FindInitializationErrors(std::vector<std::string> * errors) const119 void Message::FindInitializationErrors(std::vector<std::string>* errors) const {
120 return ReflectionOps::FindInitializationErrors(*this, "", errors);
121 }
122
InitializationErrorString() const123 std::string Message::InitializationErrorString() const {
124 std::vector<std::string> errors;
125 FindInitializationErrors(&errors);
126 return Join(errors, ", ");
127 }
128
CheckInitialized() const129 void Message::CheckInitialized() const {
130 GOOGLE_CHECK(IsInitialized()) << "Message of type \"" << GetDescriptor()->full_name()
131 << "\" is missing required fields: "
132 << InitializationErrorString();
133 }
134
DiscardUnknownFields()135 void Message::DiscardUnknownFields() {
136 return ReflectionOps::DiscardUnknownFields(this);
137 }
138
139 namespace internal {
140
141 class ReflectionAccessor {
142 public:
GetOffset(void * msg,const google::protobuf::FieldDescriptor * f,const google::protobuf::Reflection * r)143 static void* GetOffset(void* msg, const google::protobuf::FieldDescriptor* f,
144 const google::protobuf::Reflection* r) {
145 return static_cast<char*>(msg) + r->schema_.GetFieldOffset(f);
146 }
147
GetRepeatedEnum(const Reflection * reflection,const FieldDescriptor * field,Message * msg)148 static void* GetRepeatedEnum(const Reflection* reflection,
149 const FieldDescriptor* field, Message* msg) {
150 return reflection->MutableRawRepeatedField(
151 msg, field, FieldDescriptor::CPPTYPE_ENUM, 0, nullptr);
152 }
153
MutableInternalMetadataWithArena(const Reflection * reflection,Message * msg)154 static InternalMetadataWithArena* MutableInternalMetadataWithArena(
155 const Reflection* reflection, Message* msg) {
156 return reflection->MutableInternalMetadataWithArena(msg);
157 }
158 };
159
160 } // namespace internal
161
SetField(uint64 val,const FieldDescriptor * field,Message * msg,const Reflection * reflection)162 void SetField(uint64 val, const FieldDescriptor* field, Message* msg,
163 const Reflection* reflection) {
164 #define STORE_TYPE(CPPTYPE_METHOD) \
165 do \
166 if (field->is_repeated()) { \
167 reflection->Add##CPPTYPE_METHOD(msg, field, value); \
168 } else { \
169 reflection->Set##CPPTYPE_METHOD(msg, field, value); \
170 } \
171 while (0)
172
173 switch (field->type()) {
174 #define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \
175 case FieldDescriptor::TYPE_##TYPE: { \
176 CPPTYPE value = val; \
177 STORE_TYPE(CPPTYPE_METHOD); \
178 break; \
179 }
180
181 // Varints
182 HANDLE_TYPE(INT32, int32, Int32)
183 HANDLE_TYPE(INT64, int64, Int64)
184 HANDLE_TYPE(UINT32, uint32, UInt32)
185 HANDLE_TYPE(UINT64, uint64, UInt64)
186 case FieldDescriptor::TYPE_SINT32: {
187 int32 value = WireFormatLite::ZigZagDecode32(val);
188 STORE_TYPE(Int32);
189 break;
190 }
191 case FieldDescriptor::TYPE_SINT64: {
192 int64 value = WireFormatLite::ZigZagDecode64(val);
193 STORE_TYPE(Int64);
194 break;
195 }
196 HANDLE_TYPE(BOOL, bool, Bool)
197
198 // Fixed
199 HANDLE_TYPE(FIXED32, uint32, UInt32)
200 HANDLE_TYPE(FIXED64, uint64, UInt64)
201 HANDLE_TYPE(SFIXED32, int32, Int32)
202 HANDLE_TYPE(SFIXED64, int64, Int64)
203
204 case FieldDescriptor::TYPE_FLOAT: {
205 float value;
206 uint32 bit_rep = val;
207 std::memcpy(&value, &bit_rep, sizeof(value));
208 STORE_TYPE(Float);
209 break;
210 }
211 case FieldDescriptor::TYPE_DOUBLE: {
212 double value;
213 uint64 bit_rep = val;
214 std::memcpy(&value, &bit_rep, sizeof(value));
215 STORE_TYPE(Double);
216 break;
217 }
218 case FieldDescriptor::TYPE_ENUM: {
219 int value = val;
220 if (field->is_repeated()) {
221 reflection->AddEnumValue(msg, field, value);
222 } else {
223 reflection->SetEnumValue(msg, field, value);
224 }
225 break;
226 }
227 default:
228 GOOGLE_LOG(FATAL) << "Error in descriptors, primitve field with field type "
229 << field->type();
230 }
231 #undef STORE_TYPE
232 #undef HANDLE_TYPE
233 }
234
ReflectiveValidator(const void * arg,int val)235 bool ReflectiveValidator(const void* arg, int val) {
236 auto d = static_cast<const EnumDescriptor*>(arg);
237 return d->FindValueByNumber(val) != nullptr;
238 }
239
ParsePackedField(const FieldDescriptor * field,Message * msg,const Reflection * reflection,const char * ptr,internal::ParseContext * ctx)240 const char* ParsePackedField(const FieldDescriptor* field, Message* msg,
241 const Reflection* reflection, const char* ptr,
242 internal::ParseContext* ctx) {
243 switch (field->type()) {
244 #define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, METHOD_NAME) \
245 case FieldDescriptor::TYPE_##TYPE: \
246 return internal::Packed##METHOD_NAME##Parser( \
247 reflection->MutableRepeatedFieldInternal<CPPTYPE>(msg, field), ptr, \
248 ctx)
249 HANDLE_PACKED_TYPE(INT32, int32, Int32);
250 HANDLE_PACKED_TYPE(INT64, int64, Int64);
251 HANDLE_PACKED_TYPE(SINT32, int32, SInt32);
252 HANDLE_PACKED_TYPE(SINT64, int64, SInt64);
253 HANDLE_PACKED_TYPE(UINT32, uint32, UInt32);
254 HANDLE_PACKED_TYPE(UINT64, uint64, UInt64);
255 HANDLE_PACKED_TYPE(BOOL, bool, Bool);
256 case FieldDescriptor::TYPE_ENUM: {
257 auto object =
258 internal::ReflectionAccessor::GetRepeatedEnum(reflection, field, msg);
259 if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
260 return internal::PackedEnumParser(object, ptr, ctx);
261 } else {
262 return internal::PackedEnumParserArg(
263 object, ptr, ctx, ReflectiveValidator, field->enum_type(),
264 internal::ReflectionAccessor::MutableInternalMetadataWithArena(
265 reflection, msg),
266 field->number());
267 }
268 }
269 HANDLE_PACKED_TYPE(FIXED32, uint32, Fixed32);
270 HANDLE_PACKED_TYPE(FIXED64, uint64, Fixed64);
271 HANDLE_PACKED_TYPE(SFIXED32, int32, SFixed32);
272 HANDLE_PACKED_TYPE(SFIXED64, int64, SFixed64);
273 HANDLE_PACKED_TYPE(FLOAT, float, Float);
274 HANDLE_PACKED_TYPE(DOUBLE, double, Double);
275 #undef HANDLE_PACKED_TYPE
276
277 default:
278 GOOGLE_LOG(FATAL) << "Type is not packable " << field->type();
279 return nullptr; // Make compiler happy
280 }
281 }
282
ParseLenDelim(int field_number,const FieldDescriptor * field,Message * msg,const Reflection * reflection,const char * ptr,internal::ParseContext * ctx)283 const char* ParseLenDelim(int field_number, const FieldDescriptor* field,
284 Message* msg, const Reflection* reflection,
285 const char* ptr, internal::ParseContext* ctx) {
286 if (WireFormat::WireTypeForFieldType(field->type()) !=
287 WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
288 GOOGLE_DCHECK(field->is_packable());
289 return ParsePackedField(field, msg, reflection, ptr, ctx);
290 }
291 enum { kNone = 0, kVerify, kStrict } utf8_level = kNone;
292 const char* field_name = nullptr;
293 auto parse_string = [ptr, ctx, &utf8_level,
294 &field_name](std::string* s) -> const char* {
295 auto res = internal::InlineGreedyStringParser(s, ptr, ctx);
296 if (utf8_level != kNone) {
297 if (!internal::VerifyUTF8(s, field_name) && utf8_level == kStrict) {
298 return nullptr;
299 }
300 }
301 return res;
302 };
303 switch (field->type()) {
304 case FieldDescriptor::TYPE_STRING: {
305 bool enforce_utf8 = true;
306 bool utf8_verification = true;
307 if (enforce_utf8 &&
308 field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
309 utf8_level = kStrict;
310 } else if (utf8_verification) {
311 utf8_level = kVerify;
312 }
313 field_name = field->full_name().c_str();
314 PROTOBUF_FALLTHROUGH_INTENDED;
315 }
316 case FieldDescriptor::TYPE_BYTES: {
317 if (field->is_repeated()) {
318 int index = reflection->FieldSize(*msg, field);
319 // Add new empty value.
320 reflection->AddString(msg, field, "");
321 if (field->options().ctype() == FieldOptions::STRING ||
322 field->is_extension()) {
323 auto object =
324 reflection
325 ->MutableRepeatedPtrFieldInternal<std::string>(msg, field)
326 ->Mutable(index);
327 return parse_string(object);
328 } else {
329 auto object =
330 reflection
331 ->MutableRepeatedPtrFieldInternal<std::string>(msg, field)
332 ->Mutable(index);
333 return parse_string(object);
334 }
335 } else {
336 // Clear value and make sure it's set.
337 reflection->SetString(msg, field, "");
338 if (field->options().ctype() == FieldOptions::STRING ||
339 field->is_extension()) {
340 // HACK around inability to get mutable_string in reflection
341 std::string* object = &const_cast<std::string&>(
342 reflection->GetStringReference(*msg, field, nullptr));
343 return parse_string(object);
344 } else {
345 // HACK around inability to get mutable_string in reflection
346 std::string* object = &const_cast<std::string&>(
347 reflection->GetStringReference(*msg, field, nullptr));
348 return parse_string(object);
349 }
350 }
351 GOOGLE_LOG(FATAL) << "No other type than string supported";
352 }
353 case FieldDescriptor::TYPE_MESSAGE: {
354 Message* object;
355 if (field->is_repeated()) {
356 object = reflection->AddMessage(msg, field, ctx->data().factory);
357 } else {
358 object = reflection->MutableMessage(msg, field, ctx->data().factory);
359 }
360 return ctx->ParseMessage(object, ptr);
361 }
362 default:
363 GOOGLE_LOG(FATAL) << "Wrong type for length delim " << field->type();
364 }
365 return nullptr; // Make compiler happy.
366 }
367
GetGroup(int field_number,const FieldDescriptor * field,Message * msg,const Reflection * reflection)368 Message* GetGroup(int field_number, const FieldDescriptor* field, Message* msg,
369 const Reflection* reflection) {
370 if (field->is_repeated()) {
371 return reflection->AddMessage(msg, field, nullptr);
372 } else {
373 return reflection->MutableMessage(msg, field, nullptr);
374 }
375 }
376
_InternalParse(const char * ptr,internal::ParseContext * ctx)377 const char* Message::_InternalParse(const char* ptr,
378 internal::ParseContext* ctx) {
379 class ReflectiveFieldParser {
380 public:
381 ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx)
382 : ReflectiveFieldParser(msg, ctx, false) {}
383
384 void AddVarint(uint32 num, uint64 value) {
385 if (is_item_ && num == 2) {
386 if (!payload_.empty()) {
387 auto field = Field(value, 2);
388 if (field && field->message_type()) {
389 auto child = reflection_->MutableMessage(msg_, field);
390 // TODO(gerbens) signal error
391 child->ParsePartialFromString(payload_);
392 } else {
393 MutableUnknown()->AddLengthDelimited(value)->swap(payload_);
394 }
395 return;
396 }
397 type_id_ = value;
398 return;
399 }
400 auto field = Field(num, 0);
401 if (field) {
402 SetField(value, field, msg_, reflection_);
403 } else {
404 MutableUnknown()->AddVarint(num, value);
405 }
406 }
407 void AddFixed64(uint32 num, uint64 value) {
408 auto field = Field(num, 1);
409 if (field) {
410 SetField(value, field, msg_, reflection_);
411 } else {
412 MutableUnknown()->AddFixed64(num, value);
413 }
414 }
415 const char* ParseLengthDelimited(uint32 num, const char* ptr,
416 internal::ParseContext* ctx) {
417 if (is_item_ && num == 3) {
418 if (type_id_ == 0) {
419 return InlineGreedyStringParser(&payload_, ptr, ctx);
420 }
421 num = type_id_;
422 type_id_ = 0;
423 }
424 auto field = Field(num, 2);
425 if (field) {
426 return ParseLenDelim(num, field, msg_, reflection_, ptr, ctx);
427 } else {
428 return InlineGreedyStringParser(
429 MutableUnknown()->AddLengthDelimited(num), ptr, ctx);
430 }
431 }
432 const char* ParseGroup(uint32 num, const char* ptr,
433 internal::ParseContext* ctx) {
434 if (!is_item_ && descriptor_->options().message_set_wire_format() &&
435 num == 1) {
436 is_item_ = true;
437 ptr = ctx->ParseGroup(this, ptr, num * 8 + 3);
438 is_item_ = false;
439 type_id_ = 0;
440 return ptr;
441 }
442 auto field = Field(num, 3);
443 if (field) {
444 auto msg = GetGroup(num, field, msg_, reflection_);
445 return ctx->ParseGroup(msg, ptr, num * 8 + 3);
446 } else {
447 return UnknownFieldParse(num * 8 + 3, MutableUnknown(), ptr, ctx);
448 }
449 }
450 void AddFixed32(uint32 num, uint32 value) {
451 auto field = Field(num, 5);
452 if (field) {
453 SetField(value, field, msg_, reflection_);
454 } else {
455 MutableUnknown()->AddFixed32(num, value);
456 }
457 }
458
459 const char* _InternalParse(const char* ptr, internal::ParseContext* ctx) {
460 // We're parsing the a MessageSetItem
461 GOOGLE_DCHECK(is_item_);
462 return internal::WireFormatParser(*this, ptr, ctx);
463 }
464
465 private:
466 Message* msg_;
467 const Descriptor* descriptor_;
468 const Reflection* reflection_;
469 internal::ParseContext* ctx_;
470 UnknownFieldSet* unknown_ = nullptr;
471 bool is_item_ = false;
472 uint32 type_id_ = 0;
473 std::string payload_;
474
475 ReflectiveFieldParser(Message* msg, internal::ParseContext* ctx,
476 bool is_item)
477 : msg_(msg),
478 descriptor_(msg->GetDescriptor()),
479 reflection_(msg->GetReflection()),
480 ctx_(ctx),
481 is_item_(is_item) {
482 GOOGLE_CHECK(descriptor_) << msg->GetTypeName();
483 GOOGLE_CHECK(reflection_) << msg->GetTypeName();
484 }
485
486 const FieldDescriptor* Field(int num, int wire_type) {
487 auto field = descriptor_->FindFieldByNumber(num);
488
489 // If that failed, check if the field is an extension.
490 if (field == nullptr && descriptor_->IsExtensionNumber(num)) {
491 const DescriptorPool* pool = ctx_->data().pool;
492 if (pool == nullptr) {
493 field = reflection_->FindKnownExtensionByNumber(num);
494 } else {
495 field = pool->FindExtensionByNumber(descriptor_, num);
496 }
497 }
498 if (field == nullptr) return nullptr;
499
500 if (internal::WireFormat::WireTypeForFieldType(field->type()) !=
501 wire_type) {
502 if (field->is_packable()) {
503 if (wire_type ==
504 internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
505 return field;
506 }
507 }
508 return nullptr;
509 }
510 return field;
511 }
512
513 UnknownFieldSet* MutableUnknown() {
514 if (unknown_) return unknown_;
515 return unknown_ = reflection_->MutableUnknownFields(msg_);
516 }
517 };
518
519 ReflectiveFieldParser field_parser(this, ctx);
520 return internal::WireFormatParser(field_parser, ptr, ctx);
521 }
522
_InternalSerialize(uint8 * target,io::EpsCopyOutputStream * stream) const523 uint8* Message::_InternalSerialize(uint8* target,
524 io::EpsCopyOutputStream* stream) const {
525 return WireFormat::_InternalSerialize(*this, target, stream);
526 }
527
ByteSizeLong() const528 size_t Message::ByteSizeLong() const {
529 size_t size = WireFormat::ByteSize(*this);
530 SetCachedSize(internal::ToCachedSize(size));
531 return size;
532 }
533
SetCachedSize(int) const534 void Message::SetCachedSize(int /* size */) const {
535 GOOGLE_LOG(FATAL) << "Message class \"" << GetDescriptor()->full_name()
536 << "\" implements neither SetCachedSize() nor ByteSize(). "
537 "Must implement one or the other.";
538 }
539
SpaceUsedLong() const540 size_t Message::SpaceUsedLong() const {
541 return GetReflection()->SpaceUsedLong(*this);
542 }
543
544 // =============================================================================
545 // MessageFactory
546
~MessageFactory()547 MessageFactory::~MessageFactory() {}
548
549 namespace {
550
551 class GeneratedMessageFactory : public MessageFactory {
552 public:
553 static GeneratedMessageFactory* singleton();
554
555 void RegisterFile(const google::protobuf::internal::DescriptorTable* table);
556 void RegisterType(const Descriptor* descriptor, const Message* prototype);
557
558 // implements MessageFactory ---------------------------------------
559 const Message* GetPrototype(const Descriptor* type) override;
560
561 private:
562 // Only written at static init time, so does not require locking.
563 std::unordered_map<const char*, const google::protobuf::internal::DescriptorTable*,
564 hash<const char*>, streq>
565 file_map_;
566
567 internal::WrappedMutex mutex_;
568 // Initialized lazily, so requires locking.
569 std::unordered_map<const Descriptor*, const Message*> type_map_;
570 };
571
singleton()572 GeneratedMessageFactory* GeneratedMessageFactory::singleton() {
573 static auto instance =
574 internal::OnShutdownDelete(new GeneratedMessageFactory);
575 return instance;
576 }
577
RegisterFile(const google::protobuf::internal::DescriptorTable * table)578 void GeneratedMessageFactory::RegisterFile(
579 const google::protobuf::internal::DescriptorTable* table) {
580 if (!InsertIfNotPresent(&file_map_, table->filename, table)) {
581 GOOGLE_LOG(FATAL) << "File is already registered: " << table->filename;
582 }
583 }
584
RegisterType(const Descriptor * descriptor,const Message * prototype)585 void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor,
586 const Message* prototype) {
587 GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool())
588 << "Tried to register a non-generated type with the generated "
589 "type registry.";
590
591 // This should only be called as a result of calling a file registration
592 // function during GetPrototype(), in which case we already have locked
593 // the mutex.
594 mutex_.AssertHeld();
595 if (!InsertIfNotPresent(&type_map_, descriptor, prototype)) {
596 GOOGLE_LOG(DFATAL) << "Type is already registered: " << descriptor->full_name();
597 }
598 }
599
600
GetPrototype(const Descriptor * type)601 const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) {
602 {
603 ReaderMutexLock lock(&mutex_);
604 const Message* result = FindPtrOrNull(type_map_, type);
605 if (result != NULL) return result;
606 }
607
608 // If the type is not in the generated pool, then we can't possibly handle
609 // it.
610 if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL;
611
612 // Apparently the file hasn't been registered yet. Let's do that now.
613 const internal::DescriptorTable* registration_data =
614 FindPtrOrNull(file_map_, type->file()->name().c_str());
615 if (registration_data == NULL) {
616 GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't "
617 "registered: "
618 << type->file()->name();
619 return NULL;
620 }
621
622 WriterMutexLock lock(&mutex_);
623
624 // Check if another thread preempted us.
625 const Message* result = FindPtrOrNull(type_map_, type);
626 if (result == NULL) {
627 // Nope. OK, register everything.
628 internal::RegisterFileLevelMetadata(registration_data);
629 // Should be here now.
630 result = FindPtrOrNull(type_map_, type);
631 }
632
633 if (result == NULL) {
634 GOOGLE_LOG(DFATAL) << "Type appears to be in generated pool but wasn't "
635 << "registered: " << type->full_name();
636 }
637
638 return result;
639 }
640
641 } // namespace
642
generated_factory()643 MessageFactory* MessageFactory::generated_factory() {
644 return GeneratedMessageFactory::singleton();
645 }
646
InternalRegisterGeneratedFile(const google::protobuf::internal::DescriptorTable * table)647 void MessageFactory::InternalRegisterGeneratedFile(
648 const google::protobuf::internal::DescriptorTable* table) {
649 GeneratedMessageFactory::singleton()->RegisterFile(table);
650 }
651
InternalRegisterGeneratedMessage(const Descriptor * descriptor,const Message * prototype)652 void MessageFactory::InternalRegisterGeneratedMessage(
653 const Descriptor* descriptor, const Message* prototype) {
654 GeneratedMessageFactory::singleton()->RegisterType(descriptor, prototype);
655 }
656
657
658 namespace {
659 template <typename T>
GetSingleton()660 T* GetSingleton() {
661 static T singleton;
662 return &singleton;
663 }
664 } // namespace
665
RepeatedFieldAccessor(const FieldDescriptor * field) const666 const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor(
667 const FieldDescriptor* field) const {
668 GOOGLE_CHECK(field->is_repeated());
669 switch (field->cpp_type()) {
670 #define HANDLE_PRIMITIVE_TYPE(TYPE, type) \
671 case FieldDescriptor::CPPTYPE_##TYPE: \
672 return GetSingleton<internal::RepeatedFieldPrimitiveAccessor<type> >();
673 HANDLE_PRIMITIVE_TYPE(INT32, int32)
674 HANDLE_PRIMITIVE_TYPE(UINT32, uint32)
675 HANDLE_PRIMITIVE_TYPE(INT64, int64)
676 HANDLE_PRIMITIVE_TYPE(UINT64, uint64)
677 HANDLE_PRIMITIVE_TYPE(FLOAT, float)
678 HANDLE_PRIMITIVE_TYPE(DOUBLE, double)
679 HANDLE_PRIMITIVE_TYPE(BOOL, bool)
680 HANDLE_PRIMITIVE_TYPE(ENUM, int32)
681 #undef HANDLE_PRIMITIVE_TYPE
682 case FieldDescriptor::CPPTYPE_STRING:
683 switch (field->options().ctype()) {
684 default:
685 case FieldOptions::STRING:
686 return GetSingleton<internal::RepeatedPtrFieldStringAccessor>();
687 }
688 break;
689 case FieldDescriptor::CPPTYPE_MESSAGE:
690 if (field->is_map()) {
691 return GetSingleton<internal::MapFieldAccessor>();
692 } else {
693 return GetSingleton<internal::RepeatedPtrFieldMessageAccessor>();
694 }
695 }
696 GOOGLE_LOG(FATAL) << "Should not reach here.";
697 return NULL;
698 }
699
700 namespace internal {
701 template <>
702 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
703 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
704 // #240
705 PROTOBUF_NOINLINE
706 #endif
707 Message*
NewFromPrototype(const Message * prototype,Arena * arena)708 GenericTypeHandler<Message>::NewFromPrototype(const Message* prototype,
709 Arena* arena) {
710 return prototype->New(arena);
711 }
712 template <>
713 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
714 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
715 // #240
716 PROTOBUF_NOINLINE
717 #endif
718 Arena*
GetArena(Message * value)719 GenericTypeHandler<Message>::GetArena(Message* value) {
720 return value->GetArena();
721 }
722 template <>
723 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
724 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
725 // #240
726 PROTOBUF_NOINLINE
727 #endif
728 void*
GetMaybeArenaPointer(Message * value)729 GenericTypeHandler<Message>::GetMaybeArenaPointer(Message* value) {
730 return value->GetMaybeArenaPointer();
731 }
732 } // namespace internal
733
734 } // namespace protobuf
735 } // namespace google
736