ObjectReader.cs 19 KB

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