blob: 8944dbf010bfca4fb9c20f926a1cd0fa192806b1 [file] [log] [blame]
Jon Skeet60c059b2008-10-23 21:17:56 +01001// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc. All rights reserved.
3// http://github.com/jskeet/dotnet-protobufs/
4// Original C++/Java/Python code:
Jon Skeet68036862008-10-22 13:30:34 +01005// http://code.google.com/p/protobuf/
6//
Jon Skeet60c059b2008-10-23 21:17:56 +01007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions are
9// met:
Jon Skeet68036862008-10-22 13:30:34 +010010//
Jon Skeet60c059b2008-10-23 21:17:56 +010011// * Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13// * Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following disclaimer
15// in the documentation and/or other materials provided with the
16// distribution.
17// * Neither the name of Google Inc. nor the names of its
18// contributors may be used to endorse or promote products derived from
19// this software without specific prior written permission.
Jon Skeet68036862008-10-22 13:30:34 +010020//
Jon Skeet60c059b2008-10-23 21:17:56 +010021// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Jon Skeet68036862008-10-22 13:30:34 +010032using System;
33using System.IO;
34using Google.ProtocolBuffers.TestProtos;
35using NUnit.Framework;
36using System.Diagnostics;
37
38namespace Google.ProtocolBuffers {
39 [TestFixture]
40 public class CodedInputStreamTest {
41
42 /// <summary>
43 /// Helper to construct a byte array from a bunch of bytes. The inputs are
44 /// actually ints so that I can use hex notation and not get stupid errors
45 /// about precision.
46 /// </summary>
47 private static byte[] Bytes(params int[] bytesAsInts) {
48 byte[] bytes = new byte[bytesAsInts.Length];
49 for (int i = 0; i < bytesAsInts.Length; i++) {
50 bytes[i] = (byte)bytesAsInts[i];
51 }
52 return bytes;
53 }
54
55 /// <summary>
56 /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
57 /// </summary>
58 private static void AssertReadVarint(byte[] data, ulong value) {
59 CodedInputStream input = CodedInputStream.CreateInstance(data);
60 Assert.AreEqual((uint)value, input.ReadRawVarint32());
61
62 input = CodedInputStream.CreateInstance(data);
63 Assert.AreEqual(value, input.ReadRawVarint64());
Jon Skeetc298c892009-05-30 10:07:09 +010064 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +010065
66 // Try different block sizes.
67 for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) {
68 input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
69 Assert.AreEqual((uint)value, input.ReadRawVarint32());
70
71 input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
72 Assert.AreEqual(value, input.ReadRawVarint64());
Jon Skeetc298c892009-05-30 10:07:09 +010073 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +010074 }
Jon Skeetc298c892009-05-30 10:07:09 +010075
76 // Try reading directly from a MemoryStream. We want to verify that it
77 // doesn't read past the end of the input, so write an extra byte - this
78 // lets us test the position at the end.
79 MemoryStream memoryStream = new MemoryStream();
80 memoryStream.Write(data, 0, data.Length);
81 memoryStream.WriteByte(0);
82 memoryStream.Position = 0;
83 Assert.AreEqual((uint)value, CodedInputStream.ReadRawVarint32(memoryStream));
84 Assert.AreEqual(data.Length, memoryStream.Position);
Jon Skeet68036862008-10-22 13:30:34 +010085 }
86
87 /// <summary>
88 /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
89 /// expects them to fail with an InvalidProtocolBufferException whose
90 /// description matches the given one.
91 /// </summary>
Jon Skeetc298c892009-05-30 10:07:09 +010092 private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) {
Jon Skeet68036862008-10-22 13:30:34 +010093 CodedInputStream input = CodedInputStream.CreateInstance(data);
94 try {
95 input.ReadRawVarint32();
96 Assert.Fail("Should have thrown an exception.");
97 } catch (InvalidProtocolBufferException e) {
98 Assert.AreEqual(expected.Message, e.Message);
99 }
100
101 input = CodedInputStream.CreateInstance(data);
102 try {
103 input.ReadRawVarint64();
104 Assert.Fail("Should have thrown an exception.");
105 } catch (InvalidProtocolBufferException e) {
106 Assert.AreEqual(expected.Message, e.Message);
107 }
Jon Skeetc298c892009-05-30 10:07:09 +0100108
109 // Make sure we get the same error when reading directly from a Stream.
110 try {
111 CodedInputStream.ReadRawVarint32(new MemoryStream(data));
112 Assert.Fail("Should have thrown an exception.");
113 } catch (InvalidProtocolBufferException e) {
114 Assert.AreEqual(expected.Message, e.Message);
115 }
Jon Skeet68036862008-10-22 13:30:34 +0100116 }
117
118 [Test]
119 public void ReadVarint() {
120 AssertReadVarint(Bytes(0x00), 0);
121 AssertReadVarint(Bytes(0x01), 1);
122 AssertReadVarint(Bytes(0x7f), 127);
123 // 14882
124 AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
125 // 2961488830
126 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
127 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
128 (0x0bL << 28));
129
130 // 64-bit
131 // 7256456126
132 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
133 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
134 (0x1bL << 28));
135 // 41256202580718336
136 AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
137 (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
138 (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
139 // 11964378330978735131
140 AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
141 (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
142 (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
143 (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
144
145 // Failures
146 AssertReadVarintFailure(
147 InvalidProtocolBufferException.MalformedVarint(),
148 Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
149 0x00));
150 AssertReadVarintFailure(
151 InvalidProtocolBufferException.TruncatedMessage(),
152 Bytes(0x80));
153 }
154
155 /// <summary>
156 /// Parses the given bytes using ReadRawLittleEndian32() and checks
157 /// that the result matches the given value.
158 /// </summary>
159 private static void AssertReadLittleEndian32(byte[] data, uint value) {
160 CodedInputStream input = CodedInputStream.CreateInstance(data);
161 Assert.AreEqual(value, input.ReadRawLittleEndian32());
Jon Skeetc298c892009-05-30 10:07:09 +0100162 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +0100163
164 // Try different block sizes.
165 for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
166 input = CodedInputStream.CreateInstance(
167 new SmallBlockInputStream(data, blockSize));
168 Assert.AreEqual(value, input.ReadRawLittleEndian32());
Jon Skeetc298c892009-05-30 10:07:09 +0100169 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +0100170 }
171 }
172
173 /// <summary>
174 /// Parses the given bytes using ReadRawLittleEndian64() and checks
175 /// that the result matches the given value.
176 /// </summary>
177 private static void AssertReadLittleEndian64(byte[] data, ulong value) {
178 CodedInputStream input = CodedInputStream.CreateInstance(data);
179 Assert.AreEqual(value, input.ReadRawLittleEndian64());
Jon Skeetc298c892009-05-30 10:07:09 +0100180 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +0100181
182 // Try different block sizes.
183 for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
184 input = CodedInputStream.CreateInstance(
185 new SmallBlockInputStream(data, blockSize));
186 Assert.AreEqual(value, input.ReadRawLittleEndian64());
Jon Skeetc298c892009-05-30 10:07:09 +0100187 Assert.IsTrue(input.IsAtEnd);
Jon Skeet68036862008-10-22 13:30:34 +0100188 }
189 }
190
191 [Test]
192 public void ReadLittleEndian() {
193 AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
194 AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
195
196 AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
197 0x123456789abcdef0L);
198 AssertReadLittleEndian64(
199 Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
200 }
201
202 [Test]
203 public void DecodeZigZag32() {
204 Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
205 Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
206 Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
207 Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
208 Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
209 Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
210 Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
211 Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
212 }
213
214 [Test]
215 public void DecodeZigZag64() {
216 Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
217 Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
218 Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
219 Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
220 Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
221 Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
222 Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
223 Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
224 Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
225 Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
226 }
227
228 [Test]
229 public void ReadWholeMessage() {
230 TestAllTypes message = TestUtil.GetAllSet();
231
232 byte[] rawBytes = message.ToByteArray();
233 Assert.AreEqual(rawBytes.Length, message.SerializedSize);
234 TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
235 TestUtil.AssertAllFieldsSet(message2);
236
237 // Try different block sizes.
238 for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
239 message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
240 TestUtil.AssertAllFieldsSet(message2);
241 }
242 }
243
244 [Test]
245 public void SkipWholeMessage() {
246 TestAllTypes message = TestUtil.GetAllSet();
247 byte[] rawBytes = message.ToByteArray();
248
249 // Create two parallel inputs. Parse one as unknown fields while using
250 // skipField() to skip each field on the other. Expect the same tags.
251 CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
252 CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);
253 UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();
254
255 while (true) {
256 uint tag = input1.ReadTag();
257 Assert.AreEqual(tag, input2.ReadTag());
258 if (tag == 0) {
259 break;
260 }
261 unknownFields.MergeFieldFrom(tag, input1);
262 input2.SkipField(tag);
263 }
264 }
265
Jon Skeetc298c892009-05-30 10:07:09 +0100266 /// <summary>
267 /// Test that a bug in SkipRawBytes has been fixed: if the skip
268 /// skips exactly up to a limit, this should bnot break things
269 /// </summary>
270 [Test]
271 public void SkipRawBytesBug() {
272 byte[] rawBytes = new byte[] { 1, 2 };
273 CodedInputStream input = CodedInputStream.CreateInstance(rawBytes);
274
275 int limit = input.PushLimit(1);
276 input.SkipRawBytes(1);
277 input.PopLimit(limit);
278 Assert.AreEqual(2, input.ReadRawByte());
279 }
280
Jon Skeet68036862008-10-22 13:30:34 +0100281 public void ReadHugeBlob() {
282 // Allocate and initialize a 1MB blob.
283 byte[] blob = new byte[1 << 20];
284 for (int i = 0; i < blob.Length; i++) {
285 blob[i] = (byte)i;
286 }
287
288 // Make a message containing it.
289 TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
290 TestUtil.SetAllFields(builder);
291 builder.SetOptionalBytes(ByteString.CopyFrom(blob));
292 TestAllTypes message = builder.Build();
293
294 // Serialize and parse it. Make sure to parse from an InputStream, not
295 // directly from a ByteString, so that CodedInputStream uses buffered
296 // reading.
297 TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput());
298
299 Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes);
300
301 // Make sure all the other fields were parsed correctly.
302 TestAllTypes message3 = TestAllTypes.CreateBuilder(message2)
303 .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
304 .Build();
305 TestUtil.AssertAllFieldsSet(message3);
306 }
307
308 [Test]
309 public void ReadMaliciouslyLargeBlob() {
310 MemoryStream ms = new MemoryStream();
311 CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
312
313 uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
314 output.WriteRawVarint32(tag);
315 output.WriteRawVarint32(0x7FFFFFFF);
316 output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
317 output.Flush();
318 ms.Position = 0;
319
320 CodedInputStream input = CodedInputStream.CreateInstance(ms);
321 Assert.AreEqual(tag, input.ReadTag());
322
323 try {
324 input.ReadBytes();
325 Assert.Fail("Should have thrown an exception!");
326 } catch (InvalidProtocolBufferException) {
327 // success.
328 }
329 }
330
331 private static TestRecursiveMessage MakeRecursiveMessage(int depth) {
332 if (depth == 0) {
333 return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
334 } else {
335 return TestRecursiveMessage.CreateBuilder()
336 .SetA(MakeRecursiveMessage(depth - 1)).Build();
337 }
338 }
339
340 private static void AssertMessageDepth(TestRecursiveMessage message, int depth) {
341 if (depth == 0) {
342 Assert.IsFalse(message.HasA);
343 Assert.AreEqual(5, message.I);
344 } else {
345 Assert.IsTrue(message.HasA);
346 AssertMessageDepth(message.A, depth - 1);
347 }
348 }
349
350 [Test]
351 public void MaliciousRecursion() {
352 ByteString data64 = MakeRecursiveMessage(64).ToByteString();
353 ByteString data65 = MakeRecursiveMessage(65).ToByteString();
354
355 AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
356
357 try {
358 TestRecursiveMessage.ParseFrom(data65);
359 Assert.Fail("Should have thrown an exception!");
360 } catch (InvalidProtocolBufferException) {
361 // success.
362 }
363
364 CodedInputStream input = data64.CreateCodedInput();
365 input.SetRecursionLimit(8);
366 try {
367 TestRecursiveMessage.ParseFrom(input);
368 Assert.Fail("Should have thrown an exception!");
369 } catch (InvalidProtocolBufferException) {
370 // success.
371 }
372 }
373
374 [Test]
375 public void SizeLimit() {
376 // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
377 // apply to the latter case.
378 MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
379 CodedInputStream input = CodedInputStream.CreateInstance(ms);
380 input.SetSizeLimit(16);
381
382 try {
383 TestAllTypes.ParseFrom(input);
384 Assert.Fail("Should have thrown an exception!");
385 } catch (InvalidProtocolBufferException) {
386 // success.
387 }
388 }
389
Jon Skeetc298c892009-05-30 10:07:09 +0100390 [Test]
391 public void ResetSizeCounter() {
392 CodedInputStream input = CodedInputStream.CreateInstance(
393 new SmallBlockInputStream(new byte[256], 8));
394 input.SetSizeLimit(16);
395 input.ReadRawBytes(16);
396
397 try {
398 input.ReadRawByte();
399 Assert.Fail("Should have thrown an exception!");
Jon Skeetdf67f142009-06-05 19:29:36 +0100400 } catch (InvalidProtocolBufferException) {
Jon Skeetc298c892009-05-30 10:07:09 +0100401 // Success.
402 }
403
404 input.ResetSizeCounter();
405 input.ReadRawByte(); // No exception thrown.
406
407 try {
408 input.ReadRawBytes(16); // Hits limit again.
409 Assert.Fail("Should have thrown an exception!");
Jon Skeetdf67f142009-06-05 19:29:36 +0100410 } catch (InvalidProtocolBufferException) {
Jon Skeetc298c892009-05-30 10:07:09 +0100411 // Success.
412 }
413 }
414
Jon Skeet68036862008-10-22 13:30:34 +0100415 /// <summary>
416 /// Tests that if we read an string that contains invalid UTF-8, no exception
417 /// is thrown. Instead, the invalid bytes are replaced with the Unicode
418 /// "replacement character" U+FFFD.
419 /// </summary>
420 [Test]
421 public void ReadInvalidUtf8() {
422 MemoryStream ms = new MemoryStream();
423 CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
424
425 uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
426 output.WriteRawVarint32(tag);
427 output.WriteRawVarint32(1);
428 output.WriteRawBytes(new byte[] { 0x80 });
429 output.Flush();
430 ms.Position = 0;
431
432 CodedInputStream input = CodedInputStream.CreateInstance(ms);
433 Assert.AreEqual(tag, input.ReadTag());
434 string text = input.ReadString();
435 Assert.AreEqual('\ufffd', text[0]);
436 }
437
438 /// <summary>
439 /// A stream which limits the number of bytes it reads at a time.
440 /// We use this to make sure that CodedInputStream doesn't screw up when
441 /// reading in small blocks.
442 /// </summary>
443 private sealed class SmallBlockInputStream : MemoryStream {
444 private readonly int blockSize;
445
446 public SmallBlockInputStream(byte[] data, int blockSize)
447 : base(data) {
448 this.blockSize = blockSize;
449 }
450
451 public override int Read(byte[] buffer, int offset, int count) {
452 return base.Read(buffer, offset, Math.Min(count, blockSize));
453 }
454 }
455 }
456}