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 // Authors: wink@google.com (Wink Saville),
32 // kenton@google.com (Kenton Varda)
33 // Based on original Protocol Buffers design by
34 // Sanjay Ghemawat, Jeff Dean, and others.
35
36 #include <google/protobuf/message_lite.h>
37
38 #include <climits>
39 #include <cstdint>
40 #include <string>
41
42 #include <google/protobuf/stubs/logging.h>
43 #include <google/protobuf/stubs/common.h>
44 #include <google/protobuf/stubs/stringprintf.h>
45 #include <google/protobuf/parse_context.h>
46 #include <google/protobuf/io/coded_stream.h>
47 #include <google/protobuf/io/zero_copy_stream.h>
48 #include <google/protobuf/io/zero_copy_stream_impl.h>
49 #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
50 #include <google/protobuf/arena.h>
51 #include <google/protobuf/generated_message_table_driven.h>
52 #include <google/protobuf/generated_message_util.h>
53 #include <google/protobuf/repeated_field.h>
54 #include <google/protobuf/stubs/strutil.h>
55 #include <google/protobuf/stubs/stl_util.h>
56 #include <google/protobuf/stubs/mutex.h>
57
58 #include <google/protobuf/port_def.inc>
59
60 namespace google {
61 namespace protobuf {
62
InitializationErrorString() const63 std::string MessageLite::InitializationErrorString() const {
64 return "(cannot determine missing fields for lite message)";
65 }
66
DebugString() const67 std::string MessageLite::DebugString() const {
68 std::uintptr_t address = reinterpret_cast<std::uintptr_t>(this);
69 return StrCat("MessageLite at 0x", strings::Hex(address));
70 }
71
72 namespace {
73
74 // When serializing, we first compute the byte size, then serialize the message.
75 // If serialization produces a different number of bytes than expected, we
76 // call this function, which crashes. The problem could be due to a bug in the
77 // protobuf implementation but is more likely caused by concurrent modification
78 // of the message. This function attempts to distinguish between the two and
79 // provide a useful error message.
ByteSizeConsistencyError(size_t byte_size_before_serialization,size_t byte_size_after_serialization,size_t bytes_produced_by_serialization,const MessageLite & message)80 void ByteSizeConsistencyError(size_t byte_size_before_serialization,
81 size_t byte_size_after_serialization,
82 size_t bytes_produced_by_serialization,
83 const MessageLite& message) {
84 GOOGLE_CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization)
85 << message.GetTypeName()
86 << " was modified concurrently during serialization.";
87 GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization)
88 << "Byte size calculation and serialization were inconsistent. This "
89 "may indicate a bug in protocol buffers or it may be caused by "
90 "concurrent modification of "
91 << message.GetTypeName() << ".";
92 GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal.";
93 }
94
InitializationErrorMessage(const char * action,const MessageLite & message)95 std::string InitializationErrorMessage(const char* action,
96 const MessageLite& message) {
97 // Note: We want to avoid depending on strutil in the lite library, otherwise
98 // we'd use:
99 //
100 // return strings::Substitute(
101 // "Can't $0 message of type \"$1\" because it is missing required "
102 // "fields: $2",
103 // action, message.GetTypeName(),
104 // message.InitializationErrorString());
105
106 std::string result;
107 result += "Can't ";
108 result += action;
109 result += " message of type \"";
110 result += message.GetTypeName();
111 result += "\" because it is missing required fields: ";
112 result += message.InitializationErrorString();
113 return result;
114 }
115
as_string_view(const void * data,int size)116 inline StringPiece as_string_view(const void* data, int size) {
117 return StringPiece(static_cast<const char*>(data), size);
118 }
119
120 // Returns true of all required fields are present / have values.
CheckFieldPresence(const internal::ParseContext & ctx,const MessageLite & msg,MessageLite::ParseFlags parse_flags)121 inline bool CheckFieldPresence(const internal::ParseContext& ctx,
122 const MessageLite& msg,
123 MessageLite::ParseFlags parse_flags) {
124 if (PROTOBUF_PREDICT_FALSE((parse_flags & MessageLite::kMergePartial) != 0)) {
125 return true;
126 }
127 return msg.IsInitializedWithErrors();
128 }
129
130 } // namespace
131
LogInitializationErrorMessage() const132 void MessageLite::LogInitializationErrorMessage() const {
133 GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *this);
134 }
135
136 namespace internal {
137
138 template <bool aliasing>
MergeFromImpl(StringPiece input,MessageLite * msg,MessageLite::ParseFlags parse_flags)139 bool MergeFromImpl(StringPiece input, MessageLite* msg,
140 MessageLite::ParseFlags parse_flags) {
141 const char* ptr;
142 internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
143 aliasing, &ptr, input);
144 ptr = msg->_InternalParse(ptr, &ctx);
145 // ctx has an explicit limit set (length of string_view).
146 if (PROTOBUF_PREDICT_TRUE(ptr && ctx.EndedAtLimit())) {
147 return CheckFieldPresence(ctx, *msg, parse_flags);
148 }
149 return false;
150 }
151
152 template <bool aliasing>
MergeFromImpl(io::ZeroCopyInputStream * input,MessageLite * msg,MessageLite::ParseFlags parse_flags)153 bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
154 MessageLite::ParseFlags parse_flags) {
155 const char* ptr;
156 internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
157 aliasing, &ptr, input);
158 ptr = msg->_InternalParse(ptr, &ctx);
159 // ctx has no explicit limit (hence we end on end of stream)
160 if (PROTOBUF_PREDICT_TRUE(ptr && ctx.EndedAtEndOfStream())) {
161 return CheckFieldPresence(ctx, *msg, parse_flags);
162 }
163 return false;
164 }
165
166 template <bool aliasing>
MergeFromImpl(BoundedZCIS input,MessageLite * msg,MessageLite::ParseFlags parse_flags)167 bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
168 MessageLite::ParseFlags parse_flags) {
169 const char* ptr;
170 internal::ParseContext ctx(io::CodedInputStream::GetDefaultRecursionLimit(),
171 aliasing, &ptr, input.zcis, input.limit);
172 ptr = msg->_InternalParse(ptr, &ctx);
173 if (PROTOBUF_PREDICT_FALSE(!ptr)) return false;
174 ctx.BackUp(ptr);
175 if (PROTOBUF_PREDICT_TRUE(ctx.EndedAtLimit())) {
176 return CheckFieldPresence(ctx, *msg, parse_flags);
177 }
178 return false;
179 }
180
181 template bool MergeFromImpl<false>(StringPiece input, MessageLite* msg,
182 MessageLite::ParseFlags parse_flags);
183 template bool MergeFromImpl<true>(StringPiece input, MessageLite* msg,
184 MessageLite::ParseFlags parse_flags);
185 template bool MergeFromImpl<false>(io::ZeroCopyInputStream* input,
186 MessageLite* msg,
187 MessageLite::ParseFlags parse_flags);
188 template bool MergeFromImpl<true>(io::ZeroCopyInputStream* input,
189 MessageLite* msg,
190 MessageLite::ParseFlags parse_flags);
191 template bool MergeFromImpl<false>(BoundedZCIS input, MessageLite* msg,
192 MessageLite::ParseFlags parse_flags);
193 template bool MergeFromImpl<true>(BoundedZCIS input, MessageLite* msg,
194 MessageLite::ParseFlags parse_flags);
195
196 } // namespace internal
197
New(Arena * arena) const198 MessageLite* MessageLite::New(Arena* arena) const {
199 MessageLite* message = New();
200 if (arena != NULL) {
201 arena->Own(message);
202 }
203 return message;
204 }
205
206 class ZeroCopyCodedInputStream : public io::ZeroCopyInputStream {
207 public:
ZeroCopyCodedInputStream(io::CodedInputStream * cis)208 ZeroCopyCodedInputStream(io::CodedInputStream* cis) : cis_(cis) {}
Next(const void ** data,int * size)209 bool Next(const void** data, int* size) final {
210 if (!cis_->GetDirectBufferPointer(data, size)) return false;
211 cis_->Skip(*size);
212 return true;
213 }
BackUp(int count)214 void BackUp(int count) final { cis_->Advance(-count); }
Skip(int count)215 bool Skip(int count) final { return cis_->Skip(count); }
ByteCount() const216 int64_t ByteCount() const final { return 0; }
217
aliasing_enabled()218 bool aliasing_enabled() { return cis_->aliasing_enabled_; }
219
220 private:
221 io::CodedInputStream* cis_;
222 };
223
MergeFromImpl(io::CodedInputStream * input,MessageLite::ParseFlags parse_flags)224 bool MessageLite::MergeFromImpl(io::CodedInputStream* input,
225 MessageLite::ParseFlags parse_flags) {
226 ZeroCopyCodedInputStream zcis(input);
227 const char* ptr;
228 internal::ParseContext ctx(input->RecursionBudget(), zcis.aliasing_enabled(),
229 &ptr, &zcis);
230 // MergePartialFromCodedStream allows terminating the wireformat by 0 or
231 // end-group tag. Leaving it up to the caller to verify correct ending by
232 // calling LastTagWas on input. We need to maintain this behavior.
233 ctx.TrackCorrectEnding();
234 ctx.data().pool = input->GetExtensionPool();
235 ctx.data().factory = input->GetExtensionFactory();
236 ptr = _InternalParse(ptr, &ctx);
237 if (PROTOBUF_PREDICT_FALSE(!ptr)) return false;
238 ctx.BackUp(ptr);
239 if (!ctx.EndedAtEndOfStream()) {
240 GOOGLE_DCHECK(ctx.LastTag() != 1); // We can't end on a pushed limit.
241 if (ctx.IsExceedingLimit(ptr)) return false;
242 input->SetLastTag(ctx.LastTag());
243 } else {
244 input->SetConsumed();
245 }
246 return CheckFieldPresence(ctx, *this, parse_flags);
247 }
248
MergePartialFromCodedStream(io::CodedInputStream * input)249 bool MessageLite::MergePartialFromCodedStream(io::CodedInputStream* input) {
250 return MergeFromImpl(input, kMergePartial);
251 }
252
MergeFromCodedStream(io::CodedInputStream * input)253 bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) {
254 return MergeFromImpl(input, kMerge);
255 }
256
ParseFromCodedStream(io::CodedInputStream * input)257 bool MessageLite::ParseFromCodedStream(io::CodedInputStream* input) {
258 Clear();
259 return MergeFromImpl(input, kParse);
260 }
261
ParsePartialFromCodedStream(io::CodedInputStream * input)262 bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) {
263 Clear();
264 return MergeFromImpl(input, kParsePartial);
265 }
266
ParseFromZeroCopyStream(io::ZeroCopyInputStream * input)267 bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) {
268 return ParseFrom<kParse>(input);
269 }
270
ParsePartialFromZeroCopyStream(io::ZeroCopyInputStream * input)271 bool MessageLite::ParsePartialFromZeroCopyStream(
272 io::ZeroCopyInputStream* input) {
273 return ParseFrom<kParsePartial>(input);
274 }
275
ParseFromFileDescriptor(int file_descriptor)276 bool MessageLite::ParseFromFileDescriptor(int file_descriptor) {
277 io::FileInputStream input(file_descriptor);
278 return ParseFromZeroCopyStream(&input) && input.GetErrno() == 0;
279 }
280
ParsePartialFromFileDescriptor(int file_descriptor)281 bool MessageLite::ParsePartialFromFileDescriptor(int file_descriptor) {
282 io::FileInputStream input(file_descriptor);
283 return ParsePartialFromZeroCopyStream(&input) && input.GetErrno() == 0;
284 }
285
ParseFromIstream(std::istream * input)286 bool MessageLite::ParseFromIstream(std::istream* input) {
287 io::IstreamInputStream zero_copy_input(input);
288 return ParseFromZeroCopyStream(&zero_copy_input) && input->eof();
289 }
290
ParsePartialFromIstream(std::istream * input)291 bool MessageLite::ParsePartialFromIstream(std::istream* input) {
292 io::IstreamInputStream zero_copy_input(input);
293 return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof();
294 }
295
MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input,int size)296 bool MessageLite::MergePartialFromBoundedZeroCopyStream(
297 io::ZeroCopyInputStream* input, int size) {
298 return ParseFrom<kMergePartial>(internal::BoundedZCIS{input, size});
299 }
300
MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input,int size)301 bool MessageLite::MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
302 int size) {
303 return ParseFrom<kMerge>(internal::BoundedZCIS{input, size});
304 }
305
ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input,int size)306 bool MessageLite::ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
307 int size) {
308 return ParseFrom<kParse>(internal::BoundedZCIS{input, size});
309 }
310
ParsePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input,int size)311 bool MessageLite::ParsePartialFromBoundedZeroCopyStream(
312 io::ZeroCopyInputStream* input, int size) {
313 return ParseFrom<kParsePartial>(internal::BoundedZCIS{input, size});
314 }
315
ParseFromString(const std::string & data)316 bool MessageLite::ParseFromString(const std::string& data) {
317 return ParseFrom<kParse>(data);
318 }
319
ParsePartialFromString(const std::string & data)320 bool MessageLite::ParsePartialFromString(const std::string& data) {
321 return ParseFrom<kParsePartial>(data);
322 }
323
ParseFromArray(const void * data,int size)324 bool MessageLite::ParseFromArray(const void* data, int size) {
325 return ParseFrom<kParse>(as_string_view(data, size));
326 }
327
ParsePartialFromArray(const void * data,int size)328 bool MessageLite::ParsePartialFromArray(const void* data, int size) {
329 return ParseFrom<kParsePartial>(as_string_view(data, size));
330 }
331
MergeFromString(const std::string & data)332 bool MessageLite::MergeFromString(const std::string& data) {
333 return ParseFrom<kMerge>(data);
334 }
335
336
337 // ===================================================================
338
SerializeToArrayImpl(const MessageLite & msg,uint8 * target,int size)339 inline uint8* SerializeToArrayImpl(const MessageLite& msg, uint8* target,
340 int size) {
341 constexpr bool debug = false;
342 if (debug) {
343 // Force serialization to a stream with a block size of 1, which forces
344 // all writes to the stream to cross buffers triggering all fallback paths
345 // in the unittests when serializing to string / array.
346 io::ArrayOutputStream stream(target, size, 1);
347 uint8* ptr;
348 io::EpsCopyOutputStream out(
349 &stream, io::CodedOutputStream::IsDefaultSerializationDeterministic(),
350 &ptr);
351 ptr = msg._InternalSerialize(ptr, &out);
352 out.Trim(ptr);
353 GOOGLE_DCHECK(!out.HadError() && stream.ByteCount() == size);
354 return target + size;
355 } else {
356 io::EpsCopyOutputStream out(
357 target, size,
358 io::CodedOutputStream::IsDefaultSerializationDeterministic());
359 auto res = msg._InternalSerialize(target, &out);
360 GOOGLE_DCHECK(target + size == res);
361 return res;
362 }
363 }
364
SerializeWithCachedSizesToArray(uint8 * target) const365 uint8* MessageLite::SerializeWithCachedSizesToArray(uint8* target) const {
366 // We only optimize this when using optimize_for = SPEED. In other cases
367 // we just use the CodedOutputStream path.
368 return SerializeToArrayImpl(*this, target, GetCachedSize());
369 }
370
SerializeToCodedStream(io::CodedOutputStream * output) const371 bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const {
372 GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
373 return SerializePartialToCodedStream(output);
374 }
375
SerializePartialToCodedStream(io::CodedOutputStream * output) const376 bool MessageLite::SerializePartialToCodedStream(
377 io::CodedOutputStream* output) const {
378 const size_t size = ByteSizeLong(); // Force size to be cached.
379 if (size > INT_MAX) {
380 GOOGLE_LOG(ERROR) << GetTypeName()
381 << " exceeded maximum protobuf size of 2GB: " << size;
382 return false;
383 }
384
385 int original_byte_count = output->ByteCount();
386 SerializeWithCachedSizes(output);
387 if (output->HadError()) {
388 return false;
389 }
390 int final_byte_count = output->ByteCount();
391
392 if (final_byte_count - original_byte_count != size) {
393 ByteSizeConsistencyError(size, ByteSizeLong(),
394 final_byte_count - original_byte_count, *this);
395 }
396
397 return true;
398 }
399
SerializeToZeroCopyStream(io::ZeroCopyOutputStream * output) const400 bool MessageLite::SerializeToZeroCopyStream(
401 io::ZeroCopyOutputStream* output) const {
402 GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
403 return SerializePartialToZeroCopyStream(output);
404 }
405
SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream * output) const406 bool MessageLite::SerializePartialToZeroCopyStream(
407 io::ZeroCopyOutputStream* output) const {
408 const size_t size = ByteSizeLong(); // Force size to be cached.
409 if (size > INT_MAX) {
410 GOOGLE_LOG(ERROR) << GetTypeName()
411 << " exceeded maximum protobuf size of 2GB: " << size;
412 return false;
413 }
414
415 uint8* target;
416 io::EpsCopyOutputStream stream(
417 output, io::CodedOutputStream::IsDefaultSerializationDeterministic(),
418 &target);
419 target = _InternalSerialize(target, &stream);
420 stream.Trim(target);
421 if (stream.HadError()) return false;
422 return true;
423 }
424
SerializeToFileDescriptor(int file_descriptor) const425 bool MessageLite::SerializeToFileDescriptor(int file_descriptor) const {
426 io::FileOutputStream output(file_descriptor);
427 return SerializeToZeroCopyStream(&output) && output.Flush();
428 }
429
SerializePartialToFileDescriptor(int file_descriptor) const430 bool MessageLite::SerializePartialToFileDescriptor(int file_descriptor) const {
431 io::FileOutputStream output(file_descriptor);
432 return SerializePartialToZeroCopyStream(&output) && output.Flush();
433 }
434
SerializeToOstream(std::ostream * output) const435 bool MessageLite::SerializeToOstream(std::ostream* output) const {
436 {
437 io::OstreamOutputStream zero_copy_output(output);
438 if (!SerializeToZeroCopyStream(&zero_copy_output)) return false;
439 }
440 return output->good();
441 }
442
SerializePartialToOstream(std::ostream * output) const443 bool MessageLite::SerializePartialToOstream(std::ostream* output) const {
444 io::OstreamOutputStream zero_copy_output(output);
445 return SerializePartialToZeroCopyStream(&zero_copy_output);
446 }
447
AppendToString(std::string * output) const448 bool MessageLite::AppendToString(std::string* output) const {
449 GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
450 return AppendPartialToString(output);
451 }
452
AppendPartialToString(std::string * output) const453 bool MessageLite::AppendPartialToString(std::string* output) const {
454 size_t old_size = output->size();
455 size_t byte_size = ByteSizeLong();
456 if (byte_size > INT_MAX) {
457 GOOGLE_LOG(ERROR) << GetTypeName()
458 << " exceeded maximum protobuf size of 2GB: " << byte_size;
459 return false;
460 }
461
462 STLStringResizeUninitialized(output, old_size + byte_size);
463 uint8* start =
464 reinterpret_cast<uint8*>(io::mutable_string_data(output) + old_size);
465 SerializeToArrayImpl(*this, start, byte_size);
466 return true;
467 }
468
SerializeToString(std::string * output) const469 bool MessageLite::SerializeToString(std::string* output) const {
470 output->clear();
471 return AppendToString(output);
472 }
473
SerializePartialToString(std::string * output) const474 bool MessageLite::SerializePartialToString(std::string* output) const {
475 output->clear();
476 return AppendPartialToString(output);
477 }
478
SerializeToArray(void * data,int size) const479 bool MessageLite::SerializeToArray(void* data, int size) const {
480 GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
481 return SerializePartialToArray(data, size);
482 }
483
SerializePartialToArray(void * data,int size) const484 bool MessageLite::SerializePartialToArray(void* data, int size) const {
485 const size_t byte_size = ByteSizeLong();
486 if (byte_size > INT_MAX) {
487 GOOGLE_LOG(ERROR) << GetTypeName()
488 << " exceeded maximum protobuf size of 2GB: " << byte_size;
489 return false;
490 }
491 if (size < byte_size) return false;
492 uint8* start = reinterpret_cast<uint8*>(data);
493 SerializeToArrayImpl(*this, start, byte_size);
494 return true;
495 }
496
SerializeAsString() const497 std::string MessageLite::SerializeAsString() const {
498 // If the compiler implements the (Named) Return Value Optimization,
499 // the local variable 'output' will not actually reside on the stack
500 // of this function, but will be overlaid with the object that the
501 // caller supplied for the return value to be constructed in.
502 std::string output;
503 if (!AppendToString(&output)) output.clear();
504 return output;
505 }
506
SerializePartialAsString() const507 std::string MessageLite::SerializePartialAsString() const {
508 std::string output;
509 if (!AppendPartialToString(&output)) output.clear();
510 return output;
511 }
512
513
514 namespace internal {
515
516 template <>
NewFromPrototype(const MessageLite * prototype,Arena * arena)517 MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
518 const MessageLite* prototype, Arena* arena) {
519 return prototype->New(arena);
520 }
521 template <>
Merge(const MessageLite & from,MessageLite * to)522 void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
523 MessageLite* to) {
524 to->CheckTypeAndMergeFrom(from);
525 }
526 template <>
Merge(const std::string & from,std::string * to)527 void GenericTypeHandler<std::string>::Merge(const std::string& from,
528 std::string* to) {
529 *to = from;
530 }
531
532 } // namespace internal
533
534
535 // ===================================================================
536 // Shutdown support.
537
538 namespace internal {
539
540 struct ShutdownData {
~ShutdownDatagoogle::protobuf::internal::ShutdownData541 ~ShutdownData() {
542 std::reverse(functions.begin(), functions.end());
543 for (auto pair : functions) pair.first(pair.second);
544 }
545
getgoogle::protobuf::internal::ShutdownData546 static ShutdownData* get() {
547 static auto* data = new ShutdownData;
548 return data;
549 }
550
551 std::vector<std::pair<void (*)(const void*), const void*>> functions;
552 Mutex mutex;
553 };
554
RunZeroArgFunc(const void * arg)555 static void RunZeroArgFunc(const void* arg) {
556 void (*func)() = reinterpret_cast<void (*)()>(const_cast<void*>(arg));
557 func();
558 }
559
OnShutdown(void (* func)())560 void OnShutdown(void (*func)()) {
561 OnShutdownRun(RunZeroArgFunc, reinterpret_cast<void*>(func));
562 }
563
OnShutdownRun(void (* f)(const void *),const void * arg)564 void OnShutdownRun(void (*f)(const void*), const void* arg) {
565 auto shutdown_data = ShutdownData::get();
566 MutexLock lock(&shutdown_data->mutex);
567 shutdown_data->functions.push_back(std::make_pair(f, arg));
568 }
569
570 } // namespace internal
571
ShutdownProtobufLibrary()572 void ShutdownProtobufLibrary() {
573 // This function should be called only once, but accepts multiple calls.
574 static bool is_shutdown = false;
575 if (!is_shutdown) {
576 delete internal::ShutdownData::get();
577 is_shutdown = true;
578 }
579 }
580
581
582 } // namespace protobuf
583 } // namespace google
584