ObjectReader.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. // ObjectReader.cs
  2. //
  3. // Author:
  4. // Lluis Sanchez Gual ([email protected])
  5. // Patrik Torstensson
  6. //
  7. // (C) 2003 Lluis Sanchez Gual
  8. //
  9. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Runtime.Serialization;
  32. using System.IO;
  33. using System.Collections;
  34. using System.Reflection;
  35. using System.Runtime.Remoting.Messaging;
  36. using System.Globalization;
  37. namespace System.Runtime.Serialization.Formatters.Binary
  38. {
  39. internal class ObjectReader
  40. {
  41. BinaryFormatter _formatter;
  42. ISurrogateSelector _surrogateSelector;
  43. StreamingContext _context;
  44. SerializationBinder _binder;
  45. #if NET_1_1
  46. TypeFilterLevel _filterLevel;
  47. #endif
  48. ObjectManager _manager;
  49. Hashtable _registeredAssemblies = new Hashtable();
  50. Hashtable _typeMetadataCache = new Hashtable();
  51. object _lastObject = null;
  52. long _lastObjectID = 0;
  53. long _rootObjectID = 0;
  54. byte[] arrayBuffer;
  55. int ArrayBufferLength = 4096;
  56. class TypeMetadata
  57. {
  58. public Type Type;
  59. public Type[] MemberTypes;
  60. public string[] MemberNames;
  61. public MemberInfo[] MemberInfos;
  62. public int FieldCount;
  63. public bool NeedsSerializationInfo;
  64. }
  65. class ArrayNullFiller
  66. {
  67. public ArrayNullFiller(int count) { NullCount = count; }
  68. public int NullCount;
  69. }
  70. public ObjectReader (BinaryFormatter formatter)
  71. {
  72. _formatter = formatter;
  73. _surrogateSelector = formatter.SurrogateSelector;
  74. _context = formatter.Context;
  75. _binder = formatter.Binder;
  76. _manager = new ObjectManager (_surrogateSelector, _context);
  77. #if NET_1_1
  78. _filterLevel = formatter.FilterLevel;
  79. #endif
  80. }
  81. public void ReadObjectGraph (BinaryReader reader, bool readHeaders, out object result, out Header[] headers)
  82. {
  83. headers = null;
  84. // Reads the objects. The first object in the stream is the
  85. // root object.
  86. while (ReadNextObject (reader))
  87. {
  88. if (readHeaders && (headers == null))
  89. headers = (Header[])CurrentObject;
  90. else
  91. if (_rootObjectID == 0) _rootObjectID = _lastObjectID;
  92. }
  93. result = _manager.GetObject (_rootObjectID);
  94. }
  95. public bool ReadNextObject (BinaryReader reader)
  96. {
  97. BinaryElement element = (BinaryElement)reader.ReadByte ();
  98. if (element == BinaryElement.End)
  99. {
  100. _manager.DoFixups();
  101. _manager.RaiseDeserializationEvent();
  102. return false;
  103. }
  104. SerializationInfo info;
  105. long objectId;
  106. ReadObject (element, reader, out objectId, out _lastObject, out info);
  107. if (objectId != 0) {
  108. RegisterObject (objectId, _lastObject, info, 0, null, null);
  109. _lastObjectID = objectId;
  110. }
  111. return true;
  112. }
  113. public object CurrentObject
  114. {
  115. get { return _lastObject; }
  116. }
  117. // Reads an object from the stream. The object is registered in the ObjectManager.
  118. // The result can be either the object instance
  119. // or the id of the object (when what is found in the stream is an object reference).
  120. // If an object instance is read, the objectId is set to 0.
  121. private void ReadObject (BinaryElement element, BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
  122. {
  123. switch (element)
  124. {
  125. case BinaryElement.RefTypeObject:
  126. ReadRefTypeObjectInstance (reader, out objectId, out value, out info);
  127. break;
  128. case BinaryElement.UntypedRuntimeObject:
  129. ReadObjectInstance (reader, true, false, out objectId, out value, out info);
  130. break;
  131. case BinaryElement.UntypedExternalObject:
  132. ReadObjectInstance (reader, false, false, out objectId, out value, out info);
  133. break;
  134. case BinaryElement.RuntimeObject:
  135. ReadObjectInstance (reader, true, true, out objectId, out value, out info);
  136. break;
  137. case BinaryElement.ExternalObject:
  138. ReadObjectInstance (reader, false, true, out objectId, out value, out info);
  139. break;
  140. case BinaryElement.String:
  141. info = null;
  142. ReadStringIntance (reader, out objectId, out value);
  143. break;
  144. case BinaryElement.GenericArray:
  145. info = null;
  146. ReadGenericArray (reader, out objectId, out value);
  147. break;
  148. case BinaryElement.BoxedPrimitiveTypeValue:
  149. value = ReadBoxedPrimitiveTypeValue (reader);
  150. objectId = 0;
  151. info = null;
  152. break;
  153. case BinaryElement.NullValue:
  154. value = null;
  155. objectId = 0;
  156. info = null;
  157. break;
  158. case BinaryElement.Assembly:
  159. ReadAssembly (reader);
  160. ReadObject ((BinaryElement)reader.ReadByte (), reader, out objectId, out value, out info);
  161. break;
  162. case BinaryElement.ArrayFiller8b:
  163. value = new ArrayNullFiller(reader.ReadByte());
  164. objectId = 0;
  165. info = null;
  166. break;
  167. case BinaryElement.ArrayFiller32b:
  168. value = new ArrayNullFiller(reader.ReadInt32());
  169. objectId = 0;
  170. info = null;
  171. break;
  172. case BinaryElement.ArrayOfPrimitiveType:
  173. ReadArrayOfPrimitiveType (reader, out objectId, out value);
  174. info = null;
  175. break;
  176. case BinaryElement.ArrayOfObject:
  177. ReadArrayOfObject (reader, out objectId, out value);
  178. info = null;
  179. break;
  180. case BinaryElement.ArrayOfString:
  181. ReadArrayOfString (reader, out objectId, out value);
  182. info = null;
  183. break;
  184. default:
  185. throw new SerializationException ("Unexpected binary element: " + (int)element);
  186. }
  187. }
  188. private void ReadAssembly (BinaryReader reader)
  189. {
  190. long id = (long) reader.ReadUInt32 ();
  191. string assemblyName = reader.ReadString ();
  192. _registeredAssemblies [id] = assemblyName;
  193. }
  194. private void ReadObjectInstance (BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo, out long objectId, out object value, out SerializationInfo info)
  195. {
  196. objectId = (long) reader.ReadUInt32 ();
  197. TypeMetadata metadata = ReadTypeMetadata (reader, isRuntimeObject, hasTypeInfo);
  198. ReadObjectContent (reader, metadata, objectId, out value, out info);
  199. }
  200. private void ReadRefTypeObjectInstance (BinaryReader reader, out long objectId, out object value, out SerializationInfo info)
  201. {
  202. objectId = (long) reader.ReadUInt32 ();
  203. long refTypeObjectId = (long) reader.ReadUInt32 ();
  204. // Gets the type of the referred object and its metadata
  205. object refObj = _manager.GetObject (refTypeObjectId);
  206. if (refObj == null) throw new SerializationException ("Invalid binary format");
  207. TypeMetadata metadata = (TypeMetadata)_typeMetadataCache [refObj.GetType()];
  208. ReadObjectContent (reader, metadata, objectId, out value, out info);
  209. }
  210. private void ReadObjectContent (BinaryReader reader, TypeMetadata metadata, long objectId, out object objectInstance, out SerializationInfo info)
  211. {
  212. #if NET_1_1
  213. if (_filterLevel == TypeFilterLevel.Low)
  214. objectInstance = FormatterServices.GetSafeUninitializedObject (metadata.Type);
  215. else
  216. #endif
  217. objectInstance = FormatterServices.GetUninitializedObject (metadata.Type);
  218. info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null;
  219. if (metadata.MemberNames != null)
  220. for (int n=0; n<metadata.FieldCount; n++)
  221. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null);
  222. else
  223. for (int n=0; n<metadata.FieldCount; n++)
  224. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
  225. }
  226. private void RegisterObject (long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMemeber, int[] indices)
  227. {
  228. if (parentObjectId == 0) indices = null;
  229. if (!objectInstance.GetType().IsValueType || parentObjectId == 0)
  230. _manager.RegisterObject (objectInstance, objectId, info, 0, null, null);
  231. else
  232. {
  233. if (indices != null) indices = (int[])indices.Clone();
  234. _manager.RegisterObject (objectInstance, objectId, info, parentObjectId, parentObjectMemeber, indices);
  235. }
  236. }
  237. private void ReadStringIntance (BinaryReader reader, out long objectId, out object value)
  238. {
  239. objectId = (long) reader.ReadUInt32 ();
  240. value = reader.ReadString ();
  241. }
  242. private void ReadGenericArray (BinaryReader reader, out long objectId, out object val)
  243. {
  244. objectId = (long) reader.ReadUInt32 ();
  245. // Array structure
  246. reader.ReadByte();
  247. int rank = reader.ReadInt32();
  248. bool emptyDim = false;
  249. int[] lengths = new int[rank];
  250. for (int n=0; n<rank; n++)
  251. {
  252. lengths[n] = reader.ReadInt32();
  253. if (lengths[n] == 0) emptyDim = true;
  254. }
  255. TypeTag code = (TypeTag) reader.ReadByte ();
  256. Type elementType = ReadType (reader, code);
  257. Array array = Array.CreateInstance (elementType, lengths);
  258. if (emptyDim)
  259. {
  260. val = array;
  261. return;
  262. }
  263. int[] indices = new int[rank];
  264. // Initialize indexes
  265. for (int dim = rank-1; dim >= 0; dim--)
  266. indices[dim] = array.GetLowerBound (dim);
  267. bool end = false;
  268. while (!end)
  269. {
  270. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  271. for (int dim = array.Rank-1; dim >= 0; dim--)
  272. {
  273. indices[dim]++;
  274. if (indices[dim] > array.GetUpperBound (dim))
  275. {
  276. if (dim > 0)
  277. {
  278. indices[dim] = array.GetLowerBound (dim);
  279. continue; // Increment the next dimension's index
  280. }
  281. end = true; // That was the last dimension. Finished.
  282. }
  283. break;
  284. }
  285. }
  286. val = array;
  287. }
  288. private object ReadBoxedPrimitiveTypeValue (BinaryReader reader)
  289. {
  290. Type type = ReadType (reader, TypeTag.PrimitiveType);
  291. return ReadPrimitiveTypeValue (reader, type);
  292. }
  293. private void ReadArrayOfPrimitiveType (BinaryReader reader, out long objectId, out object val)
  294. {
  295. objectId = (long) reader.ReadUInt32 ();
  296. int length = reader.ReadInt32 ();
  297. Type elementType = ReadType (reader, TypeTag.PrimitiveType);
  298. switch (Type.GetTypeCode (elementType))
  299. {
  300. case TypeCode.Boolean: {
  301. bool[] arr = new bool [length];
  302. for (int n = 0; n < length; n++) arr [n] = reader.ReadBoolean();
  303. val = arr;
  304. break;
  305. }
  306. case TypeCode.Byte: {
  307. byte[] arr = new byte [length];
  308. int pos = 0;
  309. while (pos < length) {
  310. int nr = reader.Read (arr, pos, length - pos);
  311. if (nr == 0) break;
  312. pos += nr;
  313. }
  314. val = arr;
  315. break;
  316. }
  317. case TypeCode.Char: {
  318. char[] arr = new char [length];
  319. int pos = 0;
  320. while (pos < length) {
  321. int nr = reader.Read (arr, pos, length - pos);
  322. if (nr == 0) break;
  323. pos += nr;
  324. }
  325. val = arr;
  326. break;
  327. }
  328. case TypeCode.DateTime: {
  329. DateTime[] arr = new DateTime [length];
  330. for (int n = 0; n < length; n++) arr [n] = new DateTime (reader.ReadInt64());
  331. val = arr;
  332. break;
  333. }
  334. case TypeCode.Decimal: {
  335. Decimal[] arr = new Decimal [length];
  336. for (int n = 0; n < length; n++) arr [n] = reader.ReadDecimal();
  337. val = arr;
  338. break;
  339. }
  340. case TypeCode.Double: {
  341. Double[] arr = new Double [length];
  342. if (length > 2)
  343. BlockRead (reader, arr, 8);
  344. else
  345. for (int n = 0; n < length; n++) arr [n] = reader.ReadDouble();
  346. val = arr;
  347. break;
  348. }
  349. case TypeCode.Int16: {
  350. short[] arr = new short [length];
  351. if (length > 2)
  352. BlockRead (reader, arr, 2);
  353. else
  354. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt16();
  355. val = arr;
  356. break;
  357. }
  358. case TypeCode.Int32: {
  359. int[] arr = new int [length];
  360. if (length > 2)
  361. BlockRead (reader, arr, 4);
  362. else
  363. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt32();
  364. val = arr;
  365. break;
  366. }
  367. case TypeCode.Int64: {
  368. long[] arr = new long [length];
  369. if (length > 2)
  370. BlockRead (reader, arr, 8);
  371. else
  372. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt64();
  373. val = arr;
  374. break;
  375. }
  376. case TypeCode.SByte: {
  377. sbyte[] arr = new sbyte [length];
  378. if (length > 2)
  379. BlockRead (reader, arr, 1);
  380. else
  381. for (int n = 0; n < length; n++) arr [n] = reader.ReadSByte();
  382. val = arr;
  383. break;
  384. }
  385. case TypeCode.Single: {
  386. float[] arr = new float [length];
  387. if (length > 2)
  388. BlockRead (reader, arr, 4);
  389. else
  390. for (int n = 0; n < length; n++) arr [n] = reader.ReadSingle();
  391. val = arr;
  392. break;
  393. }
  394. case TypeCode.UInt16: {
  395. ushort[] arr = new ushort [length];
  396. if (length > 2)
  397. BlockRead (reader, arr, 2);
  398. else
  399. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt16();
  400. val = arr;
  401. break;
  402. }
  403. case TypeCode.UInt32: {
  404. uint[] arr = new uint [length];
  405. if (length > 2)
  406. BlockRead (reader, arr, 4);
  407. else
  408. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt32();
  409. val = arr;
  410. break;
  411. }
  412. case TypeCode.UInt64: {
  413. ulong[] arr = new ulong [length];
  414. if (length > 2)
  415. BlockRead (reader, arr, 8);
  416. else
  417. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt64();
  418. val = arr;
  419. break;
  420. }
  421. case TypeCode.String: {
  422. string[] arr = new string [length];
  423. for (int n = 0; n < length; n++) arr [n] = reader.ReadString();
  424. val = arr;
  425. break;
  426. }
  427. default: {
  428. if (elementType == typeof(TimeSpan)) {
  429. TimeSpan[] arr = new TimeSpan [length];
  430. for (int n = 0; n < length; n++) arr [n] = new TimeSpan (reader.ReadInt64 ());
  431. val = arr;
  432. }
  433. else
  434. throw new NotSupportedException ("Unsupported primitive type: " + elementType.FullName);
  435. break;
  436. }
  437. }
  438. }
  439. private void BlockRead (BinaryReader reader, Array array, int dataSize)
  440. {
  441. int totalSize = Buffer.ByteLength (array);
  442. if (arrayBuffer == null || (totalSize > arrayBuffer.Length && arrayBuffer.Length != ArrayBufferLength))
  443. arrayBuffer = new byte [totalSize <= ArrayBufferLength ? totalSize : ArrayBufferLength];
  444. int pos = 0;
  445. while (totalSize > 0) {
  446. int size = totalSize < arrayBuffer.Length ? totalSize : arrayBuffer.Length;
  447. int ap = 0;
  448. do {
  449. int nr = reader.Read (arrayBuffer, ap, size - ap);
  450. if (nr == 0) break;
  451. ap += nr;
  452. } while (ap < size);
  453. if (!BitConverter.IsLittleEndian && dataSize > 1)
  454. BinaryCommon.SwapBytes (arrayBuffer, size, dataSize);
  455. Buffer.BlockCopy (arrayBuffer, 0, array, pos, size);
  456. totalSize -= size;
  457. pos += size;
  458. }
  459. }
  460. private void ReadArrayOfObject (BinaryReader reader, out long objectId, out object array)
  461. {
  462. ReadSimpleArray (reader, typeof (object), out objectId, out array);
  463. }
  464. private void ReadArrayOfString (BinaryReader reader, out long objectId, out object array)
  465. {
  466. ReadSimpleArray (reader, typeof (string), out objectId, out array);
  467. }
  468. private void ReadSimpleArray (BinaryReader reader, Type elementType, out long objectId, out object val)
  469. {
  470. objectId = (long) reader.ReadUInt32 ();
  471. int length = reader.ReadInt32 ();
  472. int[] indices = new int[1];
  473. Array array = Array.CreateInstance (elementType, length);
  474. for (int n = 0; n < length; n++)
  475. {
  476. indices[0] = n;
  477. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  478. n = indices[0];
  479. }
  480. val = array;
  481. }
  482. private TypeMetadata ReadTypeMetadata (BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo)
  483. {
  484. TypeMetadata metadata = new TypeMetadata();
  485. string className = reader.ReadString ();
  486. int fieldCount = reader.ReadInt32 ();
  487. Type[] types = new Type[fieldCount];
  488. string[] names = new string[fieldCount];
  489. for (int n=0; n<fieldCount; n++)
  490. names [n] = reader.ReadString ();
  491. if (hasTypeInfo)
  492. {
  493. TypeTag[] codes = new TypeTag[fieldCount];
  494. for (int n=0; n<fieldCount; n++)
  495. codes [n] = (TypeTag) reader.ReadByte ();
  496. for (int n=0; n<fieldCount; n++)
  497. types [n] = ReadType (reader, codes[n]);
  498. }
  499. // Gets the type
  500. if (!isRuntimeObject)
  501. {
  502. long assemblyId = (long)reader.ReadUInt32();
  503. metadata.Type = GetDeserializationType (assemblyId, className);
  504. }
  505. else
  506. metadata.Type = Type.GetType (className, true);
  507. metadata.MemberTypes = types;
  508. metadata.MemberNames = names;
  509. metadata.FieldCount = names.Length;
  510. // Now check if this objects needs a SerializationInfo struct for deserialziation.
  511. // SerializationInfo is needed if the object has to be deserialized using
  512. // a serialization surrogate, or if it implements ISerializable.
  513. if (_surrogateSelector != null)
  514. {
  515. // check if the surrogate selector handles objects of the given type.
  516. ISurrogateSelector selector;
  517. ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate (metadata.Type, _context, out selector);
  518. metadata.NeedsSerializationInfo = (surrogate != null);
  519. }
  520. if (!metadata.NeedsSerializationInfo)
  521. {
  522. // Check if the object is marked with the Serializable attribute
  523. if (!metadata.Type.IsSerializable)
  524. throw new SerializationException("Serializable objects must be marked with the Serializable attribute");
  525. metadata.NeedsSerializationInfo = (metadata.Type.GetInterface ("ISerializable") != null);
  526. if (!metadata.NeedsSerializationInfo)
  527. {
  528. metadata.MemberInfos = new MemberInfo [fieldCount];
  529. for (int n=0; n<fieldCount; n++)
  530. {
  531. FieldInfo field = null;
  532. string memberName = names[n];
  533. int i = memberName.IndexOf ('+');
  534. if (i != -1) {
  535. string baseTypeName = names[n].Substring (0,i);
  536. memberName = names[n].Substring (i+1);
  537. Type t = metadata.Type.BaseType;
  538. while (t != null) {
  539. if (t.Name == baseTypeName) {
  540. field = t.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  541. break;
  542. }
  543. else
  544. t = t.BaseType;
  545. }
  546. }
  547. else
  548. field = metadata.Type.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  549. if (field == null) throw new SerializationException ("Field \"" + names[n] + "\" not found in class " + metadata.Type.FullName);
  550. metadata.MemberInfos [n] = field;
  551. if (!hasTypeInfo) {
  552. types [n] = field.FieldType;
  553. }
  554. }
  555. metadata.MemberNames = null; // Info now in MemberInfos
  556. }
  557. }
  558. // Registers the type's metadata so it can be reused later if
  559. // a RefTypeObject element is found
  560. if (!_typeMetadataCache.ContainsKey (metadata.Type))
  561. _typeMetadataCache [metadata.Type] = metadata;
  562. return metadata;
  563. }
  564. private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
  565. {
  566. // Reads a value from the stream and assigns it to the member of an object
  567. object val;
  568. if (BinaryCommon.IsPrimitive (valueType))
  569. {
  570. val = ReadPrimitiveTypeValue (reader, valueType);
  571. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  572. return;
  573. }
  574. // Gets the object
  575. BinaryElement element = (BinaryElement)reader.ReadByte ();
  576. if (element == BinaryElement.ObjectReference)
  577. {
  578. // Just read the id of the referred object and record a fixup
  579. long childObjectId = (long) reader.ReadUInt32();
  580. RecordFixup (parentObjectId, childObjectId, parentObject, info, fieldName, memberInfo, indices);
  581. return;
  582. }
  583. long objectId;
  584. SerializationInfo objectInfo;
  585. ReadObject (element, reader, out objectId, out val, out objectInfo);
  586. // There are two cases where the object cannot be assigned to the parent
  587. // and a fixup must be used:
  588. // 1) When what has been read is not an object, but an id of an object that
  589. // has not been read yet (an object reference). This is managed in the
  590. // previous block of code.
  591. // 2) When the read object is a value type object. Value type fields hold
  592. // copies of objects, not references. Thus, if the value object that
  593. // has been read has pending fixups, those fixups would be made to the
  594. // boxed copy in the ObjectManager, and not in the required object instance
  595. // First of all register the fixup, and then the object. ObjectManager is more
  596. // efficient if done in this order
  597. bool hasFixup = false;
  598. if (objectId != 0)
  599. {
  600. if (val.GetType().IsValueType)
  601. {
  602. RecordFixup (parentObjectId, objectId, parentObject, info, fieldName, memberInfo, indices);
  603. hasFixup = true;
  604. }
  605. // Register the value
  606. if (info == null && !(parentObject is Array))
  607. RegisterObject (objectId, val, objectInfo, parentObjectId, memberInfo, null);
  608. else
  609. RegisterObject (objectId, val, objectInfo, parentObjectId, null, indices);
  610. }
  611. // Assign the value to the parent object, unless there is a fixup
  612. if (!hasFixup)
  613. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  614. }
  615. private void SetObjectValue (object parentObject, string fieldName, MemberInfo memberInfo, SerializationInfo info, object value, Type valueType, int[] indices)
  616. {
  617. if (value is IObjectReference)
  618. value = ((IObjectReference)value).GetRealObject (_context);
  619. if (parentObject is Array)
  620. {
  621. if (value is ArrayNullFiller)
  622. {
  623. // It must be a single dimension array of objects.
  624. // Just increase the index. Elements are null by default.
  625. int count = ((ArrayNullFiller)value).NullCount;
  626. indices[0] += count - 1;
  627. }
  628. else
  629. ((Array)parentObject).SetValue (value, indices);
  630. }
  631. else if (info != null) {
  632. info.AddValue (fieldName, value, valueType);
  633. }
  634. else {
  635. if (memberInfo is FieldInfo)
  636. ((FieldInfo)memberInfo).SetValue (parentObject, value);
  637. else
  638. ((PropertyInfo)memberInfo).SetValue (parentObject, value, null);
  639. }
  640. }
  641. private void RecordFixup (long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices)
  642. {
  643. if (info != null) {
  644. _manager.RecordDelayedFixup (parentObjectId, fieldName, childObjectId);
  645. }
  646. else if (parentObject is Array) {
  647. if (indices.Length == 1)
  648. _manager.RecordArrayElementFixup (parentObjectId, indices[0], childObjectId);
  649. else
  650. _manager.RecordArrayElementFixup (parentObjectId, (int[])indices.Clone(), childObjectId);
  651. }
  652. else {
  653. _manager.RecordFixup (parentObjectId, memberInfo, childObjectId);
  654. }
  655. }
  656. private Type GetDeserializationType (long assemblyId, string className)
  657. {
  658. string assemblyName = (string)_registeredAssemblies[assemblyId];
  659. if (_binder != null) {
  660. Type t = _binder.BindToType (assemblyName, className);
  661. if (t != null) return t;
  662. }
  663. Assembly assembly = Assembly.Load (assemblyName);
  664. return assembly.GetType (className, true);
  665. }
  666. public Type ReadType (BinaryReader reader, TypeTag code)
  667. {
  668. switch (code)
  669. {
  670. case TypeTag.PrimitiveType:
  671. return BinaryCommon.GetTypeFromCode (reader.ReadByte());
  672. case TypeTag.String:
  673. return typeof(string);
  674. case TypeTag.ObjectType:
  675. return typeof(object);
  676. case TypeTag.RuntimeType:
  677. {
  678. string name = reader.ReadString ();
  679. return Type.GetType (name, true);
  680. }
  681. case TypeTag.GenericType:
  682. {
  683. string name = reader.ReadString ();
  684. long asmid = (long) reader.ReadUInt32();
  685. return GetDeserializationType (asmid, name);
  686. }
  687. case TypeTag.ArrayOfObject:
  688. return typeof(object[]);
  689. case TypeTag.ArrayOfString:
  690. return typeof(string[]);
  691. case TypeTag.ArrayOfPrimitiveType:
  692. Type elementType = BinaryCommon.GetTypeFromCode (reader.ReadByte());
  693. return Type.GetType(elementType.FullName + "[]");
  694. default:
  695. throw new NotSupportedException ("Unknow type tag");
  696. }
  697. }
  698. public static object ReadPrimitiveTypeValue (BinaryReader reader, Type type)
  699. {
  700. if (type == null) return null;
  701. switch (Type.GetTypeCode (type))
  702. {
  703. case TypeCode.Boolean:
  704. return reader.ReadBoolean();
  705. case TypeCode.Byte:
  706. return reader.ReadByte();
  707. case TypeCode.Char:
  708. return reader.ReadChar();
  709. case TypeCode.DateTime:
  710. return new DateTime (reader.ReadInt64());
  711. case TypeCode.Decimal:
  712. return Decimal.Parse (reader.ReadString(), CultureInfo.InvariantCulture);
  713. case TypeCode.Double:
  714. return reader.ReadDouble();
  715. case TypeCode.Int16:
  716. return reader.ReadInt16();
  717. case TypeCode.Int32:
  718. return reader.ReadInt32();
  719. case TypeCode.Int64:
  720. return reader.ReadInt64();
  721. case TypeCode.SByte:
  722. return reader.ReadSByte();
  723. case TypeCode.Single:
  724. return reader.ReadSingle();
  725. case TypeCode.UInt16:
  726. return reader.ReadUInt16();
  727. case TypeCode.UInt32:
  728. return reader.ReadUInt32();
  729. case TypeCode.UInt64:
  730. return reader.ReadUInt64();
  731. case TypeCode.String:
  732. return reader.ReadString();
  733. default:
  734. if (type == typeof(TimeSpan))
  735. return new TimeSpan (reader.ReadInt64 ());
  736. else
  737. throw new NotSupportedException ("Unsupported primitive type: " + type.FullName);
  738. }
  739. }
  740. }
  741. }