ObjectReader.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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. #if NET_2_0
  219. _manager.RaiseOnDeserializingEvent (objectInstance);
  220. #endif
  221. info = metadata.NeedsSerializationInfo ? new SerializationInfo(metadata.Type, new FormatterConverter()) : null;
  222. if (metadata.MemberNames != null)
  223. for (int n=0; n<metadata.FieldCount; n++)
  224. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberNames[n], null, null);
  225. else
  226. for (int n=0; n<metadata.FieldCount; n++)
  227. ReadValue (reader, objectInstance, objectId, info, metadata.MemberTypes[n], metadata.MemberInfos[n].Name, metadata.MemberInfos[n], null);
  228. }
  229. private void RegisterObject (long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMemeber, int[] indices)
  230. {
  231. if (parentObjectId == 0) indices = null;
  232. if (!objectInstance.GetType().IsValueType || parentObjectId == 0)
  233. _manager.RegisterObject (objectInstance, objectId, info, 0, null, null);
  234. else
  235. {
  236. if (indices != null) indices = (int[])indices.Clone();
  237. _manager.RegisterObject (objectInstance, objectId, info, parentObjectId, parentObjectMemeber, indices);
  238. }
  239. }
  240. private void ReadStringIntance (BinaryReader reader, out long objectId, out object value)
  241. {
  242. objectId = (long) reader.ReadUInt32 ();
  243. value = reader.ReadString ();
  244. }
  245. private void ReadGenericArray (BinaryReader reader, out long objectId, out object val)
  246. {
  247. objectId = (long) reader.ReadUInt32 ();
  248. // Array structure
  249. reader.ReadByte();
  250. int rank = reader.ReadInt32();
  251. bool emptyDim = false;
  252. int[] lengths = new int[rank];
  253. for (int n=0; n<rank; n++)
  254. {
  255. lengths[n] = reader.ReadInt32();
  256. if (lengths[n] == 0) emptyDim = true;
  257. }
  258. TypeTag code = (TypeTag) reader.ReadByte ();
  259. Type elementType = ReadType (reader, code);
  260. Array array = Array.CreateInstance (elementType, lengths);
  261. if (emptyDim)
  262. {
  263. val = array;
  264. return;
  265. }
  266. int[] indices = new int[rank];
  267. // Initialize indexes
  268. for (int dim = rank-1; dim >= 0; dim--)
  269. indices[dim] = array.GetLowerBound (dim);
  270. bool end = false;
  271. while (!end)
  272. {
  273. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  274. for (int dim = array.Rank-1; dim >= 0; dim--)
  275. {
  276. indices[dim]++;
  277. if (indices[dim] > array.GetUpperBound (dim))
  278. {
  279. if (dim > 0)
  280. {
  281. indices[dim] = array.GetLowerBound (dim);
  282. continue; // Increment the next dimension's index
  283. }
  284. end = true; // That was the last dimension. Finished.
  285. }
  286. break;
  287. }
  288. }
  289. val = array;
  290. }
  291. private object ReadBoxedPrimitiveTypeValue (BinaryReader reader)
  292. {
  293. Type type = ReadType (reader, TypeTag.PrimitiveType);
  294. return ReadPrimitiveTypeValue (reader, type);
  295. }
  296. private void ReadArrayOfPrimitiveType (BinaryReader reader, out long objectId, out object val)
  297. {
  298. objectId = (long) reader.ReadUInt32 ();
  299. int length = reader.ReadInt32 ();
  300. Type elementType = ReadType (reader, TypeTag.PrimitiveType);
  301. switch (Type.GetTypeCode (elementType))
  302. {
  303. case TypeCode.Boolean: {
  304. bool[] arr = new bool [length];
  305. for (int n = 0; n < length; n++) arr [n] = reader.ReadBoolean();
  306. val = arr;
  307. break;
  308. }
  309. case TypeCode.Byte: {
  310. byte[] arr = new byte [length];
  311. int pos = 0;
  312. while (pos < length) {
  313. int nr = reader.Read (arr, pos, length - pos);
  314. if (nr == 0) break;
  315. pos += nr;
  316. }
  317. val = arr;
  318. break;
  319. }
  320. case TypeCode.Char: {
  321. char[] arr = new char [length];
  322. int pos = 0;
  323. while (pos < length) {
  324. int nr = reader.Read (arr, pos, length - pos);
  325. if (nr == 0) break;
  326. pos += nr;
  327. }
  328. val = arr;
  329. break;
  330. }
  331. case TypeCode.DateTime: {
  332. DateTime[] arr = new DateTime [length];
  333. for (int n = 0; n < length; n++) {
  334. ulong nr = reader.ReadUInt64 ();
  335. const ulong mask = (1ul << 62) - 1;
  336. long ticks = (long) (nr & mask);
  337. #if NET_2_0
  338. DateTimeKind kind = (DateTimeKind) (nr >> 62);
  339. arr [n] = new DateTime (ticks, kind);
  340. #else
  341. arr [n] = new DateTime (ticks);
  342. #endif
  343. }
  344. val = arr;
  345. break;
  346. }
  347. case TypeCode.Decimal: {
  348. Decimal[] arr = new Decimal [length];
  349. for (int n = 0; n < length; n++) arr [n] = reader.ReadDecimal();
  350. val = arr;
  351. break;
  352. }
  353. case TypeCode.Double: {
  354. Double[] arr = new Double [length];
  355. if (length > 2)
  356. BlockRead (reader, arr, 8);
  357. else
  358. for (int n = 0; n < length; n++) arr [n] = reader.ReadDouble();
  359. val = arr;
  360. break;
  361. }
  362. case TypeCode.Int16: {
  363. short[] arr = new short [length];
  364. if (length > 2)
  365. BlockRead (reader, arr, 2);
  366. else
  367. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt16();
  368. val = arr;
  369. break;
  370. }
  371. case TypeCode.Int32: {
  372. int[] arr = new int [length];
  373. if (length > 2)
  374. BlockRead (reader, arr, 4);
  375. else
  376. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt32();
  377. val = arr;
  378. break;
  379. }
  380. case TypeCode.Int64: {
  381. long[] arr = new long [length];
  382. if (length > 2)
  383. BlockRead (reader, arr, 8);
  384. else
  385. for (int n = 0; n < length; n++) arr [n] = reader.ReadInt64();
  386. val = arr;
  387. break;
  388. }
  389. case TypeCode.SByte: {
  390. sbyte[] arr = new sbyte [length];
  391. if (length > 2)
  392. BlockRead (reader, arr, 1);
  393. else
  394. for (int n = 0; n < length; n++) arr [n] = reader.ReadSByte();
  395. val = arr;
  396. break;
  397. }
  398. case TypeCode.Single: {
  399. float[] arr = new float [length];
  400. if (length > 2)
  401. BlockRead (reader, arr, 4);
  402. else
  403. for (int n = 0; n < length; n++) arr [n] = reader.ReadSingle();
  404. val = arr;
  405. break;
  406. }
  407. case TypeCode.UInt16: {
  408. ushort[] arr = new ushort [length];
  409. if (length > 2)
  410. BlockRead (reader, arr, 2);
  411. else
  412. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt16();
  413. val = arr;
  414. break;
  415. }
  416. case TypeCode.UInt32: {
  417. uint[] arr = new uint [length];
  418. if (length > 2)
  419. BlockRead (reader, arr, 4);
  420. else
  421. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt32();
  422. val = arr;
  423. break;
  424. }
  425. case TypeCode.UInt64: {
  426. ulong[] arr = new ulong [length];
  427. if (length > 2)
  428. BlockRead (reader, arr, 8);
  429. else
  430. for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt64();
  431. val = arr;
  432. break;
  433. }
  434. case TypeCode.String: {
  435. string[] arr = new string [length];
  436. for (int n = 0; n < length; n++) arr [n] = reader.ReadString();
  437. val = arr;
  438. break;
  439. }
  440. default: {
  441. if (elementType == typeof(TimeSpan)) {
  442. TimeSpan[] arr = new TimeSpan [length];
  443. for (int n = 0; n < length; n++) arr [n] = new TimeSpan (reader.ReadInt64 ());
  444. val = arr;
  445. }
  446. else
  447. throw new NotSupportedException ("Unsupported primitive type: " + elementType.FullName);
  448. break;
  449. }
  450. }
  451. }
  452. private void BlockRead (BinaryReader reader, Array array, int dataSize)
  453. {
  454. int totalSize = Buffer.ByteLength (array);
  455. if (arrayBuffer == null || (totalSize > arrayBuffer.Length && arrayBuffer.Length != ArrayBufferLength))
  456. arrayBuffer = new byte [totalSize <= ArrayBufferLength ? totalSize : ArrayBufferLength];
  457. int pos = 0;
  458. while (totalSize > 0) {
  459. int size = totalSize < arrayBuffer.Length ? totalSize : arrayBuffer.Length;
  460. int ap = 0;
  461. do {
  462. int nr = reader.Read (arrayBuffer, ap, size - ap);
  463. if (nr == 0) break;
  464. ap += nr;
  465. } while (ap < size);
  466. if (!BitConverter.IsLittleEndian && dataSize > 1)
  467. BinaryCommon.SwapBytes (arrayBuffer, size, dataSize);
  468. Buffer.BlockCopy (arrayBuffer, 0, array, pos, size);
  469. totalSize -= size;
  470. pos += size;
  471. }
  472. }
  473. private void ReadArrayOfObject (BinaryReader reader, out long objectId, out object array)
  474. {
  475. ReadSimpleArray (reader, typeof (object), out objectId, out array);
  476. }
  477. private void ReadArrayOfString (BinaryReader reader, out long objectId, out object array)
  478. {
  479. ReadSimpleArray (reader, typeof (string), out objectId, out array);
  480. }
  481. private void ReadSimpleArray (BinaryReader reader, Type elementType, out long objectId, out object val)
  482. {
  483. objectId = (long) reader.ReadUInt32 ();
  484. int length = reader.ReadInt32 ();
  485. int[] indices = new int[1];
  486. Array array = Array.CreateInstance (elementType, length);
  487. for (int n = 0; n < length; n++)
  488. {
  489. indices[0] = n;
  490. ReadValue (reader, array, objectId, null, elementType, null, null, indices);
  491. n = indices[0];
  492. }
  493. val = array;
  494. }
  495. private TypeMetadata ReadTypeMetadata (BinaryReader reader, bool isRuntimeObject, bool hasTypeInfo)
  496. {
  497. TypeMetadata metadata = new TypeMetadata();
  498. string className = reader.ReadString ();
  499. int fieldCount = reader.ReadInt32 ();
  500. Type[] types = new Type[fieldCount];
  501. string[] names = new string[fieldCount];
  502. for (int n=0; n<fieldCount; n++)
  503. names [n] = reader.ReadString ();
  504. if (hasTypeInfo)
  505. {
  506. TypeTag[] codes = new TypeTag[fieldCount];
  507. for (int n=0; n<fieldCount; n++)
  508. codes [n] = (TypeTag) reader.ReadByte ();
  509. for (int n=0; n<fieldCount; n++)
  510. types [n] = ReadType (reader, codes[n]);
  511. }
  512. // Gets the type
  513. if (!isRuntimeObject)
  514. {
  515. long assemblyId = (long)reader.ReadUInt32();
  516. metadata.Type = GetDeserializationType (assemblyId, className);
  517. }
  518. else
  519. metadata.Type = Type.GetType (className, true);
  520. metadata.MemberTypes = types;
  521. metadata.MemberNames = names;
  522. metadata.FieldCount = names.Length;
  523. // Now check if this objects needs a SerializationInfo struct for deserialziation.
  524. // SerializationInfo is needed if the object has to be deserialized using
  525. // a serialization surrogate, or if it implements ISerializable.
  526. if (_surrogateSelector != null)
  527. {
  528. // check if the surrogate selector handles objects of the given type.
  529. ISurrogateSelector selector;
  530. ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate (metadata.Type, _context, out selector);
  531. metadata.NeedsSerializationInfo = (surrogate != null);
  532. }
  533. if (!metadata.NeedsSerializationInfo)
  534. {
  535. // Check if the object is marked with the Serializable attribute
  536. if (!metadata.Type.IsSerializable)
  537. throw new SerializationException("Serializable objects must be marked with the Serializable attribute");
  538. metadata.NeedsSerializationInfo = (metadata.Type.GetInterface ("ISerializable") != null);
  539. if (!metadata.NeedsSerializationInfo)
  540. {
  541. metadata.MemberInfos = new MemberInfo [fieldCount];
  542. for (int n=0; n<fieldCount; n++)
  543. {
  544. FieldInfo field = null;
  545. string memberName = names[n];
  546. int i = memberName.IndexOf ('+');
  547. if (i != -1) {
  548. string baseTypeName = names[n].Substring (0,i);
  549. memberName = names[n].Substring (i+1);
  550. Type t = metadata.Type.BaseType;
  551. while (t != null) {
  552. if (t.Name == baseTypeName) {
  553. field = t.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  554. break;
  555. }
  556. else
  557. t = t.BaseType;
  558. }
  559. }
  560. else
  561. field = metadata.Type.GetField (memberName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  562. if (field == null) throw new SerializationException ("Field \"" + names[n] + "\" not found in class " + metadata.Type.FullName);
  563. metadata.MemberInfos [n] = field;
  564. if (!hasTypeInfo) {
  565. types [n] = field.FieldType;
  566. }
  567. }
  568. metadata.MemberNames = null; // Info now in MemberInfos
  569. }
  570. }
  571. // Registers the type's metadata so it can be reused later if
  572. // a RefTypeObject element is found
  573. if (!_typeMetadataCache.ContainsKey (metadata.Type))
  574. _typeMetadataCache [metadata.Type] = metadata;
  575. return metadata;
  576. }
  577. private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
  578. {
  579. // Reads a value from the stream and assigns it to the member of an object
  580. object val;
  581. if (BinaryCommon.IsPrimitive (valueType))
  582. {
  583. val = ReadPrimitiveTypeValue (reader, valueType);
  584. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  585. return;
  586. }
  587. // Gets the object
  588. BinaryElement element = (BinaryElement)reader.ReadByte ();
  589. if (element == BinaryElement.ObjectReference)
  590. {
  591. // Just read the id of the referred object and record a fixup
  592. long childObjectId = (long) reader.ReadUInt32();
  593. RecordFixup (parentObjectId, childObjectId, parentObject, info, fieldName, memberInfo, indices);
  594. return;
  595. }
  596. long objectId;
  597. SerializationInfo objectInfo;
  598. ReadObject (element, reader, out objectId, out val, out objectInfo);
  599. // There are two cases where the object cannot be assigned to the parent
  600. // and a fixup must be used:
  601. // 1) When what has been read is not an object, but an id of an object that
  602. // has not been read yet (an object reference). This is managed in the
  603. // previous block of code.
  604. // 2) When the read object is a value type object. Value type fields hold
  605. // copies of objects, not references. Thus, if the value object that
  606. // has been read has pending fixups, those fixups would be made to the
  607. // boxed copy in the ObjectManager, and not in the required object instance
  608. // First of all register the fixup, and then the object. ObjectManager is more
  609. // efficient if done in this order
  610. bool hasFixup = false;
  611. if (objectId != 0)
  612. {
  613. if (val.GetType().IsValueType)
  614. {
  615. RecordFixup (parentObjectId, objectId, parentObject, info, fieldName, memberInfo, indices);
  616. hasFixup = true;
  617. }
  618. // Register the value
  619. if (info == null && !(parentObject is Array))
  620. RegisterObject (objectId, val, objectInfo, parentObjectId, memberInfo, null);
  621. else
  622. RegisterObject (objectId, val, objectInfo, parentObjectId, null, indices);
  623. }
  624. // Assign the value to the parent object, unless there is a fixup
  625. if (!hasFixup)
  626. SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
  627. }
  628. private void SetObjectValue (object parentObject, string fieldName, MemberInfo memberInfo, SerializationInfo info, object value, Type valueType, int[] indices)
  629. {
  630. if (value is IObjectReference)
  631. value = ((IObjectReference)value).GetRealObject (_context);
  632. if (parentObject is Array)
  633. {
  634. if (value is ArrayNullFiller)
  635. {
  636. // It must be a single dimension array of objects.
  637. // Just increase the index. Elements are null by default.
  638. int count = ((ArrayNullFiller)value).NullCount;
  639. indices[0] += count - 1;
  640. }
  641. else
  642. ((Array)parentObject).SetValue (value, indices);
  643. }
  644. else if (info != null) {
  645. info.AddValue (fieldName, value, valueType);
  646. }
  647. else {
  648. if (memberInfo is FieldInfo)
  649. ((FieldInfo)memberInfo).SetValue (parentObject, value);
  650. else
  651. ((PropertyInfo)memberInfo).SetValue (parentObject, value, null);
  652. }
  653. }
  654. private void RecordFixup (long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices)
  655. {
  656. if (info != null) {
  657. _manager.RecordDelayedFixup (parentObjectId, fieldName, childObjectId);
  658. }
  659. else if (parentObject is Array) {
  660. if (indices.Length == 1)
  661. _manager.RecordArrayElementFixup (parentObjectId, indices[0], childObjectId);
  662. else
  663. _manager.RecordArrayElementFixup (parentObjectId, (int[])indices.Clone(), childObjectId);
  664. }
  665. else {
  666. _manager.RecordFixup (parentObjectId, memberInfo, childObjectId);
  667. }
  668. }
  669. private Type GetDeserializationType (long assemblyId, string className)
  670. {
  671. Type t;
  672. string assemblyName = (string)_registeredAssemblies[assemblyId];
  673. if (_binder != null) {
  674. t = _binder.BindToType (assemblyName, className);
  675. if (t != null)
  676. return t;
  677. }
  678. Assembly assembly = Assembly.Load (assemblyName);
  679. t = assembly.GetType (className, true);
  680. if (t != null)
  681. return t;
  682. throw new SerializationException ("Couldn't find type '" + className + "'.");
  683. }
  684. public Type ReadType (BinaryReader reader, TypeTag code)
  685. {
  686. switch (code)
  687. {
  688. case TypeTag.PrimitiveType:
  689. return BinaryCommon.GetTypeFromCode (reader.ReadByte());
  690. case TypeTag.String:
  691. return typeof(string);
  692. case TypeTag.ObjectType:
  693. return typeof(object);
  694. case TypeTag.RuntimeType:
  695. {
  696. string name = reader.ReadString ();
  697. #if NET_2_0
  698. // map MS.NET's System.RuntimeType to System.MonoType
  699. if (_context.State == StreamingContextStates.Remoting)
  700. if (name == "System.RuntimeType")
  701. return typeof (MonoType);
  702. else if (name == "System.RuntimeType[]")
  703. return typeof (MonoType[]);
  704. #endif
  705. Type t = Type.GetType (name);
  706. if (t != null)
  707. return t;
  708. throw new SerializationException (String.Format ("Could not find type '{0}'.", name));
  709. }
  710. case TypeTag.GenericType:
  711. {
  712. string name = reader.ReadString ();
  713. long asmid = (long) reader.ReadUInt32();
  714. return GetDeserializationType (asmid, name);
  715. }
  716. case TypeTag.ArrayOfObject:
  717. return typeof(object[]);
  718. case TypeTag.ArrayOfString:
  719. return typeof(string[]);
  720. case TypeTag.ArrayOfPrimitiveType:
  721. Type elementType = BinaryCommon.GetTypeFromCode (reader.ReadByte());
  722. return Type.GetType(elementType.FullName + "[]");
  723. default:
  724. throw new NotSupportedException ("Unknow type tag");
  725. }
  726. }
  727. public static object ReadPrimitiveTypeValue (BinaryReader reader, Type type)
  728. {
  729. if (type == null) return null;
  730. switch (Type.GetTypeCode (type))
  731. {
  732. case TypeCode.Boolean:
  733. return reader.ReadBoolean();
  734. case TypeCode.Byte:
  735. return reader.ReadByte();
  736. case TypeCode.Char:
  737. return reader.ReadChar();
  738. case TypeCode.DateTime:
  739. return new DateTime (reader.ReadInt64());
  740. case TypeCode.Decimal:
  741. return Decimal.Parse (reader.ReadString(), CultureInfo.InvariantCulture);
  742. case TypeCode.Double:
  743. return reader.ReadDouble();
  744. case TypeCode.Int16:
  745. return reader.ReadInt16();
  746. case TypeCode.Int32:
  747. return reader.ReadInt32();
  748. case TypeCode.Int64:
  749. return reader.ReadInt64();
  750. case TypeCode.SByte:
  751. return reader.ReadSByte();
  752. case TypeCode.Single:
  753. return reader.ReadSingle();
  754. case TypeCode.UInt16:
  755. return reader.ReadUInt16();
  756. case TypeCode.UInt32:
  757. return reader.ReadUInt32();
  758. case TypeCode.UInt64:
  759. return reader.ReadUInt64();
  760. case TypeCode.String:
  761. return reader.ReadString();
  762. default:
  763. if (type == typeof(TimeSpan))
  764. return new TimeSpan (reader.ReadInt64 ());
  765. else
  766. throw new NotSupportedException ("Unsupported primitive type: " + type.FullName);
  767. }
  768. }
  769. }
  770. }