wire_format_unittest.cc 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  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. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #include <google/protobuf/wire_format.h>
  34. #include <google/protobuf/wire_format_lite_inl.h>
  35. #include <google/protobuf/descriptor.h>
  36. #include <google/protobuf/io/zero_copy_stream_impl.h>
  37. #include <google/protobuf/io/coded_stream.h>
  38. #include <google/protobuf/unittest.pb.h>
  39. #include <google/protobuf/unittest_proto3_arena.pb.h>
  40. #include <google/protobuf/unittest_mset.pb.h>
  41. #include <google/protobuf/unittest_mset_wire_format.pb.h>
  42. #include <google/protobuf/test_util.h>
  43. #include <google/protobuf/stubs/logging.h>
  44. #include <google/protobuf/stubs/common.h>
  45. #include <google/protobuf/stubs/logging.h>
  46. #include <google/protobuf/testing/googletest.h>
  47. #include <gtest/gtest.h>
  48. #include <google/protobuf/stubs/stl_util.h>
  49. namespace google {
  50. namespace protobuf {
  51. namespace internal {
  52. namespace {
  53. TEST(WireFormatTest, EnumsInSync) {
  54. // Verify that WireFormatLite::FieldType and WireFormatLite::CppType match
  55. // FieldDescriptor::Type and FieldDescriptor::CppType.
  56. EXPECT_EQ(implicit_cast<int>(FieldDescriptor::MAX_TYPE),
  57. implicit_cast<int>(WireFormatLite::MAX_FIELD_TYPE));
  58. EXPECT_EQ(implicit_cast<int>(FieldDescriptor::MAX_CPPTYPE),
  59. implicit_cast<int>(WireFormatLite::MAX_CPPTYPE));
  60. for (int i = 1; i <= WireFormatLite::MAX_FIELD_TYPE; i++) {
  61. EXPECT_EQ(
  62. implicit_cast<int>(FieldDescriptor::TypeToCppType(
  63. static_cast<FieldDescriptor::Type>(i))),
  64. implicit_cast<int>(WireFormatLite::FieldTypeToCppType(
  65. static_cast<WireFormatLite::FieldType>(i))));
  66. }
  67. }
  68. TEST(WireFormatTest, MaxFieldNumber) {
  69. // Make sure the max field number constant is accurate.
  70. EXPECT_EQ((1 << (32 - WireFormatLite::kTagTypeBits)) - 1,
  71. FieldDescriptor::kMaxNumber);
  72. }
  73. TEST(WireFormatTest, Parse) {
  74. unittest::TestAllTypes source, dest;
  75. string data;
  76. // Serialize using the generated code.
  77. TestUtil::SetAllFields(&source);
  78. source.SerializeToString(&data);
  79. // Parse using WireFormat.
  80. io::ArrayInputStream raw_input(data.data(), data.size());
  81. io::CodedInputStream input(&raw_input);
  82. WireFormat::ParseAndMergePartial(&input, &dest);
  83. // Check.
  84. TestUtil::ExpectAllFieldsSet(dest);
  85. }
  86. TEST(WireFormatTest, ParseExtensions) {
  87. unittest::TestAllExtensions source, dest;
  88. string data;
  89. // Serialize using the generated code.
  90. TestUtil::SetAllExtensions(&source);
  91. source.SerializeToString(&data);
  92. // Parse using WireFormat.
  93. io::ArrayInputStream raw_input(data.data(), data.size());
  94. io::CodedInputStream input(&raw_input);
  95. WireFormat::ParseAndMergePartial(&input, &dest);
  96. // Check.
  97. TestUtil::ExpectAllExtensionsSet(dest);
  98. }
  99. TEST(WireFormatTest, ParsePacked) {
  100. unittest::TestPackedTypes source, dest;
  101. string data;
  102. // Serialize using the generated code.
  103. TestUtil::SetPackedFields(&source);
  104. source.SerializeToString(&data);
  105. // Parse using WireFormat.
  106. io::ArrayInputStream raw_input(data.data(), data.size());
  107. io::CodedInputStream input(&raw_input);
  108. WireFormat::ParseAndMergePartial(&input, &dest);
  109. // Check.
  110. TestUtil::ExpectPackedFieldsSet(dest);
  111. }
  112. TEST(WireFormatTest, ParsePackedFromUnpacked) {
  113. // Serialize using the generated code.
  114. unittest::TestUnpackedTypes source;
  115. TestUtil::SetUnpackedFields(&source);
  116. string data = source.SerializeAsString();
  117. // Parse using WireFormat.
  118. unittest::TestPackedTypes dest;
  119. io::ArrayInputStream raw_input(data.data(), data.size());
  120. io::CodedInputStream input(&raw_input);
  121. WireFormat::ParseAndMergePartial(&input, &dest);
  122. // Check.
  123. TestUtil::ExpectPackedFieldsSet(dest);
  124. }
  125. TEST(WireFormatTest, ParseUnpackedFromPacked) {
  126. // Serialize using the generated code.
  127. unittest::TestPackedTypes source;
  128. TestUtil::SetPackedFields(&source);
  129. string data = source.SerializeAsString();
  130. // Parse using WireFormat.
  131. unittest::TestUnpackedTypes dest;
  132. io::ArrayInputStream raw_input(data.data(), data.size());
  133. io::CodedInputStream input(&raw_input);
  134. WireFormat::ParseAndMergePartial(&input, &dest);
  135. // Check.
  136. TestUtil::ExpectUnpackedFieldsSet(dest);
  137. }
  138. TEST(WireFormatTest, ParsePackedExtensions) {
  139. unittest::TestPackedExtensions source, dest;
  140. string data;
  141. // Serialize using the generated code.
  142. TestUtil::SetPackedExtensions(&source);
  143. source.SerializeToString(&data);
  144. // Parse using WireFormat.
  145. io::ArrayInputStream raw_input(data.data(), data.size());
  146. io::CodedInputStream input(&raw_input);
  147. WireFormat::ParseAndMergePartial(&input, &dest);
  148. // Check.
  149. TestUtil::ExpectPackedExtensionsSet(dest);
  150. }
  151. TEST(WireFormatTest, ParseOneof) {
  152. unittest::TestOneof2 source, dest;
  153. string data;
  154. // Serialize using the generated code.
  155. TestUtil::SetOneof1(&source);
  156. source.SerializeToString(&data);
  157. // Parse using WireFormat.
  158. io::ArrayInputStream raw_input(data.data(), data.size());
  159. io::CodedInputStream input(&raw_input);
  160. WireFormat::ParseAndMergePartial(&input, &dest);
  161. // Check.
  162. TestUtil::ExpectOneofSet1(dest);
  163. }
  164. TEST(WireFormatTest, OneofOnlySetLast) {
  165. unittest::TestOneofBackwardsCompatible source;
  166. unittest::TestOneof oneof_dest;
  167. string data;
  168. // Set two fields
  169. source.set_foo_int(100);
  170. source.set_foo_string("101");
  171. // Serialize and parse to oneof message.
  172. source.SerializeToString(&data);
  173. io::ArrayInputStream raw_input(data.data(), data.size());
  174. io::CodedInputStream input(&raw_input);
  175. WireFormat::ParseAndMergePartial(&input, &oneof_dest);
  176. // Only the last field is set.
  177. EXPECT_FALSE(oneof_dest.has_foo_int());
  178. EXPECT_TRUE(oneof_dest.has_foo_string());
  179. }
  180. TEST(WireFormatTest, ByteSize) {
  181. unittest::TestAllTypes message;
  182. TestUtil::SetAllFields(&message);
  183. EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message));
  184. message.Clear();
  185. EXPECT_EQ(0, message.ByteSize());
  186. EXPECT_EQ(0, WireFormat::ByteSize(message));
  187. }
  188. TEST(WireFormatTest, ByteSizeExtensions) {
  189. unittest::TestAllExtensions message;
  190. TestUtil::SetAllExtensions(&message);
  191. EXPECT_EQ(message.ByteSize(),
  192. WireFormat::ByteSize(message));
  193. message.Clear();
  194. EXPECT_EQ(0, message.ByteSize());
  195. EXPECT_EQ(0, WireFormat::ByteSize(message));
  196. }
  197. TEST(WireFormatTest, ByteSizePacked) {
  198. unittest::TestPackedTypes message;
  199. TestUtil::SetPackedFields(&message);
  200. EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message));
  201. message.Clear();
  202. EXPECT_EQ(0, message.ByteSize());
  203. EXPECT_EQ(0, WireFormat::ByteSize(message));
  204. }
  205. TEST(WireFormatTest, ByteSizePackedExtensions) {
  206. unittest::TestPackedExtensions message;
  207. TestUtil::SetPackedExtensions(&message);
  208. EXPECT_EQ(message.ByteSize(),
  209. WireFormat::ByteSize(message));
  210. message.Clear();
  211. EXPECT_EQ(0, message.ByteSize());
  212. EXPECT_EQ(0, WireFormat::ByteSize(message));
  213. }
  214. TEST(WireFormatTest, ByteSizeOneof) {
  215. unittest::TestOneof2 message;
  216. TestUtil::SetOneof1(&message);
  217. EXPECT_EQ(message.ByteSize(),
  218. WireFormat::ByteSize(message));
  219. message.Clear();
  220. EXPECT_EQ(0, message.ByteSize());
  221. EXPECT_EQ(0, WireFormat::ByteSize(message));
  222. }
  223. TEST(WireFormatTest, Serialize) {
  224. unittest::TestAllTypes message;
  225. string generated_data;
  226. string dynamic_data;
  227. TestUtil::SetAllFields(&message);
  228. int size = message.ByteSize();
  229. // Serialize using the generated code.
  230. {
  231. io::StringOutputStream raw_output(&generated_data);
  232. io::CodedOutputStream output(&raw_output);
  233. message.SerializeWithCachedSizes(&output);
  234. ASSERT_FALSE(output.HadError());
  235. }
  236. // Serialize using WireFormat.
  237. {
  238. io::StringOutputStream raw_output(&dynamic_data);
  239. io::CodedOutputStream output(&raw_output);
  240. WireFormat::SerializeWithCachedSizes(message, size, &output);
  241. ASSERT_FALSE(output.HadError());
  242. }
  243. // Should be the same.
  244. // Don't use EXPECT_EQ here because we're comparing raw binary data and
  245. // we really don't want it dumped to stdout on failure.
  246. EXPECT_TRUE(dynamic_data == generated_data);
  247. }
  248. TEST(WireFormatTest, SerializeExtensions) {
  249. unittest::TestAllExtensions message;
  250. string generated_data;
  251. string dynamic_data;
  252. TestUtil::SetAllExtensions(&message);
  253. int size = message.ByteSize();
  254. // Serialize using the generated code.
  255. {
  256. io::StringOutputStream raw_output(&generated_data);
  257. io::CodedOutputStream output(&raw_output);
  258. message.SerializeWithCachedSizes(&output);
  259. ASSERT_FALSE(output.HadError());
  260. }
  261. // Serialize using WireFormat.
  262. {
  263. io::StringOutputStream raw_output(&dynamic_data);
  264. io::CodedOutputStream output(&raw_output);
  265. WireFormat::SerializeWithCachedSizes(message, size, &output);
  266. ASSERT_FALSE(output.HadError());
  267. }
  268. // Should be the same.
  269. // Don't use EXPECT_EQ here because we're comparing raw binary data and
  270. // we really don't want it dumped to stdout on failure.
  271. EXPECT_TRUE(dynamic_data == generated_data);
  272. }
  273. TEST(WireFormatTest, SerializeFieldsAndExtensions) {
  274. unittest::TestFieldOrderings message;
  275. string generated_data;
  276. string dynamic_data;
  277. TestUtil::SetAllFieldsAndExtensions(&message);
  278. int size = message.ByteSize();
  279. // Serialize using the generated code.
  280. {
  281. io::StringOutputStream raw_output(&generated_data);
  282. io::CodedOutputStream output(&raw_output);
  283. message.SerializeWithCachedSizes(&output);
  284. ASSERT_FALSE(output.HadError());
  285. }
  286. // Serialize using WireFormat.
  287. {
  288. io::StringOutputStream raw_output(&dynamic_data);
  289. io::CodedOutputStream output(&raw_output);
  290. WireFormat::SerializeWithCachedSizes(message, size, &output);
  291. ASSERT_FALSE(output.HadError());
  292. }
  293. // Should be the same.
  294. // Don't use EXPECT_EQ here because we're comparing raw binary data and
  295. // we really don't want it dumped to stdout on failure.
  296. EXPECT_TRUE(dynamic_data == generated_data);
  297. // Should output in canonical order.
  298. TestUtil::ExpectAllFieldsAndExtensionsInOrder(dynamic_data);
  299. TestUtil::ExpectAllFieldsAndExtensionsInOrder(generated_data);
  300. }
  301. TEST(WireFormatTest, SerializeOneof) {
  302. unittest::TestOneof2 message;
  303. string generated_data;
  304. string dynamic_data;
  305. TestUtil::SetOneof1(&message);
  306. int size = message.ByteSize();
  307. // Serialize using the generated code.
  308. {
  309. io::StringOutputStream raw_output(&generated_data);
  310. io::CodedOutputStream output(&raw_output);
  311. message.SerializeWithCachedSizes(&output);
  312. ASSERT_FALSE(output.HadError());
  313. }
  314. // Serialize using WireFormat.
  315. {
  316. io::StringOutputStream raw_output(&dynamic_data);
  317. io::CodedOutputStream output(&raw_output);
  318. WireFormat::SerializeWithCachedSizes(message, size, &output);
  319. ASSERT_FALSE(output.HadError());
  320. }
  321. // Should be the same.
  322. // Don't use EXPECT_EQ here because we're comparing raw binary data and
  323. // we really don't want it dumped to stdout on failure.
  324. EXPECT_TRUE(dynamic_data == generated_data);
  325. }
  326. TEST(WireFormatTest, ParseMultipleExtensionRanges) {
  327. // Make sure we can parse a message that contains multiple extensions ranges.
  328. unittest::TestFieldOrderings source;
  329. string data;
  330. TestUtil::SetAllFieldsAndExtensions(&source);
  331. source.SerializeToString(&data);
  332. {
  333. unittest::TestFieldOrderings dest;
  334. EXPECT_TRUE(dest.ParseFromString(data));
  335. EXPECT_EQ(source.DebugString(), dest.DebugString());
  336. }
  337. // Also test using reflection-based parsing.
  338. {
  339. unittest::TestFieldOrderings dest;
  340. io::ArrayInputStream raw_input(data.data(), data.size());
  341. io::CodedInputStream coded_input(&raw_input);
  342. EXPECT_TRUE(WireFormat::ParseAndMergePartial(&coded_input, &dest));
  343. EXPECT_EQ(source.DebugString(), dest.DebugString());
  344. }
  345. }
  346. const int kUnknownTypeId = 1550055;
  347. TEST(WireFormatTest, SerializeMessageSet) {
  348. // Set up a TestMessageSet with two known messages and an unknown one.
  349. proto2_wireformat_unittest::TestMessageSet message_set;
  350. message_set.MutableExtension(
  351. unittest::TestMessageSetExtension1::message_set_extension)->set_i(123);
  352. message_set.MutableExtension(
  353. unittest::TestMessageSetExtension2::message_set_extension)->set_str("foo");
  354. message_set.mutable_unknown_fields()->AddLengthDelimited(
  355. kUnknownTypeId, "bar");
  356. string data;
  357. ASSERT_TRUE(message_set.SerializeToString(&data));
  358. // Parse back using RawMessageSet and check the contents.
  359. unittest::RawMessageSet raw;
  360. ASSERT_TRUE(raw.ParseFromString(data));
  361. EXPECT_EQ(0, raw.unknown_fields().field_count());
  362. ASSERT_EQ(3, raw.item_size());
  363. EXPECT_EQ(
  364. unittest::TestMessageSetExtension1::descriptor()->extension(0)->number(),
  365. raw.item(0).type_id());
  366. EXPECT_EQ(
  367. unittest::TestMessageSetExtension2::descriptor()->extension(0)->number(),
  368. raw.item(1).type_id());
  369. EXPECT_EQ(kUnknownTypeId, raw.item(2).type_id());
  370. unittest::TestMessageSetExtension1 message1;
  371. EXPECT_TRUE(message1.ParseFromString(raw.item(0).message()));
  372. EXPECT_EQ(123, message1.i());
  373. unittest::TestMessageSetExtension2 message2;
  374. EXPECT_TRUE(message2.ParseFromString(raw.item(1).message()));
  375. EXPECT_EQ("foo", message2.str());
  376. EXPECT_EQ("bar", raw.item(2).message());
  377. }
  378. TEST(WireFormatTest, SerializeMessageSetVariousWaysAreEqual) {
  379. // Serialize a MessageSet to a stream and to a flat array using generated
  380. // code, and also using WireFormat, and check that the results are equal.
  381. // Set up a TestMessageSet with two known messages and an unknown one, as
  382. // above.
  383. proto2_wireformat_unittest::TestMessageSet message_set;
  384. message_set.MutableExtension(
  385. unittest::TestMessageSetExtension1::message_set_extension)->set_i(123);
  386. message_set.MutableExtension(
  387. unittest::TestMessageSetExtension2::message_set_extension)->set_str("foo");
  388. message_set.mutable_unknown_fields()->AddLengthDelimited(
  389. kUnknownTypeId, "bar");
  390. int size = message_set.ByteSize();
  391. EXPECT_EQ(size, message_set.GetCachedSize());
  392. ASSERT_EQ(size, WireFormat::ByteSize(message_set));
  393. string flat_data;
  394. string stream_data;
  395. string dynamic_data;
  396. flat_data.resize(size);
  397. stream_data.resize(size);
  398. // Serialize to flat array
  399. {
  400. uint8* target = reinterpret_cast<uint8*>(string_as_array(&flat_data));
  401. uint8* end = message_set.SerializeWithCachedSizesToArray(target);
  402. EXPECT_EQ(size, end - target);
  403. }
  404. // Serialize to buffer
  405. {
  406. io::ArrayOutputStream array_stream(string_as_array(&stream_data), size, 1);
  407. io::CodedOutputStream output_stream(&array_stream);
  408. message_set.SerializeWithCachedSizes(&output_stream);
  409. ASSERT_FALSE(output_stream.HadError());
  410. }
  411. // Serialize to buffer with WireFormat.
  412. {
  413. io::StringOutputStream string_stream(&dynamic_data);
  414. io::CodedOutputStream output_stream(&string_stream);
  415. WireFormat::SerializeWithCachedSizes(message_set, size, &output_stream);
  416. ASSERT_FALSE(output_stream.HadError());
  417. }
  418. EXPECT_TRUE(flat_data == stream_data);
  419. EXPECT_TRUE(flat_data == dynamic_data);
  420. }
  421. TEST(WireFormatTest, ParseMessageSet) {
  422. // Set up a RawMessageSet with two known messages and an unknown one.
  423. unittest::RawMessageSet raw;
  424. {
  425. unittest::RawMessageSet::Item* item = raw.add_item();
  426. item->set_type_id(
  427. unittest::TestMessageSetExtension1::descriptor()->extension(0)->number());
  428. unittest::TestMessageSetExtension1 message;
  429. message.set_i(123);
  430. message.SerializeToString(item->mutable_message());
  431. }
  432. {
  433. unittest::RawMessageSet::Item* item = raw.add_item();
  434. item->set_type_id(
  435. unittest::TestMessageSetExtension2::descriptor()->extension(0)->number());
  436. unittest::TestMessageSetExtension2 message;
  437. message.set_str("foo");
  438. message.SerializeToString(item->mutable_message());
  439. }
  440. {
  441. unittest::RawMessageSet::Item* item = raw.add_item();
  442. item->set_type_id(kUnknownTypeId);
  443. item->set_message("bar");
  444. }
  445. string data;
  446. ASSERT_TRUE(raw.SerializeToString(&data));
  447. // Parse as a TestMessageSet and check the contents.
  448. proto2_wireformat_unittest::TestMessageSet message_set;
  449. ASSERT_TRUE(message_set.ParseFromString(data));
  450. EXPECT_EQ(123, message_set.GetExtension(
  451. unittest::TestMessageSetExtension1::message_set_extension).i());
  452. EXPECT_EQ("foo", message_set.GetExtension(
  453. unittest::TestMessageSetExtension2::message_set_extension).str());
  454. ASSERT_EQ(1, message_set.unknown_fields().field_count());
  455. ASSERT_EQ(UnknownField::TYPE_LENGTH_DELIMITED,
  456. message_set.unknown_fields().field(0).type());
  457. EXPECT_EQ("bar", message_set.unknown_fields().field(0).length_delimited());
  458. // Also parse using WireFormat.
  459. proto2_wireformat_unittest::TestMessageSet dynamic_message_set;
  460. io::CodedInputStream input(reinterpret_cast<const uint8*>(data.data()),
  461. data.size());
  462. ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &dynamic_message_set));
  463. EXPECT_EQ(message_set.DebugString(), dynamic_message_set.DebugString());
  464. }
  465. TEST(WireFormatTest, ParseMessageSetWithReverseTagOrder) {
  466. string data;
  467. {
  468. unittest::TestMessageSetExtension1 message;
  469. message.set_i(123);
  470. // Build a MessageSet manually with its message content put before its
  471. // type_id.
  472. io::StringOutputStream output_stream(&data);
  473. io::CodedOutputStream coded_output(&output_stream);
  474. coded_output.WriteTag(WireFormatLite::kMessageSetItemStartTag);
  475. // Write the message content first.
  476. WireFormatLite::WriteTag(WireFormatLite::kMessageSetMessageNumber,
  477. WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
  478. &coded_output);
  479. coded_output.WriteVarint32(message.ByteSize());
  480. message.SerializeWithCachedSizes(&coded_output);
  481. // Write the type id.
  482. uint32 type_id = message.GetDescriptor()->extension(0)->number();
  483. WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber,
  484. type_id, &coded_output);
  485. coded_output.WriteTag(WireFormatLite::kMessageSetItemEndTag);
  486. }
  487. {
  488. proto2_wireformat_unittest::TestMessageSet message_set;
  489. ASSERT_TRUE(message_set.ParseFromString(data));
  490. EXPECT_EQ(123, message_set.GetExtension(
  491. unittest::TestMessageSetExtension1::message_set_extension).i());
  492. }
  493. {
  494. // Test parse the message via Reflection.
  495. proto2_wireformat_unittest::TestMessageSet message_set;
  496. io::CodedInputStream input(
  497. reinterpret_cast<const uint8*>(data.data()), data.size());
  498. EXPECT_TRUE(WireFormat::ParseAndMergePartial(&input, &message_set));
  499. EXPECT_TRUE(input.ConsumedEntireMessage());
  500. EXPECT_EQ(123, message_set.GetExtension(
  501. unittest::TestMessageSetExtension1::message_set_extension).i());
  502. }
  503. }
  504. TEST(WireFormatTest, ParseBrokenMessageSet) {
  505. proto2_wireformat_unittest::TestMessageSet message_set;
  506. string input("goodbye"); // Invalid wire format data.
  507. EXPECT_FALSE(message_set.ParseFromString(input));
  508. }
  509. TEST(WireFormatTest, RecursionLimit) {
  510. unittest::TestRecursiveMessage message;
  511. message.mutable_a()->mutable_a()->mutable_a()->mutable_a()->set_i(1);
  512. string data;
  513. message.SerializeToString(&data);
  514. {
  515. io::ArrayInputStream raw_input(data.data(), data.size());
  516. io::CodedInputStream input(&raw_input);
  517. input.SetRecursionLimit(4);
  518. unittest::TestRecursiveMessage message2;
  519. EXPECT_TRUE(message2.ParseFromCodedStream(&input));
  520. }
  521. {
  522. io::ArrayInputStream raw_input(data.data(), data.size());
  523. io::CodedInputStream input(&raw_input);
  524. input.SetRecursionLimit(3);
  525. unittest::TestRecursiveMessage message2;
  526. EXPECT_FALSE(message2.ParseFromCodedStream(&input));
  527. }
  528. }
  529. TEST(WireFormatTest, UnknownFieldRecursionLimit) {
  530. unittest::TestEmptyMessage message;
  531. message.mutable_unknown_fields()
  532. ->AddGroup(1234)
  533. ->AddGroup(1234)
  534. ->AddGroup(1234)
  535. ->AddGroup(1234)
  536. ->AddVarint(1234, 123);
  537. string data;
  538. message.SerializeToString(&data);
  539. {
  540. io::ArrayInputStream raw_input(data.data(), data.size());
  541. io::CodedInputStream input(&raw_input);
  542. input.SetRecursionLimit(4);
  543. unittest::TestEmptyMessage message2;
  544. EXPECT_TRUE(message2.ParseFromCodedStream(&input));
  545. }
  546. {
  547. io::ArrayInputStream raw_input(data.data(), data.size());
  548. io::CodedInputStream input(&raw_input);
  549. input.SetRecursionLimit(3);
  550. unittest::TestEmptyMessage message2;
  551. EXPECT_FALSE(message2.ParseFromCodedStream(&input));
  552. }
  553. }
  554. TEST(WireFormatTest, ZigZag) {
  555. // avoid line-wrapping
  556. #define LL(x) GOOGLE_LONGLONG(x)
  557. #define ULL(x) GOOGLE_ULONGLONG(x)
  558. #define ZigZagEncode32(x) WireFormatLite::ZigZagEncode32(x)
  559. #define ZigZagDecode32(x) WireFormatLite::ZigZagDecode32(x)
  560. #define ZigZagEncode64(x) WireFormatLite::ZigZagEncode64(x)
  561. #define ZigZagDecode64(x) WireFormatLite::ZigZagDecode64(x)
  562. EXPECT_EQ(0u, ZigZagEncode32( 0));
  563. EXPECT_EQ(1u, ZigZagEncode32(-1));
  564. EXPECT_EQ(2u, ZigZagEncode32( 1));
  565. EXPECT_EQ(3u, ZigZagEncode32(-2));
  566. EXPECT_EQ(0x7FFFFFFEu, ZigZagEncode32(0x3FFFFFFF));
  567. EXPECT_EQ(0x7FFFFFFFu, ZigZagEncode32(0xC0000000));
  568. EXPECT_EQ(0xFFFFFFFEu, ZigZagEncode32(0x7FFFFFFF));
  569. EXPECT_EQ(0xFFFFFFFFu, ZigZagEncode32(0x80000000));
  570. EXPECT_EQ( 0, ZigZagDecode32(0u));
  571. EXPECT_EQ(-1, ZigZagDecode32(1u));
  572. EXPECT_EQ( 1, ZigZagDecode32(2u));
  573. EXPECT_EQ(-2, ZigZagDecode32(3u));
  574. EXPECT_EQ(0x3FFFFFFF, ZigZagDecode32(0x7FFFFFFEu));
  575. EXPECT_EQ(0xC0000000, ZigZagDecode32(0x7FFFFFFFu));
  576. EXPECT_EQ(0x7FFFFFFF, ZigZagDecode32(0xFFFFFFFEu));
  577. EXPECT_EQ(0x80000000, ZigZagDecode32(0xFFFFFFFFu));
  578. EXPECT_EQ(0u, ZigZagEncode64( 0));
  579. EXPECT_EQ(1u, ZigZagEncode64(-1));
  580. EXPECT_EQ(2u, ZigZagEncode64( 1));
  581. EXPECT_EQ(3u, ZigZagEncode64(-2));
  582. EXPECT_EQ(ULL(0x000000007FFFFFFE), ZigZagEncode64(LL(0x000000003FFFFFFF)));
  583. EXPECT_EQ(ULL(0x000000007FFFFFFF), ZigZagEncode64(LL(0xFFFFFFFFC0000000)));
  584. EXPECT_EQ(ULL(0x00000000FFFFFFFE), ZigZagEncode64(LL(0x000000007FFFFFFF)));
  585. EXPECT_EQ(ULL(0x00000000FFFFFFFF), ZigZagEncode64(LL(0xFFFFFFFF80000000)));
  586. EXPECT_EQ(ULL(0xFFFFFFFFFFFFFFFE), ZigZagEncode64(LL(0x7FFFFFFFFFFFFFFF)));
  587. EXPECT_EQ(ULL(0xFFFFFFFFFFFFFFFF), ZigZagEncode64(LL(0x8000000000000000)));
  588. EXPECT_EQ( 0, ZigZagDecode64(0u));
  589. EXPECT_EQ(-1, ZigZagDecode64(1u));
  590. EXPECT_EQ( 1, ZigZagDecode64(2u));
  591. EXPECT_EQ(-2, ZigZagDecode64(3u));
  592. EXPECT_EQ(LL(0x000000003FFFFFFF), ZigZagDecode64(ULL(0x000000007FFFFFFE)));
  593. EXPECT_EQ(LL(0xFFFFFFFFC0000000), ZigZagDecode64(ULL(0x000000007FFFFFFF)));
  594. EXPECT_EQ(LL(0x000000007FFFFFFF), ZigZagDecode64(ULL(0x00000000FFFFFFFE)));
  595. EXPECT_EQ(LL(0xFFFFFFFF80000000), ZigZagDecode64(ULL(0x00000000FFFFFFFF)));
  596. EXPECT_EQ(LL(0x7FFFFFFFFFFFFFFF), ZigZagDecode64(ULL(0xFFFFFFFFFFFFFFFE)));
  597. EXPECT_EQ(LL(0x8000000000000000), ZigZagDecode64(ULL(0xFFFFFFFFFFFFFFFF)));
  598. // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
  599. // were chosen semi-randomly via keyboard bashing.
  600. EXPECT_EQ( 0, ZigZagDecode32(ZigZagEncode32( 0)));
  601. EXPECT_EQ( 1, ZigZagDecode32(ZigZagEncode32( 1)));
  602. EXPECT_EQ( -1, ZigZagDecode32(ZigZagEncode32( -1)));
  603. EXPECT_EQ(14927, ZigZagDecode32(ZigZagEncode32(14927)));
  604. EXPECT_EQ(-3612, ZigZagDecode32(ZigZagEncode32(-3612)));
  605. EXPECT_EQ( 0, ZigZagDecode64(ZigZagEncode64( 0)));
  606. EXPECT_EQ( 1, ZigZagDecode64(ZigZagEncode64( 1)));
  607. EXPECT_EQ( -1, ZigZagDecode64(ZigZagEncode64( -1)));
  608. EXPECT_EQ(14927, ZigZagDecode64(ZigZagEncode64(14927)));
  609. EXPECT_EQ(-3612, ZigZagDecode64(ZigZagEncode64(-3612)));
  610. EXPECT_EQ(LL(856912304801416), ZigZagDecode64(ZigZagEncode64(
  611. LL(856912304801416))));
  612. EXPECT_EQ(LL(-75123905439571256), ZigZagDecode64(ZigZagEncode64(
  613. LL(-75123905439571256))));
  614. }
  615. TEST(WireFormatTest, RepeatedScalarsDifferentTagSizes) {
  616. // At one point checks would trigger when parsing repeated fixed scalar
  617. // fields.
  618. protobuf_unittest::TestRepeatedScalarDifferentTagSizes msg1, msg2;
  619. for (int i = 0; i < 100; ++i) {
  620. msg1.add_repeated_fixed32(i);
  621. msg1.add_repeated_int32(i);
  622. msg1.add_repeated_fixed64(i);
  623. msg1.add_repeated_int64(i);
  624. msg1.add_repeated_float(i);
  625. msg1.add_repeated_uint64(i);
  626. }
  627. // Make sure that we have a variety of tag sizes.
  628. const google::protobuf::Descriptor* desc = msg1.GetDescriptor();
  629. const google::protobuf::FieldDescriptor* field;
  630. field = desc->FindFieldByName("repeated_fixed32");
  631. ASSERT_TRUE(field != NULL);
  632. ASSERT_EQ(1, WireFormat::TagSize(field->number(), field->type()));
  633. field = desc->FindFieldByName("repeated_int32");
  634. ASSERT_TRUE(field != NULL);
  635. ASSERT_EQ(1, WireFormat::TagSize(field->number(), field->type()));
  636. field = desc->FindFieldByName("repeated_fixed64");
  637. ASSERT_TRUE(field != NULL);
  638. ASSERT_EQ(2, WireFormat::TagSize(field->number(), field->type()));
  639. field = desc->FindFieldByName("repeated_int64");
  640. ASSERT_TRUE(field != NULL);
  641. ASSERT_EQ(2, WireFormat::TagSize(field->number(), field->type()));
  642. field = desc->FindFieldByName("repeated_float");
  643. ASSERT_TRUE(field != NULL);
  644. ASSERT_EQ(3, WireFormat::TagSize(field->number(), field->type()));
  645. field = desc->FindFieldByName("repeated_uint64");
  646. ASSERT_TRUE(field != NULL);
  647. ASSERT_EQ(3, WireFormat::TagSize(field->number(), field->type()));
  648. EXPECT_TRUE(msg2.ParseFromString(msg1.SerializeAsString()));
  649. EXPECT_EQ(msg1.DebugString(), msg2.DebugString());
  650. }
  651. TEST(WireFormatTest, CompatibleTypes) {
  652. const int64 data = 0x100000000LL;
  653. unittest::Int64Message msg1;
  654. msg1.set_data(data);
  655. string serialized;
  656. msg1.SerializeToString(&serialized);
  657. // Test int64 is compatible with bool
  658. unittest::BoolMessage msg2;
  659. ASSERT_TRUE(msg2.ParseFromString(serialized));
  660. ASSERT_EQ(static_cast<bool>(data), msg2.data());
  661. // Test int64 is compatible with uint64
  662. unittest::Uint64Message msg3;
  663. ASSERT_TRUE(msg3.ParseFromString(serialized));
  664. ASSERT_EQ(static_cast<uint64>(data), msg3.data());
  665. // Test int64 is compatible with int32
  666. unittest::Int32Message msg4;
  667. ASSERT_TRUE(msg4.ParseFromString(serialized));
  668. ASSERT_EQ(static_cast<int32>(data), msg4.data());
  669. // Test int64 is compatible with uint32
  670. unittest::Uint32Message msg5;
  671. ASSERT_TRUE(msg5.ParseFromString(serialized));
  672. ASSERT_EQ(static_cast<uint32>(data), msg5.data());
  673. }
  674. class Proto3PrimitiveRepeatedWireFormatTest : public ::testing::Test {
  675. protected:
  676. Proto3PrimitiveRepeatedWireFormatTest()
  677. : packedTestAllTypes_(
  678. "\xFA\x01\x01\x01"
  679. "\x82\x02\x01\x01"
  680. "\x8A\x02\x01\x01"
  681. "\x92\x02\x01\x01"
  682. "\x9A\x02\x01\x02"
  683. "\xA2\x02\x01\x02"
  684. "\xAA\x02\x04\x01\x00\x00\x00"
  685. "\xB2\x02\x08\x01\x00\x00\x00\x00\x00\x00\x00"
  686. "\xBA\x02\x04\x01\x00\x00\x00"
  687. "\xC2\x02\x08\x01\x00\x00\x00\x00\x00\x00\x00"
  688. "\xCA\x02\x04\x00\x00\x80\x3f"
  689. "\xD2\x02\x08\x00\x00\x00\x00\x00\x00\xf0\x3f"
  690. "\xDA\x02\x01\x01"
  691. "\x9A\x03\x01\x01",
  692. 86),
  693. packedTestUnpackedTypes_(
  694. "\x0A\x01\x01"
  695. "\x12\x01\x01"
  696. "\x1A\x01\x01"
  697. "\x22\x01\x01"
  698. "\x2A\x01\x02"
  699. "\x32\x01\x02"
  700. "\x3A\x04\x01\x00\x00\x00"
  701. "\x42\x08\x01\x00\x00\x00\x00\x00\x00\x00"
  702. "\x4A\x04\x01\x00\x00\x00"
  703. "\x52\x08\x01\x00\x00\x00\x00\x00\x00\x00"
  704. "\x5A\x04\x00\x00\x80\x3f"
  705. "\x62\x08\x00\x00\x00\x00\x00\x00\xf0\x3f"
  706. "\x6A\x01\x01"
  707. "\x72\x01\x01",
  708. 72),
  709. unpackedTestAllTypes_(
  710. "\xF8\x01\x01"
  711. "\x80\x02\x01"
  712. "\x88\x02\x01"
  713. "\x90\x02\x01"
  714. "\x98\x02\x02"
  715. "\xA0\x02\x02"
  716. "\xAD\x02\x01\x00\x00\x00"
  717. "\xB1\x02\x01\x00\x00\x00\x00\x00\x00\x00"
  718. "\xBD\x02\x01\x00\x00\x00"
  719. "\xC1\x02\x01\x00\x00\x00\x00\x00\x00\x00"
  720. "\xCD\x02\x00\x00\x80\x3f"
  721. "\xD1\x02\x00\x00\x00\x00\x00\x00\xf0\x3f"
  722. "\xD8\x02\x01"
  723. "\x98\x03\x01",
  724. 72),
  725. unpackedTestUnpackedTypes_(
  726. "\x08\x01"
  727. "\x10\x01"
  728. "\x18\x01"
  729. "\x20\x01"
  730. "\x28\x02"
  731. "\x30\x02"
  732. "\x3D\x01\x00\x00\x00"
  733. "\x41\x01\x00\x00\x00\x00\x00\x00\x00"
  734. "\x4D\x01\x00\x00\x00"
  735. "\x51\x01\x00\x00\x00\x00\x00\x00\x00"
  736. "\x5D\x00\x00\x80\x3f"
  737. "\x61\x00\x00\x00\x00\x00\x00\xf0\x3f"
  738. "\x68\x01"
  739. "\x70\x01",
  740. 58) {}
  741. template <class Proto>
  742. void SetProto3PrimitiveRepeatedFields(Proto* message) {
  743. message->add_repeated_int32(1);
  744. message->add_repeated_int64(1);
  745. message->add_repeated_uint32(1);
  746. message->add_repeated_uint64(1);
  747. message->add_repeated_sint32(1);
  748. message->add_repeated_sint64(1);
  749. message->add_repeated_fixed32(1);
  750. message->add_repeated_fixed64(1);
  751. message->add_repeated_sfixed32(1);
  752. message->add_repeated_sfixed64(1);
  753. message->add_repeated_float(1.0);
  754. message->add_repeated_double(1.0);
  755. message->add_repeated_bool(true);
  756. message->add_repeated_nested_enum(
  757. proto3_arena_unittest::TestAllTypes_NestedEnum_FOO);
  758. }
  759. template <class Proto>
  760. void ExpectProto3PrimitiveRepeatedFieldsSet(const Proto& message) {
  761. EXPECT_EQ(1, message.repeated_int32(0));
  762. EXPECT_EQ(1, message.repeated_int64(0));
  763. EXPECT_EQ(1, message.repeated_uint32(0));
  764. EXPECT_EQ(1, message.repeated_uint64(0));
  765. EXPECT_EQ(1, message.repeated_sint32(0));
  766. EXPECT_EQ(1, message.repeated_sint64(0));
  767. EXPECT_EQ(1, message.repeated_fixed32(0));
  768. EXPECT_EQ(1, message.repeated_fixed64(0));
  769. EXPECT_EQ(1, message.repeated_sfixed32(0));
  770. EXPECT_EQ(1, message.repeated_sfixed64(0));
  771. EXPECT_EQ(1.0, message.repeated_float(0));
  772. EXPECT_EQ(1.0, message.repeated_double(0));
  773. EXPECT_EQ(true, message.repeated_bool(0));
  774. EXPECT_EQ(proto3_arena_unittest::TestAllTypes_NestedEnum_FOO,
  775. message.repeated_nested_enum(0));
  776. }
  777. template <class Proto>
  778. void TestSerialization(Proto* message, const string& expected) {
  779. SetProto3PrimitiveRepeatedFields(message);
  780. int size = message->ByteSize();
  781. // Serialize using the generated code.
  782. string generated_data;
  783. {
  784. io::StringOutputStream raw_output(&generated_data);
  785. io::CodedOutputStream output(&raw_output);
  786. message->SerializeWithCachedSizes(&output);
  787. ASSERT_FALSE(output.HadError());
  788. }
  789. EXPECT_TRUE(expected == generated_data);
  790. // Serialize using the dynamic code.
  791. string dynamic_data;
  792. {
  793. io::StringOutputStream raw_output(&dynamic_data);
  794. io::CodedOutputStream output(&raw_output);
  795. WireFormat::SerializeWithCachedSizes(*message, size, &output);
  796. ASSERT_FALSE(output.HadError());
  797. }
  798. EXPECT_TRUE(expected == dynamic_data);
  799. }
  800. template <class Proto>
  801. void TestParsing(Proto* message, const string& compatible_data) {
  802. message->Clear();
  803. message->ParseFromString(compatible_data);
  804. ExpectProto3PrimitiveRepeatedFieldsSet(*message);
  805. message->Clear();
  806. io::CodedInputStream input(
  807. reinterpret_cast<const uint8*>(compatible_data.data()),
  808. compatible_data.size());
  809. WireFormat::ParseAndMergePartial(&input, message);
  810. ExpectProto3PrimitiveRepeatedFieldsSet(*message);
  811. }
  812. const string packedTestAllTypes_;
  813. const string packedTestUnpackedTypes_;
  814. const string unpackedTestAllTypes_;
  815. const string unpackedTestUnpackedTypes_;
  816. };
  817. TEST_F(Proto3PrimitiveRepeatedWireFormatTest, Proto3PrimitiveRepeated) {
  818. proto3_arena_unittest::TestAllTypes packed_message;
  819. proto3_arena_unittest::TestUnpackedTypes unpacked_message;
  820. TestSerialization(&packed_message, packedTestAllTypes_);
  821. TestParsing(&packed_message, packedTestAllTypes_);
  822. TestParsing(&packed_message, unpackedTestAllTypes_);
  823. TestSerialization(&unpacked_message, unpackedTestUnpackedTypes_);
  824. TestParsing(&unpacked_message, packedTestUnpackedTypes_);
  825. TestParsing(&unpacked_message, unpackedTestUnpackedTypes_);
  826. }
  827. class WireFormatInvalidInputTest : public testing::Test {
  828. protected:
  829. // Make a serialized TestAllTypes in which the field optional_nested_message
  830. // contains exactly the given bytes, which may be invalid.
  831. string MakeInvalidEmbeddedMessage(const char* bytes, int size) {
  832. const FieldDescriptor* field =
  833. unittest::TestAllTypes::descriptor()->FindFieldByName(
  834. "optional_nested_message");
  835. GOOGLE_CHECK(field != NULL);
  836. string result;
  837. {
  838. io::StringOutputStream raw_output(&result);
  839. io::CodedOutputStream output(&raw_output);
  840. WireFormatLite::WriteBytes(field->number(), string(bytes, size), &output);
  841. }
  842. return result;
  843. }
  844. // Make a serialized TestAllTypes in which the field optionalgroup
  845. // contains exactly the given bytes -- which may be invalid -- and
  846. // possibly no end tag.
  847. string MakeInvalidGroup(const char* bytes, int size, bool include_end_tag) {
  848. const FieldDescriptor* field =
  849. unittest::TestAllTypes::descriptor()->FindFieldByName(
  850. "optionalgroup");
  851. GOOGLE_CHECK(field != NULL);
  852. string result;
  853. {
  854. io::StringOutputStream raw_output(&result);
  855. io::CodedOutputStream output(&raw_output);
  856. output.WriteVarint32(WireFormat::MakeTag(field));
  857. output.WriteString(string(bytes, size));
  858. if (include_end_tag) {
  859. output.WriteVarint32(WireFormatLite::MakeTag(
  860. field->number(), WireFormatLite::WIRETYPE_END_GROUP));
  861. }
  862. }
  863. return result;
  864. }
  865. };
  866. TEST_F(WireFormatInvalidInputTest, InvalidSubMessage) {
  867. unittest::TestAllTypes message;
  868. // Control case.
  869. EXPECT_TRUE(message.ParseFromString(MakeInvalidEmbeddedMessage("", 0)));
  870. // The byte is a valid varint, but not a valid tag (zero).
  871. EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\0", 1)));
  872. // The byte is a malformed varint.
  873. EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\200", 1)));
  874. // The byte is an endgroup tag, but we aren't parsing a group.
  875. EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\014", 1)));
  876. // The byte is a valid varint but not a valid tag (bad wire type).
  877. EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\017", 1)));
  878. }
  879. TEST_F(WireFormatInvalidInputTest, InvalidMessageWithExtraZero) {
  880. string data;
  881. {
  882. // Serialize a valid proto
  883. unittest::TestAllTypes message;
  884. message.set_optional_int32(1);
  885. message.SerializeToString(&data);
  886. data.push_back(0); // Append invalid zero tag
  887. }
  888. // Control case.
  889. {
  890. io::ArrayInputStream ais(data.data(), data.size());
  891. io::CodedInputStream is(&ais);
  892. unittest::TestAllTypes message;
  893. // It should fail but currently passes.
  894. EXPECT_TRUE(message.MergePartialFromCodedStream(&is));
  895. // Parsing from the string should fail.
  896. EXPECT_FALSE(message.ParseFromString(data));
  897. }
  898. }
  899. TEST_F(WireFormatInvalidInputTest, InvalidGroup) {
  900. unittest::TestAllTypes message;
  901. // Control case.
  902. EXPECT_TRUE(message.ParseFromString(MakeInvalidGroup("", 0, true)));
  903. // Missing end tag. Groups cannot end at EOF.
  904. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("", 0, false)));
  905. // The byte is a valid varint, but not a valid tag (zero).
  906. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\0", 1, false)));
  907. // The byte is a malformed varint.
  908. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\200", 1, false)));
  909. // The byte is an endgroup tag, but not the right one for this group.
  910. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\014", 1, false)));
  911. // The byte is a valid varint but not a valid tag (bad wire type).
  912. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\017", 1, true)));
  913. }
  914. TEST_F(WireFormatInvalidInputTest, InvalidUnknownGroup) {
  915. // Use TestEmptyMessage so that the group made by MakeInvalidGroup will not
  916. // be a known tag number.
  917. unittest::TestEmptyMessage message;
  918. // Control case.
  919. EXPECT_TRUE(message.ParseFromString(MakeInvalidGroup("", 0, true)));
  920. // Missing end tag. Groups cannot end at EOF.
  921. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("", 0, false)));
  922. // The byte is a valid varint, but not a valid tag (zero).
  923. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\0", 1, false)));
  924. // The byte is a malformed varint.
  925. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\200", 1, false)));
  926. // The byte is an endgroup tag, but not the right one for this group.
  927. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\014", 1, false)));
  928. // The byte is a valid varint but not a valid tag (bad wire type).
  929. EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\017", 1, true)));
  930. }
  931. TEST_F(WireFormatInvalidInputTest, InvalidStringInUnknownGroup) {
  932. // Test a bug fix: SkipMessage should fail if the message contains a string
  933. // whose length would extend beyond the message end.
  934. unittest::TestAllTypes message;
  935. message.set_optional_string("foo foo foo foo");
  936. string data;
  937. message.SerializeToString(&data);
  938. // Chop some bytes off the end.
  939. data.resize(data.size() - 4);
  940. // Try to skip it. Note that the bug was only present when parsing to an
  941. // UnknownFieldSet.
  942. io::ArrayInputStream raw_input(data.data(), data.size());
  943. io::CodedInputStream coded_input(&raw_input);
  944. UnknownFieldSet unknown_fields;
  945. EXPECT_FALSE(WireFormat::SkipMessage(&coded_input, &unknown_fields));
  946. }
  947. // Test differences between string and bytes.
  948. // Value of a string type must be valid UTF-8 string. When UTF-8
  949. // validation is enabled (GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED):
  950. // WriteInvalidUTF8String: see error message.
  951. // ReadInvalidUTF8String: see error message.
  952. // WriteValidUTF8String: fine.
  953. // ReadValidUTF8String: fine.
  954. // WriteAnyBytes: fine.
  955. // ReadAnyBytes: fine.
  956. const char * kInvalidUTF8String = "Invalid UTF-8: \xA0\xB0\xC0\xD0";
  957. // This used to be "Valid UTF-8: \x01\x02\u8C37\u6B4C", but MSVC seems to
  958. // interpret \u differently from GCC.
  959. const char * kValidUTF8String = "Valid UTF-8: \x01\x02\350\260\267\346\255\214";
  960. template<typename T>
  961. bool WriteMessage(const char *value, T *message, string *wire_buffer) {
  962. message->set_data(value);
  963. wire_buffer->clear();
  964. message->AppendToString(wire_buffer);
  965. return (wire_buffer->size() > 0);
  966. }
  967. template<typename T>
  968. bool ReadMessage(const string &wire_buffer, T *message) {
  969. return message->ParseFromArray(wire_buffer.data(), wire_buffer.size());
  970. }
  971. bool StartsWith(const string& s, const string& prefix) {
  972. return s.substr(0, prefix.length()) == prefix;
  973. }
  974. class Utf8ValidationTest : public ::testing::Test {
  975. protected:
  976. Utf8ValidationTest() {}
  977. virtual ~Utf8ValidationTest() {}
  978. virtual void SetUp() {
  979. }
  980. };
  981. TEST_F(Utf8ValidationTest, WriteInvalidUTF8String) {
  982. string wire_buffer;
  983. protobuf_unittest::OneString input;
  984. std::vector<string> errors;
  985. {
  986. ScopedMemoryLog log;
  987. WriteMessage(kInvalidUTF8String, &input, &wire_buffer);
  988. errors = log.GetMessages(ERROR);
  989. }
  990. #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  991. ASSERT_EQ(1, errors.size());
  992. EXPECT_TRUE(StartsWith(errors[0],
  993. "String field 'protobuf_unittest.OneString.data' "
  994. "contains invalid UTF-8 data when "
  995. "serializing a protocol buffer. Use the "
  996. "'bytes' type if you intend to send raw bytes."));
  997. #else
  998. ASSERT_EQ(0, errors.size());
  999. #endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1000. }
  1001. TEST_F(Utf8ValidationTest, ReadInvalidUTF8String) {
  1002. string wire_buffer;
  1003. protobuf_unittest::OneString input;
  1004. WriteMessage(kInvalidUTF8String, &input, &wire_buffer);
  1005. protobuf_unittest::OneString output;
  1006. std::vector<string> errors;
  1007. {
  1008. ScopedMemoryLog log;
  1009. ReadMessage(wire_buffer, &output);
  1010. errors = log.GetMessages(ERROR);
  1011. }
  1012. #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1013. ASSERT_EQ(1, errors.size());
  1014. EXPECT_TRUE(StartsWith(errors[0],
  1015. "String field 'protobuf_unittest.OneString.data' "
  1016. "contains invalid UTF-8 data when "
  1017. "parsing a protocol buffer. Use the "
  1018. "'bytes' type if you intend to send raw bytes."));
  1019. #else
  1020. ASSERT_EQ(0, errors.size());
  1021. #endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1022. }
  1023. TEST_F(Utf8ValidationTest, WriteValidUTF8String) {
  1024. string wire_buffer;
  1025. protobuf_unittest::OneString input;
  1026. std::vector<string> errors;
  1027. {
  1028. ScopedMemoryLog log;
  1029. WriteMessage(kValidUTF8String, &input, &wire_buffer);
  1030. errors = log.GetMessages(ERROR);
  1031. }
  1032. ASSERT_EQ(0, errors.size());
  1033. }
  1034. TEST_F(Utf8ValidationTest, ReadValidUTF8String) {
  1035. string wire_buffer;
  1036. protobuf_unittest::OneString input;
  1037. WriteMessage(kValidUTF8String, &input, &wire_buffer);
  1038. protobuf_unittest::OneString output;
  1039. std::vector<string> errors;
  1040. {
  1041. ScopedMemoryLog log;
  1042. ReadMessage(wire_buffer, &output);
  1043. errors = log.GetMessages(ERROR);
  1044. }
  1045. ASSERT_EQ(0, errors.size());
  1046. EXPECT_EQ(input.data(), output.data());
  1047. }
  1048. // Bytes: anything can pass as bytes, use invalid UTF-8 string to test
  1049. TEST_F(Utf8ValidationTest, WriteArbitraryBytes) {
  1050. string wire_buffer;
  1051. protobuf_unittest::OneBytes input;
  1052. std::vector<string> errors;
  1053. {
  1054. ScopedMemoryLog log;
  1055. WriteMessage(kInvalidUTF8String, &input, &wire_buffer);
  1056. errors = log.GetMessages(ERROR);
  1057. }
  1058. ASSERT_EQ(0, errors.size());
  1059. }
  1060. TEST_F(Utf8ValidationTest, ReadArbitraryBytes) {
  1061. string wire_buffer;
  1062. protobuf_unittest::OneBytes input;
  1063. WriteMessage(kInvalidUTF8String, &input, &wire_buffer);
  1064. protobuf_unittest::OneBytes output;
  1065. std::vector<string> errors;
  1066. {
  1067. ScopedMemoryLog log;
  1068. ReadMessage(wire_buffer, &output);
  1069. errors = log.GetMessages(ERROR);
  1070. }
  1071. ASSERT_EQ(0, errors.size());
  1072. EXPECT_EQ(input.data(), output.data());
  1073. }
  1074. TEST_F(Utf8ValidationTest, ParseRepeatedString) {
  1075. protobuf_unittest::MoreBytes input;
  1076. input.add_data(kValidUTF8String);
  1077. input.add_data(kInvalidUTF8String);
  1078. input.add_data(kInvalidUTF8String);
  1079. string wire_buffer = input.SerializeAsString();
  1080. protobuf_unittest::MoreString output;
  1081. std::vector<string> errors;
  1082. {
  1083. ScopedMemoryLog log;
  1084. ReadMessage(wire_buffer, &output);
  1085. errors = log.GetMessages(ERROR);
  1086. }
  1087. #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1088. ASSERT_EQ(2, errors.size());
  1089. #else
  1090. ASSERT_EQ(0, errors.size());
  1091. #endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1092. EXPECT_EQ(wire_buffer, output.SerializeAsString());
  1093. }
  1094. // Test the old VerifyUTF8String() function, which may still be called by old
  1095. // generated code.
  1096. TEST_F(Utf8ValidationTest, OldVerifyUTF8String) {
  1097. string data(kInvalidUTF8String);
  1098. std::vector<string> errors;
  1099. {
  1100. ScopedMemoryLog log;
  1101. WireFormat::VerifyUTF8String(data.data(), data.size(),
  1102. WireFormat::SERIALIZE);
  1103. errors = log.GetMessages(ERROR);
  1104. }
  1105. #ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED
  1106. ASSERT_EQ(1, errors.size());
  1107. EXPECT_TRUE(StartsWith(errors[0],
  1108. "String field contains invalid UTF-8 data when "
  1109. "serializing a protocol buffer. Use the "
  1110. "'bytes' type if you intend to send raw bytes."));
  1111. #else
  1112. ASSERT_EQ(0, errors.size());
  1113. #endif
  1114. }
  1115. TEST(RepeatedVarint, Int32) {
  1116. RepeatedField<int32> v;
  1117. // Insert -2^n, 2^n and 2^n-1.
  1118. for (int n = 0; n < 10; n++) {
  1119. v.Add(-(1 << n));
  1120. v.Add(1 << n);
  1121. v.Add((1 << n) - 1);
  1122. }
  1123. // Check consistency with the scalar Int32Size.
  1124. size_t expected = 0;
  1125. for (int i = 0; i < v.size(); i++) {
  1126. expected += WireFormatLite::Int32Size(v[i]);
  1127. }
  1128. EXPECT_EQ(expected, WireFormatLite::Int32Size(v));
  1129. }
  1130. TEST(RepeatedVarint, Int64) {
  1131. RepeatedField<int64> v;
  1132. // Insert -2^n, 2^n and 2^n-1.
  1133. for (int n = 0; n < 10; n++) {
  1134. v.Add(-(1 << n));
  1135. v.Add(1 << n);
  1136. v.Add((1 << n) - 1);
  1137. }
  1138. // Check consistency with the scalar Int64Size.
  1139. size_t expected = 0;
  1140. for (int i = 0; i < v.size(); i++) {
  1141. expected += WireFormatLite::Int64Size(v[i]);
  1142. }
  1143. EXPECT_EQ(expected, WireFormatLite::Int64Size(v));
  1144. }
  1145. TEST(RepeatedVarint, SInt32) {
  1146. RepeatedField<int32> v;
  1147. // Insert -2^n, 2^n and 2^n-1.
  1148. for (int n = 0; n < 10; n++) {
  1149. v.Add(-(1 << n));
  1150. v.Add(1 << n);
  1151. v.Add((1 << n) - 1);
  1152. }
  1153. // Check consistency with the scalar SInt32Size.
  1154. size_t expected = 0;
  1155. for (int i = 0; i < v.size(); i++) {
  1156. expected += WireFormatLite::SInt32Size(v[i]);
  1157. }
  1158. EXPECT_EQ(expected, WireFormatLite::SInt32Size(v));
  1159. }
  1160. TEST(RepeatedVarint, SInt64) {
  1161. RepeatedField<int64> v;
  1162. // Insert -2^n, 2^n and 2^n-1.
  1163. for (int n = 0; n < 10; n++) {
  1164. v.Add(-(1 << n));
  1165. v.Add(1 << n);
  1166. v.Add((1 << n) - 1);
  1167. }
  1168. // Check consistency with the scalar SInt64Size.
  1169. size_t expected = 0;
  1170. for (int i = 0; i < v.size(); i++) {
  1171. expected += WireFormatLite::SInt64Size(v[i]);
  1172. }
  1173. EXPECT_EQ(expected, WireFormatLite::SInt64Size(v));
  1174. }
  1175. TEST(RepeatedVarint, UInt32) {
  1176. RepeatedField<uint32> v;
  1177. // Insert 2^n and 2^n-1.
  1178. for (int n = 0; n < 10; n++) {
  1179. v.Add(1 << n);
  1180. v.Add((1 << n) - 1);
  1181. }
  1182. // Check consistency with the scalar UInt32Size.
  1183. size_t expected = 0;
  1184. for (int i = 0; i < v.size(); i++) {
  1185. expected += WireFormatLite::UInt32Size(v[i]);
  1186. }
  1187. EXPECT_EQ(expected, WireFormatLite::UInt32Size(v));
  1188. }
  1189. TEST(RepeatedVarint, UInt64) {
  1190. RepeatedField<uint64> v;
  1191. // Insert 2^n and 2^n-1.
  1192. for (int n = 0; n < 10; n++) {
  1193. v.Add(1 << n);
  1194. v.Add((1 << n) - 1);
  1195. }
  1196. // Check consistency with the scalar UInt64Size.
  1197. size_t expected = 0;
  1198. for (int i = 0; i < v.size(); i++) {
  1199. expected += WireFormatLite::UInt64Size(v[i]);
  1200. }
  1201. EXPECT_EQ(expected, WireFormatLite::UInt64Size(v));
  1202. }
  1203. TEST(RepeatedVarint, Enum) {
  1204. RepeatedField<int> v;
  1205. // Insert 2^n and 2^n-1.
  1206. for (int n = 0; n < 10; n++) {
  1207. v.Add(1 << n);
  1208. v.Add((1 << n) - 1);
  1209. }
  1210. // Check consistency with the scalar EnumSize.
  1211. size_t expected = 0;
  1212. for (int i = 0; i < v.size(); i++) {
  1213. expected += WireFormatLite::EnumSize(v[i]);
  1214. }
  1215. EXPECT_EQ(expected, WireFormatLite::EnumSize(v));
  1216. }
  1217. } // namespace
  1218. } // namespace internal
  1219. } // namespace protobuf
  1220. } // namespace google