/
coded_stream.h
1718 lines (1515 loc) · 67.8 KB
/
coded_stream.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file contains the CodedInputStream and CodedOutputStream classes,
// which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively,
// and allow you to read or write individual pieces of data in various
// formats. In particular, these implement the varint encoding for
// integers, a simple variable-length encoding in which smaller numbers
// take fewer bytes.
//
// Typically these classes will only be used internally by the protocol
// buffer library in order to encode and decode protocol buffers. Clients
// of the library only need to know about this class if they wish to write
// custom message parsing or serialization procedures.
//
// CodedOutputStream example:
// // Write some data to "myfile". First we write a 4-byte "magic number"
// // to identify the file type, then write a length-delimited string. The
// // string is composed of a varint giving the length followed by the raw
// // bytes.
// int fd = open("myfile", O_CREAT | O_WRONLY);
// ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
// CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
//
// int magic_number = 1234;
// char text[] = "Hello world!";
// coded_output->WriteLittleEndian32(magic_number);
// coded_output->WriteVarint32(strlen(text));
// coded_output->WriteRaw(text, strlen(text));
//
// delete coded_output;
// delete raw_output;
// close(fd);
//
// CodedInputStream example:
// // Read a file created by the above code.
// int fd = open("myfile", O_RDONLY);
// ZeroCopyInputStream* raw_input = new FileInputStream(fd);
// CodedInputStream* coded_input = new CodedInputStream(raw_input);
//
// coded_input->ReadLittleEndian32(&magic_number);
// if (magic_number != 1234) {
// cerr << "File not in expected format." << endl;
// return;
// }
//
// uint32 size;
// coded_input->ReadVarint32(&size);
//
// char* text = new char[size + 1];
// coded_input->ReadRaw(buffer, size);
// text[size] = '\0';
//
// delete coded_input;
// delete raw_input;
// close(fd);
//
// cout << "Text is: " << text << endl;
// delete [] text;
//
// For those who are interested, varint encoding is defined as follows:
//
// The encoding operates on unsigned integers of up to 64 bits in length.
// Each byte of the encoded value has the format:
// * bits 0-6: Seven bits of the number being encoded.
// * bit 7: Zero if this is the last byte in the encoding (in which
// case all remaining bits of the number are zero) or 1 if
// more bytes follow.
// The first byte contains the least-significant 7 bits of the number, the
// second byte (if present) contains the next-least-significant 7 bits,
// and so on. So, the binary number 1011000101011 would be encoded in two
// bytes as "10101011 00101100".
//
// In theory, varint could be used to encode integers of any length.
// However, for practicality we set a limit at 64 bits. The maximum encoded
// length of a number is thus 10 bytes.
#ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
#define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__
#include <assert.h>
#include <atomic>
#include <climits>
#include <cstddef>
#include <cstring>
#include <string>
#include <type_traits>
#include <utility>
#ifdef _WIN32
// Assuming windows is always little-endian.
#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER)
// If MSVC has "/RTCc" set, it will complain about truncating casts at
// runtime. This file contains some intentional truncating casts.
#pragma runtime_checks("c", off)
#endif
#else
#ifdef __APPLE__
#include <machine/endian.h> // __BYTE_ORDER
#else
#include <endian.h> // __BYTE_ORDER
#endif
#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \
(defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \
!defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST)
#define PROTOBUF_LITTLE_ENDIAN 1
#endif
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/port.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/port_def.inc>
namespace google {
namespace protobuf {
class DescriptorPool;
class MessageFactory;
class ZeroCopyCodedInputStream;
namespace internal {
void MapTestForceDeterministic();
class EpsCopyByteStream;
} // namespace internal
namespace io {
// Defined in this file.
class CodedInputStream;
class CodedOutputStream;
// Defined in other files.
class ZeroCopyInputStream; // zero_copy_stream.h
class ZeroCopyOutputStream; // zero_copy_stream.h
// Class which reads and decodes binary data which is composed of varint-
// encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream.
// Most users will not need to deal with CodedInputStream.
//
// Most methods of CodedInputStream that return a bool return false if an
// underlying I/O error occurs or if the data is malformed. Once such a
// failure occurs, the CodedInputStream is broken and is no longer useful.
// After a failure, callers also should assume writes to "out" args may have
// occurred, though nothing useful can be determined from those writes.
class PROTOBUF_EXPORT CodedInputStream {
public:
// Create a CodedInputStream that reads from the given ZeroCopyInputStream.
explicit CodedInputStream(ZeroCopyInputStream* input);
// Create a CodedInputStream that reads from the given flat array. This is
// faster than using an ArrayInputStream. PushLimit(size) is implied by
// this constructor.
explicit CodedInputStream(const uint8* buffer, int size);
// Destroy the CodedInputStream and position the underlying
// ZeroCopyInputStream at the first unread byte. If an error occurred while
// reading (causing a method to return false), then the exact position of
// the input stream may be anywhere between the last value that was read
// successfully and the stream's byte limit.
~CodedInputStream();
// Return true if this CodedInputStream reads from a flat array instead of
// a ZeroCopyInputStream.
inline bool IsFlat() const;
// Skips a number of bytes. Returns false if an underlying read error
// occurs.
inline bool Skip(int count);
// Sets *data to point directly at the unread part of the CodedInputStream's
// underlying buffer, and *size to the size of that buffer, but does not
// advance the stream's current position. This will always either produce
// a non-empty buffer or return false. If the caller consumes any of
// this data, it should then call Skip() to skip over the consumed bytes.
// This may be useful for implementing external fast parsing routines for
// types of data not covered by the CodedInputStream interface.
bool GetDirectBufferPointer(const void** data, int* size);
// Like GetDirectBufferPointer, but this method is inlined, and does not
// attempt to Refresh() if the buffer is currently empty.
PROTOBUF_ALWAYS_INLINE
void GetDirectBufferPointerInline(const void** data, int* size);
// Read raw bytes, copying them into the given buffer.
bool ReadRaw(void* buffer, int size);
// Like ReadRaw, but reads into a string.
bool ReadString(std::string* buffer, int size);
// Read a 32-bit little-endian integer.
bool ReadLittleEndian32(uint32* value);
// Read a 64-bit little-endian integer.
bool ReadLittleEndian64(uint64* value);
// These methods read from an externally provided buffer. The caller is
// responsible for ensuring that the buffer has sufficient space.
// Read a 32-bit little-endian integer.
static const uint8* ReadLittleEndian32FromArray(const uint8* buffer,
uint32* value);
// Read a 64-bit little-endian integer.
static const uint8* ReadLittleEndian64FromArray(const uint8* buffer,
uint64* value);
// Read an unsigned integer with Varint encoding, truncating to 32 bits.
// Reading a 32-bit value is equivalent to reading a 64-bit one and casting
// it to uint32, but may be more efficient.
bool ReadVarint32(uint32* value);
// Read an unsigned integer with Varint encoding.
bool ReadVarint64(uint64* value);
// Reads a varint off the wire into an "int". This should be used for reading
// sizes off the wire (sizes of strings, submessages, bytes fields, etc).
//
// The value from the wire is interpreted as unsigned. If its value exceeds
// the representable value of an integer on this platform, instead of
// truncating we return false. Truncating (as performed by ReadVarint32()
// above) is an acceptable approach for fields representing an integer, but
// when we are parsing a size from the wire, truncating the value would result
// in us misparsing the payload.
bool ReadVarintSizeAsInt(int* value);
// Read a tag. This calls ReadVarint32() and returns the result, or returns
// zero (which is not a valid tag) if ReadVarint32() fails. Also, ReadTag
// (but not ReadTagNoLastTag) updates the last tag value, which can be checked
// with LastTagWas().
//
// Always inline because this is only called in one place per parse loop
// but it is called for every iteration of said loop, so it should be fast.
// GCC doesn't want to inline this by default.
PROTOBUF_ALWAYS_INLINE uint32 ReadTag() {
return last_tag_ = ReadTagNoLastTag();
}
PROTOBUF_ALWAYS_INLINE uint32 ReadTagNoLastTag();
// This usually a faster alternative to ReadTag() when cutoff is a manifest
// constant. It does particularly well for cutoff >= 127. The first part
// of the return value is the tag that was read, though it can also be 0 in
// the cases where ReadTag() would return 0. If the second part is true
// then the tag is known to be in [0, cutoff]. If not, the tag either is
// above cutoff or is 0. (There's intentional wiggle room when tag is 0,
// because that can arise in several ways, and for best performance we want
// to avoid an extra "is tag == 0?" check here.)
PROTOBUF_ALWAYS_INLINE
std::pair<uint32, bool> ReadTagWithCutoff(uint32 cutoff) {
std::pair<uint32, bool> result = ReadTagWithCutoffNoLastTag(cutoff);
last_tag_ = result.first;
return result;
}
PROTOBUF_ALWAYS_INLINE
std::pair<uint32, bool> ReadTagWithCutoffNoLastTag(uint32 cutoff);
// Usually returns true if calling ReadVarint32() now would produce the given
// value. Will always return false if ReadVarint32() would not return the
// given value. If ExpectTag() returns true, it also advances past
// the varint. For best performance, use a compile-time constant as the
// parameter.
// Always inline because this collapses to a small number of instructions
// when given a constant parameter, but GCC doesn't want to inline by default.
PROTOBUF_ALWAYS_INLINE bool ExpectTag(uint32 expected);
// Like above, except this reads from the specified buffer. The caller is
// responsible for ensuring that the buffer is large enough to read a varint
// of the expected size. For best performance, use a compile-time constant as
// the expected tag parameter.
//
// Returns a pointer beyond the expected tag if it was found, or NULL if it
// was not.
PROTOBUF_ALWAYS_INLINE
static const uint8* ExpectTagFromArray(const uint8* buffer, uint32 expected);
// Usually returns true if no more bytes can be read. Always returns false
// if more bytes can be read. If ExpectAtEnd() returns true, a subsequent
// call to LastTagWas() will act as if ReadTag() had been called and returned
// zero, and ConsumedEntireMessage() will return true.
bool ExpectAtEnd();
// If the last call to ReadTag() or ReadTagWithCutoff() returned the given
// value, returns true. Otherwise, returns false.
// ReadTagNoLastTag/ReadTagWithCutoffNoLastTag do not preserve the last
// returned value.
//
// This is needed because parsers for some types of embedded messages
// (with field type TYPE_GROUP) don't actually know that they've reached the
// end of a message until they see an ENDGROUP tag, which was actually part
// of the enclosing message. The enclosing message would like to check that
// tag to make sure it had the right number, so it calls LastTagWas() on
// return from the embedded parser to check.
bool LastTagWas(uint32 expected);
void SetLastTag(uint32 tag) { last_tag_ = tag; }
// When parsing message (but NOT a group), this method must be called
// immediately after MergeFromCodedStream() returns (if it returns true)
// to further verify that the message ended in a legitimate way. For
// example, this verifies that parsing did not end on an end-group tag.
// It also checks for some cases where, due to optimizations,
// MergeFromCodedStream() can incorrectly return true.
bool ConsumedEntireMessage();
void SetConsumed() { legitimate_message_end_ = true; }
// Limits ----------------------------------------------------------
// Limits are used when parsing length-delimited embedded messages.
// After the message's length is read, PushLimit() is used to prevent
// the CodedInputStream from reading beyond that length. Once the
// embedded message has been parsed, PopLimit() is called to undo the
// limit.
// Opaque type used with PushLimit() and PopLimit(). Do not modify
// values of this type yourself. The only reason that this isn't a
// struct with private internals is for efficiency.
typedef int Limit;
// Places a limit on the number of bytes that the stream may read,
// starting from the current position. Once the stream hits this limit,
// it will act like the end of the input has been reached until PopLimit()
// is called.
//
// As the names imply, the stream conceptually has a stack of limits. The
// shortest limit on the stack is always enforced, even if it is not the
// top limit.
//
// The value returned by PushLimit() is opaque to the caller, and must
// be passed unchanged to the corresponding call to PopLimit().
Limit PushLimit(int byte_limit);
// Pops the last limit pushed by PushLimit(). The input must be the value
// returned by that call to PushLimit().
void PopLimit(Limit limit);
// Returns the number of bytes left until the nearest limit on the
// stack is hit, or -1 if no limits are in place.
int BytesUntilLimit() const;
// Returns current position relative to the beginning of the input stream.
int CurrentPosition() const;
// Total Bytes Limit -----------------------------------------------
// To prevent malicious users from sending excessively large messages
// and causing memory exhaustion, CodedInputStream imposes a hard limit on
// the total number of bytes it will read.
// Sets the maximum number of bytes that this CodedInputStream will read
// before refusing to continue. To prevent servers from allocating enormous
// amounts of memory to hold parsed messages, the maximum message length
// should be limited to the shortest length that will not harm usability.
// The default limit is INT_MAX (~2GB) and apps should set shorter limits
// if possible. An error will always be printed to stderr if the limit is
// reached.
//
// Note: setting a limit less than the current read position is interpreted
// as a limit on the current position.
//
// This is unrelated to PushLimit()/PopLimit().
void SetTotalBytesLimit(int total_bytes_limit);
PROTOBUF_DEPRECATED_MSG(
"Please use the single parameter version of SetTotalBytesLimit(). The "
"second parameter is ignored.")
void SetTotalBytesLimit(int total_bytes_limit, int) {
SetTotalBytesLimit(total_bytes_limit);
}
// The Total Bytes Limit minus the Current Position, or -1 if the total bytes
// limit is INT_MAX.
int BytesUntilTotalBytesLimit() const;
// Recursion Limit -------------------------------------------------
// To prevent corrupt or malicious messages from causing stack overflows,
// we must keep track of the depth of recursion when parsing embedded
// messages and groups. CodedInputStream keeps track of this because it
// is the only object that is passed down the stack during parsing.
// Sets the maximum recursion depth. The default is 100.
void SetRecursionLimit(int limit);
int RecursionBudget() { return recursion_budget_; }
static int GetDefaultRecursionLimit() { return default_recursion_limit_; }
// Increments the current recursion depth. Returns true if the depth is
// under the limit, false if it has gone over.
bool IncrementRecursionDepth();
// Decrements the recursion depth if possible.
void DecrementRecursionDepth();
// Decrements the recursion depth blindly. This is faster than
// DecrementRecursionDepth(). It should be used only if all previous
// increments to recursion depth were successful.
void UnsafeDecrementRecursionDepth();
// Shorthand for make_pair(PushLimit(byte_limit), --recursion_budget_).
// Using this can reduce code size and complexity in some cases. The caller
// is expected to check that the second part of the result is non-negative (to
// bail out if the depth of recursion is too high) and, if all is well, to
// later pass the first part of the result to PopLimit() or similar.
std::pair<CodedInputStream::Limit, int> IncrementRecursionDepthAndPushLimit(
int byte_limit);
// Shorthand for PushLimit(ReadVarint32(&length) ? length : 0).
Limit ReadLengthAndPushLimit();
// Helper that is equivalent to: {
// bool result = ConsumedEntireMessage();
// PopLimit(limit);
// UnsafeDecrementRecursionDepth();
// return result; }
// Using this can reduce code size and complexity in some cases.
// Do not use unless the current recursion depth is greater than zero.
bool DecrementRecursionDepthAndPopLimit(Limit limit);
// Helper that is equivalent to: {
// bool result = ConsumedEntireMessage();
// PopLimit(limit);
// return result; }
// Using this can reduce code size and complexity in some cases.
bool CheckEntireMessageConsumedAndPopLimit(Limit limit);
// Extension Registry ----------------------------------------------
// ADVANCED USAGE: 99.9% of people can ignore this section.
//
// By default, when parsing extensions, the parser looks for extension
// definitions in the pool which owns the outer message's Descriptor.
// However, you may call SetExtensionRegistry() to provide an alternative
// pool instead. This makes it possible, for example, to parse a message
// using a generated class, but represent some extensions using
// DynamicMessage.
// Set the pool used to look up extensions. Most users do not need to call
// this as the correct pool will be chosen automatically.
//
// WARNING: It is very easy to misuse this. Carefully read the requirements
// below. Do not use this unless you are sure you need it. Almost no one
// does.
//
// Let's say you are parsing a message into message object m, and you want
// to take advantage of SetExtensionRegistry(). You must follow these
// requirements:
//
// The given DescriptorPool must contain m->GetDescriptor(). It is not
// sufficient for it to simply contain a descriptor that has the same name
// and content -- it must be the *exact object*. In other words:
// assert(pool->FindMessageTypeByName(m->GetDescriptor()->full_name()) ==
// m->GetDescriptor());
// There are two ways to satisfy this requirement:
// 1) Use m->GetDescriptor()->pool() as the pool. This is generally useless
// because this is the pool that would be used anyway if you didn't call
// SetExtensionRegistry() at all.
// 2) Use a DescriptorPool which has m->GetDescriptor()->pool() as an
// "underlay". Read the documentation for DescriptorPool for more
// information about underlays.
//
// You must also provide a MessageFactory. This factory will be used to
// construct Message objects representing extensions. The factory's
// GetPrototype() MUST return non-NULL for any Descriptor which can be found
// through the provided pool.
//
// If the provided factory might return instances of protocol-compiler-
// generated (i.e. compiled-in) types, or if the outer message object m is
// a generated type, then the given factory MUST have this property: If
// GetPrototype() is given a Descriptor which resides in
// DescriptorPool::generated_pool(), the factory MUST return the same
// prototype which MessageFactory::generated_factory() would return. That
// is, given a descriptor for a generated type, the factory must return an
// instance of the generated class (NOT DynamicMessage). However, when
// given a descriptor for a type that is NOT in generated_pool, the factory
// is free to return any implementation.
//
// The reason for this requirement is that generated sub-objects may be
// accessed via the standard (non-reflection) extension accessor methods,
// and these methods will down-cast the object to the generated class type.
// If the object is not actually of that type, the results would be undefined.
// On the other hand, if an extension is not compiled in, then there is no
// way the code could end up accessing it via the standard accessors -- the
// only way to access the extension is via reflection. When using reflection,
// DynamicMessage and generated messages are indistinguishable, so it's fine
// if these objects are represented using DynamicMessage.
//
// Using DynamicMessageFactory on which you have called
// SetDelegateToGeneratedFactory(true) should be sufficient to satisfy the
// above requirement.
//
// If either pool or factory is NULL, both must be NULL.
//
// Note that this feature is ignored when parsing "lite" messages as they do
// not have descriptors.
void SetExtensionRegistry(const DescriptorPool* pool,
MessageFactory* factory);
// Get the DescriptorPool set via SetExtensionRegistry(), or NULL if no pool
// has been provided.
const DescriptorPool* GetExtensionPool();
// Get the MessageFactory set via SetExtensionRegistry(), or NULL if no
// factory has been provided.
MessageFactory* GetExtensionFactory();
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedInputStream);
const uint8* buffer_;
const uint8* buffer_end_; // pointer to the end of the buffer.
ZeroCopyInputStream* input_;
int total_bytes_read_; // total bytes read from input_, including
// the current buffer
// If total_bytes_read_ surpasses INT_MAX, we record the extra bytes here
// so that we can BackUp() on destruction.
int overflow_bytes_;
// LastTagWas() stuff.
uint32 last_tag_; // result of last ReadTag() or ReadTagWithCutoff().
// This is set true by ReadTag{Fallback/Slow}() if it is called when exactly
// at EOF, or by ExpectAtEnd() when it returns true. This happens when we
// reach the end of a message and attempt to read another tag.
bool legitimate_message_end_;
// See EnableAliasing().
bool aliasing_enabled_;
// Limits
Limit current_limit_; // if position = -1, no limit is applied
// For simplicity, if the current buffer crosses a limit (either a normal
// limit created by PushLimit() or the total bytes limit), buffer_size_
// only tracks the number of bytes before that limit. This field
// contains the number of bytes after it. Note that this implies that if
// buffer_size_ == 0 and buffer_size_after_limit_ > 0, we know we've
// hit a limit. However, if both are zero, it doesn't necessarily mean
// we aren't at a limit -- the buffer may have ended exactly at the limit.
int buffer_size_after_limit_;
// Maximum number of bytes to read, period. This is unrelated to
// current_limit_. Set using SetTotalBytesLimit().
int total_bytes_limit_;
// Current recursion budget, controlled by IncrementRecursionDepth() and
// similar. Starts at recursion_limit_ and goes down: if this reaches
// -1 we are over budget.
int recursion_budget_;
// Recursion depth limit, set by SetRecursionLimit().
int recursion_limit_;
// See SetExtensionRegistry().
const DescriptorPool* extension_pool_;
MessageFactory* extension_factory_;
// Private member functions.
// Fallback when Skip() goes past the end of the current buffer.
bool SkipFallback(int count, int original_buffer_size);
// Advance the buffer by a given number of bytes.
void Advance(int amount);
// Back up input_ to the current buffer position.
void BackUpInputToCurrentPosition();
// Recomputes the value of buffer_size_after_limit_. Must be called after
// current_limit_ or total_bytes_limit_ changes.
void RecomputeBufferLimits();
// Writes an error message saying that we hit total_bytes_limit_.
void PrintTotalBytesLimitError();
// Called when the buffer runs out to request more data. Implies an
// Advance(BufferSize()).
bool Refresh();
// When parsing varints, we optimize for the common case of small values, and
// then optimize for the case when the varint fits within the current buffer
// piece. The Fallback method is used when we can't use the one-byte
// optimization. The Slow method is yet another fallback when the buffer is
// not large enough. Making the slow path out-of-line speeds up the common
// case by 10-15%. The slow path is fairly uncommon: it only triggers when a
// message crosses multiple buffers. Note: ReadVarint32Fallback() and
// ReadVarint64Fallback() are called frequently and generally not inlined, so
// they have been optimized to avoid "out" parameters. The former returns -1
// if it fails and the uint32 it read otherwise. The latter has a bool
// indicating success or failure as part of its return type.
int64 ReadVarint32Fallback(uint32 first_byte_or_zero);
int ReadVarintSizeAsIntFallback();
std::pair<uint64, bool> ReadVarint64Fallback();
bool ReadVarint32Slow(uint32* value);
bool ReadVarint64Slow(uint64* value);
int ReadVarintSizeAsIntSlow();
bool ReadLittleEndian32Fallback(uint32* value);
bool ReadLittleEndian64Fallback(uint64* value);
// Fallback/slow methods for reading tags. These do not update last_tag_,
// but will set legitimate_message_end_ if we are at the end of the input
// stream.
uint32 ReadTagFallback(uint32 first_byte_or_zero);
uint32 ReadTagSlow();
bool ReadStringFallback(std::string* buffer, int size);
// Return the size of the buffer.
int BufferSize() const;
static const int kDefaultTotalBytesLimit = INT_MAX;
static int default_recursion_limit_; // 100 by default.
friend class google::protobuf::ZeroCopyCodedInputStream;
friend class google::protobuf::internal::EpsCopyByteStream;
};
// EpsCopyOutputStream wraps a ZeroCopyOutputStream and exposes a new stream,
// which has the property you can write kSlopBytes (16 bytes) from the current
// position without bounds checks. The cursor into the stream is managed by
// the user of the class and is an explicit parameter in the methods. Careful
// use of this class, ie. keep ptr a local variable, eliminates the need to
// for the compiler to sync the ptr value between register and memory.
class PROTOBUF_EXPORT EpsCopyOutputStream {
public:
enum { kSlopBytes = 16 };
// Initialize from a stream.
EpsCopyOutputStream(ZeroCopyOutputStream* stream, bool deterministic,
uint8** pp)
: end_(buffer_),
stream_(stream),
is_serialization_deterministic_(deterministic) {
*pp = buffer_;
}
// Only for array serialization. No overflow protection, end_ will be the
// pointed to the end of the array. When using this the total size is already
// known, so no need to maintain the slop region.
EpsCopyOutputStream(void* data, int size, bool deterministic)
: end_(static_cast<uint8*>(data) + size),
buffer_end_(nullptr),
stream_(nullptr),
is_serialization_deterministic_(deterministic) {}
// Initialize from stream but with the first buffer already given (eager).
EpsCopyOutputStream(void* data, int size, ZeroCopyOutputStream* stream,
bool deterministic, uint8** pp)
: stream_(stream), is_serialization_deterministic_(deterministic) {
*pp = SetInitialBuffer(data, size);
}
// Flush everything that's written into the underlying ZeroCopyOutputStream
// and trims the underlying stream to the location of ptr.
uint8* Trim(uint8* ptr);
// After this it's guaranteed you can safely write kSlopBytes to ptr. This
// will never fail! The underlying stream can produce an error. Use HadError
// to check for errors.
PROTOBUF_MUST_USE_RESULT uint8* EnsureSpace(uint8* ptr) {
if (PROTOBUF_PREDICT_FALSE(ptr >= end_)) {
return EnsureSpaceFallback(ptr);
}
return ptr;
}
uint8* WriteRaw(const void* data, int size, uint8* ptr) {
if (PROTOBUF_PREDICT_FALSE(end_ - ptr < size)) {
return WriteRawFallback(data, size, ptr);
}
std::memcpy(ptr, data, size);
return ptr + size;
}
// Writes the buffer specified by data, size to the stream. Possibly by
// aliasing the buffer (ie. not copying the data). The caller is responsible
// to make sure the buffer is alive for the duration of the
// ZeroCopyOutputStream.
uint8* WriteRawMaybeAliased(const void* data, int size, uint8* ptr) {
if (aliasing_enabled_) {
return WriteAliasedRaw(data, size, ptr);
} else {
return WriteRaw(data, size, ptr);
}
}
uint8* WriteStringMaybeAliased(uint32 num, const std::string& s, uint8* ptr) {
std::ptrdiff_t size = s.size();
if (PROTOBUF_PREDICT_FALSE(
size >= 128 || end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
return WriteStringMaybeAliasedOutline(num, s, ptr);
}
ptr = UnsafeVarint((num << 3) | 2, ptr);
*ptr++ = static_cast<uint8>(size);
std::memcpy(ptr, s.data(), size);
return ptr + size;
}
uint8* WriteBytesMaybeAliased(uint32 num, const std::string& s, uint8* ptr) {
return WriteStringMaybeAliased(num, s, ptr);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteString(uint32 num, const T& s,
uint8* ptr) {
std::ptrdiff_t size = s.size();
if (PROTOBUF_PREDICT_FALSE(
size >= 128 || end_ - ptr + 16 - TagSize(num << 3) - 1 < size)) {
return WriteStringOutline(num, s, ptr);
}
ptr = UnsafeVarint((num << 3) | 2, ptr);
*ptr++ = static_cast<uint8>(size);
std::memcpy(ptr, s.data(), size);
return ptr + size;
}
template <typename T>
uint8* WriteBytes(uint32 num, const T& s, uint8* ptr) {
return WriteString(num, s, ptr);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteInt32Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, Encode64);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteUInt32Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, Encode32);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteSInt32Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, ZigZagEncode32);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteInt64Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, Encode64);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteUInt64Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, Encode64);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteSInt64Packed(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, ZigZagEncode64);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteEnumPacked(int num, const T& r, int size,
uint8* ptr) {
return WriteVarintPacked(num, r, size, ptr, Encode64);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE uint8* WriteFixedPacked(int num, const T& r,
uint8* ptr) {
ptr = EnsureSpace(ptr);
constexpr auto element_size = sizeof(typename T::value_type);
auto size = r.size() * element_size;
ptr = WriteLengthDelim(num, size, ptr);
return WriteRawLittleEndian<element_size>(r.data(), static_cast<int>(size),
ptr);
}
// Returns true if there was an underlying I/O error since this object was
// created.
bool HadError() const { return had_error_; }
// Instructs the EpsCopyOutputStream to allow the underlying
// ZeroCopyOutputStream to hold pointers to the original structure instead of
// copying, if it supports it (i.e. output->AllowsAliasing() is true). If the
// underlying stream does not support aliasing, then enabling it has no
// affect. For now, this only affects the behavior of
// WriteRawMaybeAliased().
//
// NOTE: It is caller's responsibility to ensure that the chunk of memory
// remains live until all of the data has been consumed from the stream.
void EnableAliasing(bool enabled);
// See documentation on CodedOutputStream::SetSerializationDeterministic.
void SetSerializationDeterministic(bool value) {
is_serialization_deterministic_ = value;
}
// See documentation on CodedOutputStream::IsSerializationDeterministic.
bool IsSerializationDeterministic() const {
return is_serialization_deterministic_;
}
// The number of bytes written to the stream at position ptr, relative to the
// stream's overall position.
int64 ByteCount(uint8* ptr) const;
private:
uint8* end_;
uint8* buffer_end_ = buffer_;
uint8 buffer_[2 * kSlopBytes];
ZeroCopyOutputStream* stream_;
bool had_error_ = false;
bool aliasing_enabled_ = false; // See EnableAliasing().
bool is_serialization_deterministic_;
uint8* EnsureSpaceFallback(uint8* ptr);
inline uint8* Next();
int Flush(uint8* ptr);
std::ptrdiff_t GetSize(uint8* ptr) const {
GOOGLE_DCHECK(ptr <= end_ + kSlopBytes); // NOLINT
return end_ + kSlopBytes - ptr;
}
uint8* Error() {
had_error_ = true;
// We use the patch buffer to always guarantee space to write to.
end_ = buffer_ + kSlopBytes;
return buffer_;
}
static constexpr int TagSize(uint32 tag) {
return (tag < (1 << 7))
? 1
: (tag < (1 << 14))
? 2
: (tag < (1 << 21)) ? 3 : (tag < (1 << 28)) ? 4 : 5;
}
PROTOBUF_ALWAYS_INLINE uint8* WriteTag(uint32 num, uint32 wt, uint8* ptr) {
GOOGLE_DCHECK(ptr < end_); // NOLINT
return UnsafeVarint((num << 3) | wt, ptr);
}
PROTOBUF_ALWAYS_INLINE uint8* WriteLengthDelim(int num, uint32 size,
uint8* ptr) {
ptr = WriteTag(num, 2, ptr);
return UnsafeWriteSize(size, ptr);
}
uint8* WriteRawFallback(const void* data, int size, uint8* ptr);
uint8* WriteAliasedRaw(const void* data, int size, uint8* ptr);
uint8* WriteStringMaybeAliasedOutline(uint32 num, const std::string& s,
uint8* ptr);
uint8* WriteStringOutline(uint32 num, const std::string& s, uint8* ptr);
template <typename T, typename E>
PROTOBUF_ALWAYS_INLINE uint8* WriteVarintPacked(int num, const T& r, int size,
uint8* ptr, const E& encode) {
ptr = EnsureSpace(ptr);
ptr = WriteLengthDelim(num, size, ptr);
auto it = r.data();
auto end = it + r.size();
do {
ptr = EnsureSpace(ptr);
ptr = UnsafeVarint(encode(*it++), ptr);
} while (it < end);
return ptr;
}
static uint32 Encode32(uint32 v) { return v; }
static uint64 Encode64(uint64 v) { return v; }
static uint32 ZigZagEncode32(int32 v) {
return (static_cast<uint32>(v) << 1) ^ static_cast<uint32>(v >> 31);
}
static uint64 ZigZagEncode64(int64 v) {
return (static_cast<uint64>(v) << 1) ^ static_cast<uint64>(v >> 63);
}
template <typename T>
PROTOBUF_ALWAYS_INLINE static uint8* UnsafeVarint(T value, uint8* ptr) {
static_assert(std::is_unsigned<T>::value,
"Varint serialization must be unsigned");
if (value < 0x80) {
ptr[0] = static_cast<uint8>(value);
return ptr + 1;
}
ptr[0] = static_cast<uint8>(value | 0x80);
value >>= 7;
if (value < 0x80) {
ptr[1] = static_cast<uint8>(value);
return ptr + 2;
}
ptr++;
do {
*ptr = static_cast<uint8>(value | 0x80);
value >>= 7;
++ptr;
} while (PROTOBUF_PREDICT_FALSE(value >= 0x80));
*ptr++ = static_cast<uint8>(value);
return ptr;
}
PROTOBUF_ALWAYS_INLINE static uint8* UnsafeWriteSize(uint32 value,
uint8* ptr) {
while (PROTOBUF_PREDICT_FALSE(value >= 0x80)) {
*ptr = static_cast<uint8>(value | 0x80);
value >>= 7;
++ptr;
}
*ptr++ = static_cast<uint8>(value);
return ptr;
}
template <int S>
uint8* WriteRawLittleEndian(const void* data, int size, uint8* ptr);
#ifndef PROTOBUF_LITTLE_ENDIAN
uint8* WriteRawLittleEndian32(const void* data, int size, uint8* ptr);
uint8* WriteRawLittleEndian64(const void* data, int size, uint8* ptr);
#endif
// These methods are for CodedOutputStream. Ideally they should be private
// but to match current behavior of CodedOutputStream as close as possible
// we allow it some functionality.
public:
uint8* SetInitialBuffer(void* data, int size) {
auto ptr = static_cast<uint8*>(data);
if (size > kSlopBytes) {
end_ = ptr + size - kSlopBytes;
buffer_end_ = nullptr;
return ptr;
} else {
end_ = buffer_ + size;
buffer_end_ = ptr;
return buffer_;
}
}
private:
// Needed by CodedOutputStream HadError. HadError needs to flush the patch
// buffers to ensure there is no error as of yet.
uint8* FlushAndResetBuffer(uint8*);
// The following functions mimic the old CodedOutputStream behavior as close
// as possible. They flush the current state to the stream, behave as
// the old CodedOutputStream and then return to normal operation.
bool Skip(int count, uint8** pp);
bool GetDirectBufferPointer(void** data, int* size, uint8** pp);
uint8* GetDirectBufferForNBytesAndAdvance(int size, uint8** pp);
friend class CodedOutputStream;
};
template <>
inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<1>(const void* data,
int size,
uint8* ptr) {
return WriteRaw(data, size, ptr);
}
template <>
inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<4>(const void* data,
int size,
uint8* ptr) {
#ifdef PROTOBUF_LITTLE_ENDIAN
return WriteRaw(data, size, ptr);
#else
return WriteRawLittleEndian32(data, size, ptr);
#endif
}
template <>
inline uint8* EpsCopyOutputStream::WriteRawLittleEndian<8>(const void* data,
int size,
uint8* ptr) {
#ifdef PROTOBUF_LITTLE_ENDIAN
return WriteRaw(data, size, ptr);
#else
return WriteRawLittleEndian64(data, size, ptr);