CodedInputStreamTest.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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 = new CodedInputStream(data);
  60. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  61. input = new CodedInputStream(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 = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
  68. Assert.AreEqual((uint) value, input.ReadRawVarint32());
  69. input = new CodedInputStream(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 = new CodedInputStream(data);
  91. var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
  92. Assert.AreEqual(expected.Message, exception.Message);
  93. input = new CodedInputStream(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 = new CodedInputStream(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 = new CodedInputStream(
  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 = new CodedInputStream(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 = new CodedInputStream(
  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 = new CodedOutputStream(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 = new CodedInputStream(ms);
  251. Assert.AreEqual(tag, input.ReadTag());
  252. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  253. }
  254. // Representations of a tag for field 0 with various wire types
  255. [Test]
  256. [TestCase(0)]
  257. [TestCase(1)]
  258. [TestCase(2)]
  259. [TestCase(3)]
  260. [TestCase(4)]
  261. [TestCase(5)]
  262. public void ReadTag_ZeroFieldRejected(byte tag)
  263. {
  264. CodedInputStream cis = new CodedInputStream(new byte[] { tag });
  265. Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag());
  266. }
  267. internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
  268. {
  269. if (depth == 0)
  270. {
  271. return new TestRecursiveMessage { I = 5 };
  272. }
  273. else
  274. {
  275. return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
  276. }
  277. }
  278. internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
  279. {
  280. if (depth == 0)
  281. {
  282. Assert.IsNull(message.A);
  283. Assert.AreEqual(5, message.I);
  284. }
  285. else
  286. {
  287. Assert.IsNotNull(message.A);
  288. AssertMessageDepth(message.A, depth - 1);
  289. }
  290. }
  291. [Test]
  292. public void MaliciousRecursion()
  293. {
  294. ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString();
  295. ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString();
  296. AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit);
  297. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit));
  298. CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1);
  299. Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
  300. }
  301. [Test]
  302. public void SizeLimit()
  303. {
  304. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  305. // apply to the latter case.
  306. MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
  307. CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
  308. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
  309. }
  310. /// <summary>
  311. /// Tests that if we read an string that contains invalid UTF-8, no exception
  312. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  313. /// "replacement character" U+FFFD.
  314. /// </summary>
  315. [Test]
  316. public void ReadInvalidUtf8()
  317. {
  318. MemoryStream ms = new MemoryStream();
  319. CodedOutputStream output = new CodedOutputStream(ms);
  320. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  321. output.WriteRawVarint32(tag);
  322. output.WriteRawVarint32(1);
  323. output.WriteRawBytes(new byte[] {0x80});
  324. output.Flush();
  325. ms.Position = 0;
  326. CodedInputStream input = new CodedInputStream(ms);
  327. Assert.AreEqual(tag, input.ReadTag());
  328. string text = input.ReadString();
  329. Assert.AreEqual('\ufffd', text[0]);
  330. }
  331. [Test]
  332. public void ReadNegativeSizedStringThrowsInvalidProtocolBufferException()
  333. {
  334. MemoryStream ms = new MemoryStream();
  335. CodedOutputStream output = new CodedOutputStream(ms);
  336. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  337. output.WriteRawVarint32(tag);
  338. output.WriteLength(-1);
  339. output.Flush();
  340. ms.Position = 0;
  341. CodedInputStream input = new CodedInputStream(ms);
  342. Assert.AreEqual(tag, input.ReadTag());
  343. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString());
  344. }
  345. [Test]
  346. public void ReadNegativeSizedBytesThrowsInvalidProtocolBufferException()
  347. {
  348. MemoryStream ms = new MemoryStream();
  349. CodedOutputStream output = new CodedOutputStream(ms);
  350. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  351. output.WriteRawVarint32(tag);
  352. output.WriteLength(-1);
  353. output.Flush();
  354. ms.Position = 0;
  355. CodedInputStream input = new CodedInputStream(ms);
  356. Assert.AreEqual(tag, input.ReadTag());
  357. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
  358. }
  359. /// <summary>
  360. /// A stream which limits the number of bytes it reads at a time.
  361. /// We use this to make sure that CodedInputStream doesn't screw up when
  362. /// reading in small blocks.
  363. /// </summary>
  364. private sealed class SmallBlockInputStream : MemoryStream
  365. {
  366. private readonly int blockSize;
  367. public SmallBlockInputStream(byte[] data, int blockSize)
  368. : base(data)
  369. {
  370. this.blockSize = blockSize;
  371. }
  372. public override int Read(byte[] buffer, int offset, int count)
  373. {
  374. return base.Read(buffer, offset, Math.Min(count, blockSize));
  375. }
  376. }
  377. [Test]
  378. public void TestNegativeEnum()
  379. {
  380. byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
  381. CodedInputStream input = new CodedInputStream(bytes);
  382. Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
  383. Assert.IsTrue(input.IsAtEnd);
  384. }
  385. //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
  386. [Test]
  387. public void TestSlowPathAvoidance()
  388. {
  389. using (var ms = new MemoryStream())
  390. {
  391. CodedOutputStream output = new CodedOutputStream(ms);
  392. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  393. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  394. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  395. output.WriteBytes(ByteString.CopyFrom(new byte[100]));
  396. output.Flush();
  397. ms.Position = 0;
  398. CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
  399. uint tag = input.ReadTag();
  400. Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
  401. Assert.AreEqual(100, input.ReadBytes().Length);
  402. tag = input.ReadTag();
  403. Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
  404. Assert.AreEqual(100, input.ReadBytes().Length);
  405. }
  406. }
  407. [Test]
  408. public void Tag0Throws()
  409. {
  410. var input = new CodedInputStream(new byte[] { 0 });
  411. Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
  412. }
  413. [Test]
  414. public void SkipGroup()
  415. {
  416. // Create an output stream with a group in:
  417. // Field 1: string "field 1"
  418. // Field 2: group containing:
  419. // Field 1: fixed int32 value 100
  420. // Field 2: string "ignore me"
  421. // Field 3: nested group containing
  422. // Field 1: fixed int64 value 1000
  423. // Field 3: string "field 3"
  424. var stream = new MemoryStream();
  425. var output = new CodedOutputStream(stream);
  426. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  427. output.WriteString("field 1");
  428. // The outer group...
  429. output.WriteTag(2, WireFormat.WireType.StartGroup);
  430. output.WriteTag(1, WireFormat.WireType.Fixed32);
  431. output.WriteFixed32(100);
  432. output.WriteTag(2, WireFormat.WireType.LengthDelimited);
  433. output.WriteString("ignore me");
  434. // The nested group...
  435. output.WriteTag(3, WireFormat.WireType.StartGroup);
  436. output.WriteTag(1, WireFormat.WireType.Fixed64);
  437. output.WriteFixed64(1000);
  438. // Note: Not sure the field number is relevant for end group...
  439. output.WriteTag(3, WireFormat.WireType.EndGroup);
  440. // End the outer group
  441. output.WriteTag(2, WireFormat.WireType.EndGroup);
  442. output.WriteTag(3, WireFormat.WireType.LengthDelimited);
  443. output.WriteString("field 3");
  444. output.Flush();
  445. stream.Position = 0;
  446. // Now act like a generated client
  447. var input = new CodedInputStream(stream);
  448. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  449. Assert.AreEqual("field 1", input.ReadString());
  450. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  451. input.SkipLastField(); // Should consume the whole group, including the nested one.
  452. Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
  453. Assert.AreEqual("field 3", input.ReadString());
  454. }
  455. [Test]
  456. public void SkipGroup_WrongEndGroupTag()
  457. {
  458. // Create an output stream with:
  459. // Field 1: string "field 1"
  460. // Start group 2
  461. // Field 3: fixed int32
  462. // End group 4 (should give an error)
  463. var stream = new MemoryStream();
  464. var output = new CodedOutputStream(stream);
  465. output.WriteTag(1, WireFormat.WireType.LengthDelimited);
  466. output.WriteString("field 1");
  467. // The outer group...
  468. output.WriteTag(2, WireFormat.WireType.StartGroup);
  469. output.WriteTag(3, WireFormat.WireType.Fixed32);
  470. output.WriteFixed32(100);
  471. output.WriteTag(4, WireFormat.WireType.EndGroup);
  472. output.Flush();
  473. stream.Position = 0;
  474. // Now act like a generated client
  475. var input = new CodedInputStream(stream);
  476. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
  477. Assert.AreEqual("field 1", input.ReadString());
  478. Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
  479. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  480. }
  481. [Test]
  482. public void RogueEndGroupTag()
  483. {
  484. // If we have an end-group tag without a leading start-group tag, generated
  485. // code will just call SkipLastField... so that should fail.
  486. var stream = new MemoryStream();
  487. var output = new CodedOutputStream(stream);
  488. output.WriteTag(1, WireFormat.WireType.EndGroup);
  489. output.Flush();
  490. stream.Position = 0;
  491. var input = new CodedInputStream(stream);
  492. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
  493. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  494. }
  495. [Test]
  496. public void EndOfStreamReachedWhileSkippingGroup()
  497. {
  498. var stream = new MemoryStream();
  499. var output = new CodedOutputStream(stream);
  500. output.WriteTag(1, WireFormat.WireType.StartGroup);
  501. output.WriteTag(2, WireFormat.WireType.StartGroup);
  502. output.WriteTag(2, WireFormat.WireType.EndGroup);
  503. output.Flush();
  504. stream.Position = 0;
  505. // Now act like a generated client
  506. var input = new CodedInputStream(stream);
  507. input.ReadTag();
  508. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  509. }
  510. [Test]
  511. public void RecursionLimitAppliedWhileSkippingGroup()
  512. {
  513. var stream = new MemoryStream();
  514. var output = new CodedOutputStream(stream);
  515. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  516. {
  517. output.WriteTag(1, WireFormat.WireType.StartGroup);
  518. }
  519. for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
  520. {
  521. output.WriteTag(1, WireFormat.WireType.EndGroup);
  522. }
  523. output.Flush();
  524. stream.Position = 0;
  525. // Now act like a generated client
  526. var input = new CodedInputStream(stream);
  527. Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
  528. Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
  529. }
  530. [Test]
  531. public void Construction_Invalid()
  532. {
  533. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
  534. Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
  535. Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
  536. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
  537. Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
  538. }
  539. [Test]
  540. public void CreateWithLimits_InvalidLimits()
  541. {
  542. var stream = new MemoryStream();
  543. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
  544. Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
  545. }
  546. [Test]
  547. public void Dispose_DisposesUnderlyingStream()
  548. {
  549. var memoryStream = new MemoryStream();
  550. Assert.IsTrue(memoryStream.CanRead);
  551. using (var cis = new CodedInputStream(memoryStream))
  552. {
  553. }
  554. Assert.IsFalse(memoryStream.CanRead); // Disposed
  555. }
  556. [Test]
  557. public void Dispose_WithLeaveOpen()
  558. {
  559. var memoryStream = new MemoryStream();
  560. Assert.IsTrue(memoryStream.CanRead);
  561. using (var cis = new CodedInputStream(memoryStream, true))
  562. {
  563. }
  564. Assert.IsTrue(memoryStream.CanRead); // We left the stream open
  565. }
  566. [Test]
  567. public void Dispose_FromByteArray()
  568. {
  569. var stream = new CodedInputStream(new byte[10]);
  570. stream.Dispose();
  571. }
  572. [Test]
  573. public void TestParseMessagesCloseTo2G()
  574. {
  575. byte[] serializedMessage = GenerateBigSerializedMessage();
  576. // How many of these big messages do we need to take us near our 2GB limit?
  577. int count = Int32.MaxValue / serializedMessage.Length;
  578. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  579. // our big serialized message 'count' times.
  580. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  581. {
  582. Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream));
  583. }
  584. }
  585. [Test]
  586. public void TestParseMessagesOver2G()
  587. {
  588. byte[] serializedMessage = GenerateBigSerializedMessage();
  589. // How many of these big messages do we need to take us near our 2GB limit?
  590. int count = Int32.MaxValue / serializedMessage.Length;
  591. // Now add one to take us over the 2GB limit
  592. count++;
  593. // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
  594. // our big serialized message 'count' times.
  595. using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
  596. {
  597. Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream),
  598. "Protocol message was too large. May be malicious. " +
  599. "Use CodedInputStream.SetSizeLimit() to increase the size limit.");
  600. }
  601. }
  602. /// <returns>A serialized big message</returns>
  603. private static byte[] GenerateBigSerializedMessage()
  604. {
  605. byte[] value = new byte[16 * 1024 * 1024];
  606. TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
  607. message.SingleBytes = ByteString.CopyFrom(value);
  608. return message.ToByteArray();
  609. }
  610. /// <summary>
  611. /// A MemoryStream that repeats a byte arrays' content a number of times.
  612. /// Simulates really large input without consuming loads of memory. Used above
  613. /// to test the parsing behavior when the input size exceeds 2GB or close to it.
  614. /// </summary>
  615. private class RepeatingMemoryStream: MemoryStream
  616. {
  617. private readonly byte[] bytes;
  618. private readonly int maxIterations;
  619. private int index = 0;
  620. public RepeatingMemoryStream(byte[] bytes, int maxIterations)
  621. {
  622. this.bytes = bytes;
  623. this.maxIterations = maxIterations;
  624. }
  625. public override int Read(byte[] buffer, int offset, int count)
  626. {
  627. if (bytes.Length == 0)
  628. {
  629. return 0;
  630. }
  631. int numBytesCopiedTotal = 0;
  632. while (numBytesCopiedTotal < count && index < maxIterations)
  633. {
  634. int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count);
  635. Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy);
  636. numBytesCopiedTotal += numBytesToCopy;
  637. offset += numBytesToCopy;
  638. count -= numBytesCopiedTotal;
  639. Position += numBytesToCopy;
  640. if (Position >= bytes.Length)
  641. {
  642. Position = 0;
  643. index++;
  644. }
  645. }
  646. return numBytesCopiedTotal;
  647. }
  648. }
  649. }
  650. }