CodedInputStreamTest.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. namespace Google.ProtocolBuffers {
  21. [TestFixture]
  22. public class CodedInputStreamTest {
  23. /// <summary>
  24. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  25. /// actually ints so that I can use hex notation and not get stupid errors
  26. /// about precision.
  27. /// </summary>
  28. private static byte[] Bytes(params int[] bytesAsInts) {
  29. byte[] bytes = new byte[bytesAsInts.Length];
  30. for (int i = 0; i < bytesAsInts.Length; i++) {
  31. bytes[i] = (byte)bytesAsInts[i];
  32. }
  33. return bytes;
  34. }
  35. /// <summary>
  36. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  37. /// </summary>
  38. private static void AssertReadVarint(byte[] data, ulong value) {
  39. CodedInputStream input = CodedInputStream.CreateInstance(data);
  40. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  41. input = CodedInputStream.CreateInstance(data);
  42. Assert.AreEqual(value, input.ReadRawVarint64());
  43. // Try different block sizes.
  44. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) {
  45. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  46. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  47. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  48. Assert.AreEqual(value, input.ReadRawVarint64());
  49. }
  50. }
  51. /// <summary>
  52. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  53. /// expects them to fail with an InvalidProtocolBufferException whose
  54. /// description matches the given one.
  55. /// </summary>
  56. private void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) {
  57. CodedInputStream input = CodedInputStream.CreateInstance(data);
  58. try {
  59. input.ReadRawVarint32();
  60. Assert.Fail("Should have thrown an exception.");
  61. } catch (InvalidProtocolBufferException e) {
  62. Assert.AreEqual(expected.Message, e.Message);
  63. }
  64. input = CodedInputStream.CreateInstance(data);
  65. try {
  66. input.ReadRawVarint64();
  67. Assert.Fail("Should have thrown an exception.");
  68. } catch (InvalidProtocolBufferException e) {
  69. Assert.AreEqual(expected.Message, e.Message);
  70. }
  71. }
  72. [Test]
  73. public void ReadVarint() {
  74. AssertReadVarint(Bytes(0x00), 0);
  75. AssertReadVarint(Bytes(0x01), 1);
  76. AssertReadVarint(Bytes(0x7f), 127);
  77. // 14882
  78. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  79. // 2961488830
  80. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  81. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  82. (0x0bL << 28));
  83. // 64-bit
  84. // 7256456126
  85. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  86. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  87. (0x1bL << 28));
  88. // 41256202580718336
  89. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  90. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  91. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  92. // 11964378330978735131
  93. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  94. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  95. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  96. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  97. // Failures
  98. AssertReadVarintFailure(
  99. InvalidProtocolBufferException.MalformedVarint(),
  100. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  101. 0x00));
  102. AssertReadVarintFailure(
  103. InvalidProtocolBufferException.TruncatedMessage(),
  104. Bytes(0x80));
  105. }
  106. /// <summary>
  107. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  108. /// that the result matches the given value.
  109. /// </summary>
  110. private static void AssertReadLittleEndian32(byte[] data, uint value) {
  111. CodedInputStream input = CodedInputStream.CreateInstance(data);
  112. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  113. // Try different block sizes.
  114. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  115. input = CodedInputStream.CreateInstance(
  116. new SmallBlockInputStream(data, blockSize));
  117. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  118. }
  119. }
  120. /// <summary>
  121. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  122. /// that the result matches the given value.
  123. /// </summary>
  124. private static void AssertReadLittleEndian64(byte[] data, ulong value) {
  125. CodedInputStream input = CodedInputStream.CreateInstance(data);
  126. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  127. // Try different block sizes.
  128. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  129. input = CodedInputStream.CreateInstance(
  130. new SmallBlockInputStream(data, blockSize));
  131. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  132. }
  133. }
  134. [Test]
  135. public void ReadLittleEndian() {
  136. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  137. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
  138. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  139. 0x123456789abcdef0L);
  140. AssertReadLittleEndian64(
  141. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
  142. }
  143. [Test]
  144. public void DecodeZigZag32() {
  145. Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
  146. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
  147. Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
  148. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
  149. Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
  150. Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
  151. Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
  152. Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
  153. }
  154. [Test]
  155. public void DecodeZigZag64() {
  156. Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
  157. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
  158. Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
  159. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
  160. Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
  161. Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
  162. Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
  163. Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
  164. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  165. Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  166. }
  167. [Test]
  168. public void ReadWholeMessage() {
  169. TestAllTypes message = TestUtil.GetAllSet();
  170. byte[] rawBytes = message.ToByteArray();
  171. Assert.AreEqual(rawBytes.Length, message.SerializedSize);
  172. TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
  173. TestUtil.AssertAllFieldsSet(message2);
  174. // Try different block sizes.
  175. for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
  176. message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
  177. TestUtil.AssertAllFieldsSet(message2);
  178. }
  179. }
  180. /* TODO(jonskeet): Reinstate this when protoc is ready
  181. public void testSkipWholeMessage() throws Exception {
  182. TestAllTypes message = TestUtil.getAllSet();
  183. byte[] rawBytes = message.toByteArray();
  184. // Create two parallel inputs. Parse one as unknown fields while using
  185. // skipField() to skip each field on the other. Expect the same tags.
  186. CodedInputStream input1 = CodedInputStream.newInstance(rawBytes);
  187. CodedInputStream input2 = CodedInputStream.newInstance(rawBytes);
  188. UnknownFieldSet.Builder unknownFields = UnknownFieldSet.newBuilder();
  189. while (true) {
  190. int tag = input1.readTag();
  191. assertEquals(tag, input2.readTag());
  192. if (tag == 0) {
  193. break;
  194. }
  195. unknownFields.mergeFieldFrom(tag, input1);
  196. input2.skipField(tag);
  197. }
  198. }*/
  199. /* TODO(jonskeet): Reinstate this when protoc is ready
  200. public void testReadHugeBlob() throws Exception {
  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.newBuilder();
  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 =
  215. TestAllTypes.parseFrom(message.toByteString().newInput());
  216. assertEquals(message.getOptionalBytes(), message2.getOptionalBytes());
  217. // Make sure all the other fields were parsed correctly.
  218. TestAllTypes message3 = TestAllTypes.newBuilder(message2)
  219. .setOptionalBytes(TestUtil.getAllSet().getOptionalBytes())
  220. .build();
  221. TestUtil.assertAllFieldsSet(message3);
  222. }*/
  223. [Test]
  224. public void ReadMaliciouslyLargeBlob() {
  225. MemoryStream ms = new MemoryStream();
  226. CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
  227. uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
  228. output.WriteRawVarint32(tag);
  229. output.WriteRawVarint32(0x7FFFFFFF);
  230. output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
  231. output.Flush();
  232. ms.Position = 0;
  233. CodedInputStream input = CodedInputStream.CreateInstance(ms);
  234. Assert.AreEqual(tag, input.ReadTag());
  235. try {
  236. input.ReadBytes();
  237. Assert.Fail("Should have thrown an exception!");
  238. } catch (InvalidProtocolBufferException) {
  239. // success.
  240. }
  241. }
  242. /* TODO(jonskeet): Reinstate this when protoc is ready
  243. private TestRecursiveMessage makeRecursiveMessage(int depth) {
  244. if (depth == 0) {
  245. return TestRecursiveMessage.newBuilder().setI(5).build();
  246. } else {
  247. return TestRecursiveMessage.newBuilder()
  248. .setA(makeRecursiveMessage(depth - 1)).build();
  249. }
  250. }
  251. private void assertMessageDepth(TestRecursiveMessage message, int depth) {
  252. if (depth == 0) {
  253. assertFalse(message.hasA());
  254. assertEquals(5, message.getI());
  255. } else {
  256. assertTrue(message.hasA());
  257. assertMessageDepth(message.getA(), depth - 1);
  258. }
  259. }
  260. public void testMaliciousRecursion() {
  261. ByteString data64 = makeRecursiveMessage(64).toByteString();
  262. ByteString data65 = makeRecursiveMessage(65).toByteString();
  263. assertMessageDepth(TestRecursiveMessage.parseFrom(data64), 64);
  264. try {
  265. TestRecursiveMessage.parseFrom(data65);
  266. fail("Should have thrown an exception!");
  267. } catch (InvalidProtocolBufferException e) {
  268. // success.
  269. }
  270. CodedInputStream input = data64.newCodedInput();
  271. input.setRecursionLimit(8);
  272. try {
  273. TestRecursiveMessage.parseFrom(input);
  274. fail("Should have thrown an exception!");
  275. } catch (InvalidProtocolBufferException e) {
  276. // success.
  277. }
  278. }
  279. */
  280. /* TODO(jonskeet): Reinstate this when protoc is ready
  281. public void testSizeLimit() throws Exception {
  282. CodedInputStream input = CodedInputStream.newInstance(
  283. TestUtil.getAllSet().toByteString().newInput());
  284. input.setSizeLimit(16);
  285. try {
  286. TestAllTypes.parseFrom(input);
  287. fail("Should have thrown an exception!");
  288. } catch (InvalidProtocolBufferException e) {
  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. }