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