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 NUnit.Framework;
  19. namespace Google.ProtocolBuffers {
  20. [TestFixture]
  21. public class CodedInputStreamTest {
  22. /// <summary>
  23. /// Helper to construct a byte array from a bunch of bytes. The inputs are
  24. /// actually ints so that I can use hex notation and not get stupid errors
  25. /// about precision.
  26. /// </summary>
  27. private static byte[] Bytes(params int[] bytesAsInts) {
  28. byte[] bytes = new byte[bytesAsInts.Length];
  29. for (int i = 0; i < bytesAsInts.Length; i++) {
  30. bytes[i] = (byte)bytesAsInts[i];
  31. }
  32. return bytes;
  33. }
  34. /// <summary>
  35. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  36. /// </summary>
  37. private static void AssertReadVarint(byte[] data, ulong value) {
  38. CodedInputStream input = CodedInputStream.CreateInstance(data);
  39. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  40. input = CodedInputStream.CreateInstance(data);
  41. Assert.AreEqual(value, input.ReadRawVarint64());
  42. // Try different block sizes.
  43. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) {
  44. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  45. Assert.AreEqual((uint)value, input.ReadRawVarint32());
  46. input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
  47. Assert.AreEqual(value, input.ReadRawVarint64());
  48. }
  49. }
  50. /// <summary>
  51. /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
  52. /// expects them to fail with an InvalidProtocolBufferException whose
  53. /// description matches the given one.
  54. /// </summary>
  55. private void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) {
  56. CodedInputStream input = CodedInputStream.CreateInstance(data);
  57. try {
  58. input.ReadRawVarint32();
  59. Assert.Fail("Should have thrown an exception.");
  60. } catch (InvalidProtocolBufferException e) {
  61. Assert.AreEqual(expected.Message, e.Message);
  62. }
  63. input = CodedInputStream.CreateInstance(data);
  64. try {
  65. input.ReadRawVarint64();
  66. Assert.Fail("Should have thrown an exception.");
  67. } catch (InvalidProtocolBufferException e) {
  68. Assert.AreEqual(expected.Message, e.Message);
  69. }
  70. }
  71. [Test]
  72. public void ReadVarint() {
  73. AssertReadVarint(Bytes(0x00), 0);
  74. AssertReadVarint(Bytes(0x01), 1);
  75. AssertReadVarint(Bytes(0x7f), 127);
  76. // 14882
  77. AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
  78. // 2961488830
  79. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
  80. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  81. (0x0bL << 28));
  82. // 64-bit
  83. // 7256456126
  84. AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
  85. (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
  86. (0x1bL << 28));
  87. // 41256202580718336
  88. AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
  89. (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
  90. (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
  91. // 11964378330978735131
  92. AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
  93. (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
  94. (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
  95. (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
  96. // Failures
  97. AssertReadVarintFailure(
  98. InvalidProtocolBufferException.MalformedVarint(),
  99. Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
  100. 0x00));
  101. AssertReadVarintFailure(
  102. InvalidProtocolBufferException.TruncatedMessage(),
  103. Bytes(0x80));
  104. }
  105. /// <summary>
  106. /// Parses the given bytes using ReadRawLittleEndian32() and checks
  107. /// that the result matches the given value.
  108. /// </summary>
  109. private static void AssertReadLittleEndian32(byte[] data, int value) {
  110. CodedInputStream input = CodedInputStream.CreateInstance(data);
  111. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  112. // Try different block sizes.
  113. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  114. input = CodedInputStream.CreateInstance(
  115. new SmallBlockInputStream(data, blockSize));
  116. Assert.AreEqual(value, input.ReadRawLittleEndian32());
  117. }
  118. }
  119. /// <summary>
  120. /// Parses the given bytes using ReadRawLittleEndian64() and checks
  121. /// that the result matches the given value.
  122. /// </summary>
  123. private static void AssertReadLittleEndian64(byte[] data, long value) {
  124. CodedInputStream input = CodedInputStream.CreateInstance(data);
  125. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  126. // Try different block sizes.
  127. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
  128. input = CodedInputStream.CreateInstance(
  129. new SmallBlockInputStream(data, blockSize));
  130. Assert.AreEqual(value, input.ReadRawLittleEndian64());
  131. }
  132. }
  133. [Test]
  134. public void ReadLittleEndian() {
  135. AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
  136. AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), unchecked((int)0x9abcdef0));
  137. AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
  138. 0x123456789abcdef0L);
  139. AssertReadLittleEndian64(
  140. Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), unchecked((long)0x9abcdef012345678L));
  141. }
  142. [Test]
  143. public void DecodeZigZag32() {
  144. Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
  145. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
  146. Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
  147. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
  148. Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
  149. Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
  150. Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
  151. Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
  152. }
  153. [Test]
  154. public void DecodeZigZag64() {
  155. Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
  156. Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
  157. Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
  158. Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
  159. Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
  160. Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
  161. Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
  162. Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
  163. Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
  164. Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
  165. }
  166. /* TODO(jonskeet): Reinstate this when protoc is ready
  167. public void testReadWholeMessage() throws Exception {
  168. TestAllTypes message = TestUtil.getAllSet();
  169. byte[] rawBytes = message.toByteArray();
  170. assertEquals(rawBytes.length, message.getSerializedSize());
  171. TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
  172. TestUtil.assertAllFieldsSet(message2);
  173. // Try different block sizes.
  174. for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
  175. message2 = TestAllTypes.parseFrom(
  176. 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. }