ObjectReader.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. // ObjectReader.cs
  2. //
  3. // Author:
  4. // Lluis Sanchez Gual ([email protected])
  5. // Patrik Torstensson
  6. //
  7. // (C) 2003 Lluis Sanchez Gual
  8. // FIXME: Implement the missing binary elements
  9. using System;
  10. using System.Runtime.Serialization;
  11. using System.IO;
  12. using System.Collections;
  13. using System.Reflection;
  14. using System.Runtime.Remoting.Messaging;
  15. namespace System.Runtime.Serialization.Formatters.Binary
  16. {
  17. internal class ObjectReader
  18. {
  19. ISurrogateSelector _surrogateSelector;
  20. StreamingContext _context;
  21. SerializationBinder _binder;
  22. ObjectManager _manager;
  23. Hashtable _registeredAssemblies = new Hashtable();
  24. Hashtable _typeMetadataCache = new Hashtable();
  25. object _lastObject = null;
  26. long _lastObjectID = 0;
  27. long _rootObjectID = 0;
  28. class TypeMetadata
  29. {
  30. public Type Type;
  31. public Type[] MemberTypes;
  32. public string[] MemberNames;
  33. public MemberInfo[] MemberInfos;
  34. public int FieldCount;
  35. public bool NeedsSerializationInfo;
  36. }
  37. class ArrayNullFiller
  38. {
  39. public ArrayNullFiller(int count) { NullCount = count; }
  40. public int NullCount;
  41. }
  42. public ObjectReader(ISurrogateSelector surrogateSelector, StreamingContext context, SerializationBinder binder)
  43. {
  44. _manager = new ObjectManager (surrogateSelector, context);
  45. _surrogateSelector = surrogateSelector;
  46. _context = context;
  47. _binder = binder;
  48. }
  49. public void ReadObjectGraph (BinaryReader reader, bool readHeaders, out object result, out Header[] headers)
  50. {
  51. headers = null;
  52. // Reads the objects. The first object in the stream is the
  53. // root object.
  54. while (ReadNextObject (reader))
  55. {
  56. if (readHeaders && (headers == null))
  57. headers = (Header[])CurrentObject;
  58. else
  59. if (_rootObjectID == 0) _rootObjectID = _lastObjectID;
  60. }
  61. result = _manager.GetObject (_rootObjectID);
  62. }
  63. public bool ReadNextObject (BinaryReader reader)
  64. {
  65. BinaryElement element = (BinaryElement)reader.ReadByte ();
  66. if (element == BinaryElement.End)
  67. {
  68. _manager.DoFixups();
  69. _manager.RaiseDeserializationEvent();
  70. return false;
  71. }
  72. SerializationInfo info;
  73. long objectId;
  74. ReadObject (element, reader, out objectId, out _lastObject, out info);
  75. if (objectId != 0) {
  76. RegisterObject (objectId, _lastObject, info, 0, null, null);
  77. _lastObjectID = objectId;
  78. }
  79. return true;
  80. }
  81. public object CurrentObject
  82. {
  83. get { return _lastObject; }
  84. }
  85. // Reads an object from the stream. The object is registered in the ObjectManager.
  86. // The result can be either the object instance
  87. // or the id of the object (when what is found in the stream is an object reference).
  88. // If an object instance is read, the objectId is set to 0.
  89. private void ReadObject (BinaryElement element, BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
  90. {
  91. switch (element)
  92. {
  93. case BinaryElement.RefTypeObject:
  94. ReadRefTypeObjectInstance (reader, out objectId, out value, out info);
  95. break;
  96. case BinaryElement.RuntimeObject:
  97. ReadObjectInstance (reader, true, out objectId, out value, out info);
  98. break;
  99. case BinaryElement.ExternalObject:
  100. ReadObjectInstance (reader, false, out objectId, out value, out info);
  101. break;
  102. case BinaryElement.String:
  103. info = null;
  104. ReadStringIntance (reader, out objectId, out value);
  105. break;
  106. case BinaryElement.GenericArray:
  107. info = null;
  108. ReadGenericArray (reader, out objectId, out value);
  109. break;
  110. case BinaryElement.BoxedPrimitiveTypeValue:
  111. value = ReadBoxedPrimitiveTypeValue (reader);
  112. objectId = 0;
  113. info = null;
  114. break;
  115. case BinaryElement.NullValue:
  116. value = null;
  117. objectId = 0;
  118. info = null;
  119. break;
  120. case BinaryElement.Assembly:
  121. ReadAssembly (reader);
  122. ReadObject ((BinaryElement)reader.ReadByte (), reader, out objectId, out value, out info);
  123. break;
  124. case BinaryElement.ArrayFiller8b:
  125. value = new ArrayNullFiller(reader.ReadByte());
  126. objectId = 0;
  127. info = null;
  128. break;
  129. case BinaryElement.ArrayFiller32b:
  130. value = new ArrayNullFiller(reader.ReadInt32());
  131. objectId = 0;
  132. info = null;
  133. break;
  134. case BinaryElement.ArrayOfPrimitiveType:
  135. ReadArrayOfPrimitiveType (reader, out objectId, out value);
  136. info = null;
  137. break;
  138. case BinaryElement.ArrayOfObject:
  139. ReadArrayOfObject (reader, out objectId, out value);
  140. info = null;
  141. break;
  142. case BinaryElement.ArrayOfString:
  143. ReadArrayOfString (reader, out objectId, out value);
  144. info = null;
  145. break;
  146. default:
  147. throw new SerializationException ("Unexpected binary element: " + (int)element);
  148. }
  149. }
  150. private void ReadAssembly (BinaryReader reader)
  151. {
  152. long id = (long) reader.ReadUInt32 ();
  153. string assemblyName = reader.ReadString ();
  154. _registeredAssemblies [id] = assemblyName;
  155. }
  156. private void ReadObjectInstance (BinaryReader reader, bool isRuntimeObject, out long objectId, out object value, out SerializationInfo info)
  157. {
  158. objectId = (long) reader.ReadUInt32 ();
  159. TypeMetadata metadata = ReadTypeMetadata (reader, isRuntimeObject);
  160. ReadObjectContent (reader, metadata, objectId, out value, out info);
  161. }
  162. private void ReadRefTypeObjectInstance (BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
  163. {
  164. objectId = (long) reader.ReadUInt32 ();
  165. long refTypeObjectId = (long) reader.ReadUInt32 ();
  166. // Gets the type of the referred object and its metadata
  167. object refObj = _manager.GetObject (refTypeObjectId);
  168. if (refObj == null) throw new SerializationException ("Invalid binary format");
  169. TypeMetadata metadata = (TypeMetadata)_typeMetadataCache [refObj.GetType()];
  170. ReadObjectContent (reader, metadata, objectId, out value, out info);
  171. }
  172. private void ReadObjectContent (BinaryReader reader, TypeMetadata metadata, long objectId, out object objectInstance, out SerializationInfo info)
  173. {
  174. objectInstance = FormatterServices.GetUninitializedObject (metadata.Type);
  175. info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null;
  176. if (metadata.MemberNames != null)
  177. for (int n=0; n<metadata.FieldCount; n++)
  178. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null);
  179. else
  180. for (int n=0; n<metadata.FieldCount; n++)
  181. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
  182. }
  183. private void RegisterObject (long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMemeber, int[] indices)
  184. {
  185. if (parentObjectId == 0) indices = null;
  186. if (!objectInstance.GetType().IsValueType || parentObjectId == 0)
  187. _manager.RegisterObject (objectInstance, objectId, info, 0, null, null);
  188. else
  189. {
  190. if (indices != null) indices = (int[])indices.Clone();
  191. _manager.RegisterObject (objectInstance, objectId, info, parentObjectId, parentObjectMemeber, indices);
  192. }
  193. }
  194. private void ReadStringIntance (BinaryReader reader, out long objectId, out object value)
  195. {
  196. objectId = (long) reader.ReadUInt32 ();
  197. value = reader.ReadString ();
  198. }
  199. private void ReadGenericArray (BinaryReader reader, out long objectId, out object val)
  200. {
  201. objectId = (long) reader.ReadUInt32 ();
  202. ArrayStructure structure = (ArrayStructure) reader.ReadByte();
  203. int rank = reader.ReadInt32();
  204. bool emptyDim = false;
  205. int[] lengths = new int[rank];
  206. for (int n=0; n<rank; n++)
  207. {
  208. lengths[n] = reader.ReadInt32();
  209. if (lengths[n] == 0) emptyDim = true;
  210. }
  211. TypeTag code = (TypeTag) reader.ReadByte ();
  212. Type elementType = ReadType (reader, code);
  213. Array array = Array.CreateInstance (elementType, lengths);
  214. if (emptyDim)
  215. {
  216. val = array;
  217. return;
  218. }
  219. int[] indices = new int[rank];
  220. // Initialize indexes
  221. for (int dim = rank-1; dim >= 0; dim--)
  222. indices[dim] = array.GetLowerBound (dim);
  223. bool end = false;
  224. while (!end)
  225. {
  226. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  227. for (int dim = array.Rank-1; dim >= 0; dim--)
  228. {
  229. indices[dim]++;
  230. if (indices[dim] > array.GetUpperBound (dim))
  231. {
  232. if (dim > 0)
  233. {
  234. indices[dim] = array.GetLowerBound (dim);
  235. continue; // Increment the next dimension's index
  236. }
  237. end = true; // That was the last dimension. Finished.
  238. }
  239. break;
  240. }
  241. }
  242. val = array;
  243. }
  244. private object ReadBoxedPrimitiveTypeValue (BinaryReader reader)
  245. {
  246. Type type = ReadType (reader, TypeTag.PrimitiveType);
  247. return ReadPrimitiveTypeValue (reader, type);
  248. }
  249. private void ReadArrayOfPrimitiveType (BinaryReader reader, out long objectId, out object val)
  250. {
  251. objectId = (long) reader.ReadUInt32 ();
  252. int length = reader.ReadInt32 ();
  253. Type elementType = ReadType (reader, TypeTag.PrimitiveType);
  254. Array array = Array.CreateInstance (elementType, length);
  255. for (int n = 0; n < length; n++)
  256. array.SetValue (ReadPrimitiveTypeValue (reader, elementType), n);
  257. val = array;
  258. }
  259. private void ReadArrayOfObject (BinaryReader reader, out long objectId, out object array)
  260. {
  261. ReadSimpleArray (reader, typeof (object), out objectId, out array);
  262. }
  263. private void ReadArrayOfString (BinaryReader reader, out long objectId, out object array)
  264. {
  265. ReadSimpleArray (reader, typeof (string), out objectId, out array);
  266. }
  267. private void ReadSimpleArray (BinaryReader reader, Type elementType, out long objectId, out object val)
  268. {
  269. objectId = (long) reader.ReadUInt32 ();
  270. int length = reader.ReadInt32 ();
  271. int[] indices = new int[1];
  272. Array array = Array.CreateInstance (elementType, length);
  273. for (int n = 0; n < length; n++)
  274. {
  275. indices[0] = n;
  276. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  277. n = indices[0];
  278. }
  279. val = array;
  280. }
  281. private TypeMetadata ReadTypeMetadata (BinaryReader reader, bool isRuntimeObject)
  282. {
  283. TypeMetadata metadata = new TypeMetadata();
  284. string className = reader.ReadString ();
  285. int fieldCount = reader.ReadInt32 ();
  286. Type[] types = new Type[fieldCount];
  287. string[] names = new string[fieldCount];
  288. TypeTag[] codes = new TypeTag[fieldCount];
  289. for (int n=0; n<fieldCount; n++)
  290. names [n] = reader.ReadString ();
  291. for (int n=0; n<fieldCount; n++)
  292. codes [n] = (TypeTag) reader.ReadByte ();
  293. for (int n=0; n<fieldCount; n++)
  294. types [n] = ReadType (reader, codes[n]);
  295. // Gets the type
  296. if (!isRuntimeObject)
  297. {
  298. long assemblyId = (long)reader.ReadUInt32();
  299. metadata.Type = GetDeserializationType (assemblyId, className);
  300. }
  301. else
  302. metadata.Type = Type.GetType (className, true);
  303. metadata.MemberTypes = types;
  304. metadata.MemberNames = names;
  305. metadata.FieldCount = names.Length;
  306. // Now check if this objects needs a SerializationInfo struct for deserialziation.
  307. // SerializationInfo is needed if the object has to be deserialized using
  308. // a serialization surrogate, or if it implements ISerializable.
  309. if (_surrogateSelector != null)
  310. {
  311. // check if the surrogate selector handles objects of the given type.
  312. ISurrogateSelector selector;
  313. ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate (metadata.Type, _context, out selector);
  314. metadata.NeedsSerializationInfo = (surrogate != null);
  315. }
  316. if (!metadata.NeedsSerializationInfo)
  317. {
  318. // Check if the object is marked with the Serializable attribute
  319. if (!metadata.Type.IsSerializable)
  320. throw new SerializationException("Serializable objects must be marked with the Serializable attribute");
  321. metadata.NeedsSerializationInfo = (metadata.Type.GetInterface ("ISerializable") != null);
  322. if (!metadata.NeedsSerializationInfo)
  323. {
  324. metadata.MemberInfos = new MemberInfo [fieldCount];
  325. for (int n=0; n<fieldCount; n++)
  326. {
  327. MemberInfo[] members = metadata.Type.GetMember (names[n], MemberTypes.Field | MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  328. if (members.Length > 1) throw new SerializationException ("There are two public members named \"" + names[n] + "\" in the class hirearchy of " + metadata.Type.FullName);
  329. if (members.Length == 0) throw new SerializationException ("Field \"" + names[n] + "\" not found in class " + metadata.Type.FullName);
  330. metadata.MemberInfos [n] = members[0];
  331. }
  332. metadata.MemberNames = null; // Info now in MemberInfos
  333. }
  334. }
  335. // Registers the type's metadata so it can be reused later if
  336. // a RefTypeObject element is found
  337. if (!_typeMetadataCache.ContainsKey (metadata.Type))
  338. _typeMetadataCache [metadata.Type] = metadata;
  339. return metadata;
  340. }
  341. private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
  342. {
  343. // Reads a value from the stream and assigns it to the member of an object
  344. object val;
  345. if (BinaryCommon.IsPrimitive (valueType))
  346. {
  347. val = ReadPrimitiveTypeValue (reader, valueType);
  348. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  349. return;
  350. }
  351. // Gets the object
  352. BinaryElement element = (BinaryElement)reader.ReadByte ();
  353. if (element == BinaryElement.ObjectReference)
  354. {
  355. // Just read the id of the referred object and record a fixup
  356. long childObjectId = (long) reader.ReadUInt32();
  357. RecordFixup (parentObjectId, childObjectId, parentObject, info, fieldName, memberInfo, indices);
  358. return;
  359. }
  360. long objectId;
  361. SerializationInfo objectInfo;
  362. ReadObject (element, reader, out objectId, out val, out objectInfo);
  363. // There are two cases where the object cannot be assigned to the parent
  364. // and a fixup must be used:
  365. // 1) When what has been read is not an object, but an id of an object that
  366. // has not been read yet (an object reference). This is managed in the
  367. // previous block of code.
  368. // 2) When the read object is a value type object. Value type fields hold
  369. // copies of objects, not references. Thus, if the value object that
  370. // has been read has pending fixups, those fixups would be made to the
  371. // boxed copy in the ObjectManager, and not in the required object instance
  372. // First of all register the fixup, and then the object. ObjectManager is more
  373. // efficient if done in this order
  374. bool hasFixup = false;
  375. if (objectId != 0)
  376. {
  377. if (val.GetType().IsValueType)
  378. {
  379. RecordFixup (parentObjectId, objectId, parentObject, info, fieldName, memberInfo, indices);
  380. hasFixup = true;
  381. }
  382. // Register the value
  383. if (info == null && !parentObject.GetType().IsArray)
  384. RegisterObject (objectId, val, objectInfo, parentObjectId, memberInfo, null);
  385. else
  386. RegisterObject (objectId, val, objectInfo, parentObjectId, null, indices);
  387. }
  388. // Assign the value to the parent object, unless there is a fixup
  389. if (!hasFixup)
  390. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  391. }
  392. private void SetObjectValue (object parentObject, string fieldName, MemberInfo memberInfo, SerializationInfo info, object value, Type valueType, int[] indices)
  393. {
  394. if (value is IObjectReference)
  395. value = ((IObjectReference)value).GetRealObject (_context);
  396. if (parentObject.GetType().IsArray)
  397. {
  398. if (value is ArrayNullFiller)
  399. {
  400. // It must be a single dimension array of objects.
  401. // Just increase the index. Elements are null by default.
  402. int count = ((ArrayNullFiller)value).NullCount;
  403. indices[0] += count - 1;
  404. }
  405. else
  406. ((Array)parentObject).SetValue (value, indices);
  407. }
  408. else if (info != null) {
  409. info.AddValue (fieldName, value, valueType);
  410. }
  411. else {
  412. if (memberInfo is FieldInfo)
  413. ((FieldInfo)memberInfo).SetValue (parentObject, value);
  414. else
  415. ((PropertyInfo)memberInfo).SetValue (parentObject, value, null);
  416. }
  417. }
  418. private void RecordFixup (long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices)
  419. {
  420. if (info != null) {
  421. _manager.RecordDelayedFixup (parentObjectId, fieldName, childObjectId);
  422. }
  423. else if (parentObject.GetType().IsArray) {
  424. if (indices.Length == 1)
  425. _manager.RecordArrayElementFixup (parentObjectId, indices[0], childObjectId);
  426. else
  427. _manager.RecordArrayElementFixup (parentObjectId, (int[])indices.Clone(), childObjectId);
  428. }
  429. else {
  430. _manager.RecordFixup (parentObjectId, memberInfo, childObjectId);
  431. }
  432. }
  433. private Type GetDeserializationType (long assemblyId, string className)
  434. {
  435. string assemblyName = (string)_registeredAssemblies[assemblyId];
  436. if (_binder == null)
  437. {
  438. Assembly assembly = Assembly.Load (assemblyName);
  439. return assembly.GetType (className, true);
  440. }
  441. else
  442. return _binder.BindToType (assemblyName, className);
  443. }
  444. public Type ReadType (BinaryReader reader, TypeTag code)
  445. {
  446. switch (code)
  447. {
  448. case TypeTag.PrimitiveType:
  449. return BinaryCommon.GetTypeFromCode (reader.ReadByte());
  450. case TypeTag.String:
  451. return typeof(string);
  452. case TypeTag.ObjectType:
  453. return typeof(object);
  454. case TypeTag.RuntimeType:
  455. {
  456. string name = reader.ReadString ();
  457. return Type.GetType (name, true);
  458. }
  459. case TypeTag.GenericType:
  460. {
  461. string name = reader.ReadString ();
  462. long asmid = (long) reader.ReadUInt32();
  463. return GetDeserializationType (asmid, name);
  464. }
  465. case TypeTag.ArrayOfObject:
  466. return typeof(object[]);
  467. case TypeTag.ArrayOfString:
  468. return typeof(string[]);
  469. case TypeTag.ArrayOfPrimitiveType:
  470. Type elementType = BinaryCommon.GetTypeFromCode (reader.ReadByte());
  471. return Type.GetType(elementType.FullName + "[]");
  472. default:
  473. throw new NotSupportedException ("Unknow type tag");
  474. }
  475. }
  476. public static object ReadPrimitiveTypeValue (BinaryReader reader, Type type)
  477. {
  478. if (type == null) return null;
  479. switch (Type.GetTypeCode (type))
  480. {
  481. case TypeCode.Boolean:
  482. return reader.ReadBoolean();
  483. case TypeCode.Byte:
  484. return reader.ReadByte();
  485. case TypeCode.Char:
  486. return reader.ReadChar();
  487. case TypeCode.DateTime:
  488. return new DateTime (reader.ReadInt64());
  489. case TypeCode.Decimal:
  490. return reader.ReadDecimal();
  491. case TypeCode.Double:
  492. return reader.ReadDouble();
  493. case TypeCode.Int16:
  494. return reader.ReadInt16();
  495. case TypeCode.Int32:
  496. return reader.ReadInt32();
  497. case TypeCode.Int64:
  498. return reader.ReadInt64();
  499. case TypeCode.SByte:
  500. return reader.ReadSByte();
  501. case TypeCode.Single:
  502. return reader.ReadSingle();
  503. case TypeCode.UInt16:
  504. return reader.ReadUInt16();
  505. case TypeCode.UInt32:
  506. return reader.ReadUInt32();
  507. case TypeCode.UInt64:
  508. return reader.ReadUInt64();
  509. case TypeCode.String:
  510. return reader.ReadString();
  511. default:
  512. if (type == typeof(TimeSpan))
  513. return new TimeSpan (reader.ReadInt64 ());
  514. else
  515. throw new NotSupportedException ("Unsupported primitive type: " + type.FullName);
  516. }
  517. }
  518. }
  519. }