CodedInputStreamTest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. using System;
  17. using System.IO;
  18. using Google.ProtocolBuffers.TestProtos;
  19. using NUnit.Framework;
  20. using System.Diagnostics;
  21. namespace Google.ProtocolBuffers {
  22. [TestFixture]
  23. public class CodedInputStreamTest {
  24. /// <summary>
  25. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  26. /// actually ints so that I can use hex notation and not get stupid errors
  27. /// about precision.
  28. /// </summary>
  29. private static byte[] Bytes(params int[] bytesAsInts) {
  30. byte[] bytes = new byte[bytesAsInts.Length];
  31. for (int i = 0; i < bytesAsInts.Length; i++) {
  32. bytes[i] = (byte)bytesAsInts[i];
  33. }
  34. return bytes;
  35. }
  36. /// <summary>
  37. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  38. /// </summary>
  39. private static void AssertReadVarint(byte[] data, ulong value) {
  40. CodedInputStream input = CodedInputStream.CreateInstance(data);
  41. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  42. input = CodedInputStream.CreateInstance(data);
  43. Assert.AreEqual(value, input.ReadRawVarint64());
  44. // Try different block sizes.
  45. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) {
  46. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  47. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  48. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  49. Assert.AreEqual(value, input.ReadRawVarint64());
  50. }
  51. }
  52. /// <summary>
  53. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  54. /// expects them to fail with an InvalidProtocolBufferException whose
  55. /// description matches the given one.
  56. /// </summary>
  57. private void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) {
  58. CodedInputStream input = CodedInputStream.CreateInstance(data);
  59. try {
  60. input.ReadRawVarint32();
  61. Assert.Fail("Should have thrown an exception.");
  62. } catch (InvalidProtocolBufferException e) {
  63. Assert.AreEqual(expected.Message, e.Message);
  64. }
  65. input = CodedInputStream.CreateInstance(data);
  66. try {
  67. input.ReadRawVarint64();
  68. Assert.Fail("Should have thrown an exception.");
  69. } catch (InvalidProtocolBufferException e) {
  70. Assert.AreEqual(expected.Message, e.Message);
  71. }
  72. }
  73. [Test]
  74. public void ReadVarint() {
  75. AssertReadVarint(Bytes(0x00), 0);
  76. AssertReadVarint(Bytes(0x01), 1);
  77. AssertReadVarint(Bytes(0x7f), 127);
  78. // 14882
  79. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  80. // 2961488830
  81. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  82. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  83. (0x0bL << 28));
  84. // 64-bit
  85. // 7256456126
  86. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  87. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  88. (0x1bL << 28));
  89. // 41256202580718336
  90. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  91. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  92. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  93. // 11964378330978735131
  94. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  95. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  96. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  97. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  98. // Failures
  99. AssertReadVarintFailure(
  100. InvalidProtocolBufferException.MalformedVarint(),
  101. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  102. 0x00));
  103. AssertReadVarintFailure(
  104. InvalidProtocolBufferException.TruncatedMessage(),
  105. Bytes(0x80));
  106. }
  107. /// <summary>
  108. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  109. /// that the result matches the given value.
  110. /// </summary>
  111. private static void AssertReadLittleEndian32(byte[] data, uint value) {
  112. CodedInputStream input = CodedInputStream.CreateInstance(data);
  113. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  114. // Try different block sizes.
  115. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  116. input = CodedInputStream.CreateInstance(
  117. new SmallBlockInputStream(data, blockSize));
  118. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  119. }
  120. }
  121. /// <summary>
  122. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  123. /// that the result matches the given value.
  124. /// </summary>
  125. private static void AssertReadLittleEndian64(byte[] data, ulong value) {
  126. CodedInputStream input = CodedInputStream.CreateInstance(data);
  127. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  128. // Try different block sizes.
  129. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  130. input = CodedInputStream.CreateInstance(
  131. new SmallBlockInputStream(data, blockSize));
  132. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  133. }
  134. }
  135. [Test]
  136. public void ReadLittleEndian() {
  137. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  138. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  139. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  140. 0x123456789abcdef0L);
  141. AssertReadLittleEndian64(
  142. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  143. }
  144. [Test]
  145. public void DecodeZigZag32() {
  146. Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
  147. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
  148. Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
  149. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
  150. Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
  151. Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
  152. Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
  153. Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
  154. }
  155. [Test]
  156. public void DecodeZigZag64() {
  157. Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
  158. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
  159. Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
  160. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
  161. Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
  162. Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
  163. Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
  164. Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
  165. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  166. Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  167. }
  168. [Test]
  169. public void ReadWholeMessage() {
  170. TestAllTypes message = TestUtil.GetAllSet();
  171. byte[] rawBytes = message.ToByteArray();
  172. Assert.AreEqual(rawBytes.Length, message.SerializedSize);
  173. TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
  174. TestUtil.AssertAllFieldsSet(message2);
  175. // Try different block sizes.
  176. for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
  177. message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  178. TestUtil.AssertAllFieldsSet(message2);
  179. }
  180. }
  181. [Test]
  182. public void SkipWholeMessage() {
  183. TestAllTypes message = TestUtil.GetAllSet();
  184. byte[] rawBytes = message.ToByteArray();
  185. // Create two parallel inputs. Parse one as unknown fields while using
  186. // skipField() to skip each field on the other. Expect the same tags.
  187. CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
  188. CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);
  189. UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();
  190. while (true) {
  191. uint tag = input1.ReadTag();
  192. Assert.AreEqual(tag, input2.ReadTag());
  193. if (tag == 0) {
  194. break;
  195. }
  196. unknownFields.MergeFieldFrom(tag, input1);
  197. input2.SkipField(tag);
  198. }
  199. }
  200. public void ReadHugeBlob() {
  201. // Allocate and initialize a 1MB blob.
  202. byte[] blob = new byte[1 << 20];
  203. for (int i = 0; i < blob.Length; i++) {
  204. blob[i] = (byte)i;
  205. }
  206. // Make a message containing it.
  207. TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
  208. TestUtil.SetAllFields(builder);
  209. builder.SetOptionalBytes(ByteString.CopyFrom(blob));
  210. TestAllTypes message = builder.Build();
  211. // Serialize and parse it. Make sure to parse from an InputStream, not
  212. // directly from a ByteString, so that CodedInputStream uses buffered
  213. // reading.
  214. TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput());
  215. Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes);
  216. // Make sure all the other fields were parsed correctly.
  217. TestAllTypes message3 = TestAllTypes.CreateBuilder(message2)
  218. .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
  219. .Build();
  220. TestUtil.AssertAllFieldsSet(message3);
  221. }
  222. [Test]
  223. public void ReadMaliciouslyLargeBlob() {
  224. MemoryStream ms = new MemoryStream();
  225. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  226. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  227. output.WriteRawVarint32(tag);
  228. output.WriteRawVarint32(0x7FFFFFFF);
  229. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  230. output.Flush();
  231. ms.Position = 0;
  232. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  233. Assert.AreEqual(tag, input.ReadTag());
  234. try {
  235. input.ReadBytes();
  236. Assert.Fail("Should have thrown an exception!");
  237. } catch (InvalidProtocolBufferException) {
  238. // success.
  239. }
  240. }
  241. private static TestRecursiveMessage MakeRecursiveMessage(int depth) {
  242. if (depth == 0) {
  243. return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
  244. } else {
  245. return TestRecursiveMessage.CreateBuilder()
  246. .SetA(MakeRecursiveMessage(depth - 1)).Build();
  247. }
  248. }
  249. private static void AssertMessageDepth(TestRecursiveMessage message, int depth) {
  250. if (depth == 0) {
  251. Assert.IsFalse(message.HasA);
  252. Assert.AreEqual(5, message.I);
  253. } else {
  254. Assert.IsTrue(message.HasA);
  255. AssertMessageDepth(message.A, depth - 1);
  256. }
  257. }
  258. [Test]
  259. public void MaliciousRecursion() {
  260. ByteString data64 = MakeRecursiveMessage(64).ToByteString();
  261. ByteString data65 = MakeRecursiveMessage(65).ToByteString();
  262. AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
  263. try {
  264. TestRecursiveMessage.ParseFrom(data65);
  265. Assert.Fail("Should have thrown an exception!");
  266. } catch (InvalidProtocolBufferException) {
  267. // success.
  268. }
  269. CodedInputStream input = data64.CreateCodedInput();
  270. input.SetRecursionLimit(8);
  271. try {
  272. TestRecursiveMessage.ParseFrom(input);
  273. Assert.Fail("Should have thrown an exception!");
  274. } catch (InvalidProtocolBufferException) {
  275. // success.
  276. }
  277. }
  278. [Test]
  279. public void SizeLimit() {
  280. // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
  281. // apply to the latter case.
  282. MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
  283. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  284. input.SetSizeLimit(16);
  285. try {
  286. TestAllTypes.ParseFrom(input);
  287. Assert.Fail("Should have thrown an exception!");
  288. } catch (InvalidProtocolBufferException) {
  289. // success.
  290. }
  291. }
  292. /// <summary>
  293. /// Tests that if we read an string that contains invalid UTF-8, no exception
  294. /// is thrown. Instead, the invalid bytes are replaced with the Unicode
  295. /// "replacement character" U+FFFD.
  296. /// </summary>
  297. [Test]
  298. public void ReadInvalidUtf8() {
  299. MemoryStream ms = new MemoryStream();
  300. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  301. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  302. output.WriteRawVarint32(tag);
  303. output.WriteRawVarint32(1);
  304. output.WriteRawBytes(new byte[] { 0x80 });
  305. output.Flush();
  306. ms.Position = 0;
  307. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  308. Assert.AreEqual(tag, input.ReadTag());
  309. string text = input.ReadString();
  310. Assert.AreEqual('\ufffd', text[0]);
  311. }
  312. /// <summary>
  313. /// A stream which limits the number of bytes it reads at a time.
  314. /// We use this to make sure that CodedInputStream doesn't screw up when
  315. /// reading in small blocks.
  316. /// </summary>
  317. private sealed class SmallBlockInputStream : MemoryStream {
  318. private readonly int blockSize;
  319. public SmallBlockInputStream(byte[] data, int blockSize)
  320. : base(data) {
  321. this.blockSize = blockSize;
  322. }
  323. public override int Read(byte[] buffer, int offset, int count) {
  324. return base.Read(buffer, offset, Math.Min(count, blockSize));
  325. }
  326. }
  327. }
  328. }