• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <google/protobuf/message.h>
36 
37 #include <iostream>
38 #include <stack>
39 #include <unordered_map>
40 
41 #include <google/protobuf/stubs/casts.h>
42 #include <google/protobuf/stubs/logging.h>
43 #include <google/protobuf/stubs/common.h>
44 #include <google/protobuf/descriptor.pb.h>
45 #include <google/protobuf/parse_context.h>
46 #include <google/protobuf/reflection_internal.h>
47 #include <google/protobuf/io/coded_stream.h>
48 #include <google/protobuf/io/zero_copy_stream_impl.h>
49 #include <google/protobuf/descriptor.h>
50 #include <google/protobuf/generated_message_reflection.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 
_InternalParse(const char * ptr,internal::ParseContext * ctx)139 const char* Message::_InternalParse(const char* ptr,
140                                     internal::ParseContext* ctx) {
141   return WireFormat::_InternalParse(this, ptr, ctx);
142 }
143 
_InternalSerialize(uint8 * target,io::EpsCopyOutputStream * stream) const144 uint8* Message::_InternalSerialize(uint8* target,
145                                    io::EpsCopyOutputStream* stream) const {
146   return WireFormat::_InternalSerialize(*this, target, stream);
147 }
148 
ByteSizeLong() const149 size_t Message::ByteSizeLong() const {
150   size_t size = WireFormat::ByteSize(*this);
151   SetCachedSize(internal::ToCachedSize(size));
152   return size;
153 }
154 
SetCachedSize(int) const155 void Message::SetCachedSize(int /* size */) const {
156   GOOGLE_LOG(FATAL) << "Message class \"" << GetDescriptor()->full_name()
157              << "\" implements neither SetCachedSize() nor ByteSize().  "
158                 "Must implement one or the other.";
159 }
160 
SpaceUsedLong() const161 size_t Message::SpaceUsedLong() const {
162   return GetReflection()->SpaceUsedLong(*this);
163 }
164 
165 // =============================================================================
166 // MessageFactory
167 
~MessageFactory()168 MessageFactory::~MessageFactory() {}
169 
170 namespace {
171 
172 
173 #define HASH_MAP std::unordered_map
174 #define STR_HASH_FXN hash<const char*>
175 
176 
177 class GeneratedMessageFactory : public MessageFactory {
178  public:
179   static GeneratedMessageFactory* singleton();
180 
181   void RegisterFile(const google::protobuf::internal::DescriptorTable* table);
182   void RegisterType(const Descriptor* descriptor, const Message* prototype);
183 
184   // implements MessageFactory ---------------------------------------
185   const Message* GetPrototype(const Descriptor* type) override;
186 
187  private:
188   // Only written at static init time, so does not require locking.
189   HASH_MAP<const char*, const google::protobuf::internal::DescriptorTable*, STR_HASH_FXN,
190            streq>
191       file_map_;
192 
193   internal::WrappedMutex mutex_;
194   // Initialized lazily, so requires locking.
195   std::unordered_map<const Descriptor*, const Message*> type_map_;
196 };
197 
singleton()198 GeneratedMessageFactory* GeneratedMessageFactory::singleton() {
199   static auto instance =
200       internal::OnShutdownDelete(new GeneratedMessageFactory);
201   return instance;
202 }
203 
RegisterFile(const google::protobuf::internal::DescriptorTable * table)204 void GeneratedMessageFactory::RegisterFile(
205     const google::protobuf::internal::DescriptorTable* table) {
206   if (!InsertIfNotPresent(&file_map_, table->filename, table)) {
207     GOOGLE_LOG(FATAL) << "File is already registered: " << table->filename;
208   }
209 }
210 
RegisterType(const Descriptor * descriptor,const Message * prototype)211 void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor,
212                                            const Message* prototype) {
213   GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool())
214       << "Tried to register a non-generated type with the generated "
215          "type registry.";
216 
217   // This should only be called as a result of calling a file registration
218   // function during GetPrototype(), in which case we already have locked
219   // the mutex.
220   mutex_.AssertHeld();
221   if (!InsertIfNotPresent(&type_map_, descriptor, prototype)) {
222     GOOGLE_LOG(DFATAL) << "Type is already registered: " << descriptor->full_name();
223   }
224 }
225 
226 
GetPrototype(const Descriptor * type)227 const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) {
228   {
229     ReaderMutexLock lock(&mutex_);
230     const Message* result = FindPtrOrNull(type_map_, type);
231     if (result != NULL) return result;
232   }
233 
234   // If the type is not in the generated pool, then we can't possibly handle
235   // it.
236   if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL;
237 
238   // Apparently the file hasn't been registered yet.  Let's do that now.
239   const internal::DescriptorTable* registration_data =
240       FindPtrOrNull(file_map_, type->file()->name().c_str());
241   if (registration_data == NULL) {
242     GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't "
243                    "registered: "
244                 << type->file()->name();
245     return NULL;
246   }
247 
248   WriterMutexLock lock(&mutex_);
249 
250   // Check if another thread preempted us.
251   const Message* result = FindPtrOrNull(type_map_, type);
252   if (result == NULL) {
253     // Nope.  OK, register everything.
254     internal::RegisterFileLevelMetadata(registration_data);
255     // Should be here now.
256     result = FindPtrOrNull(type_map_, type);
257   }
258 
259   if (result == NULL) {
260     GOOGLE_LOG(DFATAL) << "Type appears to be in generated pool but wasn't "
261                 << "registered: " << type->full_name();
262   }
263 
264   return result;
265 }
266 
267 }  // namespace
268 
generated_factory()269 MessageFactory* MessageFactory::generated_factory() {
270   return GeneratedMessageFactory::singleton();
271 }
272 
InternalRegisterGeneratedFile(const google::protobuf::internal::DescriptorTable * table)273 void MessageFactory::InternalRegisterGeneratedFile(
274     const google::protobuf::internal::DescriptorTable* table) {
275   GeneratedMessageFactory::singleton()->RegisterFile(table);
276 }
277 
InternalRegisterGeneratedMessage(const Descriptor * descriptor,const Message * prototype)278 void MessageFactory::InternalRegisterGeneratedMessage(
279     const Descriptor* descriptor, const Message* prototype) {
280   GeneratedMessageFactory::singleton()->RegisterType(descriptor, prototype);
281 }
282 
283 
284 namespace {
285 template <typename T>
GetSingleton()286 T* GetSingleton() {
287   static T singleton;
288   return &singleton;
289 }
290 }  // namespace
291 
RepeatedFieldAccessor(const FieldDescriptor * field) const292 const internal::RepeatedFieldAccessor* Reflection::RepeatedFieldAccessor(
293     const FieldDescriptor* field) const {
294   GOOGLE_CHECK(field->is_repeated());
295   switch (field->cpp_type()) {
296 #define HANDLE_PRIMITIVE_TYPE(TYPE, type) \
297   case FieldDescriptor::CPPTYPE_##TYPE:   \
298     return GetSingleton<internal::RepeatedFieldPrimitiveAccessor<type> >();
299     HANDLE_PRIMITIVE_TYPE(INT32, int32)
300     HANDLE_PRIMITIVE_TYPE(UINT32, uint32)
301     HANDLE_PRIMITIVE_TYPE(INT64, int64)
302     HANDLE_PRIMITIVE_TYPE(UINT64, uint64)
303     HANDLE_PRIMITIVE_TYPE(FLOAT, float)
304     HANDLE_PRIMITIVE_TYPE(DOUBLE, double)
305     HANDLE_PRIMITIVE_TYPE(BOOL, bool)
306     HANDLE_PRIMITIVE_TYPE(ENUM, int32)
307 #undef HANDLE_PRIMITIVE_TYPE
308     case FieldDescriptor::CPPTYPE_STRING:
309       switch (field->options().ctype()) {
310         default:
311         case FieldOptions::STRING:
312           return GetSingleton<internal::RepeatedPtrFieldStringAccessor>();
313       }
314       break;
315     case FieldDescriptor::CPPTYPE_MESSAGE:
316       if (field->is_map()) {
317         return GetSingleton<internal::MapFieldAccessor>();
318       } else {
319         return GetSingleton<internal::RepeatedPtrFieldMessageAccessor>();
320       }
321   }
322   GOOGLE_LOG(FATAL) << "Should not reach here.";
323   return NULL;
324 }
325 
326 namespace internal {
327 template <>
328 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
329 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
330 // #240
331 PROTOBUF_NOINLINE
332 #endif
333     Message*
NewFromPrototype(const Message * prototype,Arena * arena)334     GenericTypeHandler<Message>::NewFromPrototype(const Message* prototype,
335                                                   Arena* arena) {
336   return prototype->New(arena);
337 }
338 template <>
339 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
340 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
341 // #240
342 PROTOBUF_NOINLINE
343 #endif
344     Arena*
GetArena(Message * value)345     GenericTypeHandler<Message>::GetArena(Message* value) {
346   return value->GetArena();
347 }
348 template <>
349 #if defined(_MSC_VER) && (_MSC_VER >= 1800)
350 // Note: force noinline to workaround MSVC compiler bug with /Zc:inline, issue
351 // #240
352 PROTOBUF_NOINLINE
353 #endif
354     void*
GetMaybeArenaPointer(Message * value)355     GenericTypeHandler<Message>::GetMaybeArenaPointer(Message* value) {
356   return value->GetMaybeArenaPointer();
357 }
358 }  // namespace internal
359 
360 }  // namespace protobuf
361 }  // namespace google
362