message_lite.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. // Authors: wink@google.com (Wink Saville),
  31. // kenton@google.com (Kenton Varda)
  32. // Based on original Protocol Buffers design by
  33. // Sanjay Ghemawat, Jeff Dean, and others.
  34. #include <google/protobuf/message_lite.h>
  35. #include <google/protobuf/arena.h>
  36. #include <google/protobuf/repeated_field.h>
  37. #include <string>
  38. #include <google/protobuf/stubs/logging.h>
  39. #include <google/protobuf/stubs/common.h>
  40. #include <google/protobuf/io/coded_stream.h>
  41. #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
  42. #include <google/protobuf/stubs/stl_util.h>
  43. namespace google {
  44. namespace protobuf {
  45. MessageLite::~MessageLite() {}
  46. string MessageLite::InitializationErrorString() const {
  47. return "(cannot determine missing fields for lite message)";
  48. }
  49. namespace {
  50. // When serializing, we first compute the byte size, then serialize the message.
  51. // If serialization produces a different number of bytes than expected, we
  52. // call this function, which crashes. The problem could be due to a bug in the
  53. // protobuf implementation but is more likely caused by concurrent modification
  54. // of the message. This function attempts to distinguish between the two and
  55. // provide a useful error message.
  56. void ByteSizeConsistencyError(int byte_size_before_serialization,
  57. int byte_size_after_serialization,
  58. int bytes_produced_by_serialization) {
  59. GOOGLE_CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization)
  60. << "Protocol message was modified concurrently during serialization.";
  61. GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization)
  62. << "Byte size calculation and serialization were inconsistent. This "
  63. "may indicate a bug in protocol buffers or it may be caused by "
  64. "concurrent modification of the message.";
  65. GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal.";
  66. }
  67. string InitializationErrorMessage(const char* action,
  68. const MessageLite& message) {
  69. // Note: We want to avoid depending on strutil in the lite library, otherwise
  70. // we'd use:
  71. //
  72. // return strings::Substitute(
  73. // "Can't $0 message of type \"$1\" because it is missing required "
  74. // "fields: $2",
  75. // action, message.GetTypeName(),
  76. // message.InitializationErrorString());
  77. string result;
  78. result += "Can't ";
  79. result += action;
  80. result += " message of type \"";
  81. result += message.GetTypeName();
  82. result += "\" because it is missing required fields: ";
  83. result += message.InitializationErrorString();
  84. return result;
  85. }
  86. // Several of the Parse methods below just do one thing and then call another
  87. // method. In a naive implementation, we might have ParseFromString() call
  88. // ParseFromArray() which would call ParseFromZeroCopyStream() which would call
  89. // ParseFromCodedStream() which would call MergeFromCodedStream() which would
  90. // call MergePartialFromCodedStream(). However, when parsing very small
  91. // messages, every function call introduces significant overhead. To avoid
  92. // this without reproducing code, we use these forced-inline helpers.
  93. GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineMergeFromCodedStream(
  94. io::CodedInputStream* input, MessageLite* message);
  95. GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromCodedStream(
  96. io::CodedInputStream* input, MessageLite* message);
  97. GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromCodedStream(
  98. io::CodedInputStream* input, MessageLite* message);
  99. GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParseFromArray(
  100. const void* data, int size, MessageLite* message);
  101. GOOGLE_ATTRIBUTE_ALWAYS_INLINE bool InlineParsePartialFromArray(
  102. const void* data, int size, MessageLite* message);
  103. inline bool InlineMergeFromCodedStream(io::CodedInputStream* input,
  104. MessageLite* message) {
  105. if (!message->MergePartialFromCodedStream(input)) return false;
  106. if (!message->IsInitialized()) {
  107. GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message);
  108. return false;
  109. }
  110. return true;
  111. }
  112. inline bool InlineParseFromCodedStream(io::CodedInputStream* input,
  113. MessageLite* message) {
  114. message->Clear();
  115. return InlineMergeFromCodedStream(input, message);
  116. }
  117. inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input,
  118. MessageLite* message) {
  119. message->Clear();
  120. return message->MergePartialFromCodedStream(input);
  121. }
  122. inline bool InlineParseFromArray(
  123. const void* data, int size, MessageLite* message) {
  124. io::CodedInputStream input(reinterpret_cast<const uint8*>(data), size);
  125. return InlineParseFromCodedStream(&input, message) &&
  126. input.ConsumedEntireMessage();
  127. }
  128. inline bool InlineParsePartialFromArray(
  129. const void* data, int size, MessageLite* message) {
  130. io::CodedInputStream input(reinterpret_cast<const uint8*>(data), size);
  131. return InlineParsePartialFromCodedStream(&input, message) &&
  132. input.ConsumedEntireMessage();
  133. }
  134. } // namespace
  135. MessageLite* MessageLite::New(::google::protobuf::Arena* arena) const {
  136. MessageLite* message = New();
  137. if (arena != NULL) {
  138. arena->Own(message);
  139. }
  140. return message;
  141. }
  142. bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) {
  143. return InlineMergeFromCodedStream(input, this);
  144. }
  145. bool MessageLite::ParseFromCodedStream(io::CodedInputStream* input) {
  146. return InlineParseFromCodedStream(input, this);
  147. }
  148. bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) {
  149. return InlineParsePartialFromCodedStream(input, this);
  150. }
  151. bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) {
  152. io::CodedInputStream decoder(input);
  153. return ParseFromCodedStream(&decoder) && decoder.ConsumedEntireMessage();
  154. }
  155. bool MessageLite::ParsePartialFromZeroCopyStream(
  156. io::ZeroCopyInputStream* input) {
  157. io::CodedInputStream decoder(input);
  158. return ParsePartialFromCodedStream(&decoder) &&
  159. decoder.ConsumedEntireMessage();
  160. }
  161. bool MessageLite::ParseFromBoundedZeroCopyStream(
  162. io::ZeroCopyInputStream* input, int size) {
  163. io::CodedInputStream decoder(input);
  164. decoder.PushLimit(size);
  165. return ParseFromCodedStream(&decoder) &&
  166. decoder.ConsumedEntireMessage() &&
  167. decoder.BytesUntilLimit() == 0;
  168. }
  169. bool MessageLite::ParsePartialFromBoundedZeroCopyStream(
  170. io::ZeroCopyInputStream* input, int size) {
  171. io::CodedInputStream decoder(input);
  172. decoder.PushLimit(size);
  173. return ParsePartialFromCodedStream(&decoder) &&
  174. decoder.ConsumedEntireMessage() &&
  175. decoder.BytesUntilLimit() == 0;
  176. }
  177. bool MessageLite::ParseFromString(const string& data) {
  178. return InlineParseFromArray(data.data(), data.size(), this);
  179. }
  180. bool MessageLite::ParsePartialFromString(const string& data) {
  181. return InlineParsePartialFromArray(data.data(), data.size(), this);
  182. }
  183. bool MessageLite::ParseFromArray(const void* data, int size) {
  184. return InlineParseFromArray(data, size, this);
  185. }
  186. bool MessageLite::ParsePartialFromArray(const void* data, int size) {
  187. return InlineParsePartialFromArray(data, size, this);
  188. }
  189. // ===================================================================
  190. uint8* MessageLite::SerializeWithCachedSizesToArray(uint8* target) const {
  191. // We only optimize this when using optimize_for = SPEED. In other cases
  192. // we just use the CodedOutputStream path.
  193. int size = GetCachedSize();
  194. io::ArrayOutputStream out(target, size);
  195. io::CodedOutputStream coded_out(&out);
  196. SerializeWithCachedSizes(&coded_out);
  197. GOOGLE_CHECK(!coded_out.HadError());
  198. return target + size;
  199. }
  200. bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const {
  201. GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
  202. return SerializePartialToCodedStream(output);
  203. }
  204. bool MessageLite::SerializePartialToCodedStream(
  205. io::CodedOutputStream* output) const {
  206. const int size = ByteSize(); // Force size to be cached.
  207. if (size < 0) {
  208. // Messages >2G cannot be serialized due to overflow computing ByteSize.
  209. GOOGLE_LOG(ERROR) << "Error computing ByteSize (possible overflow?).";
  210. return false;
  211. }
  212. uint8* buffer = output->GetDirectBufferForNBytesAndAdvance(size);
  213. if (buffer != NULL) {
  214. uint8* end = SerializeWithCachedSizesToArray(buffer);
  215. if (end - buffer != size) {
  216. ByteSizeConsistencyError(size, ByteSize(), end - buffer);
  217. }
  218. return true;
  219. } else {
  220. int original_byte_count = output->ByteCount();
  221. SerializeWithCachedSizes(output);
  222. if (output->HadError()) {
  223. return false;
  224. }
  225. int final_byte_count = output->ByteCount();
  226. if (final_byte_count - original_byte_count != size) {
  227. ByteSizeConsistencyError(size, ByteSize(),
  228. final_byte_count - original_byte_count);
  229. }
  230. return true;
  231. }
  232. }
  233. bool MessageLite::SerializeToZeroCopyStream(
  234. io::ZeroCopyOutputStream* output) const {
  235. io::CodedOutputStream encoder(output);
  236. return SerializeToCodedStream(&encoder);
  237. }
  238. bool MessageLite::SerializePartialToZeroCopyStream(
  239. io::ZeroCopyOutputStream* output) const {
  240. io::CodedOutputStream encoder(output);
  241. return SerializePartialToCodedStream(&encoder);
  242. }
  243. bool MessageLite::AppendToString(string* output) const {
  244. GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
  245. return AppendPartialToString(output);
  246. }
  247. bool MessageLite::AppendPartialToString(string* output) const {
  248. int old_size = output->size();
  249. int byte_size = ByteSize();
  250. if (byte_size < 0) {
  251. // Messages >2G cannot be serialized due to overflow computing ByteSize.
  252. GOOGLE_LOG(ERROR) << "Error computing ByteSize (possible overflow?).";
  253. return false;
  254. }
  255. STLStringResizeUninitialized(output, old_size + byte_size);
  256. uint8* start =
  257. reinterpret_cast<uint8*>(io::mutable_string_data(output) + old_size);
  258. uint8* end = SerializeWithCachedSizesToArray(start);
  259. if (end - start != byte_size) {
  260. ByteSizeConsistencyError(byte_size, ByteSize(), end - start);
  261. }
  262. return true;
  263. }
  264. bool MessageLite::SerializeToString(string* output) const {
  265. output->clear();
  266. return AppendToString(output);
  267. }
  268. bool MessageLite::SerializePartialToString(string* output) const {
  269. output->clear();
  270. return AppendPartialToString(output);
  271. }
  272. bool MessageLite::SerializeToArray(void* data, int size) const {
  273. GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this);
  274. return SerializePartialToArray(data, size);
  275. }
  276. bool MessageLite::SerializePartialToArray(void* data, int size) const {
  277. int byte_size = ByteSize();
  278. if (size < byte_size) return false;
  279. uint8* start = reinterpret_cast<uint8*>(data);
  280. uint8* end = SerializeWithCachedSizesToArray(start);
  281. if (end - start != byte_size) {
  282. ByteSizeConsistencyError(byte_size, ByteSize(), end - start);
  283. }
  284. return true;
  285. }
  286. string MessageLite::SerializeAsString() const {
  287. // If the compiler implements the (Named) Return Value Optimization,
  288. // the local variable 'output' will not actually reside on the stack
  289. // of this function, but will be overlaid with the object that the
  290. // caller supplied for the return value to be constructed in.
  291. string output;
  292. if (!AppendToString(&output))
  293. output.clear();
  294. return output;
  295. }
  296. string MessageLite::SerializePartialAsString() const {
  297. string output;
  298. if (!AppendPartialToString(&output))
  299. output.clear();
  300. return output;
  301. }
  302. namespace internal {
  303. template<>
  304. MessageLite* GenericTypeHandler<MessageLite>::NewFromPrototype(
  305. const MessageLite* prototype, google::protobuf::Arena* arena) {
  306. return prototype->New(arena);
  307. }
  308. template <>
  309. void GenericTypeHandler<MessageLite>::Merge(const MessageLite& from,
  310. MessageLite* to) {
  311. to->CheckTypeAndMergeFrom(from);
  312. }
  313. } // namespace internal
  314. } // namespace protobuf
  315. } // namespace google