CodedInputStreamTest.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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.IO;
  34. using Google.Protobuf.TestProtos;
  35. using NUnit.Framework;
  36. namespace Google.Protobuf
  37. {
  38. public class CodedInputStreamTest
  39. {
  40. /// <summary>
  41. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  42. /// actually ints so that I can use hex notation and not get stupid errors
  43. /// about precision.
  44. /// </summary>
  45. private static byte[] Bytes(params int[] bytesAsInts)
  46. {
  47. byte[] bytes = new byte[bytesAsInts.Length];
  48. for (int i = 0; i < bytesAsInts.Length; i++)
  49. {
  50. bytes[i] = (byte) bytesAsInts[i];
  51. }
  52. return bytes;
  53. }
  54. /// <summary>
  55. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
  56. /// </summary>
  57. private static void AssertReadVarint(byte[] data, ulong value)
  58. {
  59. CodedInputStream input = CodedInputStream.CreateInstance(data);
  60. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  61. input = CodedInputStream.CreateInstance(data);
  62. Assert.AreEqual(value, input.ReadRawVarint64());
  63. Assert.IsTrue(input.IsAtEnd);
  64. // Try different block sizes.
  65. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
  66. {
  67. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  68. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  69. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  70. Assert.AreEqual(value, input.ReadRawVarint64());
  71. Assert.IsTrue(input.IsAtEnd);
  72. }
  73. // Try reading directly from a MemoryStream. We want to verify that it
  74. // doesn't read past the end of the input, so write an extra byte - this
  75. // lets us test the position at the end.
  76. MemoryStream memoryStream = new MemoryStream();
  77. memoryStream.Write(data, 0, data.Length);
  78. memoryStream.WriteByte(0);
  79. memoryStream.Position = 0;
  80. Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
  81. Assert.AreEqual(data.Length, memoryStream.Position);
  82. }
  83. /// <summary>
  84. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  85. /// expects them to fail with an InvalidProtocolBufferException whose
  86. /// description matches the given one.
  87. /// </summary>
  88. private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
  89. {
  90. CodedInputStream input = CodedInputStream.CreateInstance(data);
  91. var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
  92. Assert.AreEqual(expected.Message, exception.Message);
  93. input = CodedInputStream.CreateInstance(data);
  94. exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
  95. Assert.AreEqual(expected.Message, exception.Message);
  96. // Make sure we get the same error when reading directly from a Stream.
  97. exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
  98. Assert.AreEqual(expected.Message, exception.Message);
  99. }
  100. [Test]
  101. public void ReadVarint()
  102. {
  103. AssertReadVarint(Bytes(0x00), 0);
  104. AssertReadVarint(Bytes(0x01), 1);
  105. AssertReadVarint(Bytes(0x7f), 127);
  106. // 14882
  107. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  108. // 2961488830
  109. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  110. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  111. (0x0bL << 28));
  112. // 64-bit
  113. // 7256456126
  114. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  115. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  116. (0x1bL << 28));
  117. // 41256202580718336
  118. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  119. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  120. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  121. // 11964378330978735131
  122. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  123. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  124. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  125. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  126. // Failures
  127. AssertReadVarintFailure(
  128. InvalidProtocolBufferException.MalformedVarint(),
  129. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  130. 0x00));
  131. AssertReadVarintFailure(
  132. InvalidProtocolBufferException.TruncatedMessage(),
  133. Bytes(0x80));
  134. }
  135. /// <summary>
  136. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  137. /// that the result matches the given value.
  138. /// </summary>
  139. private static void AssertReadLittleEndian32(byte[] data, uint value)
  140. {
  141. CodedInputStream input = CodedInputStream.CreateInstance(data);
  142. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  143. Assert.IsTrue(input.IsAtEnd);
  144. // Try different block sizes.
  145. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  146. {
  147. input = CodedInputStream.CreateInstance(
  148. new SmallBlockInputStream(data, blockSize));
  149. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  150. Assert.IsTrue(input.IsAtEnd);
  151. }
  152. }
  153. /// <summary>
  154. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  155. /// that the result matches the given value.
  156. /// </summary>
  157. private static void AssertReadLittleEndian64(byte[] data, ulong value)
  158. {
  159. CodedInputStream input = CodedInputStream.CreateInstance(data);
  160. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  161. Assert.IsTrue(input.IsAtEnd);
  162. // Try different block sizes.
  163. for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
  164. {
  165. input = CodedInputStream.CreateInstance(
  166. new SmallBlockInputStream(data, blockSize));
  167. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  168. Assert.IsTrue(input.IsAtEnd);
  169. }
  170. }
  171. [Test]
  172. public void ReadLittleEndian()
  173. {
  174. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  175. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  176. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  177. 0x123456789abcdef0L);
  178. AssertReadLittleEndian64(
  179. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  180. }
  181. [Test]
  182. public void DecodeZigZag32()
  183. {
  184. Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
  185. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
  186. Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
  187. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
  188. Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
  189. Assert.AreEqual(unchecked((int) 0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
  190. Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
  191. Assert.AreEqual(unchecked((int) 0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
  192. }
  193. [Test]
  194. public void DecodeZigZag64()
  195. {
  196. Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
  197. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
  198. Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
  199. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
  200. Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
  201. Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
  202. Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
  203. Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
  204. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  205. Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  206. }
  207. [Test]
  208. public void ReadWholeMessage_VaryingBlockSizes()
  209. {
  210. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  211. byte[] rawBytes = message.ToByteArray();
  212. Assert.AreEqual(rawBytes.Length, message.CalculateSize());
  213. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
  214. Assert.AreEqual(message, message2);
  215. // Try different block sizes.
  216. for (int blockSize = 1; blockSize < 256; blockSize *= 2)
  217. {
  218. message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  219. Assert.AreEqual(message, message2);
  220. }
  221. }
  222. [Test]
  223. public void ReadHugeBlob()
  224. {
  225. // Allocate and initialize a 1MB blob.
  226. byte[] blob = new byte[1 << 20];
  227. for (int i = 0; i < blob.Length; i++)
  228. {
  229. blob[i] = (byte) i;
  230. }
  231. // Make a message containing it.
  232. var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
  233. // Serialize and parse it. Make sure to parse from an InputStream, not
  234. // directly from a ByteString, so that CodedInputStream uses buffered
  235. // reading.
  236. TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
  237. Assert.AreEqual(message, message2);
  238. }
  239. [Test]
  240. public void ReadMaliciouslyLargeBlob()
  241. {
  242. MemoryStream ms = new MemoryStream();
  243. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  244. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  245. output.WriteRawVarint32(tag);
  246. output.WriteRawVarint32(0x7FFFFFFF);
  247. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  248. output.Flush();
  249. ms.Position = 0;
  250. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  251. uint testtag;
  252. Assert.IsTrue(input.ReadTag(out testtag));
  253. Assert.AreEqual(tag, testtag);
  254. // TODO(jonskeet): Should this be ArgumentNullException instead?
  255. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  256. }
  257. private static TestRecursiveMessage MakeRecursiveMessage(int depth)
  258. {
  259. if (depth == 0)
  260. {
  261. return new TestRecursiveMessage { I = 5 };
  262. }
  263. else
  264. {
  265. return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
  266. }
  267. }
  268. private static void AssertMessageDepth(TestRecursiveMessage message, int depth)
  269. {
  270. if (depth == 0)
  271. {
  272. Assert.IsNull(message.A);
  273. Assert.AreEqual(5, message.I);
  274. }
  275. else
  276. {
  277. Assert.IsNotNull(message.A);
  278. AssertMessageDepth(message.A, depth - 1);
  279. }
  280. }
  281. [Test]
  282. public void MaliciousRecursion()
  283. {
  284. ByteString data64 = MakeRecursiveMessage(64).ToByteString();
  285. ByteString data65 = MakeRecursiveMessage(65).ToByteString();
  286. AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
  287. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
  288. CodedInputStream input = data64.CreateCodedInput();
  289. input.SetRecursionLimit(8);
  290. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
  291. }
  292. /*
  293. [Test]
  294. public void SizeLimit()
  295. {
  296. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  297. // apply to the latter case.
  298. MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
  299. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  300. input.SetSizeLimit(16);
  301. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.ParseFrom(input));
  302. }*/
  303. [Test]
  304. public void ResetSizeCounter()
  305. {
  306. CodedInputStream input = CodedInputStream.CreateInstance(
  307. new SmallBlockInputStream(new byte[256], 8));
  308. input.SetSizeLimit(16);
  309. input.ReadRawBytes(16);
  310. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawByte());
  311. input.ResetSizeCounter();
  312. input.ReadRawByte(); // No exception thrown.
  313. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawBytes(16));
  314. }
  315. /// <summary>
  316. /// Tests that if we read an string that contains invalid UTF-8, no exception
  317. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  318. /// "replacement character" U+FFFD.
  319. /// </summary>
  320. [Test]
  321. public void ReadInvalidUtf8()
  322. {
  323. MemoryStream ms = new MemoryStream();
  324. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  325. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  326. output.WriteRawVarint32(tag);
  327. output.WriteRawVarint32(1);
  328. output.WriteRawBytes(new byte[] {0x80});
  329. output.Flush();
  330. ms.Position = 0;
  331. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  332. uint actualTag;
  333. Assert.IsTrue(input.ReadTag(out actualTag));
  334. Assert.AreEqual(tag, actualTag);
  335. string text = input.ReadString();
  336. Assert.AreEqual('\ufffd', text[0]);
  337. }
  338. /// <summary>
  339. /// A stream which limits the number of bytes it reads at a time.
  340. /// We use this to make sure that CodedInputStream doesn't screw up when
  341. /// reading in small blocks.
  342. /// </summary>
  343. private sealed class SmallBlockInputStream : MemoryStream
  344. {
  345. private readonly int blockSize;
  346. public SmallBlockInputStream(byte[] data, int blockSize)
  347. : base(data)
  348. {
  349. this.blockSize = blockSize;
  350. }
  351. public override int Read(byte[] buffer, int offset, int count)
  352. {
  353. return base.Read(buffer, offset, Math.Min(count, blockSize));
  354. }
  355. }
  356. [Test]
  357. public void TestNegativeEnum()
  358. {
  359. byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
  360. CodedInputStream input = CodedInputStream.CreateInstance(bytes);
  361. Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
  362. Assert.IsTrue(input.IsAtEnd);
  363. }
  364. //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
  365. [Test]
  366. public void TestSlowPathAvoidance()
  367. {
  368. using (var ms = new MemoryStream())
  369. {
  370. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  371. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  372. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  373. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  374. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  375. output.Flush();
  376. ms.Position = 0;
  377. CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]);
  378. uint tag;
  379. Assert.IsTrue(input.ReadTag(out tag));
  380. Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
  381. Assert.AreEqual(100, input.ReadBytes().Length);
  382. Assert.IsTrue(input.ReadTag(out tag));
  383. Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
  384. Assert.AreEqual(100, input.ReadBytes().Length);
  385. }
  386. }
  387. }
  388. }