blob: 8795fa65f4d5c12eb75ad73d0d0faade8d34d7ca [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001#region Copyright notice and license
2// Protocol Buffers - Google's data interchange format
3// Copyright 2008 Google Inc. All rights reserved.
4// https://developers.google.com/protocol-buffers/
5//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
10// * Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12// * Redistributions in binary form must reproduce the above
13// copyright notice, this list of conditions and the following disclaimer
14// in the documentation and/or other materials provided with the
15// distribution.
16// * Neither the name of Google Inc. nor the names of its
17// contributors may be used to endorse or promote products derived from
18// this software without specific prior written permission.
19//
20// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31#endregion
32
33using System;
34using System.IO;
35using Google.Protobuf.TestProtos;
36using NUnit.Framework;
37
38namespace Google.Protobuf
39{
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 {
49 byte[] bytes = new byte[bytesAsInts.Length];
50 for (int i = 0; i < bytesAsInts.Length; i++)
51 {
52 bytes[i] = (byte) bytesAsInts[i];
53 }
54 return bytes;
55 }
56
57 /// <summary>
58 /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
59 /// </summary>
60 private static void AssertReadVarint(byte[] data, ulong value)
61 {
62 CodedInputStream input = new CodedInputStream(data);
63 Assert.AreEqual((uint) value, input.ReadRawVarint32());
64
65 input = new CodedInputStream(data);
66 Assert.AreEqual(value, input.ReadRawVarint64());
67 Assert.IsTrue(input.IsAtEnd);
68
69 // Try different block sizes.
70 for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
71 {
72 input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
73 Assert.AreEqual((uint) value, input.ReadRawVarint32());
74
75 input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
76 Assert.AreEqual(value, input.ReadRawVarint64());
77 Assert.IsTrue(input.IsAtEnd);
78 }
79
80 // Try reading directly from a MemoryStream. We want to verify that it
81 // doesn't read past the end of the input, so write an extra byte - this
82 // lets us test the position at the end.
83 MemoryStream memoryStream = new MemoryStream();
84 memoryStream.Write(data, 0, data.Length);
85 memoryStream.WriteByte(0);
86 memoryStream.Position = 0;
87 Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
88 Assert.AreEqual(data.Length, memoryStream.Position);
89 }
90
91 /// <summary>
92 /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
93 /// expects them to fail with an InvalidProtocolBufferException whose
94 /// description matches the given one.
95 /// </summary>
96 private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
97 {
98 CodedInputStream input = new CodedInputStream(data);
99 var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
100 Assert.AreEqual(expected.Message, exception.Message);
101
102 input = new CodedInputStream(data);
103 exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
104 Assert.AreEqual(expected.Message, exception.Message);
105
106 // Make sure we get the same error when reading directly from a Stream.
107 exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
108 Assert.AreEqual(expected.Message, exception.Message);
109 }
110
111 [Test]
112 public void ReadVarint()
113 {
114 AssertReadVarint(Bytes(0x00), 0);
115 AssertReadVarint(Bytes(0x01), 1);
116 AssertReadVarint(Bytes(0x7f), 127);
117 // 14882
118 AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
119 // 2961488830
120 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
121 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
122 (0x0bL << 28));
123
124 // 64-bit
125 // 7256456126
126 AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
127 (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
128 (0x1bL << 28));
129 // 41256202580718336
130 AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
131 (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
132 (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
133 // 11964378330978735131
134 AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
135 (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
136 (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) |
137 (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63));
138
139 // Failures
140 AssertReadVarintFailure(
141 InvalidProtocolBufferException.MalformedVarint(),
142 Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
143 0x00));
144 AssertReadVarintFailure(
145 InvalidProtocolBufferException.TruncatedMessage(),
146 Bytes(0x80));
147 }
148
149 /// <summary>
150 /// Parses the given bytes using ReadRawLittleEndian32() and checks
151 /// that the result matches the given value.
152 /// </summary>
153 private static void AssertReadLittleEndian32(byte[] data, uint value)
154 {
155 CodedInputStream input = new CodedInputStream(data);
156 Assert.AreEqual(value, input.ReadRawLittleEndian32());
157 Assert.IsTrue(input.IsAtEnd);
158
159 // Try different block sizes.
160 for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
161 {
162 input = new CodedInputStream(
163 new SmallBlockInputStream(data, blockSize));
164 Assert.AreEqual(value, input.ReadRawLittleEndian32());
165 Assert.IsTrue(input.IsAtEnd);
166 }
167 }
168
169 /// <summary>
170 /// Parses the given bytes using ReadRawLittleEndian64() and checks
171 /// that the result matches the given value.
172 /// </summary>
173 private static void AssertReadLittleEndian64(byte[] data, ulong value)
174 {
175 CodedInputStream input = new CodedInputStream(data);
176 Assert.AreEqual(value, input.ReadRawLittleEndian64());
177 Assert.IsTrue(input.IsAtEnd);
178
179 // Try different block sizes.
180 for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
181 {
182 input = new CodedInputStream(
183 new SmallBlockInputStream(data, blockSize));
184 Assert.AreEqual(value, input.ReadRawLittleEndian64());
185 Assert.IsTrue(input.IsAtEnd);
186 }
187 }
188
189 [Test]
190 public void ReadLittleEndian()
191 {
192 AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
193 AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
194
195 AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
196 0x123456789abcdef0L);
197 AssertReadLittleEndian64(
198 Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL);
199 }
200
201 [Test]
202 public void DecodeZigZag32()
203 {
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 {
217 Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(0));
218 Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(1));
219 Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(2));
220 Assert.AreEqual(-2, CodedInputStream.DecodeZigZag64(3));
221 Assert.AreEqual(0x000000003FFFFFFFL, CodedInputStream.DecodeZigZag64(0x000000007FFFFFFEL));
222 Assert.AreEqual(unchecked((long) 0xFFFFFFFFC0000000L), CodedInputStream.DecodeZigZag64(0x000000007FFFFFFFL));
223 Assert.AreEqual(0x000000007FFFFFFFL, CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFEL));
224 Assert.AreEqual(unchecked((long) 0xFFFFFFFF80000000L), CodedInputStream.DecodeZigZag64(0x00000000FFFFFFFFL));
225 Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
226 Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
227 }
228
229 [Test]
230 public void ReadWholeMessage_VaryingBlockSizes()
231 {
232 TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
233
234 byte[] rawBytes = message.ToByteArray();
235 Assert.AreEqual(rawBytes.Length, message.CalculateSize());
236 TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes);
237 Assert.AreEqual(message, message2);
238
239 // Try different block sizes.
240 for (int blockSize = 1; blockSize < 256; blockSize *= 2)
241 {
242 message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize));
243 Assert.AreEqual(message, message2);
244 }
245 }
246
247 [Test]
248 public void ReadHugeBlob()
249 {
250 // Allocate and initialize a 1MB blob.
251 byte[] blob = new byte[1 << 20];
252 for (int i = 0; i < blob.Length; i++)
253 {
254 blob[i] = (byte) i;
255 }
256
257 // Make a message containing it.
258 var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) };
259
260 // Serialize and parse it. Make sure to parse from an InputStream, not
261 // directly from a ByteString, so that CodedInputStream uses buffered
262 // reading.
263 TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString());
264
265 Assert.AreEqual(message, message2);
266 }
267
268 [Test]
269 public void ReadMaliciouslyLargeBlob()
270 {
271 MemoryStream ms = new MemoryStream();
272 CodedOutputStream output = new CodedOutputStream(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 = new CodedInputStream(ms);
282 Assert.AreEqual(tag, input.ReadTag());
283
284 Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
285 }
286
Austin Schuh40c16522018-10-28 20:27:54 -0700287 // Representations of a tag for field 0 with various wire types
288 [Test]
289 [TestCase(0)]
290 [TestCase(1)]
291 [TestCase(2)]
292 [TestCase(3)]
293 [TestCase(4)]
294 [TestCase(5)]
295 public void ReadTag_ZeroFieldRejected(byte tag)
296 {
297 CodedInputStream cis = new CodedInputStream(new byte[] { tag });
298 Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag());
299 }
300
Brian Silverman9c614bc2016-02-15 20:20:02 -0500301 internal static TestRecursiveMessage MakeRecursiveMessage(int depth)
302 {
303 if (depth == 0)
304 {
305 return new TestRecursiveMessage { I = 5 };
306 }
307 else
308 {
309 return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
310 }
311 }
312
313 internal static void AssertMessageDepth(TestRecursiveMessage message, int depth)
314 {
315 if (depth == 0)
316 {
317 Assert.IsNull(message.A);
318 Assert.AreEqual(5, message.I);
319 }
320 else
321 {
322 Assert.IsNotNull(message.A);
323 AssertMessageDepth(message.A, depth - 1);
324 }
325 }
326
327 [Test]
328 public void MaliciousRecursion()
329 {
330 ByteString data64 = MakeRecursiveMessage(64).ToByteString();
331 ByteString data65 = MakeRecursiveMessage(65).ToByteString();
332
333 AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
334
335 Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
336
337 CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63);
338 Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
339 }
340
341 [Test]
342 public void SizeLimit()
343 {
344 // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't
345 // apply to the latter case.
346 MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray());
347 CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100);
348 Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input));
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 {
359 MemoryStream ms = new MemoryStream();
360 CodedOutputStream output = new CodedOutputStream(ms);
361
362 uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
363 output.WriteRawVarint32(tag);
364 output.WriteRawVarint32(1);
365 output.WriteRawBytes(new byte[] {0x80});
366 output.Flush();
367 ms.Position = 0;
368
369 CodedInputStream input = new CodedInputStream(ms);
370
371 Assert.AreEqual(tag, input.ReadTag());
372 string text = input.ReadString();
373 Assert.AreEqual('\ufffd', text[0]);
374 }
375
376 /// <summary>
377 /// A stream which limits the number of bytes it reads at a time.
378 /// We use this to make sure that CodedInputStream doesn't screw up when
379 /// reading in small blocks.
380 /// </summary>
381 private sealed class SmallBlockInputStream : MemoryStream
382 {
383 private readonly int blockSize;
384
385 public SmallBlockInputStream(byte[] data, int blockSize)
386 : base(data)
387 {
388 this.blockSize = blockSize;
389 }
390
391 public override int Read(byte[] buffer, int offset, int count)
392 {
393 return base.Read(buffer, offset, Math.Min(count, blockSize));
394 }
395 }
396
397 [Test]
398 public void TestNegativeEnum()
399 {
400 byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
401 CodedInputStream input = new CodedInputStream(bytes);
402 Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
403 Assert.IsTrue(input.IsAtEnd);
404 }
405
406 //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily
407 [Test]
408 public void TestSlowPathAvoidance()
409 {
410 using (var ms = new MemoryStream())
411 {
412 CodedOutputStream output = new CodedOutputStream(ms);
413 output.WriteTag(1, WireFormat.WireType.LengthDelimited);
414 output.WriteBytes(ByteString.CopyFrom(new byte[100]));
415 output.WriteTag(2, WireFormat.WireType.LengthDelimited);
416 output.WriteBytes(ByteString.CopyFrom(new byte[100]));
417 output.Flush();
418
419 ms.Position = 0;
Austin Schuh40c16522018-10-28 20:27:54 -0700420 CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false);
Brian Silverman9c614bc2016-02-15 20:20:02 -0500421
422 uint tag = input.ReadTag();
423 Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
424 Assert.AreEqual(100, input.ReadBytes().Length);
425
426 tag = input.ReadTag();
427 Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
428 Assert.AreEqual(100, input.ReadBytes().Length);
429 }
430 }
431
432 [Test]
433 public void Tag0Throws()
434 {
435 var input = new CodedInputStream(new byte[] { 0 });
436 Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
437 }
438
439 [Test]
440 public void SkipGroup()
441 {
442 // Create an output stream with a group in:
443 // Field 1: string "field 1"
444 // Field 2: group containing:
445 // Field 1: fixed int32 value 100
446 // Field 2: string "ignore me"
447 // Field 3: nested group containing
448 // Field 1: fixed int64 value 1000
449 // Field 3: string "field 3"
450 var stream = new MemoryStream();
451 var output = new CodedOutputStream(stream);
452 output.WriteTag(1, WireFormat.WireType.LengthDelimited);
453 output.WriteString("field 1");
454
455 // The outer group...
456 output.WriteTag(2, WireFormat.WireType.StartGroup);
457 output.WriteTag(1, WireFormat.WireType.Fixed32);
458 output.WriteFixed32(100);
459 output.WriteTag(2, WireFormat.WireType.LengthDelimited);
460 output.WriteString("ignore me");
461 // The nested group...
462 output.WriteTag(3, WireFormat.WireType.StartGroup);
463 output.WriteTag(1, WireFormat.WireType.Fixed64);
464 output.WriteFixed64(1000);
465 // Note: Not sure the field number is relevant for end group...
466 output.WriteTag(3, WireFormat.WireType.EndGroup);
467
468 // End the outer group
469 output.WriteTag(2, WireFormat.WireType.EndGroup);
470
471 output.WriteTag(3, WireFormat.WireType.LengthDelimited);
472 output.WriteString("field 3");
473 output.Flush();
474 stream.Position = 0;
475
476 // Now act like a generated client
477 var input = new CodedInputStream(stream);
478 Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
479 Assert.AreEqual("field 1", input.ReadString());
480 Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
481 input.SkipLastField(); // Should consume the whole group, including the nested one.
482 Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
483 Assert.AreEqual("field 3", input.ReadString());
484 }
485
486 [Test]
Austin Schuh40c16522018-10-28 20:27:54 -0700487 public void SkipGroup_WrongEndGroupTag()
488 {
489 // Create an output stream with:
490 // Field 1: string "field 1"
491 // Start group 2
492 // Field 3: fixed int32
493 // End group 4 (should give an error)
494 var stream = new MemoryStream();
495 var output = new CodedOutputStream(stream);
496 output.WriteTag(1, WireFormat.WireType.LengthDelimited);
497 output.WriteString("field 1");
498
499 // The outer group...
500 output.WriteTag(2, WireFormat.WireType.StartGroup);
501 output.WriteTag(3, WireFormat.WireType.Fixed32);
502 output.WriteFixed32(100);
503 output.WriteTag(4, WireFormat.WireType.EndGroup);
504 output.Flush();
505 stream.Position = 0;
506
507 // Now act like a generated client
508 var input = new CodedInputStream(stream);
509 Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
510 Assert.AreEqual("field 1", input.ReadString());
511 Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
512 Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
513 }
514
515 [Test]
516 public void RogueEndGroupTag()
517 {
518 // If we have an end-group tag without a leading start-group tag, generated
519 // code will just call SkipLastField... so that should fail.
520
521 var stream = new MemoryStream();
522 var output = new CodedOutputStream(stream);
523 output.WriteTag(1, WireFormat.WireType.EndGroup);
524 output.Flush();
525 stream.Position = 0;
526
527 var input = new CodedInputStream(stream);
528 Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
529 Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
530 }
531
532 [Test]
Brian Silverman9c614bc2016-02-15 20:20:02 -0500533 public void EndOfStreamReachedWhileSkippingGroup()
534 {
535 var stream = new MemoryStream();
536 var output = new CodedOutputStream(stream);
537 output.WriteTag(1, WireFormat.WireType.StartGroup);
538 output.WriteTag(2, WireFormat.WireType.StartGroup);
539 output.WriteTag(2, WireFormat.WireType.EndGroup);
540
541 output.Flush();
542 stream.Position = 0;
543
544 // Now act like a generated client
545 var input = new CodedInputStream(stream);
546 input.ReadTag();
Austin Schuh40c16522018-10-28 20:27:54 -0700547 Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
Brian Silverman9c614bc2016-02-15 20:20:02 -0500548 }
549
550 [Test]
551 public void RecursionLimitAppliedWhileSkippingGroup()
552 {
553 var stream = new MemoryStream();
554 var output = new CodedOutputStream(stream);
555 for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
556 {
557 output.WriteTag(1, WireFormat.WireType.StartGroup);
558 }
559 for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
560 {
561 output.WriteTag(1, WireFormat.WireType.EndGroup);
562 }
563 output.Flush();
564 stream.Position = 0;
565
566 // Now act like a generated client
567 var input = new CodedInputStream(stream);
568 Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
Austin Schuh40c16522018-10-28 20:27:54 -0700569 Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
Brian Silverman9c614bc2016-02-15 20:20:02 -0500570 }
571
572 [Test]
573 public void Construction_Invalid()
574 {
575 Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null));
576 Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0));
577 Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null));
578 Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0));
579 Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10));
580 }
581
582 [Test]
583 public void CreateWithLimits_InvalidLimits()
584 {
585 var stream = new MemoryStream();
586 Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1));
587 Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0));
588 }
Austin Schuh40c16522018-10-28 20:27:54 -0700589
590 [Test]
591 public void Dispose_DisposesUnderlyingStream()
592 {
593 var memoryStream = new MemoryStream();
594 Assert.IsTrue(memoryStream.CanRead);
595 using (var cis = new CodedInputStream(memoryStream))
596 {
597 }
598 Assert.IsFalse(memoryStream.CanRead); // Disposed
599 }
600
601 [Test]
602 public void Dispose_WithLeaveOpen()
603 {
604 var memoryStream = new MemoryStream();
605 Assert.IsTrue(memoryStream.CanRead);
606 using (var cis = new CodedInputStream(memoryStream, true))
607 {
608 }
609 Assert.IsTrue(memoryStream.CanRead); // We left the stream open
610 }
611
612 [Test]
613 public void Dispose_FromByteArray()
614 {
615 var stream = new CodedInputStream(new byte[10]);
616 stream.Dispose();
617 }
618
619 [Test]
620 public void TestParseMessagesCloseTo2G()
621 {
622 byte[] serializedMessage = GenerateBigSerializedMessage();
623 // How many of these big messages do we need to take us near our 2GB limit?
624 int count = Int32.MaxValue / serializedMessage.Length;
625 // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
626 // our big serialized message 'count' times.
627 using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
628 {
629 Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream));
630 }
631 }
632
633 [Test]
634 public void TestParseMessagesOver2G()
635 {
636 byte[] serializedMessage = GenerateBigSerializedMessage();
637 // How many of these big messages do we need to take us near our 2GB limit?
638 int count = Int32.MaxValue / serializedMessage.Length;
639 // Now add one to take us over the 2GB limit
640 count++;
641 // Now make a MemoryStream that will fake a near-2GB stream of messages by returning
642 // our big serialized message 'count' times.
643 using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count))
644 {
645 Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream),
646 "Protocol message was too large. May be malicious. " +
647 "Use CodedInputStream.SetSizeLimit() to increase the size limit.");
648 }
649 }
650
651 /// <returns>A serialized big message</returns>
652 private static byte[] GenerateBigSerializedMessage()
653 {
654 byte[] value = new byte[16 * 1024 * 1024];
655 TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
656 message.SingleBytes = ByteString.CopyFrom(value);
657 return message.ToByteArray();
658 }
659
660 /// <summary>
661 /// A MemoryStream that repeats a byte arrays' content a number of times.
662 /// Simulates really large input without consuming loads of memory. Used above
663 /// to test the parsing behavior when the input size exceeds 2GB or close to it.
664 /// </summary>
665 private class RepeatingMemoryStream: MemoryStream
666 {
667 private readonly byte[] bytes;
668 private readonly int maxIterations;
669 private int index = 0;
670
671 public RepeatingMemoryStream(byte[] bytes, int maxIterations)
672 {
673 this.bytes = bytes;
674 this.maxIterations = maxIterations;
675 }
676
677 public override int Read(byte[] buffer, int offset, int count)
678 {
679 if (bytes.Length == 0)
680 {
681 return 0;
682 }
683 int numBytesCopiedTotal = 0;
684 while (numBytesCopiedTotal < count && index < maxIterations)
685 {
686 int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count);
687 Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy);
688 numBytesCopiedTotal += numBytesToCopy;
689 offset += numBytesToCopy;
690 count -= numBytesCopiedTotal;
691 Position += numBytesToCopy;
692 if (Position >= bytes.Length)
693 {
694 Position = 0;
695 index++;
696 }
697 }
698 return numBytesCopiedTotal;
699 }
700 }
Brian Silverman9c614bc2016-02-15 20:20:02 -0500701 }
702}