CodedInputStreamTest.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Buffers;
  34. using System.IO;
  35. using Google.Protobuf.TestProtos;
  36. using Proto2 = Google.Protobuf.TestProtos.Proto2;
  37. using NUnit.Framework;
  38. namespace Google.Protobuf
  39. {
  40. public class CodedInputStreamTest
  41. {
  42. /// <summary>
  43. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  44. /// actually ints so that I can use hex notation and not get stupid errors
  45. /// about precision.
  46. /// </summary>
  47. private static byte[] Bytes(params int[] bytesAsInts)
  48. {
  49. byte[] bytes = new byte[bytesAsInts.Length];
  50. for (int i = 0; i < bytesAsInts.Length; i++)
  51. {
  52. bytes[i] = (byte) bytesAsInts[i];
  53. }
  54. return bytes;
  55. }
  56. /// <summary>
  57. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
  58. /// </summary>
  59. private static void AssertReadVarint(byte[] data, ulong value)
  60. {
  61. CodedInputStream input = new CodedInputStream(data);
  62. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  63. Assert.IsTrue(input.IsAtEnd);
  64. input = new CodedInputStream(data);
  65. Assert.AreEqual(value, input.ReadRawVarint64());
  66. Assert.IsTrue(input.IsAtEnd);
  67. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  68. {
  69. Assert.AreEqual((uint) value, ctx.ReadUInt32());
  70. }, true);
  71. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  72. {
  73. Assert.AreEqual(value, ctx.ReadUInt64());
  74. }, true);
  75. // Try different block sizes.
  76. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
  77. {
  78. input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
  79. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  80. input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
  81. Assert.AreEqual(value, input.ReadRawVarint64());
  82. Assert.IsTrue(input.IsAtEnd);
  83. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
  84. {
  85. Assert.AreEqual((uint) value, ctx.ReadUInt32());
  86. }, true);
  87. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, bufferSize), (ref ParseContext ctx) =>
  88. {
  89. Assert.AreEqual(value, ctx.ReadUInt64());
  90. }, true);
  91. }
  92. // Try reading directly from a MemoryStream. We want to verify that it
  93. // doesn't read past the end of the input, so write an extra byte - this
  94. // lets us test the position at the end.
  95. MemoryStream memoryStream = new MemoryStream();
  96. memoryStream.Write(data, 0, data.Length);
  97. memoryStream.WriteByte(0);
  98. memoryStream.Position = 0;
  99. Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
  100. Assert.AreEqual(data.Length, memoryStream.Position);
  101. }
  102. /// <summary>
  103. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  104. /// expects them to fail with an InvalidProtocolBufferException whose
  105. /// description matches the given one.
  106. /// </summary>
  107. private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
  108. {
  109. CodedInputStream input = new CodedInputStream(data);
  110. var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
  111. Assert.AreEqual(expected.Message, exception.Message);
  112. input = new CodedInputStream(data);
  113. exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
  114. Assert.AreEqual(expected.Message, exception.Message);
  115. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  116. {
  117. try
  118. {
  119. ctx.ReadUInt32();
  120. Assert.Fail();
  121. }
  122. catch (InvalidProtocolBufferException ex)
  123. {
  124. Assert.AreEqual(expected.Message, ex.Message);
  125. }
  126. }, false);
  127. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  128. {
  129. try
  130. {
  131. ctx.ReadUInt64();
  132. Assert.Fail();
  133. }
  134. catch (InvalidProtocolBufferException ex)
  135. {
  136. Assert.AreEqual(expected.Message, ex.Message);
  137. }
  138. }, false);
  139. // Make sure we get the same error when reading directly from a Stream.
  140. exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
  141. Assert.AreEqual(expected.Message, exception.Message);
  142. }
  143. private delegate void ParseContextAssertAction(ref ParseContext ctx);
  144. private static void AssertReadFromParseContext(ReadOnlySequence<byte> input, ParseContextAssertAction assertAction, bool assertIsAtEnd)
  145. {
  146. ParseContext.Initialize(input, out ParseContext parseCtx);
  147. assertAction(ref parseCtx);
  148. if (assertIsAtEnd)
  149. {
  150. Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref parseCtx.buffer, ref parseCtx.state));
  151. }
  152. }
  153. [Test]
  154. public void ReadVarint()
  155. {
  156. AssertReadVarint(Bytes(0x00), 0);
  157. AssertReadVarint(Bytes(0x01), 1);
  158. AssertReadVarint(Bytes(0x7f), 127);
  159. // 14882
  160. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  161. // 2961488830
  162. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  163. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  164. (0x0bL << 28));
  165. // 64-bit
  166. // 7256456126
  167. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  168. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  169. (0x1bL << 28));
  170. // 41256202580718336
  171. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  172. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  173. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  174. // 11964378330978735131
  175. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  176. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  177. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  178. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  179. // Failures
  180. AssertReadVarintFailure(
  181. InvalidProtocolBufferException.MalformedVarint(),
  182. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  183. 0x00));
  184. AssertReadVarintFailure(
  185. InvalidProtocolBufferException.TruncatedMessage(),
  186. Bytes(0x80));
  187. }
  188. /// <summary>
  189. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  190. /// that the result matches the given value.
  191. /// </summary>
  192. private static void AssertReadLittleEndian32(byte[] data, uint value)
  193. {
  194. CodedInputStream input = new CodedInputStream(data);
  195. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  196. Assert.IsTrue(input.IsAtEnd);
  197. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  198. {
  199. Assert.AreEqual(value, ctx.ReadFixed32());
  200. }, true);
  201. // Try different block sizes.
  202. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  203. {
  204. input = new CodedInputStream(
  205. new SmallBlockInputStream(data, blockSize));
  206. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  207. Assert.IsTrue(input.IsAtEnd);
  208. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
  209. {
  210. Assert.AreEqual(value, ctx.ReadFixed32());
  211. }, true);
  212. }
  213. }
  214. /// <summary>
  215. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  216. /// that the result matches the given value.
  217. /// </summary>
  218. private static void AssertReadLittleEndian64(byte[] data, ulong value)
  219. {
  220. CodedInputStream input = new CodedInputStream(data);
  221. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  222. Assert.IsTrue(input.IsAtEnd);
  223. AssertReadFromParseContext(new ReadOnlySequence<byte>(data), (ref ParseContext ctx) =>
  224. {
  225. Assert.AreEqual(value, ctx.ReadFixed64());
  226. }, true);
  227. // Try different block sizes.
  228. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  229. {
  230. input = new CodedInputStream(
  231. new SmallBlockInputStream(data, blockSize));
  232. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  233. Assert.IsTrue(input.IsAtEnd);
  234. AssertReadFromParseContext(ReadOnlySequenceFactory.CreateWithContent(data, blockSize), (ref ParseContext ctx) =>
  235. {
  236. Assert.AreEqual(value, ctx.ReadFixed64());
  237. }, true);
  238. }
  239. }
  240. [Test]
  241. public void ReadLittleEndian()
  242. {
  243. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  244. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  245. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  246. 0x123456789abcdef0L);
  247. AssertReadLittleEndian64(
  248. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  249. }
  250. [Test]
  251. public void DecodeZigZag32()
  252. {
  253. Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(0));
  254. Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(1));
  255. Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(2));
  256. Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag32(3));
  257. Assert.AreEqual(0x3FFFFFFF, ParsingPrimitives.DecodeZigZag32(0x7FFFFFFE));
  258. Assert.AreEqual(unchecked((int) 0xC0000000), ParsingPrimitives.DecodeZigZag32(0x7FFFFFFF));
  259. Assert.AreEqual(0x7FFFFFFF, ParsingPrimitives.DecodeZigZag32(0xFFFFFFFE));
  260. Assert.AreEqual(unchecked((int) 0x80000000), ParsingPrimitives.DecodeZigZag32(0xFFFFFFFF));
  261. }
  262. [Test]
  263. public void DecodeZigZag64()
  264. {
  265. Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(0));
  266. Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(1));
  267. Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(2));
  268. Assert.AreEqual(-2, ParsingPrimitives.DecodeZigZag64(3));
  269. Assert.AreEqual(0x000000003FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFEL));
  270. Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), ParsingPrimitives.DecodeZigZag64(0x000000007FFFFFFFL));
  271. Assert.AreEqual(0x000000007FFFFFFFL, ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFEL));
  272. Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), ParsingPrimitives.DecodeZigZag64(0x00000000FFFFFFFFL));
  273. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  274. Assert.AreEqual(unchecked((long) 0x8000000000000000L), ParsingPrimitives.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  275. }
  276. [Test]
  277. public void ReadWholeMessage_VaryingBlockSizes()
  278. {
  279. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  280. byte[] rawBytes = message.ToByteArray();
  281. Assert.AreEqual(rawBytes.Length, message.CalculateSize());
  282. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
  283. Assert.AreEqual(message, message2);
  284. // Try different block sizes.
  285. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  286. {
  287. message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  288. Assert.AreEqual(message, message2);
  289. }
  290. }
  291. [Test]
  292. public void ReadWholeMessage_VaryingBlockSizes_FromSequence()
  293. {
  294. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  295. byte[] rawBytes = message.ToByteArray();
  296. Assert.AreEqual(rawBytes.Length, message.CalculateSize());
  297. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
  298. Assert.AreEqual(message, message2);
  299. // Try different block sizes.
  300. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  301. {
  302. message2 = TestAllTypes.Parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize));
  303. Assert.AreEqual(message, message2);
  304. }
  305. }
  306. [Test]
  307. public void ReadInt32Wrapper_VariableBlockSizes()
  308. {
  309. byte[] rawBytes = new byte[] { 202, 1, 11, 8, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1 };
  310. for (int blockSize = 1; blockSize <= rawBytes.Length; blockSize++)
  311. {
  312. ReadOnlySequence<byte> data = ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize);
  313. AssertReadFromParseContext(data, (ref ParseContext ctx) =>
  314. {
  315. ctx.ReadTag();
  316. var value = ParsingPrimitivesWrappers.ReadInt32Wrapper(ref ctx);
  317. Assert.AreEqual(-2, value);
  318. }, true);
  319. }
  320. }
  321. [Test]
  322. public void ReadHugeBlob()
  323. {
  324. // Allocate and initialize a 1MB blob.
  325. byte[] blob = new byte[1 << 20];
  326. for (int i = 0; i < blob.Length; i++)
  327. {
  328. blob[i] = (byte) i;
  329. }
  330. // Make a message containing it.
  331. var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
  332. // Serialize and parse it. Make sure to parse from an InputStream, not
  333. // directly from a ByteString, so that CodedInputStream uses buffered
  334. // reading.
  335. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
  336. Assert.AreEqual(message, message2);
  337. }
  338. [Test]
  339. public void ReadMaliciouslyLargeBlob()
  340. {
  341. MemoryStream ms = new MemoryStream();
  342. CodedOutputStream output = new CodedOutputStream(ms);
  343. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  344. output.WriteRawVarint32(tag);
  345. output.WriteRawVarint32(0x7FFFFFFF);
  346. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  347. output.Flush();
  348. ms.Position = 0;
  349. CodedInputStream input = new CodedInputStream(ms);
  350. Assert.AreEqual(tag, input.ReadTag());
  351. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  352. }
  353. [Test]
  354. public void ReadBlobGreaterThanCurrentLimit()
  355. {
  356. MemoryStream ms = new MemoryStream();
  357. CodedOutputStream output = new CodedOutputStream(ms);
  358. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  359. output.WriteRawVarint32(tag);
  360. output.WriteRawVarint32(4);
  361. output.WriteRawBytes(new byte[4]); // Pad with a few random bytes.
  362. output.Flush();
  363. ms.Position = 0;
  364. CodedInputStream input = new CodedInputStream(ms);
  365. Assert.AreEqual(tag, input.ReadTag());
  366. // Specify limit smaller than data length
  367. input.PushLimit(3);
  368. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  369. AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) =>
  370. {
  371. Assert.AreEqual(tag, ctx.ReadTag());
  372. SegmentedBufferHelper.PushLimit(ref ctx.state, 3);
  373. try
  374. {
  375. ctx.ReadBytes();
  376. Assert.Fail();
  377. }
  378. catch (InvalidProtocolBufferException) {}
  379. }, true);
  380. }
  381. [Test]
  382. public void ReadStringGreaterThanCurrentLimit()
  383. {
  384. MemoryStream ms = new MemoryStream();
  385. CodedOutputStream output = new CodedOutputStream(ms);
  386. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  387. output.WriteRawVarint32(tag);
  388. output.WriteRawVarint32(4);
  389. output.WriteRawBytes(new byte[4]); // Pad with a few random bytes.
  390. output.Flush();
  391. ms.Position = 0;
  392. CodedInputStream input = new CodedInputStream(ms.ToArray());
  393. Assert.AreEqual(tag, input.ReadTag());
  394. // Specify limit smaller than data length
  395. input.PushLimit(3);
  396. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString());
  397. AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) =>
  398. {
  399. Assert.AreEqual(tag, ctx.ReadTag());
  400. SegmentedBufferHelper.PushLimit(ref ctx.state, 3);
  401. try
  402. {
  403. ctx.ReadString();
  404. Assert.Fail();
  405. }
  406. catch (InvalidProtocolBufferException) { }
  407. }, true);
  408. }
  409. // Representations of a tag for field 0 with various wire types
  410. [Test]
  411. [TestCase(0)]
  412. [TestCase(1)]
  413. [TestCase(2)]
  414. [TestCase(3)]
  415. [TestCase(4)]
  416. [TestCase(5)]
  417. public void ReadTag_ZeroFieldRejected(byte tag)
  418. {
  419. CodedInputStream cis = new CodedInputStream(new byte[] { tag });
  420. Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag());
  421. }
  422. internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
  423. {
  424. if (depth == 0)
  425. {
  426. return new TestRecursiveMessage { I = 5 };
  427. }
  428. else
  429. {
  430. return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
  431. }
  432. }
  433. internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
  434. {
  435. if (depth == 0)
  436. {
  437. Assert.IsNull(message.A);
  438. Assert.AreEqual(5, message.I);
  439. }
  440. else
  441. {
  442. Assert.IsNotNull(message.A);
  443. AssertMessageDepth(message.A, depth - 1);
  444. }
  445. }
  446. [Test]
  447. public void MaliciousRecursion()
  448. {
  449. ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString();
  450. ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString();
  451. AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit);
  452. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit));
  453. CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1);
  454. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
  455. }
  456. private static byte[] MakeMaliciousRecursionUnknownFieldsPayload(int recursionDepth)
  457. {
  458. // generate recursively nested groups that will be parsed as unknown fields
  459. int unknownFieldNumber = 14; // an unused field number
  460. MemoryStream ms = new MemoryStream();
  461. CodedOutputStream output = new CodedOutputStream(ms);
  462. for (int i = 0; i < recursionDepth; i++)
  463. {
  464. output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.StartGroup));
  465. }
  466. for (int i = 0; i < recursionDepth; i++)
  467. {
  468. output.WriteTag(WireFormat.MakeTag(unknownFieldNumber, WireFormat.WireType.EndGroup));
  469. }
  470. output.Flush();
  471. return ms.ToArray();
  472. }
  473. [Test]
  474. public void MaliciousRecursion_UnknownFields()
  475. {
  476. byte[] payloadAtRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit);
  477. byte[] payloadBeyondRecursiveLimit = MakeMaliciousRecursionUnknownFieldsPayload(CodedInputStream.DefaultRecursionLimit + 1);
  478. Assert.DoesNotThrow(() => TestRecursiveMessage.Parser.ParseFrom(payloadAtRecursiveLimit));
  479. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payloadBeyondRecursiveLimit));
  480. }
  481. [Test]
  482. public void ReadGroup_WrongEndGroupTag()
  483. {
  484. int groupFieldNumber = Proto2.TestAllTypes.OptionalGroupFieldNumber;
  485. // write Proto2.TestAllTypes with "optional_group" set, but use wrong EndGroup closing tag
  486. MemoryStream ms = new MemoryStream();
  487. CodedOutputStream output = new CodedOutputStream(ms);
  488. output.WriteTag(WireFormat.MakeTag(groupFieldNumber, WireFormat.WireType.StartGroup));
  489. output.WriteGroup(new Proto2.TestAllTypes.Types.OptionalGroup { A = 12345 });
  490. // end group with different field number
  491. output.WriteTag(WireFormat.MakeTag(groupFieldNumber + 1, WireFormat.WireType.EndGroup));
  492. output.Flush();
  493. var payload = ms.ToArray();
  494. Assert.Throws<InvalidProtocolBufferException>(() => Proto2.TestAllTypes.Parser.ParseFrom(payload));
  495. }
  496. [Test]
  497. public void ReadGroup_UnknownFields_WrongEndGroupTag()
  498. {
  499. MemoryStream ms = new MemoryStream();
  500. CodedOutputStream output = new CodedOutputStream(ms);
  501. output.WriteTag(WireFormat.MakeTag(14, WireFormat.WireType.StartGroup));
  502. // end group with different field number
  503. output.WriteTag(WireFormat.MakeTag(15, WireFormat.WireType.EndGroup));
  504. output.Flush();
  505. var payload = ms.ToArray();
  506. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(payload));
  507. }
  508. [Test]
  509. public void SizeLimit()
  510. {
  511. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  512. // apply to the latter case.
  513. MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
  514. CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
  515. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
  516. }
  517. /// <summary>
  518. /// Tests that if we read an string that contains invalid UTF-8, no exception
  519. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  520. /// "replacement character" U+FFFD.
  521. /// </summary>
  522. [Test]
  523. public void ReadInvalidUtf8()
  524. {
  525. MemoryStream ms = new MemoryStream();
  526. CodedOutputStream output = new CodedOutputStream(ms);
  527. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  528. output.WriteRawVarint32(tag);
  529. output.WriteRawVarint32(1);
  530. output.WriteRawBytes(new byte[] {0x80});
  531. output.Flush();
  532. ms.Position = 0;
  533. CodedInputStream input = new CodedInputStream(ms);
  534. Assert.AreEqual(tag, input.ReadTag());
  535. string text = input.ReadString();
  536. Assert.AreEqual('\ufffd', text[0]);
  537. }
  538. [Test]
  539. public void ReadNegativeSizedStringThrowsInvalidProtocolBufferException()
  540. {
  541. MemoryStream ms = new MemoryStream();
  542. CodedOutputStream output = new CodedOutputStream(ms);
  543. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  544. output.WriteRawVarint32(tag);
  545. output.WriteLength(-1);
  546. output.Flush();
  547. ms.Position = 0;
  548. CodedInputStream input = new CodedInputStream(ms);
  549. Assert.AreEqual(tag, input.ReadTag());
  550. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString());
  551. }
  552. [Test]
  553. public void ReadNegativeSizedBytesThrowsInvalidProtocolBufferException()
  554. {
  555. MemoryStream ms = new MemoryStream();
  556. CodedOutputStream output = new CodedOutputStream(ms);
  557. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  558. output.WriteRawVarint32(tag);
  559. output.WriteLength(-1);
  560. output.Flush();
  561. ms.Position = 0;
  562. CodedInputStream input = new CodedInputStream(ms);
  563. Assert.AreEqual(tag, input.ReadTag());
  564. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  565. }
  566. /// <summary>
  567. /// A stream which limits the number of bytes it reads at a time.
  568. /// We use this to make sure that CodedInputStream doesn't screw up when
  569. /// reading in small blocks.
  570. /// </summary>
  571. private sealed class SmallBlockInputStream : MemoryStream
  572. {
  573. private readonly int blockSize;
  574. public SmallBlockInputStream(byte[] data, int blockSize)
  575. : base(data)
  576. {
  577. this.blockSize = blockSize;
  578. }
  579. public override int Read(byte[] buffer, int offset, int count)
  580. {
  581. return base.Read(buffer, offset, Math.Min(count, blockSize));
  582. }
  583. }
  584. [Test]
  585. public void TestNegativeEnum()
  586. {
  587. byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
  588. CodedInputStream input = new CodedInputStream(bytes);
  589. Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
  590. Assert.IsTrue(input.IsAtEnd);
  591. }
  592. //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
  593. [Test]
  594. public void TestSlowPathAvoidance()
  595. {
  596. using (var ms = new MemoryStream())
  597. {
  598. CodedOutputStream output = new CodedOutputStream(ms);
  599. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  600. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  601. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  602. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  603. output.Flush();
  604. ms.Position = 0;
  605. CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
  606. uint tag = input.ReadTag();
  607. Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
  608. Assert.AreEqual(100, input.ReadBytes().Length);
  609. tag = input.ReadTag();
  610. Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
  611. Assert.AreEqual(100, input.ReadBytes().Length);
  612. }
  613. }
  614. [Test]
  615. public void Tag0Throws()
  616. {
  617. var input = new CodedInputStream(new byte[] { 0 });
  618. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
  619. }
  620. [Test]
  621. public void SkipGroup()
  622. {
  623. // Create an output stream with a group in:
  624. // Field 1: string "field 1"
  625. // Field 2: group containing:
  626. // Field 1: fixed int32 value 100
  627. // Field 2: string "ignore me"
  628. // Field 3: nested group containing
  629. // Field 1: fixed int64 value 1000
  630. // Field 3: string "field 3"
  631. var stream = new MemoryStream();
  632. var output = new CodedOutputStream(stream);
  633. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  634. output.WriteString("field 1");
  635. // The outer group...
  636. output.WriteTag(2, WireFormat.WireType.StartGroup);
  637. output.WriteTag(1, WireFormat.WireType.Fixed32);
  638. output.WriteFixed32(100);
  639. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  640. output.WriteString("ignore me");
  641. // The nested group...
  642. output.WriteTag(3, WireFormat.WireType.StartGroup);
  643. output.WriteTag(1, WireFormat.WireType.Fixed64);
  644. output.WriteFixed64(1000);
  645. // Note: Not sure the field number is relevant for end group...
  646. output.WriteTag(3, WireFormat.WireType.EndGroup);
  647. // End the outer group
  648. output.WriteTag(2, WireFormat.WireType.EndGroup);
  649. output.WriteTag(3, WireFormat.WireType.LengthDelimited);
  650. output.WriteString("field 3");
  651. output.Flush();
  652. stream.Position = 0;
  653. // Now act like a generated client
  654. var input = new CodedInputStream(stream);
  655. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  656. Assert.AreEqual("field 1", input.ReadString());
  657. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  658. input.SkipLastField(); // Should consume the whole group, including the nested one.
  659. Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
  660. Assert.AreEqual("field 3", input.ReadString());
  661. }
  662. [Test]
  663. public void SkipGroup_WrongEndGroupTag()
  664. {
  665. // Create an output stream with:
  666. // Field 1: string "field 1"
  667. // Start group 2
  668. // Field 3: fixed int32
  669. // End group 4 (should give an error)
  670. var stream = new MemoryStream();
  671. var output = new CodedOutputStream(stream);
  672. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  673. output.WriteString("field 1");
  674. // The outer group...
  675. output.WriteTag(2, WireFormat.WireType.StartGroup);
  676. output.WriteTag(3, WireFormat.WireType.Fixed32);
  677. output.WriteFixed32(100);
  678. output.WriteTag(4, WireFormat.WireType.EndGroup);
  679. output.Flush();
  680. stream.Position = 0;
  681. // Now act like a generated client
  682. var input = new CodedInputStream(stream);
  683. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  684. Assert.AreEqual("field 1", input.ReadString());
  685. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  686. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  687. }
  688. [Test]
  689. public void RogueEndGroupTag()
  690. {
  691. // If we have an end-group tag without a leading start-group tag, generated
  692. // code will just call SkipLastField... so that should fail.
  693. var stream = new MemoryStream();
  694. var output = new CodedOutputStream(stream);
  695. output.WriteTag(1, WireFormat.WireType.EndGroup);
  696. output.Flush();
  697. stream.Position = 0;
  698. var input = new CodedInputStream(stream);
  699. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
  700. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  701. }
  702. [Test]
  703. public void EndOfStreamReachedWhileSkippingGroup()
  704. {
  705. var stream = new MemoryStream();
  706. var output = new CodedOutputStream(stream);
  707. output.WriteTag(1, WireFormat.WireType.StartGroup);
  708. output.WriteTag(2, WireFormat.WireType.StartGroup);
  709. output.WriteTag(2, WireFormat.WireType.EndGroup);
  710. output.Flush();
  711. stream.Position = 0;
  712. // Now act like a generated client
  713. var input = new CodedInputStream(stream);
  714. input.ReadTag();
  715. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  716. }
  717. [Test]
  718. public void RecursionLimitAppliedWhileSkippingGroup()
  719. {
  720. var stream = new MemoryStream();
  721. var output = new CodedOutputStream(stream);
  722. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  723. {
  724. output.WriteTag(1, WireFormat.WireType.StartGroup);
  725. }
  726. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  727. {
  728. output.WriteTag(1, WireFormat.WireType.EndGroup);
  729. }
  730. output.Flush();
  731. stream.Position = 0;
  732. // Now act like a generated client
  733. var input = new CodedInputStream(stream);
  734. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
  735. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  736. }
  737. [Test]
  738. public void Construction_Invalid()
  739. {
  740. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
  741. Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
  742. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
  743. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
  744. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
  745. }
  746. [Test]
  747. public void CreateWithLimits_InvalidLimits()
  748. {
  749. var stream = new MemoryStream();
  750. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
  751. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
  752. }
  753. [Test]
  754. public void Dispose_DisposesUnderlyingStream()
  755. {
  756. var memoryStream = new MemoryStream();
  757. Assert.IsTrue(memoryStream.CanRead);
  758. using (var cis = new CodedInputStream(memoryStream))
  759. {
  760. }
  761. Assert.IsFalse(memoryStream.CanRead); // Disposed
  762. }
  763. [Test]
  764. public void Dispose_WithLeaveOpen()
  765. {
  766. var memoryStream = new MemoryStream();
  767. Assert.IsTrue(memoryStream.CanRead);
  768. using (var cis = new CodedInputStream(memoryStream, true))
  769. {
  770. }
  771. Assert.IsTrue(memoryStream.CanRead); // We left the stream open
  772. }
  773. [Test]
  774. public void Dispose_FromByteArray()
  775. {
  776. var stream = new CodedInputStream(new byte[10]);
  777. stream.Dispose();
  778. }
  779. [Test]
  780. public void TestParseMessagesCloseTo2G()
  781. {
  782. byte[] serializedMessage = GenerateBigSerializedMessage();
  783. // How many of these big messages do we need to take us near our 2GB limit?
  784. int count = Int32.MaxValue / serializedMessage.Length;
  785. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  786. // our big serialized message 'count' times.
  787. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  788. {
  789. Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream));
  790. }
  791. }
  792. [Test]
  793. public void TestParseMessagesOver2G()
  794. {
  795. byte[] serializedMessage = GenerateBigSerializedMessage();
  796. // How many of these big messages do we need to take us near our 2GB limit?
  797. int count = Int32.MaxValue / serializedMessage.Length;
  798. // Now add one to take us over the 2GB limit
  799. count++;
  800. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  801. // our big serialized message 'count' times.
  802. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  803. {
  804. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream),
  805. "Protocol message was too large. May be malicious. " +
  806. "Use CodedInputStream.SetSizeLimit() to increase the size limit.");
  807. }
  808. }
  809. /// <returns>A serialized big message</returns>
  810. private static byte[] GenerateBigSerializedMessage()
  811. {
  812. byte[] value = new byte[16 * 1024 * 1024];
  813. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  814. message.SingleBytes = ByteString.CopyFrom(value);
  815. return message.ToByteArray();
  816. }
  817. /// <summary>
  818. /// A MemoryStream that repeats a byte arrays' content a number of times.
  819. /// Simulates really large input without consuming loads of memory. Used above
  820. /// to test the parsing behavior when the input size exceeds 2GB or close to it.
  821. /// </summary>
  822. private class RepeatingMemoryStream: MemoryStream
  823. {
  824. private readonly byte[] bytes;
  825. private readonly int maxIterations;
  826. private int index = 0;
  827. public RepeatingMemoryStream(byte[] bytes, int maxIterations)
  828. {
  829. this.bytes = bytes;
  830. this.maxIterations = maxIterations;
  831. }
  832. public override int Read(byte[] buffer, int offset, int count)
  833. {
  834. if (bytes.Length == 0)
  835. {
  836. return 0;
  837. }
  838. int numBytesCopiedTotal = 0;
  839. while (numBytesCopiedTotal < count && index < maxIterations)
  840. {
  841. int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count);
  842. Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy);
  843. numBytesCopiedTotal += numBytesToCopy;
  844. offset += numBytesToCopy;
  845. count -= numBytesCopiedTotal;
  846. Position += numBytesToCopy;
  847. if (Position >= bytes.Length)
  848. {
  849. Position = 0;
  850. index++;
  851. }
  852. }
  853. return numBytesCopiedTotal;
  854. }
  855. }
  856. }
  857. }