blob: ce4a668313019f39a0cb39937c24d09a8acaa7fb [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());
64
65 // Try different block sizes.
66 for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) {
67 input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
68 Assert.AreEqual((uint)value, input.ReadRawVarint32());
69
70 input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize));
71 Assert.AreEqual(value, input.ReadRawVarint64());
72 }
73 }
74
75 /// <summary>
76 /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
77 /// expects them to fail with an InvalidProtocolBufferException whose
78 /// description matches the given one.
79 /// </summary>
80 private void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) {
81 CodedInputStream input = CodedInputStream.CreateInstance(data);
82 try {
83 input.ReadRawVarint32();
84 Assert.Fail("Should have thrown an exception.");
85 } catch (InvalidProtocolBufferException e) {
86 Assert.AreEqual(expected.Message, e.Message);
87 }
88
89 input = CodedInputStream.CreateInstance(data);
90 try {
91 input.ReadRawVarint64();
92 Assert.Fail("Should have thrown an exception.");
93 } catch (InvalidProtocolBufferException e) {
94 Assert.AreEqual(expected.Message, e.Message);
95 }
96 }
97
98 [Test]
99 public void ReadVarint() {
100 AssertReadVarint(Bytes(0x00), 0);
101 AssertReadVarint(Bytes(0x01), 1);
102 AssertReadVarint(Bytes(0x7f), 127);
103 // 14882
104 AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
105 // 2961488830
106 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
107 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
108 (0x0bL << 28));
109
110 // 64-bit
111 // 7256456126
112 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
113 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
114 (0x1bL << 28));
115 // 41256202580718336
116 AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
117 (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
118 (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
119 // 11964378330978735131
120 AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
121 (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
122 (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
123 (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
124
125 // Failures
126 AssertReadVarintFailure(
127 InvalidProtocolBufferException.MalformedVarint(),
128 Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
129 0x00));
130 AssertReadVarintFailure(
131 InvalidProtocolBufferException.TruncatedMessage(),
132 Bytes(0x80));
133 }
134
135 /// <summary>
136 /// Parses the given bytes using ReadRawLittleEndian32() and checks
137 /// that the result matches the given value.
138 /// </summary>
139 private static void AssertReadLittleEndian32(byte[] data, uint value) {
140 CodedInputStream input = CodedInputStream.CreateInstance(data);
141 Assert.AreEqual(value, input.ReadRawLittleEndian32());
142
143 // Try different block sizes.
144 for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
145 input = CodedInputStream.CreateInstance(
146 new SmallBlockInputStream(data, blockSize));
147 Assert.AreEqual(value, input.ReadRawLittleEndian32());
148 }
149 }
150
151 /// <summary>
152 /// Parses the given bytes using ReadRawLittleEndian64() and checks
153 /// that the result matches the given value.
154 /// </summary>
155 private static void AssertReadLittleEndian64(byte[] data, ulong value) {
156 CodedInputStream input = CodedInputStream.CreateInstance(data);
157 Assert.AreEqual(value, input.ReadRawLittleEndian64());
158
159 // Try different block sizes.
160 for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
161 input = CodedInputStream.CreateInstance(
162 new SmallBlockInputStream(data, blockSize));
163 Assert.AreEqual(value, input.ReadRawLittleEndian64());
164 }
165 }
166
167 [Test]
168 public void ReadLittleEndian() {
169 AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
170 AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
171
172 AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
173 0x123456789abcdef0L);
174 AssertReadLittleEndian64(
175 Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
176 }
177
178 [Test]
179 public void DecodeZigZag32() {
180 Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(0));
181 Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(1));
182 Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(2));
183 Assert.AreEqual(-2, CodedInputStream.DecodeZigZag32(3));
184 Assert.AreEqual(0x3FFFFFFF, CodedInputStream.DecodeZigZag32(0x7FFFFFFE));
185 Assert.AreEqual(unchecked((int)0xC0000000), CodedInputStream.DecodeZigZag32(0x7FFFFFFF));
186 Assert.AreEqual(0x7FFFFFFF, CodedInputStream.DecodeZigZag32(0xFFFFFFFE));
187 Assert.AreEqual(unchecked((int)0x80000000), CodedInputStream.DecodeZigZag32(0xFFFFFFFF));
188 }
189
190 [Test]
191 public void DecodeZigZag64() {
192 Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
193 Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
194 Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
195 Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
196 Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
197 Assert.AreEqual(unchecked((long)0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
198 Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
199 Assert.AreEqual(unchecked((long)0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
200 Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
201 Assert.AreEqual(unchecked((long)0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
202 }
203
204 [Test]
205 public void ReadWholeMessage() {
206 TestAllTypes message = TestUtil.GetAllSet();
207
208 byte[] rawBytes = message.ToByteArray();
209 Assert.AreEqual(rawBytes.Length, message.SerializedSize);
210 TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
211 TestUtil.AssertAllFieldsSet(message2);
212
213 // Try different block sizes.
214 for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
215 message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
216 TestUtil.AssertAllFieldsSet(message2);
217 }
218 }
219
220 [Test]
221 public void SkipWholeMessage() {
222 TestAllTypes message = TestUtil.GetAllSet();
223 byte[] rawBytes = message.ToByteArray();
224
225 // Create two parallel inputs. Parse one as unknown fields while using
226 // skipField() to skip each field on the other. Expect the same tags.
227 CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes);
228 CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes);
229 UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder();
230
231 while (true) {
232 uint tag = input1.ReadTag();
233 Assert.AreEqual(tag, input2.ReadTag());
234 if (tag == 0) {
235 break;
236 }
237 unknownFields.MergeFieldFrom(tag, input1);
238 input2.SkipField(tag);
239 }
240 }
241
242 public void ReadHugeBlob() {
243 // Allocate and initialize a 1MB blob.
244 byte[] blob = new byte[1 << 20];
245 for (int i = 0; i < blob.Length; i++) {
246 blob[i] = (byte)i;
247 }
248
249 // Make a message containing it.
250 TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
251 TestUtil.SetAllFields(builder);
252 builder.SetOptionalBytes(ByteString.CopyFrom(blob));
253 TestAllTypes message = builder.Build();
254
255 // Serialize and parse it. Make sure to parse from an InputStream, not
256 // directly from a ByteString, so that CodedInputStream uses buffered
257 // reading.
258 TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput());
259
260 Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes);
261
262 // Make sure all the other fields were parsed correctly.
263 TestAllTypes message3 = TestAllTypes.CreateBuilder(message2)
264 .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
265 .Build();
266 TestUtil.AssertAllFieldsSet(message3);
267 }
268
269 [Test]
270 public void ReadMaliciouslyLargeBlob() {
271 MemoryStream ms = new MemoryStream();
272 CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
273
274 uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
275 output.WriteRawVarint32(tag);
276 output.WriteRawVarint32(0x7FFFFFFF);
277 output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
278 output.Flush();
279 ms.Position = 0;
280
281 CodedInputStream input = CodedInputStream.CreateInstance(ms);
282 Assert.AreEqual(tag, input.ReadTag());
283
284 try {
285 input.ReadBytes();
286 Assert.Fail("Should have thrown an exception!");
287 } catch (InvalidProtocolBufferException) {
288 // success.
289 }
290 }
291
292 private static TestRecursiveMessage MakeRecursiveMessage(int depth) {
293 if (depth == 0) {
294 return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
295 } else {
296 return TestRecursiveMessage.CreateBuilder()
297 .SetA(MakeRecursiveMessage(depth - 1)).Build();
298 }
299 }
300
301 private static void AssertMessageDepth(TestRecursiveMessage message, int depth) {
302 if (depth == 0) {
303 Assert.IsFalse(message.HasA);
304 Assert.AreEqual(5, message.I);
305 } else {
306 Assert.IsTrue(message.HasA);
307 AssertMessageDepth(message.A, depth - 1);
308 }
309 }
310
311 [Test]
312 public void MaliciousRecursion() {
313 ByteString data64 = MakeRecursiveMessage(64).ToByteString();
314 ByteString data65 = MakeRecursiveMessage(65).ToByteString();
315
316 AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
317
318 try {
319 TestRecursiveMessage.ParseFrom(data65);
320 Assert.Fail("Should have thrown an exception!");
321 } catch (InvalidProtocolBufferException) {
322 // success.
323 }
324
325 CodedInputStream input = data64.CreateCodedInput();
326 input.SetRecursionLimit(8);
327 try {
328 TestRecursiveMessage.ParseFrom(input);
329 Assert.Fail("Should have thrown an exception!");
330 } catch (InvalidProtocolBufferException) {
331 // success.
332 }
333 }
334
335 [Test]
336 public void SizeLimit() {
337 // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
338 // apply to the latter case.
339 MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray());
340 CodedInputStream input = CodedInputStream.CreateInstance(ms);
341 input.SetSizeLimit(16);
342
343 try {
344 TestAllTypes.ParseFrom(input);
345 Assert.Fail("Should have thrown an exception!");
346 } catch (InvalidProtocolBufferException) {
347 // success.
348 }
349 }
350
351 /// <summary>
352 /// Tests that if we read an string that contains invalid UTF-8, no exception
353 /// is thrown. Instead, the invalid bytes are replaced with the Unicode
354 /// "replacement character" U+FFFD.
355 /// </summary>
356 [Test]
357 public void ReadInvalidUtf8() {
358 MemoryStream ms = new MemoryStream();
359 CodedOutputStream output = CodedOutputStream.CreateInstance(ms);
360
361 uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
362 output.WriteRawVarint32(tag);
363 output.WriteRawVarint32(1);
364 output.WriteRawBytes(new byte[] { 0x80 });
365 output.Flush();
366 ms.Position = 0;
367
368 CodedInputStream input = CodedInputStream.CreateInstance(ms);
369 Assert.AreEqual(tag, input.ReadTag());
370 string text = input.ReadString();
371 Assert.AreEqual('\ufffd', text[0]);
372 }
373
374 /// <summary>
375 /// A stream which limits the number of bytes it reads at a time.
376 /// We use this to make sure that CodedInputStream doesn't screw up when
377 /// reading in small blocks.
378 /// </summary>
379 private sealed class SmallBlockInputStream : MemoryStream {
380 private readonly int blockSize;
381
382 public SmallBlockInputStream(byte[] data, int blockSize)
383 : base(data) {
384 this.blockSize = blockSize;
385 }
386
387 public override int Read(byte[] buffer, int offset, int count) {
388 return base.Read(buffer, offset, Math.Min(count, blockSize));
389 }
390 }
391 }
392}