• 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 // Defines Message, the abstract interface implemented by non-lite
36 // protocol message objects.  Although it's possible to implement this
37 // interface manually, most users will use the protocol compiler to
38 // generate implementations.
39 //
40 // Example usage:
41 //
42 // Say you have a message defined as:
43 //
44 //   message Foo {
45 //     optional string text = 1;
46 //     repeated int32 numbers = 2;
47 //   }
48 //
49 // Then, if you used the protocol compiler to generate a class from the above
50 // definition, you could use it like so:
51 //
52 //   std::string data;  // Will store a serialized version of the message.
53 //
54 //   {
55 //     // Create a message and serialize it.
56 //     Foo foo;
57 //     foo.set_text("Hello World!");
58 //     foo.add_numbers(1);
59 //     foo.add_numbers(5);
60 //     foo.add_numbers(42);
61 //
62 //     foo.SerializeToString(&data);
63 //   }
64 //
65 //   {
66 //     // Parse the serialized message and check that it contains the
67 //     // correct data.
68 //     Foo foo;
69 //     foo.ParseFromString(data);
70 //
71 //     assert(foo.text() == "Hello World!");
72 //     assert(foo.numbers_size() == 3);
73 //     assert(foo.numbers(0) == 1);
74 //     assert(foo.numbers(1) == 5);
75 //     assert(foo.numbers(2) == 42);
76 //   }
77 //
78 //   {
79 //     // Same as the last block, but do it dynamically via the Message
80 //     // reflection interface.
81 //     Message* foo = new Foo;
82 //     const Descriptor* descriptor = foo->GetDescriptor();
83 //
84 //     // Get the descriptors for the fields we're interested in and verify
85 //     // their types.
86 //     const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
87 //     assert(text_field != nullptr);
88 //     assert(text_field->type() == FieldDescriptor::TYPE_STRING);
89 //     assert(text_field->label() == FieldDescriptor::LABEL_OPTIONAL);
90 //     const FieldDescriptor* numbers_field = descriptor->
91 //                                            FindFieldByName("numbers");
92 //     assert(numbers_field != nullptr);
93 //     assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
94 //     assert(numbers_field->label() == FieldDescriptor::LABEL_REPEATED);
95 //
96 //     // Parse the message.
97 //     foo->ParseFromString(data);
98 //
99 //     // Use the reflection interface to examine the contents.
100 //     const Reflection* reflection = foo->GetReflection();
101 //     assert(reflection->GetString(*foo, text_field) == "Hello World!");
102 //     assert(reflection->FieldSize(*foo, numbers_field) == 3);
103 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 0) == 1);
104 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 1) == 5);
105 //     assert(reflection->GetRepeatedInt32(*foo, numbers_field, 2) == 42);
106 //
107 //     delete foo;
108 //   }
109 
110 #ifndef GOOGLE_PROTOBUF_MESSAGE_H__
111 #define GOOGLE_PROTOBUF_MESSAGE_H__
112 
113 
114 #include <iosfwd>
115 #include <string>
116 #include <type_traits>
117 #include <vector>
118 
119 #include <google/protobuf/stubs/casts.h>
120 #include <google/protobuf/stubs/common.h>
121 #include <google/protobuf/arena.h>
122 #include <google/protobuf/port.h>
123 #include <google/protobuf/descriptor.h>
124 #include <google/protobuf/generated_message_reflection.h>
125 #include <google/protobuf/generated_message_util.h>
126 #include <google/protobuf/map.h>  // TODO(b/211442718): cleanup
127 #include <google/protobuf/message_lite.h>
128 
129 
130 // Must be included last.
131 #include <google/protobuf/port_def.inc>
132 
133 #ifdef SWIG
134 #error "You cannot SWIG proto headers"
135 #endif
136 
137 namespace google {
138 namespace protobuf {
139 
140 // Defined in this file.
141 class Message;
142 class Reflection;
143 class MessageFactory;
144 
145 // Defined in other files.
146 class AssignDescriptorsHelper;
147 class DynamicMessageFactory;
148 class GeneratedMessageReflectionTestHelper;
149 class MapKey;
150 class MapValueConstRef;
151 class MapValueRef;
152 class MapIterator;
153 class MapReflectionTester;
154 
155 namespace internal {
156 struct DescriptorTable;
157 class MapFieldBase;
158 class SwapFieldHelper;
159 class CachedSize;
160 }  // namespace internal
161 class UnknownFieldSet;  // unknown_field_set.h
162 namespace io {
163 class ZeroCopyInputStream;   // zero_copy_stream.h
164 class ZeroCopyOutputStream;  // zero_copy_stream.h
165 class CodedInputStream;      // coded_stream.h
166 class CodedOutputStream;     // coded_stream.h
167 }  // namespace io
168 namespace python {
169 class MapReflectionFriend;  // scalar_map_container.h
170 class MessageReflectionFriend;
171 }  // namespace python
172 namespace expr {
173 class CelMapReflectionFriend;  // field_backed_map_impl.cc
174 }
175 
176 namespace internal {
177 class MapFieldPrinterHelper;  // text_format.cc
178 }
179 namespace util {
180 class MessageDifferencer;
181 }
182 
183 
184 namespace internal {
185 class ReflectionAccessor;      // message.cc
186 class ReflectionOps;           // reflection_ops.h
187 class MapKeySorter;            // wire_format.cc
188 class WireFormat;              // wire_format.h
189 class MapFieldReflectionTest;  // map_test.cc
190 }  // namespace internal
191 
192 template <typename T>
193 class RepeatedField;  // repeated_field.h
194 
195 template <typename T>
196 class RepeatedPtrField;  // repeated_field.h
197 
198 // A container to hold message metadata.
199 struct Metadata {
200   const Descriptor* descriptor;
201   const Reflection* reflection;
202 };
203 
204 namespace internal {
205 template <class To>
GetPointerAtOffset(Message * message,uint32_t offset)206 inline To* GetPointerAtOffset(Message* message, uint32_t offset) {
207   return reinterpret_cast<To*>(reinterpret_cast<char*>(message) + offset);
208 }
209 
210 template <class To>
GetConstPointerAtOffset(const Message * message,uint32_t offset)211 const To* GetConstPointerAtOffset(const Message* message, uint32_t offset) {
212   return reinterpret_cast<const To*>(reinterpret_cast<const char*>(message) +
213                                      offset);
214 }
215 
216 template <class To>
GetConstRefAtOffset(const Message & message,uint32_t offset)217 const To& GetConstRefAtOffset(const Message& message, uint32_t offset) {
218   return *GetConstPointerAtOffset<To>(&message, offset);
219 }
220 
221 bool CreateUnknownEnumValues(const FieldDescriptor* field);
222 }  // namespace internal
223 
224 // Abstract interface for protocol messages.
225 //
226 // See also MessageLite, which contains most every-day operations.  Message
227 // adds descriptors and reflection on top of that.
228 //
229 // The methods of this class that are virtual but not pure-virtual have
230 // default implementations based on reflection.  Message classes which are
231 // optimized for speed will want to override these with faster implementations,
232 // but classes optimized for code size may be happy with keeping them.  See
233 // the optimize_for option in descriptor.proto.
234 //
235 // Users must not derive from this class. Only the protocol compiler and
236 // the internal library are allowed to create subclasses.
237 class PROTOBUF_EXPORT Message : public MessageLite {
238  public:
Message()239   constexpr Message() {}
240 
241   // Basic Operations ------------------------------------------------
242 
243   // Construct a new instance of the same type.  Ownership is passed to the
244   // caller.  (This is also defined in MessageLite, but is defined again here
245   // for return-type covariance.)
New()246   Message* New() const { return New(nullptr); }
247 
248   // Construct a new instance on the arena. Ownership is passed to the caller
249   // if arena is a nullptr.
250   Message* New(Arena* arena) const override = 0;
251 
252   // Make this message into a copy of the given message.  The given message
253   // must have the same descriptor, but need not necessarily be the same class.
254   // By default this is just implemented as "Clear(); MergeFrom(from);".
255   virtual void CopyFrom(const Message& from);
256 
257   // Merge the fields from the given message into this message.  Singular
258   // fields will be overwritten, if specified in from, except for embedded
259   // messages which will be merged.  Repeated fields will be concatenated.
260   // The given message must be of the same type as this message (i.e. the
261   // exact same class).
262   virtual void MergeFrom(const Message& from);
263 
264   // Verifies that IsInitialized() returns true.  GOOGLE_CHECK-fails otherwise, with
265   // a nice error message.
266   void CheckInitialized() const;
267 
268   // Slowly build a list of all required fields that are not set.
269   // This is much, much slower than IsInitialized() as it is implemented
270   // purely via reflection.  Generally, you should not call this unless you
271   // have already determined that an error exists by calling IsInitialized().
272   void FindInitializationErrors(std::vector<std::string>* errors) const;
273 
274   // Like FindInitializationErrors, but joins all the strings, delimited by
275   // commas, and returns them.
276   std::string InitializationErrorString() const override;
277 
278   // Clears all unknown fields from this message and all embedded messages.
279   // Normally, if unknown tag numbers are encountered when parsing a message,
280   // the tag and value are stored in the message's UnknownFieldSet and
281   // then written back out when the message is serialized.  This allows servers
282   // which simply route messages to other servers to pass through messages
283   // that have new field definitions which they don't yet know about.  However,
284   // this behavior can have security implications.  To avoid it, call this
285   // method after parsing.
286   //
287   // See Reflection::GetUnknownFields() for more on unknown fields.
288   void DiscardUnknownFields();
289 
290   // Computes (an estimate of) the total number of bytes currently used for
291   // storing the message in memory.  The default implementation calls the
292   // Reflection object's SpaceUsed() method.
293   //
294   // SpaceUsed() is noticeably slower than ByteSize(), as it is implemented
295   // using reflection (rather than the generated code implementation for
296   // ByteSize()). Like ByteSize(), its CPU time is linear in the number of
297   // fields defined for the proto.
298   virtual size_t SpaceUsedLong() const;
299 
300   PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
SpaceUsed()301   int SpaceUsed() const { return internal::ToIntSize(SpaceUsedLong()); }
302 
303   // Debugging & Testing----------------------------------------------
304 
305   // Generates a human readable form of this message, useful for debugging
306   // and other purposes.
307   std::string DebugString() const;
308   // Like DebugString(), but with less whitespace.
309   std::string ShortDebugString() const;
310   // Like DebugString(), but do not escape UTF-8 byte sequences.
311   std::string Utf8DebugString() const;
312   // Convenience function useful in GDB.  Prints DebugString() to stdout.
313   void PrintDebugString() const;
314 
315   // Reflection-based methods ----------------------------------------
316   // These methods are pure-virtual in MessageLite, but Message provides
317   // reflection-based default implementations.
318 
319   std::string GetTypeName() const override;
320   void Clear() override;
321 
322   // Returns whether all required fields have been set. Note that required
323   // fields no longer exist starting in proto3.
324   bool IsInitialized() const override;
325 
326   void CheckTypeAndMergeFrom(const MessageLite& other) override;
327   // Reflective parser
328   const char* _InternalParse(const char* ptr,
329                              internal::ParseContext* ctx) override;
330   size_t ByteSizeLong() const override;
331   uint8_t* _InternalSerialize(uint8_t* target,
332                               io::EpsCopyOutputStream* stream) const override;
333 
334  private:
335   // This is called only by the default implementation of ByteSize(), to
336   // update the cached size.  If you override ByteSize(), you do not need
337   // to override this.  If you do not override ByteSize(), you MUST override
338   // this; the default implementation will crash.
339   //
340   // The method is private because subclasses should never call it; only
341   // override it.  Yes, C++ lets you do that.  Crazy, huh?
342   virtual void SetCachedSize(int size) const;
343 
344  public:
345   // Introspection ---------------------------------------------------
346 
347 
348   // Get a non-owning pointer to a Descriptor for this message's type.  This
349   // describes what fields the message contains, the types of those fields, etc.
350   // This object remains property of the Message.
GetDescriptor()351   const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; }
352 
353   // Get a non-owning pointer to the Reflection interface for this Message,
354   // which can be used to read and modify the fields of the Message dynamically
355   // (in other words, without knowing the message type at compile time).  This
356   // object remains property of the Message.
GetReflection()357   const Reflection* GetReflection() const { return GetMetadata().reflection; }
358 
359  protected:
360   // Get a struct containing the metadata for the Message, which is used in turn
361   // to implement GetDescriptor() and GetReflection() above.
362   virtual Metadata GetMetadata() const = 0;
363 
364   struct ClassData {
365     // Note: The order of arguments (to, then from) is chosen so that the ABI
366     // of this function is the same as the CopyFrom method.  That is, the
367     // hidden "this" parameter comes first.
368     void (*copy_to_from)(Message* to, const Message& from_msg);
369     void (*merge_to_from)(Message* to, const Message& from_msg);
370   };
371   // GetClassData() returns a pointer to a ClassData struct which
372   // exists in global memory and is unique to each subclass.  This uniqueness
373   // property is used in order to quickly determine whether two messages are
374   // of the same type.
375   // TODO(jorg): change to pure virtual
GetClassData()376   virtual const ClassData* GetClassData() const { return nullptr; }
377 
378   // CopyWithSizeCheck calls Clear() and then MergeFrom(), and in debug
379   // builds, checks that calling Clear() on the destination message doesn't
380   // alter the size of the source.  It assumes the messages are known to be
381   // of the same type, and thus uses GetClassData().
382   static void CopyWithSizeCheck(Message* to, const Message& from);
383 
384   inline explicit Message(Arena* arena, bool is_message_owned = false)
MessageLite(arena,is_message_owned)385       : MessageLite(arena, is_message_owned) {}
386   size_t ComputeUnknownFieldsSize(size_t total_size,
387                                   internal::CachedSize* cached_size) const;
388   size_t MaybeComputeUnknownFieldsSize(size_t total_size,
389                                        internal::CachedSize* cached_size) const;
390 
391 
392  protected:
393   static uint64_t GetInvariantPerBuild(uint64_t salt);
394 
395  private:
396   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message);
397 };
398 
399 namespace internal {
400 // Forward-declare interfaces used to implement RepeatedFieldRef.
401 // These are protobuf internals that users shouldn't care about.
402 class RepeatedFieldAccessor;
403 }  // namespace internal
404 
405 // Forward-declare RepeatedFieldRef templates. The second type parameter is
406 // used for SFINAE tricks. Users should ignore it.
407 template <typename T, typename Enable = void>
408 class RepeatedFieldRef;
409 
410 template <typename T, typename Enable = void>
411 class MutableRepeatedFieldRef;
412 
413 // This interface contains methods that can be used to dynamically access
414 // and modify the fields of a protocol message.  Their semantics are
415 // similar to the accessors the protocol compiler generates.
416 //
417 // To get the Reflection for a given Message, call Message::GetReflection().
418 //
419 // This interface is separate from Message only for efficiency reasons;
420 // the vast majority of implementations of Message will share the same
421 // implementation of Reflection (GeneratedMessageReflection,
422 // defined in generated_message.h), and all Messages of a particular class
423 // should share the same Reflection object (though you should not rely on
424 // the latter fact).
425 //
426 // There are several ways that these methods can be used incorrectly.  For
427 // example, any of the following conditions will lead to undefined
428 // results (probably assertion failures):
429 // - The FieldDescriptor is not a field of this message type.
430 // - The method called is not appropriate for the field's type.  For
431 //   each field type in FieldDescriptor::TYPE_*, there is only one
432 //   Get*() method, one Set*() method, and one Add*() method that is
433 //   valid for that type.  It should be obvious which (except maybe
434 //   for TYPE_BYTES, which are represented using strings in C++).
435 // - A Get*() or Set*() method for singular fields is called on a repeated
436 //   field.
437 // - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated
438 //   field.
439 // - The Message object passed to any method is not of the right type for
440 //   this Reflection object (i.e. message.GetReflection() != reflection).
441 //
442 // You might wonder why there is not any abstract representation for a field
443 // of arbitrary type.  E.g., why isn't there just a "GetField()" method that
444 // returns "const Field&", where "Field" is some class with accessors like
445 // "GetInt32Value()".  The problem is that someone would have to deal with
446 // allocating these Field objects.  For generated message classes, having to
447 // allocate space for an additional object to wrap every field would at least
448 // double the message's memory footprint, probably worse.  Allocating the
449 // objects on-demand, on the other hand, would be expensive and prone to
450 // memory leaks.  So, instead we ended up with this flat interface.
451 class PROTOBUF_EXPORT Reflection final {
452  public:
453   // Get the UnknownFieldSet for the message.  This contains fields which
454   // were seen when the Message was parsed but were not recognized according
455   // to the Message's definition.
456   const UnknownFieldSet& GetUnknownFields(const Message& message) const;
457   // Get a mutable pointer to the UnknownFieldSet for the message.  This
458   // contains fields which were seen when the Message was parsed but were not
459   // recognized according to the Message's definition.
460   UnknownFieldSet* MutableUnknownFields(Message* message) const;
461 
462   // Estimate the amount of memory used by the message object.
463   size_t SpaceUsedLong(const Message& message) const;
464 
465   PROTOBUF_DEPRECATED_MSG("Please use SpaceUsedLong() instead")
SpaceUsed(const Message & message)466   int SpaceUsed(const Message& message) const {
467     return internal::ToIntSize(SpaceUsedLong(message));
468   }
469 
470   // Check if the given non-repeated field is set.
471   bool HasField(const Message& message, const FieldDescriptor* field) const;
472 
473   // Get the number of elements of a repeated field.
474   int FieldSize(const Message& message, const FieldDescriptor* field) const;
475 
476   // Clear the value of a field, so that HasField() returns false or
477   // FieldSize() returns zero.
478   void ClearField(Message* message, const FieldDescriptor* field) const;
479 
480   // Check if the oneof is set. Returns true if any field in oneof
481   // is set, false otherwise.
482   bool HasOneof(const Message& message,
483                 const OneofDescriptor* oneof_descriptor) const;
484 
485   void ClearOneof(Message* message,
486                   const OneofDescriptor* oneof_descriptor) const;
487 
488   // Returns the field descriptor if the oneof is set. nullptr otherwise.
489   const FieldDescriptor* GetOneofFieldDescriptor(
490       const Message& message, const OneofDescriptor* oneof_descriptor) const;
491 
492   // Removes the last element of a repeated field.
493   // We don't provide a way to remove any element other than the last
494   // because it invites inefficient use, such as O(n^2) filtering loops
495   // that should have been O(n).  If you want to remove an element other
496   // than the last, the best way to do it is to re-arrange the elements
497   // (using Swap()) so that the one you want removed is at the end, then
498   // call RemoveLast().
499   void RemoveLast(Message* message, const FieldDescriptor* field) const;
500   // Removes the last element of a repeated message field, and returns the
501   // pointer to the caller.  Caller takes ownership of the returned pointer.
502   PROTOBUF_NODISCARD Message* ReleaseLast(Message* message,
503                                           const FieldDescriptor* field) const;
504 
505   // Similar to ReleaseLast() without internal safety and ownershp checks. This
506   // method should only be used when the objects are on the same arena or paired
507   // with a call to `UnsafeArenaAddAllocatedMessage`.
508   Message* UnsafeArenaReleaseLast(Message* message,
509                                   const FieldDescriptor* field) const;
510 
511   // Swap the complete contents of two messages.
512   void Swap(Message* message1, Message* message2) const;
513 
514   // Swap fields listed in fields vector of two messages.
515   void SwapFields(Message* message1, Message* message2,
516                   const std::vector<const FieldDescriptor*>& fields) const;
517 
518   // Swap two elements of a repeated field.
519   void SwapElements(Message* message, const FieldDescriptor* field, int index1,
520                     int index2) const;
521 
522   // Swap without internal safety and ownership checks. This method should only
523   // be used when the objects are on the same arena.
524   void UnsafeArenaSwap(Message* lhs, Message* rhs) const;
525 
526   // SwapFields without internal safety and ownership checks. This method should
527   // only be used when the objects are on the same arena.
528   void UnsafeArenaSwapFields(
529       Message* lhs, Message* rhs,
530       const std::vector<const FieldDescriptor*>& fields) const;
531 
532   // List all fields of the message which are currently set, except for unknown
533   // fields, but including extension known to the parser (i.e. compiled in).
534   // Singular fields will only be listed if HasField(field) would return true
535   // and repeated fields will only be listed if FieldSize(field) would return
536   // non-zero.  Fields (both normal fields and extension fields) will be listed
537   // ordered by field number.
538   // Use Reflection::GetUnknownFields() or message.unknown_fields() to also get
539   // access to fields/extensions unknown to the parser.
540   void ListFields(const Message& message,
541                   std::vector<const FieldDescriptor*>* output) const;
542 
543   // Singular field getters ------------------------------------------
544   // These get the value of a non-repeated field.  They return the default
545   // value for fields that aren't set.
546 
547   int32_t GetInt32(const Message& message, const FieldDescriptor* field) const;
548   int64_t GetInt64(const Message& message, const FieldDescriptor* field) const;
549   uint32_t GetUInt32(const Message& message,
550                      const FieldDescriptor* field) const;
551   uint64_t GetUInt64(const Message& message,
552                      const FieldDescriptor* field) const;
553   float GetFloat(const Message& message, const FieldDescriptor* field) const;
554   double GetDouble(const Message& message, const FieldDescriptor* field) const;
555   bool GetBool(const Message& message, const FieldDescriptor* field) const;
556   std::string GetString(const Message& message,
557                         const FieldDescriptor* field) const;
558   const EnumValueDescriptor* GetEnum(const Message& message,
559                                      const FieldDescriptor* field) const;
560 
561   // GetEnumValue() returns an enum field's value as an integer rather than
562   // an EnumValueDescriptor*. If the integer value does not correspond to a
563   // known value descriptor, a new value descriptor is created. (Such a value
564   // will only be present when the new unknown-enum-value semantics are enabled
565   // for a message.)
566   int GetEnumValue(const Message& message, const FieldDescriptor* field) const;
567 
568   // See MutableMessage() for the meaning of the "factory" parameter.
569   const Message& GetMessage(const Message& message,
570                             const FieldDescriptor* field,
571                             MessageFactory* factory = nullptr) const;
572 
573   // Get a string value without copying, if possible.
574   //
575   // GetString() necessarily returns a copy of the string.  This can be
576   // inefficient when the std::string is already stored in a std::string object
577   // in the underlying message.  GetStringReference() will return a reference to
578   // the underlying std::string in this case.  Otherwise, it will copy the
579   // string into *scratch and return that.
580   //
581   // Note:  It is perfectly reasonable and useful to write code like:
582   //     str = reflection->GetStringReference(message, field, &str);
583   //   This line would ensure that only one copy of the string is made
584   //   regardless of the field's underlying representation.  When initializing
585   //   a newly-constructed string, though, it's just as fast and more
586   //   readable to use code like:
587   //     std::string str = reflection->GetString(message, field);
588   const std::string& GetStringReference(const Message& message,
589                                         const FieldDescriptor* field,
590                                         std::string* scratch) const;
591 
592 
593   // Singular field mutators -----------------------------------------
594   // These mutate the value of a non-repeated field.
595 
596   void SetInt32(Message* message, const FieldDescriptor* field,
597                 int32_t value) const;
598   void SetInt64(Message* message, const FieldDescriptor* field,
599                 int64_t value) const;
600   void SetUInt32(Message* message, const FieldDescriptor* field,
601                  uint32_t value) const;
602   void SetUInt64(Message* message, const FieldDescriptor* field,
603                  uint64_t value) const;
604   void SetFloat(Message* message, const FieldDescriptor* field,
605                 float value) const;
606   void SetDouble(Message* message, const FieldDescriptor* field,
607                  double value) const;
608   void SetBool(Message* message, const FieldDescriptor* field,
609                bool value) const;
610   void SetString(Message* message, const FieldDescriptor* field,
611                  std::string value) const;
612   void SetEnum(Message* message, const FieldDescriptor* field,
613                const EnumValueDescriptor* value) const;
614   // Set an enum field's value with an integer rather than EnumValueDescriptor.
615   // For proto3 this is just setting the enum field to the value specified, for
616   // proto2 it's more complicated. If value is a known enum value the field is
617   // set as usual. If the value is unknown then it is added to the unknown field
618   // set. Note this matches the behavior of parsing unknown enum values.
619   // If multiple calls with unknown values happen than they are all added to the
620   // unknown field set in order of the calls.
621   void SetEnumValue(Message* message, const FieldDescriptor* field,
622                     int value) const;
623 
624   // Get a mutable pointer to a field with a message type.  If a MessageFactory
625   // is provided, it will be used to construct instances of the sub-message;
626   // otherwise, the default factory is used.  If the field is an extension that
627   // does not live in the same pool as the containing message's descriptor (e.g.
628   // it lives in an overlay pool), then a MessageFactory must be provided.
629   // If you have no idea what that meant, then you probably don't need to worry
630   // about it (don't provide a MessageFactory).  WARNING:  If the
631   // FieldDescriptor is for a compiled-in extension, then
632   // factory->GetPrototype(field->message_type()) MUST return an instance of
633   // the compiled-in class for this type, NOT DynamicMessage.
634   Message* MutableMessage(Message* message, const FieldDescriptor* field,
635                           MessageFactory* factory = nullptr) const;
636 
637   // Replaces the message specified by 'field' with the already-allocated object
638   // sub_message, passing ownership to the message.  If the field contained a
639   // message, that message is deleted.  If sub_message is nullptr, the field is
640   // cleared.
641   void SetAllocatedMessage(Message* message, Message* sub_message,
642                            const FieldDescriptor* field) const;
643 
644   // Similar to `SetAllocatedMessage`, but omits all internal safety and
645   // ownership checks.  This method should only be used when the objects are on
646   // the same arena or paired with a call to `UnsafeArenaReleaseMessage`.
647   void UnsafeArenaSetAllocatedMessage(Message* message, Message* sub_message,
648                                       const FieldDescriptor* field) const;
649 
650   // Releases the message specified by 'field' and returns the pointer,
651   // ReleaseMessage() will return the message the message object if it exists.
652   // Otherwise, it may or may not return nullptr.  In any case, if the return
653   // value is non-null, the caller takes ownership of the pointer.
654   // If the field existed (HasField() is true), then the returned pointer will
655   // be the same as the pointer returned by MutableMessage().
656   // This function has the same effect as ClearField().
657   PROTOBUF_NODISCARD Message* ReleaseMessage(
658       Message* message, const FieldDescriptor* field,
659       MessageFactory* factory = nullptr) const;
660 
661   // Similar to `ReleaseMessage`, but omits all internal safety and ownership
662   // checks.  This method should only be used when the objects are on the same
663   // arena or paired with a call to `UnsafeArenaSetAllocatedMessage`.
664   Message* UnsafeArenaReleaseMessage(Message* message,
665                                      const FieldDescriptor* field,
666                                      MessageFactory* factory = nullptr) const;
667 
668 
669   // Repeated field getters ------------------------------------------
670   // These get the value of one element of a repeated field.
671 
672   int32_t GetRepeatedInt32(const Message& message, const FieldDescriptor* field,
673                            int index) const;
674   int64_t GetRepeatedInt64(const Message& message, const FieldDescriptor* field,
675                            int index) const;
676   uint32_t GetRepeatedUInt32(const Message& message,
677                              const FieldDescriptor* field, int index) const;
678   uint64_t GetRepeatedUInt64(const Message& message,
679                              const FieldDescriptor* field, int index) const;
680   float GetRepeatedFloat(const Message& message, const FieldDescriptor* field,
681                          int index) const;
682   double GetRepeatedDouble(const Message& message, const FieldDescriptor* field,
683                            int index) const;
684   bool GetRepeatedBool(const Message& message, const FieldDescriptor* field,
685                        int index) const;
686   std::string GetRepeatedString(const Message& message,
687                                 const FieldDescriptor* field, int index) const;
688   const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
689                                              const FieldDescriptor* field,
690                                              int index) const;
691   // GetRepeatedEnumValue() returns an enum field's value as an integer rather
692   // than an EnumValueDescriptor*. If the integer value does not correspond to a
693   // known value descriptor, a new value descriptor is created. (Such a value
694   // will only be present when the new unknown-enum-value semantics are enabled
695   // for a message.)
696   int GetRepeatedEnumValue(const Message& message, const FieldDescriptor* field,
697                            int index) const;
698   const Message& GetRepeatedMessage(const Message& message,
699                                     const FieldDescriptor* field,
700                                     int index) const;
701 
702   // See GetStringReference(), above.
703   const std::string& GetRepeatedStringReference(const Message& message,
704                                                 const FieldDescriptor* field,
705                                                 int index,
706                                                 std::string* scratch) const;
707 
708 
709   // Repeated field mutators -----------------------------------------
710   // These mutate the value of one element of a repeated field.
711 
712   void SetRepeatedInt32(Message* message, const FieldDescriptor* field,
713                         int index, int32_t value) const;
714   void SetRepeatedInt64(Message* message, const FieldDescriptor* field,
715                         int index, int64_t value) const;
716   void SetRepeatedUInt32(Message* message, const FieldDescriptor* field,
717                          int index, uint32_t value) const;
718   void SetRepeatedUInt64(Message* message, const FieldDescriptor* field,
719                          int index, uint64_t value) const;
720   void SetRepeatedFloat(Message* message, const FieldDescriptor* field,
721                         int index, float value) const;
722   void SetRepeatedDouble(Message* message, const FieldDescriptor* field,
723                          int index, double value) const;
724   void SetRepeatedBool(Message* message, const FieldDescriptor* field,
725                        int index, bool value) const;
726   void SetRepeatedString(Message* message, const FieldDescriptor* field,
727                          int index, std::string value) const;
728   void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
729                        int index, const EnumValueDescriptor* value) const;
730   // Set an enum field's value with an integer rather than EnumValueDescriptor.
731   // For proto3 this is just setting the enum field to the value specified, for
732   // proto2 it's more complicated. If value is a known enum value the field is
733   // set as usual. If the value is unknown then it is added to the unknown field
734   // set. Note this matches the behavior of parsing unknown enum values.
735   // If multiple calls with unknown values happen than they are all added to the
736   // unknown field set in order of the calls.
737   void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
738                             int index, int value) const;
739   // Get a mutable pointer to an element of a repeated field with a message
740   // type.
741   Message* MutableRepeatedMessage(Message* message,
742                                   const FieldDescriptor* field,
743                                   int index) const;
744 
745 
746   // Repeated field adders -------------------------------------------
747   // These add an element to a repeated field.
748 
749   void AddInt32(Message* message, const FieldDescriptor* field,
750                 int32_t value) const;
751   void AddInt64(Message* message, const FieldDescriptor* field,
752                 int64_t value) const;
753   void AddUInt32(Message* message, const FieldDescriptor* field,
754                  uint32_t value) const;
755   void AddUInt64(Message* message, const FieldDescriptor* field,
756                  uint64_t value) const;
757   void AddFloat(Message* message, const FieldDescriptor* field,
758                 float value) const;
759   void AddDouble(Message* message, const FieldDescriptor* field,
760                  double value) const;
761   void AddBool(Message* message, const FieldDescriptor* field,
762                bool value) const;
763   void AddString(Message* message, const FieldDescriptor* field,
764                  std::string value) const;
765   void AddEnum(Message* message, const FieldDescriptor* field,
766                const EnumValueDescriptor* value) const;
767   // Add an integer value to a repeated enum field rather than
768   // EnumValueDescriptor. For proto3 this is just setting the enum field to the
769   // value specified, for proto2 it's more complicated. If value is a known enum
770   // value the field is set as usual. If the value is unknown then it is added
771   // to the unknown field set. Note this matches the behavior of parsing unknown
772   // enum values. If multiple calls with unknown values happen than they are all
773   // added to the unknown field set in order of the calls.
774   void AddEnumValue(Message* message, const FieldDescriptor* field,
775                     int value) const;
776   // See MutableMessage() for comments on the "factory" parameter.
777   Message* AddMessage(Message* message, const FieldDescriptor* field,
778                       MessageFactory* factory = nullptr) const;
779 
780   // Appends an already-allocated object 'new_entry' to the repeated field
781   // specified by 'field' passing ownership to the message.
782   void AddAllocatedMessage(Message* message, const FieldDescriptor* field,
783                            Message* new_entry) const;
784 
785   // Similar to AddAllocatedMessage() without internal safety and ownership
786   // checks. This method should only be used when the objects are on the same
787   // arena or paired with a call to `UnsafeArenaReleaseLast`.
788   void UnsafeArenaAddAllocatedMessage(Message* message,
789                                       const FieldDescriptor* field,
790                                       Message* new_entry) const;
791 
792 
793   // Get a RepeatedFieldRef object that can be used to read the underlying
794   // repeated field. The type parameter T must be set according to the
795   // field's cpp type. The following table shows the mapping from cpp type
796   // to acceptable T.
797   //
798   //   field->cpp_type()      T
799   //   CPPTYPE_INT32        int32_t
800   //   CPPTYPE_UINT32       uint32_t
801   //   CPPTYPE_INT64        int64_t
802   //   CPPTYPE_UINT64       uint64_t
803   //   CPPTYPE_DOUBLE       double
804   //   CPPTYPE_FLOAT        float
805   //   CPPTYPE_BOOL         bool
806   //   CPPTYPE_ENUM         generated enum type or int32_t
807   //   CPPTYPE_STRING       std::string
808   //   CPPTYPE_MESSAGE      generated message type or google::protobuf::Message
809   //
810   // A RepeatedFieldRef object can be copied and the resulted object will point
811   // to the same repeated field in the same message. The object can be used as
812   // long as the message is not destroyed.
813   //
814   // Note that to use this method users need to include the header file
815   // "reflection.h" (which defines the RepeatedFieldRef class templates).
816   template <typename T>
817   RepeatedFieldRef<T> GetRepeatedFieldRef(const Message& message,
818                                           const FieldDescriptor* field) const;
819 
820   // Like GetRepeatedFieldRef() but return an object that can also be used
821   // manipulate the underlying repeated field.
822   template <typename T>
823   MutableRepeatedFieldRef<T> GetMutableRepeatedFieldRef(
824       Message* message, const FieldDescriptor* field) const;
825 
826   // DEPRECATED. Please use Get(Mutable)RepeatedFieldRef() for repeated field
827   // access. The following repeated field accessors will be removed in the
828   // future.
829   //
830   // Repeated field accessors  -------------------------------------------------
831   // The methods above, e.g. GetRepeatedInt32(msg, fd, index), provide singular
832   // access to the data in a RepeatedField.  The methods below provide aggregate
833   // access by exposing the RepeatedField object itself with the Message.
834   // Applying these templates to inappropriate types will lead to an undefined
835   // reference at link time (e.g. GetRepeatedField<***double>), or possibly a
836   // template matching error at compile time (e.g. GetRepeatedPtrField<File>).
837   //
838   // Usage example: my_doubs = refl->GetRepeatedField<double>(msg, fd);
839 
840   // DEPRECATED. Please use GetRepeatedFieldRef().
841   //
842   // for T = Cord and all protobuf scalar types except enums.
843   template <typename T>
844   PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
GetRepeatedField(const Message & msg,const FieldDescriptor * d)845   const RepeatedField<T>& GetRepeatedField(const Message& msg,
846                                            const FieldDescriptor* d) const {
847     return GetRepeatedFieldInternal<T>(msg, d);
848   }
849 
850   // DEPRECATED. Please use GetMutableRepeatedFieldRef().
851   //
852   // for T = Cord and all protobuf scalar types except enums.
853   template <typename T>
854   PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
MutableRepeatedField(Message * msg,const FieldDescriptor * d)855   RepeatedField<T>* MutableRepeatedField(Message* msg,
856                                          const FieldDescriptor* d) const {
857     return MutableRepeatedFieldInternal<T>(msg, d);
858   }
859 
860   // DEPRECATED. Please use GetRepeatedFieldRef().
861   //
862   // for T = std::string, google::protobuf::internal::StringPieceField
863   //         google::protobuf::Message & descendants.
864   template <typename T>
865   PROTOBUF_DEPRECATED_MSG("Please use GetRepeatedFieldRef() instead")
GetRepeatedPtrField(const Message & msg,const FieldDescriptor * d)866   const RepeatedPtrField<T>& GetRepeatedPtrField(
867       const Message& msg, const FieldDescriptor* d) const {
868     return GetRepeatedPtrFieldInternal<T>(msg, d);
869   }
870 
871   // DEPRECATED. Please use GetMutableRepeatedFieldRef().
872   //
873   // for T = std::string, google::protobuf::internal::StringPieceField
874   //         google::protobuf::Message & descendants.
875   template <typename T>
876   PROTOBUF_DEPRECATED_MSG("Please use GetMutableRepeatedFieldRef() instead")
MutableRepeatedPtrField(Message * msg,const FieldDescriptor * d)877   RepeatedPtrField<T>* MutableRepeatedPtrField(Message* msg,
878                                                const FieldDescriptor* d) const {
879     return MutableRepeatedPtrFieldInternal<T>(msg, d);
880   }
881 
882   // Extensions ----------------------------------------------------------------
883 
884   // Try to find an extension of this message type by fully-qualified field
885   // name.  Returns nullptr if no extension is known for this name or number.
886   const FieldDescriptor* FindKnownExtensionByName(
887       const std::string& name) const;
888 
889   // Try to find an extension of this message type by field number.
890   // Returns nullptr if no extension is known for this name or number.
891   const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
892 
893   // Feature Flags -------------------------------------------------------------
894 
895   // Does this message support storing arbitrary integer values in enum fields?
896   // If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions
897   // take arbitrary integer values, and the legacy GetEnum() getter will
898   // dynamically create an EnumValueDescriptor for any integer value without
899   // one. If |false|, setting an unknown enum value via the integer-based
900   // setters results in undefined behavior (in practice, GOOGLE_DCHECK-fails).
901   //
902   // Generic code that uses reflection to handle messages with enum fields
903   // should check this flag before using the integer-based setter, and either
904   // downgrade to a compatible value or use the UnknownFieldSet if not. For
905   // example:
906   //
907   //   int new_value = GetValueFromApplicationLogic();
908   //   if (reflection->SupportsUnknownEnumValues()) {
909   //     reflection->SetEnumValue(message, field, new_value);
910   //   } else {
911   //     if (field_descriptor->enum_type()->
912   //             FindValueByNumber(new_value) != nullptr) {
913   //       reflection->SetEnumValue(message, field, new_value);
914   //     } else if (emit_unknown_enum_values) {
915   //       reflection->MutableUnknownFields(message)->AddVarint(
916   //           field->number(), new_value);
917   //     } else {
918   //       // convert value to a compatible/default value.
919   //       new_value = CompatibleDowngrade(new_value);
920   //       reflection->SetEnumValue(message, field, new_value);
921   //     }
922   //   }
923   bool SupportsUnknownEnumValues() const;
924 
925   // Returns the MessageFactory associated with this message.  This can be
926   // useful for determining if a message is a generated message or not, for
927   // example:
928   //   if (message->GetReflection()->GetMessageFactory() ==
929   //       google::protobuf::MessageFactory::generated_factory()) {
930   //     // This is a generated message.
931   //   }
932   // It can also be used to create more messages of this type, though
933   // Message::New() is an easier way to accomplish this.
934   MessageFactory* GetMessageFactory() const;
935 
936  private:
937   template <typename T>
938   const RepeatedField<T>& GetRepeatedFieldInternal(
939       const Message& message, const FieldDescriptor* field) const;
940   template <typename T>
941   RepeatedField<T>* MutableRepeatedFieldInternal(
942       Message* message, const FieldDescriptor* field) const;
943   template <typename T>
944   const RepeatedPtrField<T>& GetRepeatedPtrFieldInternal(
945       const Message& message, const FieldDescriptor* field) const;
946   template <typename T>
947   RepeatedPtrField<T>* MutableRepeatedPtrFieldInternal(
948       Message* message, const FieldDescriptor* field) const;
949   // Obtain a pointer to a Repeated Field Structure and do some type checking:
950   //   on field->cpp_type(),
951   //   on field->field_option().ctype() (if ctype >= 0)
952   //   of field->message_type() (if message_type != nullptr).
953   // We use 2 routine rather than 4 (const vs mutable) x (scalar vs pointer).
954   void* MutableRawRepeatedField(Message* message, const FieldDescriptor* field,
955                                 FieldDescriptor::CppType, int ctype,
956                                 const Descriptor* message_type) const;
957 
958   const void* GetRawRepeatedField(const Message& message,
959                                   const FieldDescriptor* field,
960                                   FieldDescriptor::CppType cpptype, int ctype,
961                                   const Descriptor* message_type) const;
962 
963   // The following methods are used to implement (Mutable)RepeatedFieldRef.
964   // A Ref object will store a raw pointer to the repeated field data (obtained
965   // from RepeatedFieldData()) and a pointer to a Accessor (obtained from
966   // RepeatedFieldAccessor) which will be used to access the raw data.
967 
968   // Returns a raw pointer to the repeated field
969   //
970   // "cpp_type" and "message_type" are deduced from the type parameter T passed
971   // to Get(Mutable)RepeatedFieldRef. If T is a generated message type,
972   // "message_type" should be set to its descriptor. Otherwise "message_type"
973   // should be set to nullptr. Implementations of this method should check
974   // whether "cpp_type"/"message_type" is consistent with the actual type of the
975   // field. We use 1 routine rather than 2 (const vs mutable) because it is
976   // protected and it doesn't change the message.
977   void* RepeatedFieldData(Message* message, const FieldDescriptor* field,
978                           FieldDescriptor::CppType cpp_type,
979                           const Descriptor* message_type) const;
980 
981   // The returned pointer should point to a singleton instance which implements
982   // the RepeatedFieldAccessor interface.
983   const internal::RepeatedFieldAccessor* RepeatedFieldAccessor(
984       const FieldDescriptor* field) const;
985 
986   // Lists all fields of the message which are currently set, except for unknown
987   // fields and stripped fields. See ListFields for details.
988   void ListFieldsOmitStripped(
989       const Message& message,
990       std::vector<const FieldDescriptor*>* output) const;
991 
IsMessageStripped(const Descriptor * descriptor)992   bool IsMessageStripped(const Descriptor* descriptor) const {
993     return schema_.IsMessageStripped(descriptor);
994   }
995 
996   friend class TextFormat;
997 
998   void ListFieldsMayFailOnStripped(
999       const Message& message, bool should_fail,
1000       std::vector<const FieldDescriptor*>* output) const;
1001 
1002   // Returns true if the message field is backed by a LazyField.
1003   //
1004   // A message field may be backed by a LazyField without the user annotation
1005   // ([lazy = true]). While the user-annotated LazyField is lazily verified on
1006   // first touch (i.e. failure on access rather than parsing if the LazyField is
1007   // not initialized), the inferred LazyField is eagerly verified to avoid lazy
1008   // parsing error at the cost of lower efficiency. When reflecting a message
1009   // field, use this API instead of checking field->options().lazy().
IsLazyField(const FieldDescriptor * field)1010   bool IsLazyField(const FieldDescriptor* field) const {
1011     return IsLazilyVerifiedLazyField(field) ||
1012            IsEagerlyVerifiedLazyField(field);
1013   }
1014 
1015   // Returns true if the field is lazy extension. It is meant to allow python
1016   // reparse lazy field until b/157559327 is fixed.
1017   bool IsLazyExtension(const Message& message,
1018                        const FieldDescriptor* field) const;
1019 
1020   bool IsLazilyVerifiedLazyField(const FieldDescriptor* field) const;
1021   bool IsEagerlyVerifiedLazyField(const FieldDescriptor* field) const;
1022 
1023   friend class FastReflectionMessageMutator;
1024 
1025   const Descriptor* const descriptor_;
1026   const internal::ReflectionSchema schema_;
1027   const DescriptorPool* const descriptor_pool_;
1028   MessageFactory* const message_factory_;
1029 
1030   // Last non weak field index. This is an optimization when most weak fields
1031   // are at the end of the containing message. If a message proto doesn't
1032   // contain weak fields, then this field equals descriptor_->field_count().
1033   int last_non_weak_field_index_;
1034 
1035   template <typename T, typename Enable>
1036   friend class RepeatedFieldRef;
1037   template <typename T, typename Enable>
1038   friend class MutableRepeatedFieldRef;
1039   friend class ::PROTOBUF_NAMESPACE_ID::MessageLayoutInspector;
1040   friend class ::PROTOBUF_NAMESPACE_ID::AssignDescriptorsHelper;
1041   friend class DynamicMessageFactory;
1042   friend class GeneratedMessageReflectionTestHelper;
1043   friend class python::MapReflectionFriend;
1044   friend class python::MessageReflectionFriend;
1045   friend class util::MessageDifferencer;
1046 #define GOOGLE_PROTOBUF_HAS_CEL_MAP_REFLECTION_FRIEND
1047   friend class expr::CelMapReflectionFriend;
1048   friend class internal::MapFieldReflectionTest;
1049   friend class internal::MapKeySorter;
1050   friend class internal::WireFormat;
1051   friend class internal::ReflectionOps;
1052   friend class internal::SwapFieldHelper;
1053   // Needed for implementing text format for map.
1054   friend class internal::MapFieldPrinterHelper;
1055 
1056   Reflection(const Descriptor* descriptor,
1057              const internal::ReflectionSchema& schema,
1058              const DescriptorPool* pool, MessageFactory* factory);
1059 
1060   // Special version for specialized implementations of string.  We can't
1061   // call MutableRawRepeatedField directly here because we don't have access to
1062   // FieldOptions::* which are defined in descriptor.pb.h.  Including that
1063   // file here is not possible because it would cause a circular include cycle.
1064   // We use 1 routine rather than 2 (const vs mutable) because it is private
1065   // and mutable a repeated string field doesn't change the message.
1066   void* MutableRawRepeatedString(Message* message, const FieldDescriptor* field,
1067                                  bool is_string) const;
1068 
1069   friend class MapReflectionTester;
1070   // Returns true if key is in map. Returns false if key is not in map field.
1071   bool ContainsMapKey(const Message& message, const FieldDescriptor* field,
1072                       const MapKey& key) const;
1073 
1074   // If key is in map field: Saves the value pointer to val and returns
1075   // false. If key in not in map field: Insert the key into map, saves
1076   // value pointer to val and returns true. Users are able to modify the
1077   // map value by MapValueRef.
1078   bool InsertOrLookupMapValue(Message* message, const FieldDescriptor* field,
1079                               const MapKey& key, MapValueRef* val) const;
1080 
1081   // If key is in map field: Saves the value pointer to val and returns true.
1082   // Returns false if key is not in map field. Users are NOT able to modify
1083   // the value by MapValueConstRef.
1084   bool LookupMapValue(const Message& message, const FieldDescriptor* field,
1085                       const MapKey& key, MapValueConstRef* val) const;
1086   bool LookupMapValue(const Message&, const FieldDescriptor*, const MapKey&,
1087                       MapValueRef*) const = delete;
1088 
1089   // Delete and returns true if key is in the map field. Returns false
1090   // otherwise.
1091   bool DeleteMapValue(Message* message, const FieldDescriptor* field,
1092                       const MapKey& key) const;
1093 
1094   // Returns a MapIterator referring to the first element in the map field.
1095   // If the map field is empty, this function returns the same as
1096   // reflection::MapEnd. Mutation to the field may invalidate the iterator.
1097   MapIterator MapBegin(Message* message, const FieldDescriptor* field) const;
1098 
1099   // Returns a MapIterator referring to the theoretical element that would
1100   // follow the last element in the map field. It does not point to any
1101   // real element. Mutation to the field may invalidate the iterator.
1102   MapIterator MapEnd(Message* message, const FieldDescriptor* field) const;
1103 
1104   // Get the number of <key, value> pair of a map field. The result may be
1105   // different from FieldSize which can have duplicate keys.
1106   int MapSize(const Message& message, const FieldDescriptor* field) const;
1107 
1108   // Help method for MapIterator.
1109   friend class MapIterator;
1110   friend class WireFormatForMapFieldTest;
1111   internal::MapFieldBase* MutableMapData(Message* message,
1112                                          const FieldDescriptor* field) const;
1113 
1114   const internal::MapFieldBase* GetMapData(const Message& message,
1115                                            const FieldDescriptor* field) const;
1116 
1117   template <class T>
1118   const T& GetRawNonOneof(const Message& message,
1119                           const FieldDescriptor* field) const;
1120   template <class T>
1121   T* MutableRawNonOneof(Message* message, const FieldDescriptor* field) const;
1122 
1123   template <typename Type>
1124   const Type& GetRaw(const Message& message,
1125                      const FieldDescriptor* field) const;
1126   template <typename Type>
1127   inline Type* MutableRaw(Message* message, const FieldDescriptor* field) const;
1128   template <typename Type>
1129   const Type& DefaultRaw(const FieldDescriptor* field) const;
1130 
1131   const Message* GetDefaultMessageInstance(const FieldDescriptor* field) const;
1132 
1133   inline const uint32_t* GetHasBits(const Message& message) const;
1134   inline uint32_t* MutableHasBits(Message* message) const;
1135   inline uint32_t GetOneofCase(const Message& message,
1136                                const OneofDescriptor* oneof_descriptor) const;
1137   inline uint32_t* MutableOneofCase(
1138       Message* message, const OneofDescriptor* oneof_descriptor) const;
HasExtensionSet(const Message &)1139   inline bool HasExtensionSet(const Message& /* message */) const {
1140     return schema_.HasExtensionSet();
1141   }
1142   const internal::ExtensionSet& GetExtensionSet(const Message& message) const;
1143   internal::ExtensionSet* MutableExtensionSet(Message* message) const;
1144 
1145   const internal::InternalMetadata& GetInternalMetadata(
1146       const Message& message) const;
1147 
1148   internal::InternalMetadata* MutableInternalMetadata(Message* message) const;
1149 
1150   inline bool IsInlined(const FieldDescriptor* field) const;
1151 
1152   inline bool HasBit(const Message& message,
1153                      const FieldDescriptor* field) const;
1154   inline void SetBit(Message* message, const FieldDescriptor* field) const;
1155   inline void ClearBit(Message* message, const FieldDescriptor* field) const;
1156   inline void SwapBit(Message* message1, Message* message2,
1157                       const FieldDescriptor* field) const;
1158 
1159   inline const uint32_t* GetInlinedStringDonatedArray(
1160       const Message& message) const;
1161   inline uint32_t* MutableInlinedStringDonatedArray(Message* message) const;
1162   inline bool IsInlinedStringDonated(const Message& message,
1163                                      const FieldDescriptor* field) const;
1164   inline void SwapInlinedStringDonated(Message* lhs, Message* rhs,
1165                                        const FieldDescriptor* field) const;
1166 
1167   // Shallow-swap fields listed in fields vector of two messages. It is the
1168   // caller's responsibility to make sure shallow swap is safe.
1169   void UnsafeShallowSwapFields(
1170       Message* message1, Message* message2,
1171       const std::vector<const FieldDescriptor*>& fields) const;
1172 
1173   // This function only swaps the field. Should swap corresponding has_bit
1174   // before or after using this function.
1175   void SwapField(Message* message1, Message* message2,
1176                  const FieldDescriptor* field) const;
1177 
1178   // Unsafe but shallow version of SwapField.
1179   void UnsafeShallowSwapField(Message* message1, Message* message2,
1180                               const FieldDescriptor* field) const;
1181 
1182   template <bool unsafe_shallow_swap>
1183   void SwapFieldsImpl(Message* message1, Message* message2,
1184                       const std::vector<const FieldDescriptor*>& fields) const;
1185 
1186   template <bool unsafe_shallow_swap>
1187   void SwapOneofField(Message* lhs, Message* rhs,
1188                       const OneofDescriptor* oneof_descriptor) const;
1189 
1190   inline bool HasOneofField(const Message& message,
1191                             const FieldDescriptor* field) const;
1192   inline void SetOneofCase(Message* message,
1193                            const FieldDescriptor* field) const;
1194   inline void ClearOneofField(Message* message,
1195                               const FieldDescriptor* field) const;
1196 
1197   template <typename Type>
1198   inline const Type& GetField(const Message& message,
1199                               const FieldDescriptor* field) const;
1200   template <typename Type>
1201   inline void SetField(Message* message, const FieldDescriptor* field,
1202                        const Type& value) const;
1203   template <typename Type>
1204   inline Type* MutableField(Message* message,
1205                             const FieldDescriptor* field) const;
1206   template <typename Type>
1207   inline const Type& GetRepeatedField(const Message& message,
1208                                       const FieldDescriptor* field,
1209                                       int index) const;
1210   template <typename Type>
1211   inline const Type& GetRepeatedPtrField(const Message& message,
1212                                          const FieldDescriptor* field,
1213                                          int index) const;
1214   template <typename Type>
1215   inline void SetRepeatedField(Message* message, const FieldDescriptor* field,
1216                                int index, Type value) const;
1217   template <typename Type>
1218   inline Type* MutableRepeatedField(Message* message,
1219                                     const FieldDescriptor* field,
1220                                     int index) const;
1221   template <typename Type>
1222   inline void AddField(Message* message, const FieldDescriptor* field,
1223                        const Type& value) const;
1224   template <typename Type>
1225   inline Type* AddField(Message* message, const FieldDescriptor* field) const;
1226 
1227   int GetExtensionNumberOrDie(const Descriptor* type) const;
1228 
1229   // Internal versions of EnumValue API perform no checking. Called after checks
1230   // by public methods.
1231   void SetEnumValueInternal(Message* message, const FieldDescriptor* field,
1232                             int value) const;
1233   void SetRepeatedEnumValueInternal(Message* message,
1234                                     const FieldDescriptor* field, int index,
1235                                     int value) const;
1236   void AddEnumValueInternal(Message* message, const FieldDescriptor* field,
1237                             int value) const;
1238 
1239   friend inline  // inline so nobody can call this function.
1240       void
1241       RegisterAllTypesInternal(const Metadata* file_level_metadata, int size);
1242   friend inline const char* ParseLenDelim(int field_number,
1243                                           const FieldDescriptor* field,
1244                                           Message* msg,
1245                                           const Reflection* reflection,
1246                                           const char* ptr,
1247                                           internal::ParseContext* ctx);
1248   friend inline const char* ParsePackedField(const FieldDescriptor* field,
1249                                              Message* msg,
1250                                              const Reflection* reflection,
1251                                              const char* ptr,
1252                                              internal::ParseContext* ctx);
1253 
1254   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection);
1255 };
1256 
1257 // Abstract interface for a factory for message objects.
1258 class PROTOBUF_EXPORT MessageFactory {
1259  public:
MessageFactory()1260   inline MessageFactory() {}
1261   virtual ~MessageFactory();
1262 
1263   // Given a Descriptor, gets or constructs the default (prototype) Message
1264   // of that type.  You can then call that message's New() method to construct
1265   // a mutable message of that type.
1266   //
1267   // Calling this method twice with the same Descriptor returns the same
1268   // object.  The returned object remains property of the factory.  Also, any
1269   // objects created by calling the prototype's New() method share some data
1270   // with the prototype, so these must be destroyed before the MessageFactory
1271   // is destroyed.
1272   //
1273   // The given descriptor must outlive the returned message, and hence must
1274   // outlive the MessageFactory.
1275   //
1276   // Some implementations do not support all types.  GetPrototype() will
1277   // return nullptr if the descriptor passed in is not supported.
1278   //
1279   // This method may or may not be thread-safe depending on the implementation.
1280   // Each implementation should document its own degree thread-safety.
1281   virtual const Message* GetPrototype(const Descriptor* type) = 0;
1282 
1283   // Gets a MessageFactory which supports all generated, compiled-in messages.
1284   // In other words, for any compiled-in type FooMessage, the following is true:
1285   //   MessageFactory::generated_factory()->GetPrototype(
1286   //     FooMessage::descriptor()) == FooMessage::default_instance()
1287   // This factory supports all types which are found in
1288   // DescriptorPool::generated_pool().  If given a descriptor from any other
1289   // pool, GetPrototype() will return nullptr.  (You can also check if a
1290   // descriptor is for a generated message by checking if
1291   // descriptor->file()->pool() == DescriptorPool::generated_pool().)
1292   //
1293   // This factory is 100% thread-safe; calling GetPrototype() does not modify
1294   // any shared data.
1295   //
1296   // This factory is a singleton.  The caller must not delete the object.
1297   static MessageFactory* generated_factory();
1298 
1299   // For internal use only:  Registers a .proto file at static initialization
1300   // time, to be placed in generated_factory.  The first time GetPrototype()
1301   // is called with a descriptor from this file, |register_messages| will be
1302   // called, with the file name as the parameter.  It must call
1303   // InternalRegisterGeneratedMessage() (below) to register each message type
1304   // in the file.  This strange mechanism is necessary because descriptors are
1305   // built lazily, so we can't register types by their descriptor until we
1306   // know that the descriptor exists.  |filename| must be a permanent string.
1307   static void InternalRegisterGeneratedFile(
1308       const google::protobuf::internal::DescriptorTable* table);
1309 
1310   // For internal use only:  Registers a message type.  Called only by the
1311   // functions which are registered with InternalRegisterGeneratedFile(),
1312   // above.
1313   static void InternalRegisterGeneratedMessage(const Descriptor* descriptor,
1314                                                const Message* prototype);
1315 
1316 
1317  private:
1318   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory);
1319 };
1320 
1321 #define DECLARE_GET_REPEATED_FIELD(TYPE)                           \
1322   template <>                                                      \
1323   PROTOBUF_EXPORT const RepeatedField<TYPE>&                       \
1324   Reflection::GetRepeatedFieldInternal<TYPE>(                      \
1325       const Message& message, const FieldDescriptor* field) const; \
1326                                                                    \
1327   template <>                                                      \
1328   PROTOBUF_EXPORT RepeatedField<TYPE>*                             \
1329   Reflection::MutableRepeatedFieldInternal<TYPE>(                  \
1330       Message * message, const FieldDescriptor* field) const;
1331 
1332 DECLARE_GET_REPEATED_FIELD(int32_t)
DECLARE_GET_REPEATED_FIELD(int64_t)1333 DECLARE_GET_REPEATED_FIELD(int64_t)
1334 DECLARE_GET_REPEATED_FIELD(uint32_t)
1335 DECLARE_GET_REPEATED_FIELD(uint64_t)
1336 DECLARE_GET_REPEATED_FIELD(float)
1337 DECLARE_GET_REPEATED_FIELD(double)
1338 DECLARE_GET_REPEATED_FIELD(bool)
1339 
1340 #undef DECLARE_GET_REPEATED_FIELD
1341 
1342 // Tries to downcast this message to a generated message type.  Returns nullptr
1343 // if this class is not an instance of T.  This works even if RTTI is disabled.
1344 //
1345 // This also has the effect of creating a strong reference to T that will
1346 // prevent the linker from stripping it out at link time.  This can be important
1347 // if you are using a DynamicMessageFactory that delegates to the generated
1348 // factory.
1349 template <typename T>
1350 const T* DynamicCastToGenerated(const Message* from) {
1351   // Compile-time assert that T is a generated type that has a
1352   // default_instance() accessor, but avoid actually calling it.
1353   const T& (*get_default_instance)() = &T::default_instance;
1354   (void)get_default_instance;
1355 
1356   // Compile-time assert that T is a subclass of google::protobuf::Message.
1357   const Message* unused = static_cast<T*>(nullptr);
1358   (void)unused;
1359 
1360 #if PROTOBUF_RTTI
1361   return dynamic_cast<const T*>(from);
1362 #else
1363   bool ok = from != nullptr &&
1364             T::default_instance().GetReflection() == from->GetReflection();
1365   return ok ? down_cast<const T*>(from) : nullptr;
1366 #endif
1367 }
1368 
1369 template <typename T>
DynamicCastToGenerated(Message * from)1370 T* DynamicCastToGenerated(Message* from) {
1371   const Message* message_const = from;
1372   return const_cast<T*>(DynamicCastToGenerated<T>(message_const));
1373 }
1374 
1375 // Call this function to ensure that this message's reflection is linked into
1376 // the binary:
1377 //
1378 //   google::protobuf::LinkMessageReflection<pkg::FooMessage>();
1379 //
1380 // This will ensure that the following lookup will succeed:
1381 //
1382 //   DescriptorPool::generated_pool()->FindMessageTypeByName("pkg.FooMessage");
1383 //
1384 // As a side-effect, it will also guarantee that anything else from the same
1385 // .proto file will also be available for lookup in the generated pool.
1386 //
1387 // This function does not actually register the message, so it does not need
1388 // to be called before the lookup.  However it does need to occur in a function
1389 // that cannot be stripped from the binary (ie. it must be reachable from main).
1390 //
1391 // Best practice is to call this function as close as possible to where the
1392 // reflection is actually needed.  This function is very cheap to call, so you
1393 // should not need to worry about its runtime overhead except in the tightest
1394 // of loops (on x86-64 it compiles into two "mov" instructions).
1395 template <typename T>
LinkMessageReflection()1396 void LinkMessageReflection() {
1397   internal::StrongReference(T::default_instance);
1398 }
1399 
1400 // =============================================================================
1401 // Implementation details for {Get,Mutable}RawRepeatedPtrField.  We provide
1402 // specializations for <std::string>, <StringPieceField> and <Message> and
1403 // handle everything else with the default template which will match any type
1404 // having a method with signature "static const google::protobuf::Descriptor*
1405 // descriptor()". Such a type presumably is a descendant of google::protobuf::Message.
1406 
1407 template <>
1408 inline const RepeatedPtrField<std::string>&
1409 Reflection::GetRepeatedPtrFieldInternal<std::string>(
1410     const Message& message, const FieldDescriptor* field) const {
1411   return *static_cast<RepeatedPtrField<std::string>*>(
1412       MutableRawRepeatedString(const_cast<Message*>(&message), field, true));
1413 }
1414 
1415 template <>
1416 inline RepeatedPtrField<std::string>*
1417 Reflection::MutableRepeatedPtrFieldInternal<std::string>(
1418     Message* message, const FieldDescriptor* field) const {
1419   return static_cast<RepeatedPtrField<std::string>*>(
1420       MutableRawRepeatedString(message, field, true));
1421 }
1422 
1423 
1424 // -----
1425 
1426 template <>
GetRepeatedPtrFieldInternal(const Message & message,const FieldDescriptor * field)1427 inline const RepeatedPtrField<Message>& Reflection::GetRepeatedPtrFieldInternal(
1428     const Message& message, const FieldDescriptor* field) const {
1429   return *static_cast<const RepeatedPtrField<Message>*>(GetRawRepeatedField(
1430       message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1431 }
1432 
1433 template <>
MutableRepeatedPtrFieldInternal(Message * message,const FieldDescriptor * field)1434 inline RepeatedPtrField<Message>* Reflection::MutableRepeatedPtrFieldInternal(
1435     Message* message, const FieldDescriptor* field) const {
1436   return static_cast<RepeatedPtrField<Message>*>(MutableRawRepeatedField(
1437       message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1, nullptr));
1438 }
1439 
1440 template <typename PB>
GetRepeatedPtrFieldInternal(const Message & message,const FieldDescriptor * field)1441 inline const RepeatedPtrField<PB>& Reflection::GetRepeatedPtrFieldInternal(
1442     const Message& message, const FieldDescriptor* field) const {
1443   return *static_cast<const RepeatedPtrField<PB>*>(
1444       GetRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE, -1,
1445                           PB::default_instance().GetDescriptor()));
1446 }
1447 
1448 template <typename PB>
MutableRepeatedPtrFieldInternal(Message * message,const FieldDescriptor * field)1449 inline RepeatedPtrField<PB>* Reflection::MutableRepeatedPtrFieldInternal(
1450     Message* message, const FieldDescriptor* field) const {
1451   return static_cast<RepeatedPtrField<PB>*>(
1452       MutableRawRepeatedField(message, field, FieldDescriptor::CPPTYPE_MESSAGE,
1453                               -1, PB::default_instance().GetDescriptor()));
1454 }
1455 
1456 template <typename Type>
DefaultRaw(const FieldDescriptor * field)1457 const Type& Reflection::DefaultRaw(const FieldDescriptor* field) const {
1458   return *reinterpret_cast<const Type*>(schema_.GetFieldDefault(field));
1459 }
1460 
GetOneofCase(const Message & message,const OneofDescriptor * oneof_descriptor)1461 uint32_t Reflection::GetOneofCase(
1462     const Message& message, const OneofDescriptor* oneof_descriptor) const {
1463   GOOGLE_DCHECK(!oneof_descriptor->is_synthetic());
1464   return internal::GetConstRefAtOffset<uint32_t>(
1465       message, schema_.GetOneofCaseOffset(oneof_descriptor));
1466 }
1467 
HasOneofField(const Message & message,const FieldDescriptor * field)1468 bool Reflection::HasOneofField(const Message& message,
1469                                const FieldDescriptor* field) const {
1470   return (GetOneofCase(message, field->containing_oneof()) ==
1471           static_cast<uint32_t>(field->number()));
1472 }
1473 
1474 template <typename Type>
GetRaw(const Message & message,const FieldDescriptor * field)1475 const Type& Reflection::GetRaw(const Message& message,
1476                                const FieldDescriptor* field) const {
1477   GOOGLE_DCHECK(!schema_.InRealOneof(field) || HasOneofField(message, field))
1478       << "Field = " << field->full_name();
1479   return internal::GetConstRefAtOffset<Type>(message,
1480                                              schema_.GetFieldOffset(field));
1481 }
1482 }  // namespace protobuf
1483 }  // namespace google
1484 
1485 #include <google/protobuf/port_undef.inc>
1486 
1487 #endif  // GOOGLE_PROTOBUF_MESSAGE_H__
1488