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