parse_context.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #ifndef GOOGLE_PROTOBUF_PARSE_CONTEXT_H__
  31. #define GOOGLE_PROTOBUF_PARSE_CONTEXT_H__
  32. #include <cstdint>
  33. #include <cstring>
  34. #include <string>
  35. #include <google/protobuf/io/coded_stream.h>
  36. #include <google/protobuf/io/zero_copy_stream.h>
  37. #include <google/protobuf/arena.h>
  38. #include <google/protobuf/arenastring.h>
  39. #include <google/protobuf/implicit_weak_message.h>
  40. #include <google/protobuf/metadata_lite.h>
  41. #include <google/protobuf/port.h>
  42. #include <google/protobuf/repeated_field.h>
  43. #include <google/protobuf/wire_format_lite.h>
  44. #include <google/protobuf/stubs/strutil.h>
  45. #include <google/protobuf/port_def.inc>
  46. namespace google {
  47. namespace protobuf {
  48. class UnknownFieldSet;
  49. class DescriptorPool;
  50. class MessageFactory;
  51. namespace internal {
  52. // Template code below needs to know about the existence of these functions.
  53. PROTOBUF_EXPORT void WriteVarint(uint32 num, uint64 val, std::string* s);
  54. PROTOBUF_EXPORT void WriteLengthDelimited(uint32 num, StringPiece val,
  55. std::string* s);
  56. // Inline because it is just forwarding to s->WriteVarint
  57. inline void WriteVarint(uint32 num, uint64 val, UnknownFieldSet* s);
  58. inline void WriteLengthDelimited(uint32 num, StringPiece val,
  59. UnknownFieldSet* s);
  60. // The basic abstraction the parser is designed for is a slight modification
  61. // of the ZeroCopyInputStream (ZCIS) abstraction. A ZCIS presents a serialized
  62. // stream as a series of buffers that concatenate to the full stream.
  63. // Pictorially a ZCIS presents a stream in chunks like so
  64. // [---------------------------------------------------------------]
  65. // [---------------------] chunk 1
  66. // [----------------------------] chunk 2
  67. // chunk 3 [--------------]
  68. //
  69. // Where the '-' represent the bytes which are vertically lined up with the
  70. // bytes of the stream. The proto parser requires its input to be presented
  71. // similarly with the extra
  72. // property that each chunk has kSlopBytes past its end that overlaps with the
  73. // first kSlopBytes of the next chunk, or if there is no next chunk at least its
  74. // still valid to read those bytes. Again, pictorially, we now have
  75. //
  76. // [---------------------------------------------------------------]
  77. // [-------------------....] chunk 1
  78. // [------------------------....] chunk 2
  79. // chunk 3 [------------------..**]
  80. // chunk 4 [--****]
  81. // Here '-' mean the bytes of the stream or chunk and '.' means bytes past the
  82. // chunk that match up with the start of the next chunk. Above each chunk has
  83. // 4 '.' after the chunk. In the case these 'overflow' bytes represents bytes
  84. // past the stream, indicated by '*' above, their values are unspecified. It is
  85. // still legal to read them (ie. should not segfault). Reading past the
  86. // end should be detected by the user and indicated as an error.
  87. //
  88. // The reason for this, admittedly, unconventional invariant is to ruthlessly
  89. // optimize the protobuf parser. Having an overlap helps in two important ways.
  90. // Firstly it alleviates having to performing bounds checks if a piece of code
  91. // is guaranteed to not read more than kSlopBytes. Secondly, and more
  92. // importantly, the protobuf wireformat is such that reading a key/value pair is
  93. // always less than 16 bytes. This removes the need to change to next buffer in
  94. // the middle of reading primitive values. Hence there is no need to store and
  95. // load the current position.
  96. class PROTOBUF_EXPORT EpsCopyInputStream {
  97. public:
  98. enum { kSlopBytes = 16, kMaxCordBytesToCopy = 512 };
  99. explicit EpsCopyInputStream(bool enable_aliasing)
  100. : aliasing_(enable_aliasing ? kOnPatch : kNoAliasing) {}
  101. void BackUp(const char* ptr) {
  102. GOOGLE_DCHECK(ptr <= buffer_end_ + kSlopBytes);
  103. int count;
  104. if (next_chunk_ == buffer_) {
  105. count = static_cast<int>(buffer_end_ + kSlopBytes - ptr);
  106. } else {
  107. count = size_ + static_cast<int>(buffer_end_ - ptr);
  108. }
  109. if (count > 0) StreamBackUp(count);
  110. }
  111. // If return value is negative it's an error
  112. PROTOBUF_MUST_USE_RESULT int PushLimit(const char* ptr, int limit) {
  113. GOOGLE_DCHECK(limit >= 0 && limit <= INT_MAX - kSlopBytes);
  114. // This add is safe due to the invariant above, because
  115. // ptr - buffer_end_ <= kSlopBytes.
  116. limit += static_cast<int>(ptr - buffer_end_);
  117. limit_end_ = buffer_end_ + (std::min)(0, limit);
  118. auto old_limit = limit_;
  119. limit_ = limit;
  120. return old_limit - limit;
  121. }
  122. PROTOBUF_MUST_USE_RESULT bool PopLimit(int delta) {
  123. if (PROTOBUF_PREDICT_FALSE(!EndedAtLimit())) return false;
  124. limit_ = limit_ + delta;
  125. // TODO(gerbens) We could remove this line and hoist the code to
  126. // DoneFallback. Study the perf/bin-size effects.
  127. limit_end_ = buffer_end_ + (std::min)(0, limit_);
  128. return true;
  129. }
  130. PROTOBUF_MUST_USE_RESULT const char* Skip(const char* ptr, int size) {
  131. if (size <= buffer_end_ + kSlopBytes - ptr) {
  132. return ptr + size;
  133. }
  134. return SkipFallback(ptr, size);
  135. }
  136. PROTOBUF_MUST_USE_RESULT const char* ReadString(const char* ptr, int size,
  137. std::string* s) {
  138. if (size <= buffer_end_ + kSlopBytes - ptr) {
  139. s->assign(ptr, size);
  140. return ptr + size;
  141. }
  142. return ReadStringFallback(ptr, size, s);
  143. }
  144. PROTOBUF_MUST_USE_RESULT const char* AppendString(const char* ptr, int size,
  145. std::string* s) {
  146. if (size <= buffer_end_ + kSlopBytes - ptr) {
  147. s->append(ptr, size);
  148. return ptr + size;
  149. }
  150. return AppendStringFallback(ptr, size, s);
  151. }
  152. // Implemented in arenastring.cc
  153. PROTOBUF_MUST_USE_RESULT const char* ReadArenaString(const char* ptr,
  154. ArenaStringPtr* s,
  155. Arena* arena);
  156. template <typename Tag, typename T>
  157. PROTOBUF_MUST_USE_RESULT const char* ReadRepeatedFixed(const char* ptr,
  158. Tag expected_tag,
  159. RepeatedField<T>* out);
  160. template <typename T>
  161. PROTOBUF_MUST_USE_RESULT const char* ReadPackedFixed(const char* ptr,
  162. int size,
  163. RepeatedField<T>* out);
  164. template <typename Add>
  165. PROTOBUF_MUST_USE_RESULT const char* ReadPackedVarint(const char* ptr,
  166. Add add);
  167. uint32 LastTag() const { return last_tag_minus_1_ + 1; }
  168. bool ConsumeEndGroup(uint32 start_tag) {
  169. bool res = last_tag_minus_1_ == start_tag;
  170. last_tag_minus_1_ = 0;
  171. return res;
  172. }
  173. bool EndedAtLimit() const { return last_tag_minus_1_ == 0; }
  174. bool EndedAtEndOfStream() const { return last_tag_minus_1_ == 1; }
  175. void SetLastTag(uint32 tag) { last_tag_minus_1_ = tag - 1; }
  176. void SetEndOfStream() { last_tag_minus_1_ = 1; }
  177. bool IsExceedingLimit(const char* ptr) {
  178. return ptr > limit_end_ &&
  179. (next_chunk_ == nullptr || ptr - buffer_end_ > limit_);
  180. }
  181. int BytesUntilLimit(const char* ptr) const {
  182. return limit_ + static_cast<int>(buffer_end_ - ptr);
  183. }
  184. // Returns true if more data is available, if false is returned one has to
  185. // call Done for further checks.
  186. bool DataAvailable(const char* ptr) { return ptr < limit_end_; }
  187. protected:
  188. // Returns true is limit (either an explicit limit or end of stream) is
  189. // reached. It aligns *ptr across buffer seams.
  190. // If limit is exceeded it returns true and ptr is set to null.
  191. bool DoneWithCheck(const char** ptr, int d) {
  192. GOOGLE_DCHECK(*ptr);
  193. if (PROTOBUF_PREDICT_TRUE(*ptr < limit_end_)) return false;
  194. int overrun = static_cast<int>(*ptr - buffer_end_);
  195. GOOGLE_DCHECK_LE(overrun, kSlopBytes); // Guaranteed by parse loop.
  196. if (overrun ==
  197. limit_) { // No need to flip buffers if we ended on a limit.
  198. // If we actually overrun the buffer and next_chunk_ is null. It means
  199. // the stream ended and we passed the stream end.
  200. if (overrun > 0 && next_chunk_ == nullptr) *ptr = nullptr;
  201. return true;
  202. }
  203. auto res = DoneFallback(overrun, d);
  204. *ptr = res.first;
  205. return res.second;
  206. }
  207. const char* InitFrom(StringPiece flat) {
  208. overall_limit_ = 0;
  209. if (flat.size() > kSlopBytes) {
  210. limit_ = kSlopBytes;
  211. limit_end_ = buffer_end_ = flat.data() + flat.size() - kSlopBytes;
  212. next_chunk_ = buffer_;
  213. if (aliasing_ == kOnPatch) aliasing_ = kNoDelta;
  214. return flat.data();
  215. } else {
  216. std::memcpy(buffer_, flat.data(), flat.size());
  217. limit_ = 0;
  218. limit_end_ = buffer_end_ = buffer_ + flat.size();
  219. next_chunk_ = nullptr;
  220. if (aliasing_ == kOnPatch) {
  221. aliasing_ = reinterpret_cast<std::uintptr_t>(flat.data()) -
  222. reinterpret_cast<std::uintptr_t>(buffer_);
  223. }
  224. return buffer_;
  225. }
  226. }
  227. const char* InitFrom(io::ZeroCopyInputStream* zcis);
  228. const char* InitFrom(io::ZeroCopyInputStream* zcis, int limit) {
  229. if (limit == -1) return InitFrom(zcis);
  230. overall_limit_ = limit;
  231. auto res = InitFrom(zcis);
  232. limit_ = limit - static_cast<int>(buffer_end_ - res);
  233. limit_end_ = buffer_end_ + (std::min)(0, limit_);
  234. return res;
  235. }
  236. private:
  237. const char* limit_end_; // buffer_end_ + min(limit_, 0)
  238. const char* buffer_end_;
  239. const char* next_chunk_;
  240. int size_;
  241. int limit_; // relative to buffer_end_;
  242. io::ZeroCopyInputStream* zcis_ = nullptr;
  243. char buffer_[2 * kSlopBytes] = {};
  244. enum { kNoAliasing = 0, kOnPatch = 1, kNoDelta = 2 };
  245. std::uintptr_t aliasing_ = kNoAliasing;
  246. // This variable is used to communicate how the parse ended, in order to
  247. // completely verify the parsed data. A wire-format parse can end because of
  248. // one of the following conditions:
  249. // 1) A parse can end on a pushed limit.
  250. // 2) A parse can end on End Of Stream (EOS).
  251. // 3) A parse can end on 0 tag (only valid for toplevel message).
  252. // 4) A parse can end on an end-group tag.
  253. // This variable should always be set to 0, which indicates case 1. If the
  254. // parse terminated due to EOS (case 2), it's set to 1. In case the parse
  255. // ended due to a terminating tag (case 3 and 4) it's set to (tag - 1).
  256. // This var doesn't really belong in EpsCopyInputStream and should be part of
  257. // the ParseContext, but case 2 is most easily and optimally implemented in
  258. // DoneFallback.
  259. uint32 last_tag_minus_1_ = 0;
  260. int overall_limit_ = INT_MAX; // Overall limit independent of pushed limits.
  261. // Pretty random large number that seems like a safe allocation on most
  262. // systems. TODO(gerbens) do we need to set this as build flag?
  263. enum { kSafeStringSize = 50000000 };
  264. // Advances to next buffer chunk returns a pointer to the same logical place
  265. // in the stream as set by overrun. Overrun indicates the position in the slop
  266. // region the parse was left (0 <= overrun <= kSlopBytes). Returns true if at
  267. // limit, at which point the returned pointer maybe null if there was an
  268. // error. The invariant of this function is that it's guaranteed that
  269. // kSlopBytes bytes can be accessed from the returned ptr. This function might
  270. // advance more buffers than one in the underlying ZeroCopyInputStream.
  271. std::pair<const char*, bool> DoneFallback(int overrun, int depth);
  272. // Advances to the next buffer, at most one call to Next() on the underlying
  273. // ZeroCopyInputStream is made. This function DOES NOT match the returned
  274. // pointer to where in the slop region the parse ends, hence no overrun
  275. // parameter. This is useful for string operations where you always copy
  276. // to the end of the buffer (including the slop region).
  277. const char* Next();
  278. // overrun is the location in the slop region the stream currently is
  279. // (0 <= overrun <= kSlopBytes). To prevent flipping to the next buffer of
  280. // the ZeroCopyInputStream in the case the parse will end in the last
  281. // kSlopBytes of the current buffer. depth is the current depth of nested
  282. // groups (or negative if the use case does not need careful tracking).
  283. inline const char* NextBuffer(int overrun, int depth);
  284. const char* SkipFallback(const char* ptr, int size);
  285. const char* AppendStringFallback(const char* ptr, int size, std::string* str);
  286. const char* ReadStringFallback(const char* ptr, int size, std::string* str);
  287. bool StreamNext(const void** data) {
  288. bool res = zcis_->Next(data, &size_);
  289. if (res) overall_limit_ -= size_;
  290. return res;
  291. }
  292. void StreamBackUp(int count) {
  293. zcis_->BackUp(count);
  294. overall_limit_ += count;
  295. }
  296. template <typename A>
  297. const char* AppendSize(const char* ptr, int size, const A& append) {
  298. int chunk_size = buffer_end_ + kSlopBytes - ptr;
  299. do {
  300. GOOGLE_DCHECK(size > chunk_size);
  301. if (next_chunk_ == nullptr) return nullptr;
  302. append(ptr, chunk_size);
  303. ptr += chunk_size;
  304. size -= chunk_size;
  305. // TODO(gerbens) Next calls NextBuffer which generates buffers with
  306. // overlap and thus incurs cost of copying the slop regions. This is not
  307. // necessary for reading strings. We should just call Next buffers.
  308. if (limit_ <= kSlopBytes) return nullptr;
  309. ptr = Next();
  310. if (ptr == nullptr) return nullptr; // passed the limit
  311. ptr += kSlopBytes;
  312. chunk_size = buffer_end_ + kSlopBytes - ptr;
  313. } while (size > chunk_size);
  314. append(ptr, size);
  315. return ptr + size;
  316. }
  317. // AppendUntilEnd appends data until a limit (either a PushLimit or end of
  318. // stream. Normal payloads are from length delimited fields which have an
  319. // explicit size. Reading until limit only comes when the string takes
  320. // the place of a protobuf, ie RawMessage/StringRawMessage, lazy fields and
  321. // implicit weak messages. We keep these methods private and friend them.
  322. template <typename A>
  323. const char* AppendUntilEnd(const char* ptr, const A& append) {
  324. if (ptr - buffer_end_ > limit_) return nullptr;
  325. while (limit_ > kSlopBytes) {
  326. size_t chunk_size = buffer_end_ + kSlopBytes - ptr;
  327. append(ptr, chunk_size);
  328. ptr = Next();
  329. if (ptr == nullptr) return limit_end_;
  330. ptr += kSlopBytes;
  331. }
  332. auto end = buffer_end_ + limit_;
  333. GOOGLE_DCHECK(end >= ptr);
  334. append(ptr, end - ptr);
  335. return end;
  336. }
  337. PROTOBUF_MUST_USE_RESULT const char* AppendString(const char* ptr,
  338. std::string* str) {
  339. return AppendUntilEnd(
  340. ptr, [str](const char* p, ptrdiff_t s) { str->append(p, s); });
  341. }
  342. friend class ImplicitWeakMessage;
  343. };
  344. // ParseContext holds all data that is global to the entire parse. Most
  345. // importantly it contains the input stream, but also recursion depth and also
  346. // stores the end group tag, in case a parser ended on a endgroup, to verify
  347. // matching start/end group tags.
  348. class PROTOBUF_EXPORT ParseContext : public EpsCopyInputStream {
  349. public:
  350. struct Data {
  351. const DescriptorPool* pool = nullptr;
  352. MessageFactory* factory = nullptr;
  353. Arena* arena = nullptr;
  354. };
  355. template <typename... T>
  356. ParseContext(int depth, bool aliasing, const char** start, T&&... args)
  357. : EpsCopyInputStream(aliasing), depth_(depth) {
  358. *start = InitFrom(std::forward<T>(args)...);
  359. }
  360. void TrackCorrectEnding() { group_depth_ = 0; }
  361. bool Done(const char** ptr) { return DoneWithCheck(ptr, group_depth_); }
  362. int depth() const { return depth_; }
  363. Data& data() { return data_; }
  364. const Data& data() const { return data_; }
  365. template <typename T>
  366. PROTOBUF_MUST_USE_RESULT const char* ParseMessage(T* msg, const char* ptr);
  367. // We outline when the type is generic and we go through a virtual
  368. const char* ParseMessage(MessageLite* msg, const char* ptr);
  369. const char* ParseMessage(Message* msg, const char* ptr);
  370. template <typename T>
  371. PROTOBUF_MUST_USE_RESULT PROTOBUF_NDEBUG_INLINE const char* ParseGroup(
  372. T* msg, const char* ptr, uint32 tag) {
  373. if (--depth_ < 0) return nullptr;
  374. group_depth_++;
  375. ptr = msg->_InternalParse(ptr, this);
  376. group_depth_--;
  377. depth_++;
  378. if (PROTOBUF_PREDICT_FALSE(!ConsumeEndGroup(tag))) return nullptr;
  379. return ptr;
  380. }
  381. private:
  382. // Out-of-line routine to save space in ParseContext::ParseMessage<T>
  383. // int old;
  384. // ptr = ReadSizeAndPushLimitAndDepth(ptr, &old)
  385. // is equivalent to:
  386. // int size = ReadSize(&ptr);
  387. // if (!ptr) return nullptr;
  388. // int old = PushLimit(ptr, size);
  389. // if (--depth_ < 0) return nullptr;
  390. PROTOBUF_MUST_USE_RESULT const char* ReadSizeAndPushLimitAndDepth(
  391. const char* ptr, int* old_limit);
  392. // The context keeps an internal stack to keep track of the recursive
  393. // part of the parse state.
  394. // Current depth of the active parser, depth counts down.
  395. // This is used to limit recursion depth (to prevent overflow on malicious
  396. // data), but is also used to index in stack_ to store the current state.
  397. int depth_;
  398. // Unfortunately necessary for the fringe case of ending on 0 or end-group tag
  399. // in the last kSlopBytes of a ZeroCopyInputStream chunk.
  400. int group_depth_ = INT_MIN;
  401. Data data_;
  402. };
  403. template <uint32 tag>
  404. bool ExpectTag(const char* ptr) {
  405. if (tag < 128) {
  406. return *ptr == static_cast<char>(tag);
  407. } else {
  408. static_assert(tag < 128 * 128, "We only expect tags for 1 or 2 bytes");
  409. char buf[2] = {static_cast<char>(tag | 0x80), static_cast<char>(tag >> 7)};
  410. return std::memcmp(ptr, buf, 2) == 0;
  411. }
  412. }
  413. template <int>
  414. struct EndianHelper;
  415. template <>
  416. struct EndianHelper<1> {
  417. static uint8 Load(const void* p) { return *static_cast<const uint8*>(p); }
  418. };
  419. template <>
  420. struct EndianHelper<2> {
  421. static uint16 Load(const void* p) {
  422. uint16 tmp;
  423. std::memcpy(&tmp, p, 2);
  424. #ifndef PROTOBUF_LITTLE_ENDIAN
  425. tmp = bswap_16(tmp);
  426. #endif
  427. return tmp;
  428. }
  429. };
  430. template <>
  431. struct EndianHelper<4> {
  432. static uint32 Load(const void* p) {
  433. uint32 tmp;
  434. std::memcpy(&tmp, p, 4);
  435. #ifndef PROTOBUF_LITTLE_ENDIAN
  436. tmp = bswap_32(tmp);
  437. #endif
  438. return tmp;
  439. }
  440. };
  441. template <>
  442. struct EndianHelper<8> {
  443. static uint64 Load(const void* p) {
  444. uint64 tmp;
  445. std::memcpy(&tmp, p, 8);
  446. #ifndef PROTOBUF_LITTLE_ENDIAN
  447. tmp = bswap_64(tmp);
  448. #endif
  449. return tmp;
  450. }
  451. };
  452. template <typename T>
  453. T UnalignedLoad(const char* p) {
  454. auto tmp = EndianHelper<sizeof(T)>::Load(p);
  455. T res;
  456. memcpy(&res, &tmp, sizeof(T));
  457. return res;
  458. }
  459. PROTOBUF_EXPORT
  460. std::pair<const char*, uint32> VarintParseSlow32(const char* p, uint32 res);
  461. PROTOBUF_EXPORT
  462. std::pair<const char*, uint64> VarintParseSlow64(const char* p, uint32 res);
  463. inline const char* VarintParseSlow(const char* p, uint32 res, uint32* out) {
  464. auto tmp = VarintParseSlow32(p, res);
  465. *out = tmp.second;
  466. return tmp.first;
  467. }
  468. inline const char* VarintParseSlow(const char* p, uint32 res, uint64* out) {
  469. auto tmp = VarintParseSlow64(p, res);
  470. *out = tmp.second;
  471. return tmp.first;
  472. }
  473. template <typename T>
  474. PROTOBUF_MUST_USE_RESULT const char* VarintParse(const char* p, T* out) {
  475. auto ptr = reinterpret_cast<const uint8*>(p);
  476. uint32 res = ptr[0];
  477. if (!(res & 0x80)) {
  478. *out = res;
  479. return p + 1;
  480. }
  481. uint32 byte = ptr[1];
  482. res += (byte - 1) << 7;
  483. if (!(byte & 0x80)) {
  484. *out = res;
  485. return p + 2;
  486. }
  487. return VarintParseSlow(p, res, out);
  488. }
  489. // Used for tags, could read up to 5 bytes which must be available.
  490. // Caller must ensure its safe to call.
  491. PROTOBUF_EXPORT
  492. std::pair<const char*, uint32> ReadTagFallback(const char* p, uint32 res);
  493. // Same as ParseVarint but only accept 5 bytes at most.
  494. inline const char* ReadTag(const char* p, uint32* out, uint32 /*max_tag*/ = 0) {
  495. uint32 res = static_cast<uint8>(p[0]);
  496. if (res < 128) {
  497. *out = res;
  498. return p + 1;
  499. }
  500. uint32 second = static_cast<uint8>(p[1]);
  501. res += (second - 1) << 7;
  502. if (second < 128) {
  503. *out = res;
  504. return p + 2;
  505. }
  506. auto tmp = ReadTagFallback(p, res);
  507. *out = tmp.second;
  508. return tmp.first;
  509. }
  510. // Decode 2 consecutive bytes of a varint and returns the value, shifted left
  511. // by 1. It simultaneous updates *ptr to *ptr + 1 or *ptr + 2 depending if the
  512. // first byte's continuation bit is set.
  513. // If bit 15 of return value is set (equivalent to the continuation bits of both
  514. // bytes being set) the varint continues, otherwise the parse is done. On x86
  515. // movsx eax, dil
  516. // add edi, eax
  517. // adc [rsi], 1
  518. // add eax, eax
  519. // and eax, edi
  520. inline uint32 DecodeTwoBytes(const char** ptr) {
  521. uint32 value = UnalignedLoad<uint16>(*ptr);
  522. // Sign extend the low byte continuation bit
  523. uint32_t x = static_cast<int8_t>(value);
  524. // This add is an amazing operation, it cancels the low byte continuation bit
  525. // from y transferring it to the carry. Simultaneously it also shifts the 7
  526. // LSB left by one tightly against high byte varint bits. Hence value now
  527. // contains the unpacked value shifted left by 1.
  528. value += x;
  529. // Use the carry to update the ptr appropriately.
  530. *ptr += value < x ? 2 : 1;
  531. return value & (x + x); // Mask out the high byte iff no continuation
  532. }
  533. // More efficient varint parsing for big varints
  534. inline const char* ParseBigVarint(const char* p, uint64* out) {
  535. auto pnew = p;
  536. auto tmp = DecodeTwoBytes(&pnew);
  537. uint64 res = tmp >> 1;
  538. if (PROTOBUF_PREDICT_TRUE(std::int16_t(tmp) >= 0)) {
  539. *out = res;
  540. return pnew;
  541. }
  542. for (std::uint32_t i = 1; i < 5; i++) {
  543. pnew = p + 2 * i;
  544. tmp = DecodeTwoBytes(&pnew);
  545. res += (static_cast<std::uint64_t>(tmp) - 2) << (14 * i - 1);
  546. if (PROTOBUF_PREDICT_TRUE(std::int16_t(tmp) >= 0)) {
  547. *out = res;
  548. return pnew;
  549. }
  550. }
  551. return nullptr;
  552. }
  553. PROTOBUF_EXPORT
  554. std::pair<const char*, int32> ReadSizeFallback(const char* p, uint32 first);
  555. // Used for tags, could read up to 5 bytes which must be available. Additionally
  556. // it makes sure the unsigned value fits a int32, otherwise returns nullptr.
  557. // Caller must ensure its safe to call.
  558. inline uint32 ReadSize(const char** pp) {
  559. auto p = *pp;
  560. uint32 res = static_cast<uint8>(p[0]);
  561. if (res < 128) {
  562. *pp = p + 1;
  563. return res;
  564. }
  565. auto x = ReadSizeFallback(p, res);
  566. *pp = x.first;
  567. return x.second;
  568. }
  569. // Some convenience functions to simplify the generated parse loop code.
  570. // Returning the value and updating the buffer pointer allows for nicer
  571. // function composition. We rely on the compiler to inline this.
  572. // Also in debug compiles having local scoped variables tend to generated
  573. // stack frames that scale as O(num fields).
  574. inline uint64 ReadVarint64(const char** p) {
  575. uint64 tmp;
  576. *p = VarintParse(*p, &tmp);
  577. return tmp;
  578. }
  579. inline uint32 ReadVarint32(const char** p) {
  580. uint32 tmp;
  581. *p = VarintParse(*p, &tmp);
  582. return tmp;
  583. }
  584. inline int64 ReadVarintZigZag64(const char** p) {
  585. uint64 tmp;
  586. *p = VarintParse(*p, &tmp);
  587. return WireFormatLite::ZigZagDecode64(tmp);
  588. }
  589. inline int32 ReadVarintZigZag32(const char** p) {
  590. uint64 tmp;
  591. *p = VarintParse(*p, &tmp);
  592. return WireFormatLite::ZigZagDecode32(static_cast<uint32>(tmp));
  593. }
  594. template <typename T>
  595. PROTOBUF_MUST_USE_RESULT const char* ParseContext::ParseMessage(
  596. T* msg, const char* ptr) {
  597. int old;
  598. ptr = ReadSizeAndPushLimitAndDepth(ptr, &old);
  599. ptr = ptr ? msg->_InternalParse(ptr, this) : nullptr;
  600. depth_++;
  601. if (!PopLimit(old)) return nullptr;
  602. return ptr;
  603. }
  604. template <typename Tag, typename T>
  605. const char* EpsCopyInputStream::ReadRepeatedFixed(const char* ptr,
  606. Tag expected_tag,
  607. RepeatedField<T>* out) {
  608. do {
  609. out->Add(UnalignedLoad<T>(ptr));
  610. ptr += sizeof(T);
  611. if (PROTOBUF_PREDICT_FALSE(ptr >= limit_end_)) return ptr;
  612. } while (UnalignedLoad<Tag>(ptr) == expected_tag && (ptr += sizeof(Tag)));
  613. return ptr;
  614. }
  615. template <typename T>
  616. const char* EpsCopyInputStream::ReadPackedFixed(const char* ptr, int size,
  617. RepeatedField<T>* out) {
  618. int nbytes = buffer_end_ + kSlopBytes - ptr;
  619. while (size > nbytes) {
  620. int num = nbytes / sizeof(T);
  621. int old_entries = out->size();
  622. out->Reserve(old_entries + num);
  623. int block_size = num * sizeof(T);
  624. auto dst = out->AddNAlreadyReserved(num);
  625. #ifdef PROTOBUF_LITTLE_ENDIAN
  626. std::memcpy(dst, ptr, block_size);
  627. #else
  628. for (int i = 0; i < num; i++)
  629. dst[i] = UnalignedLoad<T>(ptr + i * sizeof(T));
  630. #endif
  631. size -= block_size;
  632. if (limit_ <= kSlopBytes) return nullptr;
  633. ptr = Next();
  634. if (ptr == nullptr) return nullptr;
  635. ptr += kSlopBytes - (nbytes - block_size);
  636. nbytes = buffer_end_ + kSlopBytes - ptr;
  637. }
  638. int num = size / sizeof(T);
  639. int old_entries = out->size();
  640. out->Reserve(old_entries + num);
  641. int block_size = num * sizeof(T);
  642. auto dst = out->AddNAlreadyReserved(num);
  643. #ifdef PROTOBUF_LITTLE_ENDIAN
  644. std::memcpy(dst, ptr, block_size);
  645. #else
  646. for (int i = 0; i < num; i++) dst[i] = UnalignedLoad<T>(ptr + i * sizeof(T));
  647. #endif
  648. ptr += block_size;
  649. if (size != block_size) return nullptr;
  650. return ptr;
  651. }
  652. template <typename Add>
  653. const char* ReadPackedVarintArray(const char* ptr, const char* end, Add add) {
  654. while (ptr < end) {
  655. uint64 varint;
  656. ptr = VarintParse(ptr, &varint);
  657. if (ptr == nullptr) return nullptr;
  658. add(varint);
  659. }
  660. return ptr;
  661. }
  662. template <typename Add>
  663. const char* EpsCopyInputStream::ReadPackedVarint(const char* ptr, Add add) {
  664. int size = ReadSize(&ptr);
  665. if (ptr == nullptr) return nullptr;
  666. int chunk_size = buffer_end_ - ptr;
  667. while (size > chunk_size) {
  668. ptr = ReadPackedVarintArray(ptr, buffer_end_, add);
  669. if (ptr == nullptr) return nullptr;
  670. int overrun = ptr - buffer_end_;
  671. GOOGLE_DCHECK(overrun >= 0 && overrun <= kSlopBytes);
  672. if (size - chunk_size <= kSlopBytes) {
  673. // The current buffer contains all the information needed, we don't need
  674. // to flip buffers. However we must parse from a buffer with enough space
  675. // so we are not prone to a buffer overflow.
  676. char buf[kSlopBytes + 10] = {};
  677. std::memcpy(buf, buffer_end_, kSlopBytes);
  678. GOOGLE_CHECK_LE(size - chunk_size, kSlopBytes);
  679. auto end = buf + (size - chunk_size);
  680. auto res = ReadPackedVarintArray(buf + overrun, end, add);
  681. if (res == nullptr || res != end) return nullptr;
  682. return buffer_end_ + (res - buf);
  683. }
  684. size -= overrun + chunk_size;
  685. GOOGLE_DCHECK_GT(size, 0);
  686. // We must flip buffers
  687. if (limit_ <= kSlopBytes) return nullptr;
  688. ptr = Next();
  689. if (ptr == nullptr) return nullptr;
  690. ptr += overrun;
  691. chunk_size = buffer_end_ - ptr;
  692. }
  693. auto end = ptr + size;
  694. ptr = ReadPackedVarintArray(ptr, end, add);
  695. return end == ptr ? ptr : nullptr;
  696. }
  697. // Helper for verification of utf8
  698. PROTOBUF_EXPORT
  699. bool VerifyUTF8(StringPiece s, const char* field_name);
  700. inline bool VerifyUTF8(const std::string* s, const char* field_name) {
  701. return VerifyUTF8(*s, field_name);
  702. }
  703. // All the string parsers with or without UTF checking and for all CTypes.
  704. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* InlineGreedyStringParser(
  705. std::string* s, const char* ptr, ParseContext* ctx);
  706. // Add any of the following lines to debug which parse function is failing.
  707. #define GOOGLE_PROTOBUF_ASSERT_RETURN(predicate, ret) \
  708. if (!(predicate)) { \
  709. /* ::raise(SIGINT); */ \
  710. /* GOOGLE_LOG(ERROR) << "Parse failure"; */ \
  711. return ret; \
  712. }
  713. #define GOOGLE_PROTOBUF_PARSER_ASSERT(predicate) \
  714. GOOGLE_PROTOBUF_ASSERT_RETURN(predicate, nullptr)
  715. template <typename T>
  716. PROTOBUF_MUST_USE_RESULT const char* FieldParser(uint64 tag, T& field_parser,
  717. const char* ptr,
  718. ParseContext* ctx) {
  719. uint32 number = tag >> 3;
  720. GOOGLE_PROTOBUF_PARSER_ASSERT(number != 0);
  721. using WireType = internal::WireFormatLite::WireType;
  722. switch (tag & 7) {
  723. case WireType::WIRETYPE_VARINT: {
  724. uint64 value;
  725. ptr = VarintParse(ptr, &value);
  726. GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
  727. field_parser.AddVarint(number, value);
  728. break;
  729. }
  730. case WireType::WIRETYPE_FIXED64: {
  731. uint64 value = UnalignedLoad<uint64>(ptr);
  732. ptr += 8;
  733. field_parser.AddFixed64(number, value);
  734. break;
  735. }
  736. case WireType::WIRETYPE_LENGTH_DELIMITED: {
  737. ptr = field_parser.ParseLengthDelimited(number, ptr, ctx);
  738. GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
  739. break;
  740. }
  741. case WireType::WIRETYPE_START_GROUP: {
  742. ptr = field_parser.ParseGroup(number, ptr, ctx);
  743. GOOGLE_PROTOBUF_PARSER_ASSERT(ptr);
  744. break;
  745. }
  746. case WireType::WIRETYPE_END_GROUP: {
  747. GOOGLE_LOG(FATAL) << "Can't happen";
  748. break;
  749. }
  750. case WireType::WIRETYPE_FIXED32: {
  751. uint32 value = UnalignedLoad<uint32>(ptr);
  752. ptr += 4;
  753. field_parser.AddFixed32(number, value);
  754. break;
  755. }
  756. default:
  757. return nullptr;
  758. }
  759. return ptr;
  760. }
  761. template <typename T>
  762. PROTOBUF_MUST_USE_RESULT const char* WireFormatParser(T& field_parser,
  763. const char* ptr,
  764. ParseContext* ctx) {
  765. while (!ctx->Done(&ptr)) {
  766. uint32 tag;
  767. ptr = ReadTag(ptr, &tag);
  768. GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
  769. if (tag == 0 || (tag & 7) == 4) {
  770. ctx->SetLastTag(tag);
  771. return ptr;
  772. }
  773. ptr = FieldParser(tag, field_parser, ptr, ctx);
  774. GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr);
  775. }
  776. return ptr;
  777. }
  778. // The packed parsers parse repeated numeric primitives directly into the
  779. // corresponding field
  780. // These are packed varints
  781. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedInt32Parser(
  782. void* object, const char* ptr, ParseContext* ctx);
  783. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedUInt32Parser(
  784. void* object, const char* ptr, ParseContext* ctx);
  785. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedInt64Parser(
  786. void* object, const char* ptr, ParseContext* ctx);
  787. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedUInt64Parser(
  788. void* object, const char* ptr, ParseContext* ctx);
  789. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSInt32Parser(
  790. void* object, const char* ptr, ParseContext* ctx);
  791. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSInt64Parser(
  792. void* object, const char* ptr, ParseContext* ctx);
  793. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser(
  794. void* object, const char* ptr, ParseContext* ctx);
  795. template <typename T>
  796. PROTOBUF_MUST_USE_RESULT const char* PackedEnumParser(
  797. void* object, const char* ptr, ParseContext* ctx, bool (*is_valid)(int),
  798. InternalMetadata* metadata, int field_num) {
  799. return ctx->ReadPackedVarint(
  800. ptr, [object, is_valid, metadata, field_num](uint64 val) {
  801. if (is_valid(val)) {
  802. static_cast<RepeatedField<int>*>(object)->Add(val);
  803. } else {
  804. WriteVarint(field_num, val, metadata->mutable_unknown_fields<T>());
  805. }
  806. });
  807. }
  808. template <typename T>
  809. PROTOBUF_MUST_USE_RESULT const char* PackedEnumParserArg(
  810. void* object, const char* ptr, ParseContext* ctx,
  811. bool (*is_valid)(const void*, int), const void* data,
  812. InternalMetadata* metadata, int field_num) {
  813. return ctx->ReadPackedVarint(
  814. ptr, [object, is_valid, data, metadata, field_num](uint64 val) {
  815. if (is_valid(data, val)) {
  816. static_cast<RepeatedField<int>*>(object)->Add(val);
  817. } else {
  818. WriteVarint(field_num, val, metadata->mutable_unknown_fields<T>());
  819. }
  820. });
  821. }
  822. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedBoolParser(
  823. void* object, const char* ptr, ParseContext* ctx);
  824. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFixed32Parser(
  825. void* object, const char* ptr, ParseContext* ctx);
  826. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSFixed32Parser(
  827. void* object, const char* ptr, ParseContext* ctx);
  828. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFixed64Parser(
  829. void* object, const char* ptr, ParseContext* ctx);
  830. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedSFixed64Parser(
  831. void* object, const char* ptr, ParseContext* ctx);
  832. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedFloatParser(
  833. void* object, const char* ptr, ParseContext* ctx);
  834. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* PackedDoubleParser(
  835. void* object, const char* ptr, ParseContext* ctx);
  836. // This is the only recursive parser.
  837. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownGroupLiteParse(
  838. std::string* unknown, const char* ptr, ParseContext* ctx);
  839. // This is a helper to for the UnknownGroupLiteParse but is actually also
  840. // useful in the generated code. It uses overload on std::string* vs
  841. // UnknownFieldSet* to make the generated code isomorphic between full and lite.
  842. PROTOBUF_EXPORT PROTOBUF_MUST_USE_RESULT const char* UnknownFieldParse(
  843. uint32 tag, std::string* unknown, const char* ptr, ParseContext* ctx);
  844. } // namespace internal
  845. } // namespace protobuf
  846. } // namespace google
  847. #include <google/protobuf/port_undef.inc>
  848. #endif // GOOGLE_PROTOBUF_PARSE_CONTEXT_H__