File: ObjectReader.cs

package info (click to toggle)
mono 2.6.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 327,344 kB
  • ctags: 413,649
  • sloc: cs: 2,471,883; xml: 1,768,594; ansic: 350,665; sh: 13,644; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (951 lines) | stat: -rw-r--r-- 27,538 bytes parent folder | download | duplicates (2)
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
// ObjectReader.cs
//
// Author:
//   Lluis Sanchez Gual (lluis@ideary.com)
//   Patrik Torstensson
//
// (C) 2003 Lluis Sanchez Gual

//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Runtime.Serialization;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Globalization;

namespace System.Runtime.Serialization.Formatters.Binary
{
	internal class ObjectReader
	{
//		BinaryFormatter _formatter;
		ISurrogateSelector _surrogateSelector;
		StreamingContext _context;
		SerializationBinder _binder;
		
#if NET_1_1
		TypeFilterLevel _filterLevel;
#endif

		ObjectManager _manager;
		Hashtable _registeredAssemblies = new Hashtable();
		Hashtable _typeMetadataCache = new Hashtable();

		object _lastObject = null;
		long _lastObjectID = 0;
		long _rootObjectID = 0;
		byte[] arrayBuffer;
		int ArrayBufferLength = 4096;

		class TypeMetadata
		{
			public Type Type;
			public Type[] MemberTypes;
			public string[] MemberNames;
			public MemberInfo[] MemberInfos;
			public int FieldCount;
			public bool NeedsSerializationInfo;
		}

		class ArrayNullFiller
		{
			public ArrayNullFiller(int count) { NullCount = count; }
			public int NullCount;
		}

		public ObjectReader (BinaryFormatter formatter)
		{
//			_formatter = formatter;
			_surrogateSelector = formatter.SurrogateSelector;
			_context = formatter.Context;
			_binder = formatter.Binder;
			_manager = new ObjectManager (_surrogateSelector, _context);
			
#if NET_1_1
			_filterLevel = formatter.FilterLevel;
#endif
		}

		public void ReadObjectGraph (BinaryReader reader, bool readHeaders, out object result, out Header[] headers)
		{
			BinaryElement elem = (BinaryElement)reader.ReadByte ();
			ReadObjectGraph (elem, reader, readHeaders, out result, out headers);
		}

		public void ReadObjectGraph (BinaryElement elem, BinaryReader reader, bool readHeaders, out object result, out Header[] headers)
		{
			headers = null;

			// Reads the objects. The first object in the stream is the
			// root object.
			bool next = ReadNextObject (elem, reader);
			if (next) {
				do {
					if (readHeaders && (headers == null))
						headers = (Header[])CurrentObject;
					else
						if (_rootObjectID == 0) _rootObjectID = _lastObjectID;
				} while (ReadNextObject (reader));
			}

			result = _manager.GetObject (_rootObjectID);
		}

		bool ReadNextObject (BinaryElement element, BinaryReader reader)
		{
			if (element == BinaryElement.End)
			{
				_manager.DoFixups();

				_manager.RaiseDeserializationEvent();
				return false;
			}

			SerializationInfo info;
			long objectId;

			ReadObject (element, reader, out objectId, out _lastObject, out info);

			if (objectId != 0) {
				RegisterObject (objectId, _lastObject, info, 0, null, null);
				_lastObjectID = objectId;		
			}
	
			return true;
		}

		public bool ReadNextObject (BinaryReader reader)
		{
			BinaryElement element = (BinaryElement)reader.ReadByte ();
			if (element == BinaryElement.End)
			{
				_manager.DoFixups();

				_manager.RaiseDeserializationEvent();
				return false;
			}

			SerializationInfo info;
			long objectId;

			ReadObject (element, reader, out objectId, out _lastObject, out info);

			if (objectId != 0) {
				RegisterObject (objectId, _lastObject, info, 0, null, null);
				_lastObjectID = objectId;		
			}
	
			return true;
		}

		public object CurrentObject
		{
			get { return _lastObject; }
		}

		// Reads an object from the stream. The object is registered in the ObjectManager.
		// The result can be either the object instance
		// or the id of the object (when what is found in the stream is an object reference).
		// If an object instance is read, the objectId is set to 0.
		
