-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
BinaryFormatterTests.cs
764 lines (662 loc) · 36.2 KB
/
BinaryFormatterTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public partial class BinaryFormatterTests : FileCleanupTestBase
{
// On 32-bit we can't test these high inputs as they cause OutOfMemoryExceptions.
[ConditionalTheory(typeof(Environment), nameof(Environment.Is64BitProcess))]
[SkipOnCoreClr("Long running tests: https://github.com/dotnet/runtime/issues/11191", ~RuntimeConfiguration.Release)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/35915", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoInterpreter))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/75281", typeof(PlatformDetection), nameof(PlatformDetection.IsPpc64leProcess))]
[InlineData(2 * 6_584_983 - 2)] // previous limit
[InlineData(2 * 7_199_369 - 2)] // last pre-computed prime number
public void SerializeHugeObjectGraphs(int limit)
{
Point[] pointArr = Enumerable.Range(0, limit)
.Select(i => new Point(i, i + 1))
.ToArray();
// This should not throw a SerializationException as we removed the artificial limit in the ObjectIDGenerator.
// Instead of round tripping we only serialize to minimize test time.
// This will throw on .NET Framework as the artificial limit is still enabled.
var bf = new BinaryFormatter();
AssertExtensions.ThrowsIf<SerializationException>(PlatformDetection.IsNetFramework, () =>
{
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, pointArr);
}
});
}
[Theory]
[SkipOnCoreClr("Takes too long on Checked", ~RuntimeConfiguration.Release)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34008", TestPlatforms.Linux, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34753", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[SkipOnPlatform(TestPlatforms.Browser, "Takes too long on Browser.")]
[MemberData(nameof(BasicObjectsRoundtrip_MemberData))]
public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
object clone = BinaryFormatterHelpers.Clone(obj, null, assemblyFormat, filterLevel, typeFormat);
// string.Empty and DBNull are both singletons
if (!ReferenceEquals(obj, string.Empty) && !(obj is DBNull))
{
Assert.NotSame(obj, clone);
}
EqualityExtensions.CheckEquals(obj, clone, isSamePlatform: true);
}
[Theory]
[SkipOnCoreClr("Takes too long on Checked", ~RuntimeConfiguration.Release)]
[ActiveIssue("https://github.com/mono/mono/issues/15115", TestRuntimes.Mono)]
[MemberData(nameof(SerializableObjects_MemberData))]
public void ValidateAgainstBlobs(object obj, TypeSerializableValue[] blobs)
=> ValidateAndRoundtrip(obj, blobs, false);
[Theory]
[SkipOnCoreClr("Takes too long on Checked", ~RuntimeConfiguration.Release)]
[MemberData(nameof(SerializableEqualityComparers_MemberData))]
public void ValidateEqualityComparersAgainstBlobs(object obj, TypeSerializableValue[] blobs)
=> ValidateAndRoundtrip(obj, blobs, true);
private static void ValidateAndRoundtrip(object obj, TypeSerializableValue[] blobs, bool isEqualityComparer)
{
if (obj == null)
{
throw new ArgumentNullException("The serializable object must not be null", nameof(obj));
}
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full));
}
// Check if the passed in value in a serialization entry is assignable by the passed in type.
if (obj is ISerializable customSerializableObj && HasObjectTypeIntegrity(customSerializableObj))
{
CheckObjectTypeIntegrity(customSerializableObj);
}
// TimeZoneInfo objects have three properties (DisplayName, StandardName, DaylightName)
// that are localized. Since the blobs were generated from the invariant culture, they
// will have English strings embedded. Thus, we can only test them against English
// language cultures or the invariant culture.
if (obj is TimeZoneInfo && (
CultureInfo.CurrentUICulture.TwoLetterISOLanguageName != "en" ||
CultureInfo.CurrentUICulture.Name.Length != 0))
{
return;
}
SanityCheckBlob(obj, blobs);
// ReflectionTypeLoadException and LicenseException aren't deserializable from Desktop --> Core.
// Therefore we remove the second blob which is the one from Desktop.
if (!PlatformDetection.IsNetFramework && (obj is ReflectionTypeLoadException || obj is LicenseException))
{
var tmpList = new List<TypeSerializableValue>(blobs);
tmpList.RemoveAt(1);
int index = tmpList.FindIndex(b => b.Platform.ToString().StartsWith("netfx"));
if (index >= 0)
tmpList.RemoveAt(index);
blobs = tmpList.ToArray();
}
// We store our framework blobs in index 1
int platformBlobIndex = blobs.GetPlatformIndex();
for (int i = 0; i < blobs.Length; i++)
{
// Check if the current blob is from the current running platform.
bool isSamePlatform = i == platformBlobIndex;
if (isEqualityComparer)
{
ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i].Base64Blob, FormatterAssemblyStyle.Simple));
ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i].Base64Blob, FormatterAssemblyStyle.Full));
}
else
{
EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i].Base64Blob, FormatterAssemblyStyle.Simple), isSamePlatform);
EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i].Base64Blob, FormatterAssemblyStyle.Full), isSamePlatform);
}
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void RegexExceptionSerializable()
{
try
{
#pragma warning disable RE0001 // Regex issue: {0}
new Regex("*"); // parsing "*" - Quantifier {x,y} following nothing.
#pragma warning restore RE0001 // Regex issue: {0}
}
catch (ArgumentException ex)
{
Assert.Equal("RegexParseException", ex.GetType().Name);
ArgumentException clone = BinaryFormatterHelpers.Clone(ex);
Assert.IsType<ArgumentException>(clone);
}
}
[Fact]
public void ArraySegmentDefaultCtor()
{
// This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object.
// When inner array is not initialized it throws an exception when this happens.
object obj = new ArraySegment<int>();
string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(corefxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true);
EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(netfxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true);
}
[Fact]
public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new SomeType() { SomeField = 7 };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NS4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1jYzdiMTNmZmNkMmRkZDUxBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw==";
var deserialized = (SomeType)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
[Fact]
public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NS4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1jYzdiMTNmZmNkMmRkZDUxBQEAAADuAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NS4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1jYzdiMTNmZmNkMmRkZDUxXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL";
var deserialized = (GenericTypeWithArg<SomeType>)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34008", TestPlatforms.Linux, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34753", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
[SkipOnPlatform(TestPlatforms.Browser, "Takes too long on Browser.")]
public void RoundtripManyObjectsInOneStream()
{
object[][] objects = SerializableObjects_MemberData().ToArray();
var s = new MemoryStream();
var f = new BinaryFormatter();
foreach (object[] obj in objects)
{
f.Serialize(s, obj[0]);
}
s.Position = 0;
foreach (object[] obj in objects)
{
object clone = f.Deserialize(s);
EqualityExtensions.CheckEquals(obj[0], clone, isSamePlatform: true);
}
}
[Fact]
public void SameObjectRepeatedInArray()
{
object o = new object();
object[] arr = new[] { o, o, o, o, o };
object[] result = BinaryFormatterHelpers.Clone(arr);
Assert.Equal(arr.Length, result.Length);
Assert.NotSame(arr, result);
Assert.NotSame(arr[0], result[0]);
for (int i = 1; i < result.Length; i++)
{
Assert.Same(result[0], result[i]);
}
}
[Theory]
[MemberData(nameof(NonSerializableTypes_MemberData))]
public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
var f = new BinaryFormatter()
{
AssemblyFormat = assemblyFormat,
FilterLevel = filterLevel,
TypeFormat = typeFormat
};
using (var s = new MemoryStream())
{
Assert.Throws<SerializationException>(() => f.Serialize(s, obj));
}
}
[Fact]
public void SerializeNonSerializableTypeWithSurrogate()
{
var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" };
Assert.False(p.GetType().IsSerializable);
Assert.Throws<SerializationException>(() => BinaryFormatterHelpers.Clone(p));
NonSerializablePair<int, string> result = BinaryFormatterHelpers.Clone(p, new NonSerializablePairSurrogate());
Assert.NotSame(p, result);
Assert.Equal(p.Value1, result.Value1);
Assert.Equal(p.Value2, result.Value2);
}
[Fact]
public void SerializationEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new IncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new DerivedIncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void Properties_Roundtrip()
{
var f = new BinaryFormatter();
Assert.Null(f.Binder);
var binder = new DelegateBinder();
f.Binder = binder;
Assert.Same(binder, f.Binder);
Assert.Null(f.Context.Context);
Assert.Equal(StreamingContextStates.All, f.Context.State);
var context = new StreamingContext(StreamingContextStates.Clone);
f.Context = context;
Assert.Equal(StreamingContextStates.Clone, f.Context.State);
Assert.Null(f.SurrogateSelector);
var selector = new SurrogateSelector();
f.SurrogateSelector = selector;
Assert.Same(selector, f.SurrogateSelector);
Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat);
f.AssemblyFormat = FormatterAssemblyStyle.Full;
Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat);
Assert.Equal(TypeFilterLevel.Full, f.FilterLevel);
f.FilterLevel = TypeFilterLevel.Low;
Assert.Equal(TypeFilterLevel.Low, f.FilterLevel);
Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat);
f.TypeFormat = FormatterTypeStyle.XsdString;
Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat);
}
[Fact]
public void SerializeDeserialize_InvalidArguments_ThrowsException()
{
var f = new BinaryFormatter();
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object()));
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple, false)]
[InlineData(FormatterAssemblyStyle.Full, true)]
public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) };
if (exceptionExpected)
{
Assert.Throws<SerializationException>(() => f.Deserialize(s));
}
else
{
var result = (Version2ClassWithoutOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Null(result.Value);
}
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple)]
[InlineData(FormatterAssemblyStyle.Full)]
public void OptionalField_Missing_Success(FormatterAssemblyStyle style)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) };
var result = (Version2ClassWithOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Null(result.Value);
}
[Fact]
public void ObjectReference_RealObjectSerialized()
{
var obj = new ObjRefReturnsObj { Real = 42 };
object real = BinaryFormatterHelpers.Clone<object>(obj);
Assert.Equal(42, real);
}
[OuterLoop]
[ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))]
[MemberData(nameof(FuzzInputs_MemberData))]
public void Deserialize_FuzzInput(object obj, Random rand)
{
// Get the serialized data for the object
byte[] data = BinaryFormatterHelpers.ToByteArray(obj, FormatterAssemblyStyle.Simple);
// Make some "random" changes to it
for (int i = 1; i < rand.Next(1, 100); i++)
{
data[rand.Next(data.Length)] = (byte)rand.Next(256);
}
// Try to deserialize that.
try
{
BinaryFormatterHelpers.FromByteArray(data, FormatterAssemblyStyle.Simple);
// Since there's no checksum, it's possible we changed data that didn't corrupt the instance
}
catch (ArgumentOutOfRangeException) { }
catch (ArrayTypeMismatchException) { }
catch (DecoderFallbackException) { }
catch (FormatException) { }
catch (IndexOutOfRangeException) { }
catch (InvalidCastException) { }
catch (OutOfMemoryException) { }
catch (OverflowException) { }
catch (NullReferenceException) { }
catch (SerializationException) { }
catch (TargetInvocationException) { }
catch (ArgumentException) { }
catch (FileLoadException) { }
}
[Fact]
public void Deserialize_EndOfStream_ThrowsException()
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, 1024);
for (long i = s.Length - 1; i >= 0; i--)
{
s.Position = 0;
byte[] data = new byte[i];
Assert.Equal(data.Length, s.Read(data, 0, data.Length));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data)));
}
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[MemberData(nameof(CrossProcessObjects_MemberData))]
public void Roundtrip_CrossProcess(object obj)
{
string outputPath = GetTestFilePath();
string inputPath = GetTestFilePath();
// Serialize out to a file
using (FileStream fs = File.OpenWrite(outputPath))
{
new BinaryFormatter().Serialize(fs, obj);
}
// In another process, deserialize from that file and serialize to another
RemoteExecutor.Invoke((remoteInput, remoteOutput) =>
{
Assert.False(File.Exists(remoteOutput));
using (FileStream input = File.OpenRead(remoteInput))
using (FileStream output = File.OpenWrite(remoteOutput))
{
var b = new BinaryFormatter();
b.Serialize(output, b.Deserialize(input));
}
}, outputPath, inputPath).Dispose();
// Deserialize what the other process serialized and compare it to the original
using (FileStream fs = File.OpenRead(inputPath))
{
object deserialized = new BinaryFormatter().Deserialize(fs);
Assert.Equal(obj, deserialized);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")]
public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound()
{
BinaryFormatterHelpers.Clone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 }));
}
private static void ValidateEqualityComparer(object obj)
{
Type objType = obj.GetType();
Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic.");
Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName);
Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]);
}
private static bool HasObjectTypeIntegrity(ISerializable serializable)
{
return !PlatformDetection.IsNetFramework ||
!(serializable is NotFiniteNumberException);
}
private static void CheckObjectTypeIntegrity(ISerializable serializable)
{
SerializationInfo testData = new SerializationInfo(serializable.GetType(), new FormatterConverter());
serializable.GetObjectData(testData, new StreamingContext(StreamingContextStates.Other));
foreach (SerializationEntry entry in testData)
{
if (entry.Value != null)
{
Assert.IsAssignableFrom(entry.ObjectType, entry.Value);
}
}
}
private static void SanityCheckBlob(object obj, TypeSerializableValue[] blobs)
{
// These types are unstable during serialization and produce different blobs.
string name = obj.GetType().FullName;
if (obj is WeakReference<Point> ||
obj is Collections.Specialized.HybridDictionary ||
obj is Color ||
name == "System.Collections.SortedList+SyncSortedList" ||
// Due to non-deterministic field ordering the types below will fail when using IL Emit-based Invoke.
// The types above may also be failing for the same reason.
// Remove these cases once https://github.com/dotnet/runtime/issues/46272 is fixed.
name == "System.Collections.Comparer" ||
name == "System.Collections.Hashtable" ||
name == "System.Collections.SortedList" ||
name == "System.Collections.Specialized.ListDictionary" ||
name == "System.CultureAwareComparer" ||
name == "System.Globalization.CompareInfo" ||
name == "System.Net.Cookie" ||
name == "System.Net.CookieCollection" ||
name == "System.Net.CookieContainer")
{
return;
}
// The blobs aren't identical because of different implementations on Unix vs. Windows.
if (obj is Bitmap ||
obj is Icon ||
obj is Metafile)
{
return;
}
// In most cases exceptions in Core have a different layout than in Desktop,
// therefore we are skipping the string comparison of the blobs.
if (obj is Exception)
{
return;
}
// Check if runtime generated blob is the same as the stored one
int frameworkBlobNumber = blobs.GetPlatformIndex();
if (frameworkBlobNumber < blobs.Length)
{
string runtimeBlob = BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full);
string storedComparableBlob = CreateComparableBlobInfo(blobs[frameworkBlobNumber].Base64Blob);
string runtimeComparableBlob = CreateComparableBlobInfo(runtimeBlob);
Assert.True(storedComparableBlob == runtimeComparableBlob,
$"The stored blob for type {obj.GetType().FullName} is outdated and needs to be updated.{Environment.NewLine}{Environment.NewLine}" +
$"-------------------- Stored blob ---------------------{Environment.NewLine}" +
$"Encoded: {blobs[frameworkBlobNumber].Base64Blob}{Environment.NewLine}" +
$"Decoded: {storedComparableBlob}{Environment.NewLine}{Environment.NewLine}" +
$"--------------- Runtime generated blob ---------------{Environment.NewLine}" +
$"Encoded: {runtimeBlob}{Environment.NewLine}" +
$"Decoded: {runtimeComparableBlob}");
}
}
private static string GetTestDataFilePath()
{
string GetRepoRootPath()
{
var exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
DirectoryInfo root = exeFile.Directory;
while (!Directory.Exists(Path.Combine(root.FullName, ".git")))
{
if (root.Parent == null)
return null;
root = root.Parent;
}
return root.FullName;
}
// Get path to binary formatter test data
string repositoryRootPath = GetRepoRootPath();
Assert.NotNull(repositoryRootPath);
string testDataFilePath = Path.Combine(repositoryRootPath, "src", "System.Runtime.Serialization.Formatters", "tests", "BinaryFormatterTestData.cs");
Assert.True(File.Exists(testDataFilePath));
return testDataFilePath;
}
private static string CreateComparableBlobInfo(string base64Blob)
{
string lineSeparator = ((char)0x2028).ToString();
string paragraphSeparator = ((char)0x2029).ToString();
byte[] data = Convert.FromBase64String(base64Blob);
base64Blob = Encoding.UTF8.GetString(data);
return Regex.Replace(base64Blob, @"Version=\d.\d.\d.\d.", "Version=0.0.0.0", RegexOptions.Multiline)
// Ignore the old Test key and Open public keys.
.Replace("PublicKeyToken=cc7b13ffcd2ddd51", "PublicKeyToken=null")
.Replace("PublicKeyToken=9d77cc7ad39b68eb", "PublicKeyToken=null")
.Replace("\r\n", string.Empty)
.Replace("\n", string.Empty)
.Replace("\r", string.Empty)
.Replace(lineSeparator, string.Empty)
.Replace(paragraphSeparator, string.Empty);
}
private static (int blobs, int foundBlobs, int updatedBlobs) UpdateCoreTypeBlobs(string testDataFilePath, string[] blobs)
{
// Replace existing test data blobs with updated ones
string[] testDataLines = File.ReadAllLines(testDataFilePath);
List<string> updatedTestDataLines = new List<string>();
int numberOfBlobs = 0;
int numberOfFoundBlobs = 0;
int numberOfUpdatedBlobs = 0;
for (int i = 0; i < testDataLines.Length; i++)
{
string testDataLine = testDataLines[i];
if (!testDataLine.Trim().StartsWith("yield") || numberOfBlobs >= blobs.Length)
{
updatedTestDataLines.Add(testDataLine);
continue;
}
string pattern = null;
string replacement = null;
if (PlatformDetection.IsNetFramework)
{
pattern = ", \"AAEAAAD[^\"]+\"(?!,)";
replacement = ", \"" + blobs[numberOfBlobs] + "\"";
}
else
{
pattern = "\"AAEAAAD[^\"]+\",";
replacement = "\"" + blobs[numberOfBlobs] + "\",";
}
Regex regex = new Regex(pattern);
if (regex.IsMatch(testDataLine))
{
numberOfFoundBlobs++;
}
string updatedLine = regex.Replace(testDataLine, replacement);
if (testDataLine != updatedLine)
{
numberOfUpdatedBlobs++;
}
testDataLine = updatedLine;
updatedTestDataLines.Add(testDataLine);
numberOfBlobs++;
}
// Check if all blobs were recognized and write updates to file
Assert.Equal(numberOfBlobs, blobs.Length);
File.WriteAllLines(testDataFilePath, updatedTestDataLines);
return (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs);
}
private class DelegateBinder : SerializationBinder
{
public Func<string, string, Type> BindToTypeDelegate = null;
public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName);
}
public struct MyStruct
{
public int A;
}
public static IEnumerable<object[]> NullableComparersTestData()
{
yield return new object[] { "NullableEqualityComparer`1", EqualityComparer<byte?>.Default };
yield return new object[] { "NullableEqualityComparer`1", EqualityComparer<int?>.Default };
yield return new object[] { "NullableEqualityComparer`1", EqualityComparer<float?>.Default };
yield return new object[] { "NullableEqualityComparer`1", EqualityComparer<Guid?>.Default }; // implements IEquatable<>
yield return new object[] { "ObjectEqualityComparer`1", EqualityComparer<MyStruct?>.Default }; // doesn't implement IEquatable<>
yield return new object[] { "ObjectEqualityComparer`1", EqualityComparer<DayOfWeek?>.Default };
yield return new object[] { "NullableComparer`1", Comparer<byte?>.Default };
yield return new object[] { "NullableComparer`1", Comparer<int?>.Default };
yield return new object[] { "NullableComparer`1", Comparer<float?>.Default };
yield return new object[] { "NullableComparer`1", Comparer<Guid?>.Default };
yield return new object[] { "ObjectComparer`1", Comparer<MyStruct?>.Default };
yield return new object[] { "ObjectComparer`1", Comparer<DayOfWeek?>.Default };
}
[Theory]
[MemberData(nameof(NullableComparersTestData))]
public void NullableComparersRoundtrip(string expectedType, object obj)
{
string serialized = BinaryFormatterHelpers.ToBase64String(obj);
Assert.Equal(expectedType, BinaryFormatterHelpers.FromBase64String(serialized).GetType().Name);
}
}
}