/
ObjectManager.cs
1634 lines (1421 loc) · 67.9 KB
/
ObjectManager.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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace System.Runtime.Serialization
{
[Obsolete(Obsoletions.LegacyFormatterMessage, DiagnosticId = Obsoletions.LegacyFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
public class ObjectManager
{
private const int DefaultInitialSize = 16;
private const int MaxArraySize = 0x100000; //MUST BE A POWER OF 2!
private const int ArrayMask = MaxArraySize - 1;
private const int MaxReferenceDepth = 100;
private const string ObjectManagerUnreferencedCodeMessage = "ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.";
private static readonly FieldInfo s_nullableValueField = typeof(Nullable<>).GetField("value", BindingFlags.NonPublic | BindingFlags.Instance)!;
private DeserializationEventHandler? _onDeserializationHandler;
private SerializationEventHandler? _onDeserializedHandler;
internal ObjectHolder[] _objects;
internal object? _topObject;
internal ObjectHolderList? _specialFixupObjects; //This is IObjectReference, ISerializable, or has a Surrogate.
internal long _fixupCount;
internal readonly ISurrogateSelector? _selector;
internal readonly StreamingContext _context;
public ObjectManager(ISurrogateSelector? selector, StreamingContext context)
{
_objects = new ObjectHolder[DefaultInitialSize];
_selector = selector;
_context = context;
}
private bool CanCallGetType(object? obj) => true;
internal object? TopObject
{
get { return _topObject; }
set { _topObject = value; }
}
internal ObjectHolderList SpecialFixupObjects =>
_specialFixupObjects ??= new ObjectHolderList();
internal ObjectHolder? FindObjectHolder(long objectID)
{
// The index of the bin in which we live is rightmost n bits of the objectID.
int index = (int)(objectID & ArrayMask);
if (index >= _objects.Length)
{
return null;
}
// Find the bin in which we live.
ObjectHolder? temp = _objects[index];
// Walk the chain in that bin. Return the ObjectHolder if we find it, otherwise
// return null.
while (temp != null)
{
if (temp._id == objectID)
{
return temp;
}
temp = temp._next;
}
return temp;
}
internal ObjectHolder FindOrCreateObjectHolder(long objectID)
{
ObjectHolder? holder = FindObjectHolder(objectID);
if (holder == null)
{
holder = new ObjectHolder(objectID);
AddObjectHolder(holder);
}
return holder;
}
private void AddObjectHolder(ObjectHolder holder)
{
Debug.Assert(holder != null, "holder!=null");
Debug.Assert(holder._id >= 0, "holder.m_id>=0");
//If the id that we need to place is greater than our current length, and less
//than the maximum allowable size of the array. We need to double the size
//of the array. If the array has already reached it's maximum allowable size,
//we chain elements off of the buckets.
if (holder._id >= _objects.Length && _objects.Length != MaxArraySize)
{
int newSize = MaxArraySize;
if (holder._id < (MaxArraySize / 2))
{
newSize = (_objects.Length * 2);
//Keep doubling until we're larger than our target size.
//We could also do this with log operations, but that would
//be slower than the brute force approach.
while (newSize <= holder._id && newSize < MaxArraySize)
{
newSize *= 2;
}
if (newSize > MaxArraySize)
{
newSize = MaxArraySize;
}
}
ObjectHolder[] temp = new ObjectHolder[newSize];
Array.Copy(_objects, temp, _objects.Length);
_objects = temp;
}
//Find the bin in which we live and make this new element the first element in the bin.
int index = (int)(holder._id & ArrayMask);
ObjectHolder tempHolder = _objects[index];
holder._next = tempHolder;
_objects[index] = holder;
}
private bool GetCompletionInfo(FixupHolder fixup, [NotNullWhen(true)] out ObjectHolder? holder, out object member, bool bThrowIfMissing)
{
//Set the member id (String or MemberInfo) for the member being fixed up.
member = fixup._fixupInfo;
//Find the object required for the fixup. Throw if we can't find it.
holder = FindObjectHolder(fixup._id);
if (holder == null || holder.CanObjectValueChange || holder.ObjectValue == null)
{
if (bThrowIfMissing)
{
if (holder == null)
{
throw new SerializationException(SR.Format(SR.Serialization_NeverSeen, fixup._id));
}
if (holder.IsIncompleteObjectReference)
{
throw new SerializationException(SR.Format(SR.Serialization_IORIncomplete, fixup._id));
}
throw new SerializationException(SR.Format(SR.Serialization_ObjectNotSupplied, fixup._id));
}
return false;
}
// CompletelyFixed is our poorly named property which indicates if something requires a SerializationInfo fixup
// or is an incomplete object reference. We have this particular branch to handle valuetypes which implement
// ISerializable. In that case, we can't do any fixups on them later, so we need to delay the fixups further.
if (!holder.CompletelyFixed)
{
if (holder.ObjectValue != null && holder.ObjectValue is ValueType)
{
SpecialFixupObjects.Add(holder);
return false;
}
}
return true;
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
private void FixupSpecialObject(ObjectHolder holder)
{
ISurrogateSelector? uselessSelector = null;
Debug.Assert(holder.RequiresSerInfoFixup, "[ObjectManager.FixupSpecialObject]holder.HasSurrogate||holder.HasISerializable");
if (holder.HasSurrogate)
{
ISerializationSurrogate? surrogate = holder.Surrogate;
Debug.Assert(surrogate != null, "surrogate!=null");
Debug.Assert(holder.SerializationInfo != null);
object? returnValue = surrogate.SetObjectData(holder.ObjectValue!, holder.SerializationInfo, _context, uselessSelector);
if (returnValue != null)
{
if (!holder.CanSurrogatedObjectValueChange && returnValue != holder.ObjectValue)
{
throw new SerializationException(SR.Format(SR.Serialization_NotCyclicallyReferenceableSurrogate, surrogate.GetType().FullName));
}
holder.SetObjectValue(returnValue, this);
}
holder._surrogate = null;
holder.SetFlags();
}
else
{
//Set the object data
Debug.Assert(holder.ObjectValue is ISerializable, "holder.m_object is ISerializable");
CompleteISerializableObject(holder.ObjectValue, holder.SerializationInfo, _context);
}
//Clear anything that we know that we're not going to need.
holder.SerializationInfo = null;
holder.RequiresSerInfoFixup = false;
// For value types, fixups would have been done. So the newly fixed object must be copied
// to its container.
if (holder.RequiresValueTypeFixup && holder.ValueTypeFixupPerformed)
{
DoValueTypeFixup(null, holder, holder.ObjectValue);
}
DoNewlyRegisteredObjectFixups(holder);
}
/// <summary>
/// Unfortunately, an ObjectReference could actually be a reference to another
/// object reference and we don't know how far we have to tunnel until we can find the real object. While
/// we're still getting instances of IObjectReference back and we're still getting new objects, keep calling
/// GetRealObject. Once we've got the new object, take care of all of the fixups
/// that we can do now that we've got it.
/// </summary>
/// <param name="holder"></param>
private bool ResolveObjectReference(ObjectHolder holder)
{
object? tempObject;
Debug.Assert(holder.IsIncompleteObjectReference, "holder.IsIncompleteObjectReference");
//In the pathological case, an Object implementing IObjectReference could return a reference
//to a different object which implements IObjectReference. This makes us vulnerable to a
//denial of service attack and stack overflow. If the depthCount becomes greater than
//MaxReferenceDepth, we'll throw a SerializationException.
int depthCount = 0;
//We wrap this in a try/catch block to handle the case where we're trying to resolve a chained
//list of object reference (e.g. an IObjectReference can't resolve itself without some information
//that's currently missing from the graph). We'll catch the NullReferenceException and come back
//and try again later. The downside of this scheme is that if the object actually needed to throw
//a NullReferenceException, it's being caught and turned into a SerializationException with a
//fairly cryptic message.
try
{
do
{
tempObject = holder.ObjectValue;
Debug.Assert(holder.ObjectValue != null);
holder.SetObjectValue(((IObjectReference)(holder.ObjectValue)).GetRealObject(_context), this);
//The object didn't yet have enough information to resolve the reference, so we'll
//return false and the graph walker should call us back again after more objects have
//been resolved.
if (holder.ObjectValue == null)
{
holder.SetObjectValue(tempObject, this);
return false;
}
if (depthCount++ == MaxReferenceDepth)
{
throw new SerializationException(SR.Serialization_TooManyReferences);
}
} while ((holder.ObjectValue is IObjectReference) && (tempObject != holder.ObjectValue));
}
catch (NullReferenceException)
{
return false;
}
holder.IsIncompleteObjectReference = false;
DoNewlyRegisteredObjectFixups(holder);
return true;
}
/*===============================DoValueTypeFixup===============================
**Arguments:
** memberToFix -- the member in the object contained in holder being fixed up.
** holder -- the ObjectHolder for the object (a value type in this case) being completed.
** value -- the data to set into the field.
==============================================================================*/
private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, object? value)
{
var fieldsTemp = new FieldInfo[4];
FieldInfo[] fields;
int currentFieldIndex = 0;
int[]? arrayIndex = null;
ValueTypeFixupInfo currFixup;
object? fixupObj = holder.ObjectValue;
Debug.Assert(holder != null, "[TypedReferenceBuilder.ctor]holder!=null");
Debug.Assert(holder.RequiresValueTypeFixup, "[TypedReferenceBuilder.ctor]holder.RequiresValueTypeFixup");
//In order to get a TypedReference, we need to get a list of all of the FieldInfos to
//create the path from our outermost containing object down to the actual field which
//we'd like to set. This loop is used to build up that list.
while (holder.RequiresValueTypeFixup)
{
//Enlarge the array if required (this is actually fairly unlikely as it would require that we
//be nested more than 4 deep.
if ((currentFieldIndex + 1) >= fieldsTemp.Length)
{
var temp = new FieldInfo[fieldsTemp.Length * 2];
Array.Copy(fieldsTemp, temp, fieldsTemp.Length);
fieldsTemp = temp;
}
//Get the fixup information. If we have data for our parent field, add it to our list
//and continue the walk up to find the next outermost containing object. We cache the
//object that we have. In most cases, we could have just grabbed it after this loop finished.
//However, if the outermost containing object is an array, we need the object one further
//down the chain, so we have to do a lot of caching.
currFixup = holder.ValueFixup!;
fixupObj = holder.ObjectValue; //Save the most derived
if (currFixup.ParentField != null)
{
FieldInfo parentField = currFixup.ParentField;
ObjectHolder? tempHolder = FindObjectHolder(currFixup.ContainerID);
Debug.Assert(tempHolder != null);
if (tempHolder.ObjectValue == null)
{
break;
}
FieldInfo? nullableValueField = GetNullableValueField(parentField.FieldType);
if (nullableValueField != null)
{
fieldsTemp[currentFieldIndex] = nullableValueField;
currentFieldIndex++;
}
fieldsTemp[currentFieldIndex] = parentField;
holder = tempHolder;
currentFieldIndex++;
}
else
{
//If we find an index into an array, save that information.
Debug.Assert(currFixup.ParentIndex != null, "[ObjectManager.DoValueTypeFixup]currFixup.ParentIndex!=null");
holder = FindObjectHolder(currFixup.ContainerID)!; //find the array to fix.
arrayIndex = currFixup.ParentIndex;
break;
}
}
//If the outermost container isn't an array, we need to grab it. Otherwise, we just need to hang onto
//the boxed object that we already grabbed. We'll assign the boxed object back into the array as the
//last step.
if (!(holder.ObjectValue is Array) && holder.ObjectValue != null)
{
fixupObj = holder.ObjectValue;
Debug.Assert(fixupObj != null, "[ObjectManager.DoValueTypeFixup]FixupObj!=null");
}
if (currentFieldIndex != 0)
{
//MakeTypedReference requires an array of exactly the correct size that goes from the outermost object
//in to the innermost field. We currently have an array of arbitrary size that goes from the innermost
//object outwards. We create an array of the right size and do the copy.
fields = new FieldInfo[currentFieldIndex];
for (int i = 0; i < currentFieldIndex; i++)
{
FieldInfo? fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)];
SerializationFieldInfo? serInfo = fieldInfo as SerializationFieldInfo;
fields[i] = serInfo == null ? fieldInfo : serInfo.FieldInfo;
}
Debug.Assert(fixupObj != null, "[ObjectManager.DoValueTypeFixup]fixupObj!=null");
//Make the TypedReference and use it to set the value.
TypedReference typedRef = TypedReference.MakeTypedReference(fixupObj, fields);
if (memberToFix != null)
{
memberToFix.SetValueDirect(typedRef, value!);
}
else
{
TypedReference.SetTypedReference(typedRef, value);
}
}
else if (memberToFix != null)
{
FormatterServices.SerializationSetValue(memberToFix, fixupObj, value);
}
//If we have an array index, it means that our outermost container was an array. We don't have
//any way to build a TypedReference into an array, so we'll use the array functions to set the value.
if (arrayIndex != null && holder.ObjectValue != null)
{
((Array)(holder.ObjectValue)).SetValue(fixupObj, arrayIndex);
}
return true;
}
private static FieldInfo? GetNullableValueField(Type type)
{
if (Nullable.GetUnderlyingType(type) != null)
{
return (FieldInfo)type.GetMemberWithSameMetadataDefinitionAs(s_nullableValueField);
}
return null;
}
internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete)
{
FixupHolderList? fixups = holder._missingElements;
FixupHolder? currentFixup;
SerializationInfo? si;
object? fixupInfo;
ObjectHolder? tempObjectHolder;
int fixupsPerformed = 0;
Debug.Assert(holder != null, "[ObjectManager.CompleteObject]holder.m_object!=null");
if (holder.ObjectValue == null)
{
throw new SerializationException(SR.Format(SR.Serialization_MissingObject, holder._id));
}
if (fixups == null)
{
return;
}
//If either one of these conditions is true, we need to update the data in the
//SerializationInfo before calling SetObjectData.
if (holder.HasSurrogate || holder.HasISerializable)
{
si = holder._serInfo;
if (si == null)
{
throw new SerializationException(SR.Serialization_InvalidFixupDiscovered);
}
//Walk each of the fixups and complete the name-value pair in the SerializationInfo.
if (fixups != null)
{
for (int i = 0; i < fixups._count; i++)
{
if (fixups._values[i] == null)
{
continue;
}
Debug.Assert(fixups._values[i]!._fixupType == FixupHolder.DelayedFixup, "fixups.m_values[i].m_fixupType==FixupHolder.DelayedFixup");
if (GetCompletionInfo(fixups._values[i]!, out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
{
//Walk the SerializationInfo and find the member needing completion. All we have to do
//at this point is set the member into the Object
object? holderValue = tempObjectHolder.ObjectValue;
Debug.Assert(holderValue != null);
if (CanCallGetType(holderValue))
{
si.UpdateValue((string)fixupInfo, holderValue, holderValue.GetType());
}
else
{
si.UpdateValue((string)fixupInfo, holderValue, typeof(MarshalByRefObject));
}
//Decrement our total number of fixups left to do.
fixupsPerformed++;
fixups._values[i] = null;
if (!bObjectFullyComplete)
{
holder.DecrementFixupsRemaining(this);
tempObjectHolder.RemoveDependency(holder._id);
}
}
}
}
}
else
{
for (int i = 0; i < fixups._count; i++)
{
currentFixup = fixups._values[i];
if (currentFixup == null)
{
continue;
}
if (GetCompletionInfo(currentFixup, out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
{
// Check to make sure we are not both reachable from the topObject
// and there was a typeloadexception
if (tempObjectHolder.TypeLoadExceptionReachable)
{
holder.TypeLoadException = tempObjectHolder.TypeLoadException;
// If the holder is both reachable and typeloadexceptionreachable
// throw an exception with the type name
if (holder.Reachable)
{
throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, holder.TypeLoadException!.TypeName));
}
}
// If the current holder is reachable, mark the dependant reachable as well
if (holder.Reachable)
{
tempObjectHolder.Reachable = true;
}
//There are two types of fixups that we could be doing: array or member.
//Delayed Fixups should be handled by the above branch.
switch (currentFixup._fixupType)
{
case FixupHolder.ArrayFixup:
Debug.Assert(holder.ObjectValue is Array, "holder.ObjectValue is Array");
if (holder.RequiresValueTypeFixup)
{
throw new SerializationException(SR.Serialization_ValueTypeFixup);
}
else
{
((Array)(holder.ObjectValue)).SetValue(tempObjectHolder.ObjectValue, ((int[])fixupInfo));
}
break;
case FixupHolder.MemberFixup:
Debug.Assert(fixupInfo is MemberInfo, "fixupInfo is MemberInfo");
//Fixup the member directly.
MemberInfo tempMember = (MemberInfo)fixupInfo;
if (tempMember is FieldInfo)
{
// If we have a valuetype that's been boxed to an object and requires a fixup,
// there are two possible states:
// (a)The valuetype has never been fixed up into it's container. In this case, we should
// just fix up the boxed valuetype. The task of pushing that valuetype into it's container
// will be handled later. This case is handled by the else clause of the following statement.
// (b)The valuetype has already been inserted into it's container. In that case, we need
// to go through the more complicated path laid out in DoValueTypeFixup. We can tell that the
// valuetype has already been inserted into it's container because we set ValueTypeFixupPerformed
// to true when we do this.
if (holder.RequiresValueTypeFixup && holder.ValueTypeFixupPerformed)
{
if (!DoValueTypeFixup((FieldInfo)tempMember, holder, tempObjectHolder.ObjectValue))
{
throw new SerializationException(SR.Serialization_PartialValueTypeFixup);
}
}
else
{
FormatterServices.SerializationSetValue(tempMember, holder.ObjectValue, tempObjectHolder.ObjectValue);
}
if (tempObjectHolder.RequiresValueTypeFixup)
{
tempObjectHolder.ValueTypeFixupPerformed = true;
}
}
else
{
throw new SerializationException(SR.Serialization_UnableToFixup);
}
break;
default:
throw new SerializationException(SR.Serialization_UnableToFixup);
}
//Decrement our total number of fixups left to do.
fixupsPerformed++;
fixups._values[i] = null;
if (!bObjectFullyComplete)
{
holder.DecrementFixupsRemaining(this);
tempObjectHolder.RemoveDependency(holder._id);
}
}
}
}
_fixupCount -= fixupsPerformed;
if (fixups!._count == fixupsPerformed)
{
holder._missingElements = null;
}
}
/// <summary>
/// This is called immediately after we register a new object. Walk that objects
/// dependency list (if it has one) and decrement the counters on each object for
/// the number of unsatisfiable references. If the count reaches 0, go ahead
/// and process the object.
/// </summary>
/// <param name="holder">dependencies The list of dependent objects</param>
private void DoNewlyRegisteredObjectFixups(ObjectHolder holder)
{
if (holder.CanObjectValueChange)
{
return;
}
//If we don't have any dependencies, we're done.
LongList? dependencies = holder.DependentObjects;
if (dependencies == null)
{
return;
}
//Walk all of the dependencies and decrement the counter on each of uncompleted objects.
//If one of the counters reaches 0, all of it's fields have been completed and we should
//go take care of its fixups.
dependencies.StartEnumeration();
while (dependencies.MoveNext())
{
ObjectHolder? temp = FindObjectHolder(dependencies.Current);
Debug.Assert(temp != null);
Debug.Assert(temp.DirectlyDependentObjects > 0, "temp.m_missingElementsRemaining>0");
temp.DecrementFixupsRemaining(this);
if (((temp.DirectlyDependentObjects)) == 0)
{
// If this is null, we have the case where a fixup was registered for a child, the object
// required by the fixup was provided, and the object to be fixed hasn't yet been seen.
if (temp.ObjectValue != null)
{
CompleteObject(temp, true);
}
else
{
temp.MarkForCompletionWhenAvailable();
}
}
}
}
public virtual object? GetObject(long objectID)
{
if (objectID <= 0)
{
throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID);
}
//Find the bin in which we're interested. IObjectReference's shouldn't be returned -- the graph
//needs to link to the objects to which they refer, not to the references themselves.
ObjectHolder? holder = FindObjectHolder(objectID);
if (holder == null || holder.CanObjectValueChange)
{
return null;
}
return holder.ObjectValue;
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
public virtual void RegisterObject(object obj, long objectID)
{
RegisterObject(obj, objectID, null, 0, null);
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
public void RegisterObject(object obj, long objectID, SerializationInfo info)
{
RegisterObject(obj, objectID, info, 0, null);
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
{
RegisterObject(obj, objectID, info, idOfContainingObj, member, null);
}
internal void RegisterString(string? obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
{
ObjectHolder temp;
Debug.Assert(member == null || member is FieldInfo, "RegisterString - member is FieldInfo");
temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo?)member, null);
AddObjectHolder(temp);
return;
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex)
{
ArgumentNullException.ThrowIfNull(obj);
if (objectID <= 0)
{
throw new ArgumentOutOfRangeException(nameof(objectID), SR.ArgumentOutOfRange_ObjectID);
}
if (member != null && !(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib
{
throw new SerializationException(SR.Serialization_UnknownMemberInfo);
}
ObjectHolder? temp;
ISerializationSurrogate? surrogate = null;
ISurrogateSelector useless;
if (_selector != null)
{
Type selectorType = CanCallGetType(obj) ?
obj.GetType() :
typeof(MarshalByRefObject);
//If we need a surrogate for this object, lets find it now.
surrogate = _selector.GetSurrogate(selectorType, _context, out useless);
}
//The object is interested in DeserializationEvents so lets register it.
if (obj is IDeserializationCallback)
{
DeserializationEventHandler d = new DeserializationEventHandler(((IDeserializationCallback)obj).OnDeserialization);
AddOnDeserialization(d);
}
//Formatter developers may cache and reuse arrayIndex in their code.
//So that we don't get bitten by this, take a copy up front.
if (arrayIndex != null)
{
arrayIndex = (int[])arrayIndex.Clone();
}
//This is the first time which we've seen the object, we need to create a new holder.
temp = FindObjectHolder(objectID);
if (temp == null)
{
temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex);
AddObjectHolder(temp);
if (temp.RequiresDelayedFixup)
{
SpecialFixupObjects.Add(temp);
}
// We cannot compute whether this has any fixups required or not
AddOnDeserialized(obj);
return;
}
//If the object isn't null, we've registered this before. Not good.
if (temp.ObjectValue != null)
{
throw new SerializationException(SR.Serialization_RegisterTwice);
}
//Complete the data in the ObjectHolder
temp.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex, this);
// The following case will only be true when somebody has registered a fixup on an object before
// registering the object itself. I don't believe that most well-behaved formatters will do this,
// but we need to allow it anyway. We will walk the list of fixups which have been recorded on
// the new object and fix those that we can. Because the user could still register later fixups
// on this object, we won't call any implementations of ISerializable now. If that's required,
// it will have to be handled by the code in DoFixups.
// README README: We have to do the UpdateData before
if (temp.DirectlyDependentObjects > 0)
{
CompleteObject(temp, false);
}
if (temp.RequiresDelayedFixup)
{
SpecialFixupObjects.Add(temp);
}
if (temp.CompletelyFixed)
{
//Here's where things get tricky. If this isn't an instance of IObjectReference, we need to walk it's fixup
//chain and decrement the counters on anything that has reached 0. Once we've notified all of the dependencies,
//we can simply clear the list of dependent objects.
DoNewlyRegisteredObjectFixups(temp);
temp.DependentObjects = null;
}
//Register the OnDeserialized methods to be invoked after deserialization is complete
if (temp.TotalDependentObjects > 0)
{
AddOnDeserialized(obj);
}
else
{
RaiseOnDeserializedEvent(obj);
}
}
/// <summary>
/// Completes an object implementing ISerializable. This will involve calling that
/// objects constructor which takes an instance of ISerializable and a StreamingContext.
/// </summary>
/// <param name="obj">The object to be completed.</param>
/// <param name="info">The SerializationInfo containing all info for obj.</param>
/// <param name="context">The streaming context in which the serialization is taking place.</param>
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
internal void CompleteISerializableObject(object obj, SerializationInfo? info, StreamingContext context)
{
ArgumentNullException.ThrowIfNull(obj);
if (!(obj is ISerializable))
{
throw new ArgumentException(SR.Serialization_NotISer);
}
ConstructorInfo constInfo;
Type t = obj.GetType();
try
{
constInfo = GetDeserializationConstructor(t);
}
catch (Exception e)
{
throw new SerializationException(SR.Format(SR.Serialization_ConstructorNotFound, t), e);
}
constInfo.Invoke(obj, new object?[] { info, context });
}
internal static ConstructorInfo GetDeserializationConstructor(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t)
{
foreach (ConstructorInfo ci in t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
ParameterInfo[] parameters = ci.GetParameters();
if (parameters.Length == 2 &&
parameters[0].ParameterType == typeof(SerializationInfo) &&
parameters[1].ParameterType == typeof(StreamingContext))
{
return ci;
}
}
throw new SerializationException(SR.Format(SR.Serialization_ConstructorNotFound, t.FullName));
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
public virtual void DoFixups()
{
ObjectHolder? temp;
int fixupCount = -1;
//The first thing that we need to do is fixup all of the objects which implement
//IObjectReference. This is complicated by the fact that we need to deal with IReferenceObjects
//objects that have a reference to an object implementing IObjectReference. We continually
//walk over the list of objects until we've completed all of the object references or until
//we can't resolve any more (which may happen if we have two objects implementing IObjectReference
//which have a circular dependency on each other). We don't explicitly catch the later case here,
//it will be caught when we try to do the rest of the fixups and discover that we have some that
//can't be completed.
while (fixupCount != 0)
{
fixupCount = 0;
//Walk all of the IObjectReferences and ensure that they've been properly completed.
ObjectHolderListEnumerator fixupObjectsEnum = SpecialFixupObjects.GetFixupEnumerator();
while (fixupObjectsEnum.MoveNext())
{
temp = fixupObjectsEnum.Current;
if (temp.ObjectValue == null)
{
throw new SerializationException(SR.Format(SR.Serialization_ObjectNotSupplied, temp._id));
}
if (temp.TotalDependentObjects == 0)
{
if (temp.RequiresSerInfoFixup)
{
FixupSpecialObject(temp);
fixupCount++;
}
else if (!temp.IsIncompleteObjectReference)
{
CompleteObject(temp, true);
}
if (temp.IsIncompleteObjectReference && ResolveObjectReference(temp))
{
fixupCount++;
}
}
}
}
Debug.Assert(_fixupCount >= 0, "[ObjectManager.DoFixups]m_fixupCount>=0");
//If our count is 0, we're done and should just return
if (_fixupCount == 0)
{
if (TopObject is TypeLoadExceptionHolder)
{
throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, ((TypeLoadExceptionHolder)TopObject).TypeName));
}
return;
}
//If our count isn't 0, we had at least one case where an object referenced another object twice.
//Walk the entire list until the count is 0 or until we find an object which we can't complete.
for (int i = 0; i < _objects.Length; i++)
{
temp = _objects[i];
while (temp != null)
{
if (temp.TotalDependentObjects > 0 /*|| temp.m_missingElements!=null*/)
{
CompleteObject(temp, true);
}
temp = temp._next;
}
if (_fixupCount == 0)
{
return;
}
}
// this assert can be trigered by user code that manages fixups manually
throw new SerializationException(SR.Serialization_IncorrectNumberOfFixups);
}
/// <summary>
/// Do the actual grunt work of recording a fixup and registering the dependency.
/// Create the necessary ObjectHolders and use them to do the addition.
/// </summary>
/// <param name="fixup">The FixupHolder to be added.</param>
/// <param name="objectRequired">The id of the object required to do the fixup.</param>
/// <param name="objectToBeFixed">The id of the object requiring the fixup.</param>
private void RegisterFixup(FixupHolder fixup, long objectToBeFixed, long objectRequired)
{
//Record the fixup with the object that needs it.
ObjectHolder ohToBeFixed = FindOrCreateObjectHolder(objectToBeFixed);
ObjectHolder ohRequired;
if (ohToBeFixed.RequiresSerInfoFixup && fixup._fixupType == FixupHolder.MemberFixup)
{
throw new SerializationException(SR.Serialization_InvalidFixupType);
}
//Add the fixup to the list.
ohToBeFixed.AddFixup(fixup, this);
//Find the object on which we're dependent and note the dependency.
//These dependencies will be processed when the object is supplied.
ohRequired = FindOrCreateObjectHolder(objectRequired);
ohRequired.AddDependency(objectToBeFixed);
_fixupCount++;
}
public virtual void RecordFixup(long objectToBeFixed, MemberInfo member, long objectRequired)
{
//Verify our arguments
if (objectToBeFixed <= 0 || objectRequired <= 0)
{
throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall);
}
ArgumentNullException.ThrowIfNull(member);
if (!(member is FieldInfo)) // .NET Framework checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib
{
throw new SerializationException(SR.Format(SR.Serialization_InvalidType, member.GetType()));
}
//Create a new fixup holder
FixupHolder fixup = new FixupHolder(objectRequired, member, FixupHolder.MemberFixup);
RegisterFixup(fixup, objectToBeFixed, objectRequired);
}
public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, long objectRequired)
{
//Verify our arguments
if (objectToBeFixed <= 0 || objectRequired <= 0)
{
throw new ArgumentOutOfRangeException(objectToBeFixed <= 0 ? nameof(objectToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall);
}
ArgumentNullException.ThrowIfNull(memberName);
//Create a new fixup holder
FixupHolder fixup = new FixupHolder(objectRequired, memberName, FixupHolder.DelayedFixup);
RegisterFixup(fixup, objectToBeFixed, objectRequired);
}
public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired)
{
int[] indexArray = new int[1];
indexArray[0] = index;
RecordArrayElementFixup(arrayToBeFixed, indexArray, objectRequired);
}
public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, long objectRequired)
{
//Verify our arguments
if (arrayToBeFixed <= 0 || objectRequired <= 0)
{
throw new ArgumentOutOfRangeException(arrayToBeFixed <= 0 ? nameof(arrayToBeFixed) : nameof(objectRequired), SR.Serialization_IdTooSmall);
}
ArgumentNullException.ThrowIfNull(indices);
FixupHolder fixup = new FixupHolder(objectRequired, indices, FixupHolder.ArrayFixup);
RegisterFixup(fixup, arrayToBeFixed, objectRequired);
}
public virtual void RaiseDeserializationEvent()
{
// Invoke OnDerserialized event if applicable
_onDeserializedHandler?.Invoke(_context);
_onDeserializationHandler?.Invoke(null);
}
internal virtual void AddOnDeserialization(DeserializationEventHandler handler)
{
_onDeserializationHandler = (DeserializationEventHandler)Delegate.Combine(_onDeserializationHandler, handler);
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
internal virtual void AddOnDeserialized(object obj)
{
SerializationEvents cache = SerializationEventsCache.GetSerializationEventsForType(obj.GetType());
_onDeserializedHandler = cache.AddOnDeserialized(obj, _onDeserializedHandler);
}
[RequiresUnreferencedCode(ObjectManagerUnreferencedCodeMessage)]
internal virtual void RaiseOnDeserializedEvent(object obj)
{
SerializationEvents cache = SerializationEventsCache.GetSerializationEventsForType(obj.GetType());
cache.InvokeOnDeserialized(obj, _context);
}