Coverage Report

Created: 2024-07-27 06:53

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