		private void ReadObject (BinaryElement element, BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
		{
			switch (element)
			{
				case BinaryElement.RefTypeObject:
					ReadRefTypeObjectInstance (reader, out objectId, out value, out info);
					break;

				case BinaryElement.UntypedRuntimeObject:
					ReadObjectInstance (reader, true, false, out objectId, out value, out info);
					break;

				case BinaryElement.UntypedExternalObject:
					ReadObjectInstance (reader, false, false, out objectId, out value, out info);
					break;

				case BinaryElement.RuntimeObject:
					ReadObjectInstance (reader, true, true, out objectId, out value, out info);
					break;

				case BinaryElement.ExternalObject:
					ReadObjectInstance (reader, false, true, out objectId, out value, out info);
					break;

				case BinaryElement.String:
					info = null;
					ReadStringIntance (reader, out objectId, out value);
					break;

				case BinaryElement.GenericArray:
					info = null;
					ReadGenericArray (reader, out objectId, out value);
					break;


				case BinaryElement.BoxedPrimitiveTypeValue:
					value = ReadBoxedPrimitiveTypeValue (reader);
					objectId = 0;
					info = null;
					break;

				case BinaryElement.NullValue:
					value = null;
					objectId = 0;
					info = null;
					break;

				case BinaryElement.Assembly:
					ReadAssembly (reader);
					ReadObject ((BinaryElement)reader.ReadByte (), reader, out objectId, out value, out info);
					break;

				case BinaryElement.ArrayFiller8b:
					value = new ArrayNullFiller(reader.ReadByte());
					objectId = 0;
					info = null;
					break;

				case BinaryElement.ArrayFiller32b:
					value = new ArrayNullFiller(reader.ReadInt32());
					objectId = 0;
					info = null;
					break;

				case BinaryElement.ArrayOfPrimitiveType:
					ReadArrayOfPrimitiveType (reader, out objectId, out value);
					info = null;
					break;

				case BinaryElement.ArrayOfObject:
					ReadArrayOfObject (reader, out objectId, out value);
					info = null;
					break;

				case BinaryElement.ArrayOfString:
					ReadArrayOfString (reader, out objectId, out value);
					info = null;
					break;

				default:
					throw new SerializationException ("Unexpected binary element: " + (int)element);
			}
		}

		private void ReadAssembly (BinaryReader reader)
		{
			long id = (long) reader.ReadUInt32 ();
			string assemblyName = reader.ReadString ();
			_registeredAssemblies [id] = assemblyName;
		}

		private void ReadObjectInstance (BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo, out long objectId, out object value, out SerializationInfo info)
		{
			objectId = (long) reader.ReadUInt32 ();

			TypeMetadata metadata = ReadTypeMetadata (reader, isRuntimeObject, hasTypeInfo);
			ReadObjectContent (reader, metadata, objectId, out value, out info);
		}

		private void ReadRefTypeObjectInstance (BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
		{
			objectId = (long) reader.ReadUInt32 ();
			long refTypeObjectId = (long) reader.ReadUInt32 ();

			// Gets the type of the referred object and its metadata

			object refObj = _manager.GetObject (refTypeObjectId);
			if (refObj == null) throw new SerializationException ("Invalid binary format");
			TypeMetadata metadata = (TypeMetadata)_typeMetadataCache [refObj.GetType()];

			ReadObjectContent (reader, metadata, objectId, out value, out info);
		}

		private void ReadObjectContent (BinaryReader reader, TypeMetadata metadata, long objectId, out object objectInstance, out SerializationInfo info)
		{
#if NET_1_1
			if (_filterLevel == TypeFilterLevel.Low)
				objectInstance = FormatterServices.GetSafeUninitializedObject (metadata.Type);
			else
#endif
				objectInstance = FormatterServices.GetUninitializedObject (metadata.Type);
#if NET_2_0
			_manager.RaiseOnDeserializingEvent (objectInstance);
#endif
				
			info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null;

   			if (metadata.MemberNames != null)
				for (int n=0; n<metadata.FieldCount; n++)
					ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null);
			else
				for (int n=0; n<metadata.FieldCount; n++)
					ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
		}

		private void RegisterObject (long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMemeber, int[] indices)
		{
			if (parentObjectId == 0) indices = null;

			if (!objectInstance.GetType().IsValueType || parentObjectId == 0)
				_manager.RegisterObject (objectInstance, objectId, info, 0, null, null);
			else
			{
				if (indices != null) indices = (int[])indices.Clone();
				_manager.RegisterObject (objectInstance, objectId, info, parentObjectId, parentObjectMemeber, indices);
			}
		}

		private void ReadStringIntance (BinaryReader reader, out long objectId, out object value)
		{
			objectId = (long) reader.ReadUInt32 ();
			value = reader.ReadString ();
		}

		private void ReadGenericArray (BinaryReader reader, out long objectId, out object val)
		{
			objectId = (long) reader.ReadUInt32 ();
			// Array structure
			reader.ReadByte();

			int rank = reader.ReadInt32();

			bool emptyDim = false;
			int[] lengths = new int[rank];
			for (int n=0; n<rank; n++)
			{
				lengths[n] = reader.ReadInt32();
				if (lengths[n] == 0) emptyDim = true;
			}

			TypeTag code = (TypeTag) reader.ReadByte ();
			Type elementType = ReadType (reader, code);

			Array array = Array.CreateInstance (elementType, lengths);

			if (emptyDim) 
			{ 
				val = array;
				return;
			}

			int[] indices = new int[rank];

			// Initialize indexes
			for (int dim = rank-1; dim >= 0; dim--)
				indices[dim] = array.GetLowerBound (dim);

			bool end = false;
			while (!end)
			{
				ReadValue (reader, array, objectId, null, elementType, null, null, indices);

				for (int dim = array.Rank-1; dim >= 0; dim--)
				{
					indices[dim]++;
					if (indices[dim] > array.GetUpperBound (dim))
					{
						if (dim > 0) 
						{
							indices[dim] = array.GetLowerBound (dim);
							continue;	// Increment the next dimension's index
						}
						end = true;	// That was the last dimension. Finished.
					}
					break;
				}
			}
			val = array;
		}

		private object ReadBoxedPrimitiveTypeValue (BinaryReader reader)
		{
			Type type = ReadType (reader, TypeTag.PrimitiveType);
			return ReadPrimitiveTypeValue (reader, type);
		}

		private void ReadArrayOfPrimitiveType (BinaryReader reader, out long objectId, out object val)
		{
			objectId = (long) reader.ReadUInt32 ();
			int length = reader.ReadInt32 ();
			Type elementType = ReadType (reader, TypeTag.PrimitiveType);

			switch (Type.GetTypeCode (elementType))
			{
				case TypeCode.Boolean: {
					bool[] arr = new bool [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadBoolean();
					val = arr;
					break;
				}

				case TypeCode.Byte: {
					byte[] arr = new byte [length];
					int pos = 0;
					while (pos < length) {
						int nr = reader.Read (arr, pos, length - pos);
						if (nr == 0) break;
						pos += nr;
					}
					val = arr;
					break;
				}

				case TypeCode.Char: {
					char[] arr = new char [length];
					int pos = 0;
					while (pos < length) {
						int nr = reader.Read (arr, pos, length - pos);
						if (nr == 0) break;
						pos += nr;
					}
					val = arr;
					break;
				}

				case TypeCode.DateTime: {
					DateTime[] arr = new DateTime [length];
					for (int n = 0; n < length; n++) {
						arr [n] = DateTime.FromBinary (reader.ReadInt64 ());
					}
					val = arr;
					break;
				}

				case TypeCode.Decimal: {
					Decimal[] arr = new Decimal [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadDecimal();
					val = arr;
					break;
				}

				case TypeCode.Double: {
					Double[] arr = new Double [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadDouble();
					val = arr;
					break;
				}

				case TypeCode.Int16: {
					short[] arr = new short [length];
					if (length > 2)
						BlockRead (reader, arr, 2);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt16();
					val = arr;
					break;
				}

				case TypeCode.Int32: {
					int[] arr = new int [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt32();
					val = arr;
					break;
				}

				case TypeCode.Int64: {
					long[] arr = new long [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt64();
					val = arr;
					break;
				}

				case TypeCode.SByte: {
					sbyte[] arr = new sbyte [length];
					if (length > 2)
						BlockRead (reader, arr, 1);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadSByte();
					val = arr;
					break;
				}

				case TypeCode.Single: {
					float[] arr = new float [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadSingle();
					val = arr;
					break;
				}

				case TypeCode.UInt16: {
					ushort[] arr = new ushort [length];
					if (length > 2)
						BlockRead (reader, arr, 2);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt16();
					val = arr;
					break;
				}

				case TypeCode.UInt32: {
					uint[] arr = new uint [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt32();
					val = arr;
					break;
				}

				case TypeCode.UInt64: {
					ulong[] arr = new ulong [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt64();
					val = arr;
					break;
				}

				case TypeCode.String: {
					string[] arr = new string [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadString();
					val = arr;
					break;
				}

				default: {
					if (elementType == typeof(TimeSpan)) {
						TimeSpan[] arr = new TimeSpan [length];
						for (int n = 0; n < length; n++) arr [n] = new TimeSpan (reader.ReadInt64 ());
						val = arr;
					}
					else
						throw new NotSupportedException ("Unsupported primitive type: " + elementType.FullName);
					break;
				}
			}			
		}

		private void BlockRead (BinaryReader reader, Array array, int dataSize)
		{
			int totalSize = Buffer.ByteLength (array);
			
			if (arrayBuffer == null || (totalSize > arrayBuffer.Length && arrayBuffer.Length != ArrayBufferLength))
				arrayBuffer = new byte [totalSize <= ArrayBufferLength ? totalSize : ArrayBufferLength];
			
			int pos = 0;
			while (totalSize > 0) {
				int size = totalSize < arrayBuffer.Length ? totalSize : arrayBuffer.Length;
				int ap = 0;
				do {
					int nr = reader.Read (arrayBuffer, ap, size - ap);
					if (nr == 0) break;
					ap += nr;
				} while (ap < size);
				
				if (!BitConverter.IsLittleEndian && dataSize > 1)
					BinaryCommon.SwapBytes (arrayBuffer, size, dataSize);

				Buffer.BlockCopy (arrayBuffer, 0, array, pos, size);
				totalSize -= size;
				pos += size;
			}
		}
		

		private void ReadArrayOfObject (BinaryReader reader, out long objectId, out object array)
		{
			ReadSimpleArray (reader, typeof (object), out objectId, out array);
		}
		
		private void ReadArrayOfString (BinaryReader reader, out long objectId, out object array)
		{
			ReadSimpleArray (reader, typeof (string), out objectId, out array);
		}

		private void ReadSimpleArray (BinaryReader reader, Type elementType, out long objectId, out object val)
		{
			objectId = (long) reader.ReadUInt32 ();
			int length = reader.ReadInt32 ();
			int[] indices = new int[1];

			Array array = Array.CreateInstance (elementType, length);
			for (int n = 0; n < length; n++)
			{
				indices[0] = n;
				ReadValue (reader, array, objectId, null, elementType, null, null, indices);
				n = indices[0];
			}
			val = array;
		}

		private TypeMetadata ReadTypeMetadata (BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo)
		{
			TypeMetadata metadata = new TypeMetadata();

			string className = reader.ReadString ();
			int fieldCount = reader.ReadInt32 ();

			Type[] types = new Type[fieldCount];
			string[] names = new string[fieldCount];

			for (int n=0; n<fieldCount; n++)
				names [n] = reader.ReadString ();

			if (hasTypeInfo)
			{
				TypeTag[] codes = new TypeTag[fieldCount];

				for (int n=0; n<fieldCount; n++)
					codes [n] = (TypeTag) reader.ReadByte ();
	
				for (int n=0; n<fieldCount; n++)
					types [n] = ReadType (reader, codes[n]);
			}
			
			// Gets the type

			if (!isRuntimeObject) 
			{
				long assemblyId = (long)reader.ReadUInt32();
				metadata.Type = GetDeserializationType (assemblyId, className);
			}
			else
				metadata.Type = Type.GetType (className, true);

			metadata.MemberTypes = types;
			metadata.MemberNames = names;
			metadata.FieldCount = names.Length;

			// Now check if this objects needs a SerializationInfo struct for deserialziation.
			// SerializationInfo is needed if the object has to be deserialized using
			// a serialization surrogate, or if it implements ISerializable.

			if (_surrogateSelector != null)
			{
				// check if the surrogate selector handles objects of the given type. 
				ISurrogateSelector selector;
				ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate (metadata.Type, _context, out selector);
				metadata.NeedsSerializationInfo = (surrogate != null);
			}

			if (!metadata.NeedsSerializationInfo)
			{
				// Check if the object is marked with the Serializable attribute

				if (!metadata.Type.IsSerializable)
					throw new SerializationException("Serializable objects must be marked with the Serializable attribute");

				metadata.NeedsSerializationInfo = typeof (ISerializable).IsAssignableFrom (metadata.Type);
				if (!metadata.NeedsSerializationInfo)
				{
					metadata.MemberInfos = new MemberInfo [fieldCount];
					for (int n=0; n<fieldCount; n++)
					{
						FieldInfo field = null;
						string memberName = names[n];
						
						int i = memberName.IndexOf ('+');
						if (i != -1) {
							string baseTypeName = names[n].Substring (0,i);
							memberName = names[n].Substring (i+1);
							Type t = metadata.Type.BaseType;
							while (t != null) {
								if (t.Name == baseTypeName) {
									field = t.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
									break;
								}
								else
									t = t.BaseType;
							}
						}
						else
							field = metadata.Type.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
							
						if (field == null) throw new SerializationException ("Field \"" + names[n] + "\" not found in class " + metadata.Type.FullName);
						metadata.MemberInfos [n] = field;
						
						if (!hasTypeInfo) {
							types [n] = field.FieldType;
						}
					}
					metadata.MemberNames = null;	// Info now in MemberInfos
				}
			}

			// Registers the type's metadata so it can be reused later if
			// a RefTypeObject element is found

			if (!_typeMetadataCache.ContainsKey (metadata.Type))
				_typeMetadataCache [metadata.Type] = metadata;

			return metadata;
		}


		private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
		{
			// Reads a value from the stream and assigns it to the member of an object

			object val;

			if (BinaryCommon.IsPrimitive (valueType))
			{
				val = ReadPrimitiveTypeValue (reader, valueType);
				SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
				return;
			}

			// Gets the object

			BinaryElement element = (BinaryElement)reader.ReadByte ();

			if (element == BinaryElement.ObjectReference)
			{
				// Just read the id of the referred object and record a fixup
				long childObjectId = (long) reader.ReadUInt32();
				RecordFixup (parentObjectId, childObjectId, parentObject, info, fieldName, memberInfo, indices);
				return;
			}

			long objectId;
			SerializationInfo objectInfo;

			ReadObject (element, reader, out objectId, out val, out objectInfo);

			// There are two cases where the object cannot be assigned to the parent
			// and a fixup must be used:
			//  1) When what has been read is not an object, but an id of an object that
			//     has not been read yet (an object reference). This is managed in the
			//     previous block of code.
			//  2) When the read object is a value type object. Value type fields hold
			//     copies of objects, not references. Thus, if the value object that
			//     has been read has pending fixups, those fixups would be made to the
			//     boxed copy in the ObjectManager, and not in the required object instance

			// First of all register the fixup, and then the object. ObjectManager is more
			// efficient if done in this order

			bool hasFixup = false;
			if (objectId != 0)
			{
				if (val.GetType().IsValueType)
				{
					RecordFixup (parentObjectId, objectId, parentObject, info, fieldName, memberInfo, indices);
					hasFixup = true;
				}

				// Register the value

				if (info == null && !(parentObject is Array))
					RegisterObject (objectId, val, objectInfo, parentObjectId, memberInfo, null);
				else
					RegisterObject (objectId, val, objectInfo, parentObjectId, null, indices);
			}
			// Assign the value to the parent object, unless there is a fixup
			
			if (!hasFixup) 
				SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
		}

		private void SetObjectValue (object parentObject, string fieldName, MemberInfo memberInfo, SerializationInfo info, object value, Type valueType, int[] indices)
		{
			if (value is IObjectReference)
				value = ((IObjectReference)value).GetRealObject (_context);

			if (parentObject is Array) 
			{
				if (value is ArrayNullFiller) 
				{
					// It must be a single dimension array of objects.
					// Just increase the index. Elements are null by default.
					int count = ((ArrayNullFiller)value).NullCount;
					indices[0] += count - 1;
				}
				else
					((Array)parentObject).SetValue (value, indices);
			}
			else if (info != null) {
				info.AddValue (fieldName, value, valueType);
			}
			else {
				if (memberInfo is FieldInfo)
					((FieldInfo)memberInfo).SetValue (parentObject, value);
				else
					((PropertyInfo)memberInfo).SetValue (parentObject, value, null);
			}
		}

		private void RecordFixup (long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices)
		{
			if (info != null) {
				_manager.RecordDelayedFixup (parentObjectId, fieldName, childObjectId);
			}
			else if (parentObject is Array) {
				if (indices.Length == 1)
					_manager.RecordArrayElementFixup (parentObjectId, indices[0], childObjectId);
				else
					_manager.RecordArrayElementFixup (parentObjectId, (int[])indices.Clone(), childObjectId);
			}
			else {
				_manager.RecordFixup (parentObjectId, memberInfo, childObjectId);
			}
		}

		private Type GetDeserializationType (long assemblyId, string className)
		{
			Type t;
			string assemblyName = (string)_registeredAssemblies[assemblyId];

			if (_binder != null) {
				t = _binder.BindToType (assemblyName, className);
				if (t != null)
					return t;
			}
				
			Assembly assembly = Assembly.Load (assemblyName);
			t = assembly.GetType (className, true);
			if (t != null)
				return t;
			throw new SerializationException ("Couldn't find type '" + className + "'.");
		}

		public Type ReadType (BinaryReader reader, TypeTag code)
		{
			switch (code)
			{
				case TypeTag.PrimitiveType:
					return BinaryCommon.GetTypeFromCode (reader.ReadByte());

				case TypeTag.String:
					return typeof(string);

				case TypeTag.ObjectType:
					return typeof(object);

				case TypeTag.RuntimeType:
				{
					string name = reader.ReadString ();
#if NET_2_0
					// map MS.NET's System.RuntimeType to System.MonoType
					if (_context.State == StreamingContextStates.Remoting)
						if (name == "System.RuntimeType")
							return typeof (MonoType);
						else if (name == "System.RuntimeType[]")
							return typeof (MonoType[]);
#endif
					Type t = Type.GetType (name);
					if (t != null)
						return t;

					throw new SerializationException (String.Format ("Could not find type '{0}'.", name));
				}

				case TypeTag.GenericType:
				{
					string name = reader.ReadString ();
					long asmid = (long) reader.ReadUInt32();
					return GetDeserializationType (asmid, name);
				}

				case TypeTag.ArrayOfObject:
					return typeof(object[]);

				case TypeTag.ArrayOfString:
					return typeof(string[]);

				case TypeTag.ArrayOfPrimitiveType:
					Type elementType = BinaryCommon.GetTypeFromCode (reader.ReadByte());
					return Type.GetType(elementType.FullName + "[]");

				default:
					throw new NotSupportedException ("Unknow type tag");
			}
		}
		
		public static object ReadPrimitiveTypeValue (BinaryReader reader, Type type)
		{
			if (type == null) return null;

			switch (Type.GetTypeCode (type))
			{
				case TypeCode.Boolean:
					return reader.ReadBoolean();

				case TypeCode.Byte:
					return reader.ReadByte();

				case TypeCode.Char:
					return reader.ReadChar();

				case TypeCode.DateTime: 
					return DateTime.FromBinary (reader.ReadInt64());

				case TypeCode.Decimal:
					return Decimal.Parse (reader.ReadString(), CultureInfo.InvariantCulture);

				case TypeCode.Double:
					return reader.ReadDouble();

				case TypeCode.Int16:
					return reader.ReadInt16();

				case TypeCode.Int32:
					return reader.ReadInt32();

				case TypeCode.Int64:
					return reader.ReadInt64();

				case TypeCode.SByte:
					return reader.ReadSByte();

				case TypeCode.Single:
					return reader.ReadSingle();

				case TypeCode.UInt16:
					return reader.ReadUInt16();

				case TypeCode.UInt32:
					return reader.ReadUInt32();

				case TypeCode.UInt64:
					return reader.ReadUInt64();

				case TypeCode.String:
					return reader.ReadString();

				default:
					if (type == typeof(TimeSpan))
						return new TimeSpan (reader.ReadInt64 ());
					else
						throw new NotSupportedException ("Unsupported primitive type: " + type.FullName);
			}
		}
	}
}