XmlObjectSerializerReadContextComplex.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Runtime.Serialization
  5. {
  6. using System;
  7. using System.Collections;
  8. using System.Diagnostics;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Xml;
  14. using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
  15. using System.Collections.Generic;
  16. using System.Runtime.Serialization.Diagnostics.Application;
  17. using System.Runtime.Serialization.Formatters;
  18. using System.Security;
  19. using System.Security.Permissions;
  20. using System.Runtime.CompilerServices;
  21. #if USE_REFEMIT
  22. public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
  23. #else
  24. internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext
  25. #endif
  26. {
  27. static Hashtable dataContractTypeCache = new Hashtable();
  28. bool preserveObjectReferences;
  29. protected IDataContractSurrogate dataContractSurrogate;
  30. SerializationMode mode;
  31. SerializationBinder binder;
  32. ISurrogateSelector surrogateSelector;
  33. FormatterAssemblyStyle assemblyFormat;
  34. Hashtable surrogateDataContracts;
  35. internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
  36. : base(serializer, rootTypeDataContract, dataContractResolver)
  37. {
  38. this.mode = SerializationMode.SharedContract;
  39. this.preserveObjectReferences = serializer.PreserveObjectReferences;
  40. this.dataContractSurrogate = serializer.DataContractSurrogate;
  41. }
  42. internal XmlObjectSerializerReadContextComplex(NetDataContractSerializer serializer)
  43. : base(serializer)
  44. {
  45. this.mode = SerializationMode.SharedType;
  46. this.preserveObjectReferences = true;
  47. this.binder = serializer.Binder;
  48. this.surrogateSelector = serializer.SurrogateSelector;
  49. this.assemblyFormat = serializer.AssemblyFormat;
  50. }
  51. internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
  52. : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
  53. {
  54. }
  55. internal override SerializationMode Mode
  56. {
  57. get { return mode; }
  58. }
  59. internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
  60. {
  61. DataContract dataContract = null;
  62. if (mode == SerializationMode.SharedType && surrogateSelector != null)
  63. {
  64. dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, null /*type*/, ref surrogateDataContracts);
  65. }
  66. if (dataContract != null)
  67. {
  68. if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract)
  69. {
  70. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
  71. DataContract.GetClrTypeFullName(dataContract.UnderlyingType))));
  72. }
  73. return dataContract;
  74. }
  75. return base.GetDataContract(id, typeHandle);
  76. }
  77. internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
  78. {
  79. DataContract dataContract = null;
  80. if (mode == SerializationMode.SharedType && surrogateSelector != null)
  81. {
  82. dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, GetStreamingContext(), typeHandle, type, ref surrogateDataContracts);
  83. }
  84. if (dataContract != null)
  85. {
  86. if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract)
  87. {
  88. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
  89. DataContract.GetClrTypeFullName(dataContract.UnderlyingType))));
  90. }
  91. return dataContract;
  92. }
  93. return base.GetDataContract(typeHandle, type);
  94. }
  95. public override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns)
  96. {
  97. if (mode == SerializationMode.SharedContract)
  98. {
  99. if (dataContractSurrogate == null)
  100. return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns);
  101. else
  102. return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns);
  103. }
  104. else
  105. {
  106. return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns);
  107. }
  108. }
  109. internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns)
  110. {
  111. if (mode == SerializationMode.SharedContract)
  112. {
  113. if (dataContractSurrogate == null)
  114. return base.InternalDeserialize(xmlReader, declaredType, name, ns);
  115. else
  116. return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns);
  117. }
  118. else
  119. {
  120. return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
  121. }
  122. }
  123. internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns)
  124. {
  125. if (mode == SerializationMode.SharedContract)
  126. {
  127. if (dataContractSurrogate == null)
  128. return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns);
  129. else
  130. return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns);
  131. }
  132. else
  133. {
  134. return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns);
  135. }
  136. }
  137. object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns)
  138. {
  139. object retObj = null;
  140. if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj))
  141. return retObj;
  142. DataContract dataContract;
  143. string assemblyName = attributes.ClrAssembly;
  144. string typeName = attributes.ClrType;
  145. if (assemblyName != null && typeName != null)
  146. {
  147. Assembly assembly;
  148. Type type;
  149. dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type);
  150. if (dataContract == null)
  151. {
  152. if (assembly == null)
  153. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.AssemblyNotFound, assemblyName)));
  154. if (type == null)
  155. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ClrTypeNotFound, assembly.FullName, typeName)));
  156. }
  157. //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array
  158. if (declaredType != null && declaredType.IsArray)
  159. dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
  160. }
  161. else
  162. {
  163. if (assemblyName != null)
  164. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
  165. else if (typeName != null)
  166. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
  167. else if (declaredType == null)
  168. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))));
  169. dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle);
  170. }
  171. return ReadDataContractValue(dataContract, xmlReader);
  172. }
  173. object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns)
  174. {
  175. if (TD.DCDeserializeWithSurrogateStartIsEnabled())
  176. {
  177. TD.DCDeserializeWithSurrogateStart(declaredType.FullName);
  178. }
  179. DataContract dataContract = surrogateDataContract ??
  180. GetDataContract(DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, declaredType));
  181. if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType)
  182. {
  183. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
  184. DataContract.GetClrTypeFullName(declaredType))));
  185. }
  186. ReadAttributes(xmlReader);
  187. string objectId = GetObjectId();
  188. object oldObj = InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract);
  189. object obj = DataContractSurrogateCaller.GetDeserializedObject(dataContractSurrogate, oldObj, dataContract.UnderlyingType, declaredType);
  190. ReplaceDeserializedObject(objectId, oldObj, obj);
  191. if (TD.DCDeserializeWithSurrogateStopIsEnabled())
  192. {
  193. TD.DCDeserializeWithSurrogateStop();
  194. }
  195. return obj;
  196. }
  197. Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly)
  198. {
  199. assembly = null;
  200. Type type = null;
  201. if (binder != null)
  202. type = binder.BindToType(assemblyName, typeName);
  203. if (type == null)
  204. {
  205. XmlObjectDataContractTypeKey key = new XmlObjectDataContractTypeKey(assemblyName, typeName);
  206. XmlObjectDataContractTypeInfo dataContractTypeInfo = (XmlObjectDataContractTypeInfo)dataContractTypeCache[key];
  207. if (dataContractTypeInfo == null)
  208. {
  209. if (assemblyFormat == FormatterAssemblyStyle.Full)
  210. {
  211. if (assemblyName == Globals.MscorlibAssemblyName)
  212. {
  213. assembly = Globals.TypeOfInt.Assembly;
  214. }
  215. else
  216. {
  217. assembly = Assembly.Load(assemblyName);
  218. }
  219. if (assembly != null)
  220. type = assembly.GetType(typeName);
  221. }
  222. else
  223. {
  224. assembly = XmlObjectSerializerReadContextComplex.ResolveSimpleAssemblyName(assemblyName);
  225. if (assembly != null)
  226. {
  227. // Catching any exceptions that could be thrown from a failure on assembly load
  228. // This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
  229. try
  230. {
  231. type = assembly.GetType(typeName);
  232. }
  233. catch (TypeLoadException) { }
  234. catch (FileNotFoundException) { }
  235. catch (FileLoadException) { }
  236. catch (BadImageFormatException) { }
  237. if (type == null)
  238. {
  239. type = Type.GetType(typeName, XmlObjectSerializerReadContextComplex.ResolveSimpleAssemblyName, new TopLevelAssemblyTypeResolver(assembly).ResolveType, false /* throwOnError */);
  240. }
  241. }
  242. }
  243. if (type != null)
  244. {
  245. CheckTypeForwardedTo(assembly, type.Assembly, type);
  246. dataContractTypeInfo = new XmlObjectDataContractTypeInfo(assembly, type);
  247. lock (dataContractTypeCache)
  248. {
  249. if (!dataContractTypeCache.ContainsKey(key))
  250. {
  251. dataContractTypeCache[key] = dataContractTypeInfo;
  252. }
  253. }
  254. }
  255. }
  256. else
  257. {
  258. assembly = dataContractTypeInfo.Assembly;
  259. type = dataContractTypeInfo.Type;
  260. }
  261. }
  262. return type;
  263. }
  264. DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type)
  265. {
  266. type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly);
  267. if (type != null)
  268. {
  269. return GetDataContract(type);
  270. }
  271. return null;
  272. }
  273. protected override DataContract ResolveDataContractFromTypeName()
  274. {
  275. if (mode == SerializationMode.SharedContract)
  276. {
  277. return base.ResolveDataContractFromTypeName();
  278. }
  279. else
  280. {
  281. if (attributes.ClrAssembly != null && attributes.ClrType != null)
  282. {
  283. Assembly assembly;
  284. Type type;
  285. return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type);
  286. }
  287. }
  288. return null;
  289. }
  290. [Fx.Tag.SecurityNote(Critical = "Calls the critical methods of ISurrogateSelector", Safe = "Demands for FullTrust")]
  291. [SecuritySafeCritical]
  292. [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
  293. [MethodImpl(MethodImplOptions.NoInlining)]
  294. bool CheckIfTypeSerializableForSharedTypeMode(Type memberType)
  295. {
  296. Fx.Assert(surrogateSelector != null, "Method should not be called when surrogateSelector is null.");
  297. ISurrogateSelector surrogateSelectorNotUsed;
  298. return (surrogateSelector.GetSurrogate(memberType, GetStreamingContext(), out surrogateSelectorNotUsed) != null);
  299. }
  300. internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable)
  301. {
  302. if (mode == SerializationMode.SharedType && surrogateSelector != null &&
  303. CheckIfTypeSerializableForSharedTypeMode(memberType))
  304. {
  305. return;
  306. }
  307. else
  308. {
  309. if (dataContractSurrogate != null)
  310. {
  311. while (memberType.IsArray)
  312. memberType = memberType.GetElementType();
  313. memberType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType);
  314. if (!DataContract.IsTypeSerializable(memberType))
  315. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TypeNotSerializable, memberType)));
  316. return;
  317. }
  318. }
  319. base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
  320. }
  321. internal override Type GetSurrogatedType(Type type)
  322. {
  323. if (dataContractSurrogate == null)
  324. {
  325. return base.GetSurrogatedType(type);
  326. }
  327. else
  328. {
  329. type = DataContract.UnwrapNullableType(type);
  330. Type surrogateType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type);
  331. if (this.IsGetOnlyCollection && surrogateType != type)
  332. {
  333. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser,
  334. DataContract.GetClrTypeFullName(type))));
  335. }
  336. else
  337. {
  338. return surrogateType;
  339. }
  340. }
  341. }
  342. #if USE_REFEMIT
  343. public override int GetArraySize()
  344. #else
  345. internal override int GetArraySize()
  346. #endif
  347. {
  348. return preserveObjectReferences ? attributes.ArraySZSize : -1;
  349. }
  350. static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName)
  351. {
  352. return ResolveSimpleAssemblyName(assemblyName.FullName);
  353. }
  354. static Assembly ResolveSimpleAssemblyName(string assemblyName)
  355. {
  356. Assembly assembly;
  357. if (assemblyName == Globals.MscorlibAssemblyName)
  358. {
  359. assembly = Globals.TypeOfInt.Assembly;
  360. }
  361. else
  362. {
  363. assembly = Assembly.LoadWithPartialName(assemblyName);
  364. if (assembly == null)
  365. {
  366. AssemblyName an = new AssemblyName(assemblyName);
  367. an.Version = null;
  368. assembly = Assembly.LoadWithPartialName(an.FullName);
  369. }
  370. }
  371. return assembly;
  372. }
  373. [Fx.Tag.SecurityNote(Critical = "Gets the SecurityCritical PermissionSet for sourceAssembly and destinationAssembly.",
  374. Safe = "Doesn't leak anything.")]
  375. [SecuritySafeCritical]
  376. static void CheckTypeForwardedTo(Assembly sourceAssembly, Assembly destinationAssembly, Type resolvedType)
  377. {
  378. if (sourceAssembly != destinationAssembly && !NetDataContractSerializer.UnsafeTypeForwardingEnabled && !sourceAssembly.IsFullyTrusted)
  379. {
  380. #if !NO_DESKTOP_SECURITY
  381. // We have a TypeForwardedTo attribute
  382. if (!destinationAssembly.PermissionSet.IsSubsetOf(sourceAssembly.PermissionSet))
  383. {
  384. // We look for a matching TypeForwardedFrom attribute
  385. TypeInformation typeInfo = NetDataContractSerializer.GetTypeInformation(resolvedType);
  386. if (typeInfo.HasTypeForwardedFrom)
  387. {
  388. Assembly typeForwardedFromAssembly = null;
  389. try
  390. {
  391. // if this Assembly.Load fails, we still want to throw security exception
  392. typeForwardedFromAssembly = Assembly.Load(typeInfo.AssemblyString);
  393. }
  394. catch { }
  395. if (typeForwardedFromAssembly == sourceAssembly)
  396. {
  397. return;
  398. }
  399. }
  400. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.CannotDeserializeForwardedType, DataContract.GetClrTypeFullName(resolvedType))));
  401. }
  402. #endif
  403. }
  404. }
  405. sealed class TopLevelAssemblyTypeResolver
  406. {
  407. Assembly topLevelAssembly;
  408. public TopLevelAssemblyTypeResolver(Assembly topLevelAssembly)
  409. {
  410. this.topLevelAssembly = topLevelAssembly;
  411. }
  412. public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase)
  413. {
  414. if (assembly == null)
  415. assembly = topLevelAssembly;
  416. return assembly.GetType(simpleTypeName, false, ignoreCase);
  417. }
  418. }
  419. class XmlObjectDataContractTypeInfo
  420. {
  421. Assembly assembly;
  422. Type type;
  423. public XmlObjectDataContractTypeInfo(Assembly assembly, Type type)
  424. {
  425. this.assembly = assembly;
  426. this.type = type;
  427. }
  428. public Assembly Assembly
  429. {
  430. get
  431. {
  432. return this.assembly;
  433. }
  434. }
  435. public Type Type
  436. {
  437. get
  438. {
  439. return this.type;
  440. }
  441. }
  442. }
  443. class XmlObjectDataContractTypeKey
  444. {
  445. string assemblyName;
  446. string typeName;
  447. public XmlObjectDataContractTypeKey(string assemblyName, string typeName)
  448. {
  449. this.assemblyName = assemblyName;
  450. this.typeName = typeName;
  451. }
  452. public override bool Equals(object obj)
  453. {
  454. if (object.ReferenceEquals(this, obj))
  455. return true;
  456. XmlObjectDataContractTypeKey other = obj as XmlObjectDataContractTypeKey;
  457. if (other == null)
  458. return false;
  459. if (this.assemblyName != other.assemblyName)
  460. return false;
  461. if (this.typeName != other.typeName)
  462. return false;
  463. return true;
  464. }
  465. public override int GetHashCode()
  466. {
  467. int hashCode = 0;
  468. if (this.assemblyName != null)
  469. hashCode = this.assemblyName.GetHashCode();
  470. if (this.typeName != null)
  471. hashCode ^= this.typeName.GetHashCode();
  472. return hashCode;
  473. }
  474. }
  475. }
  476. }