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