XmlDataContract.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.Runtime.Serialization
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Reflection;
  9. using System.Security;
  10. using System.Security.Permissions;
  11. using System.Threading;
  12. using System.Xml;
  13. using System.Xml.Schema;
  14. using System.Xml.Serialization;
  15. using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
  16. internal delegate IXmlSerializable CreateXmlSerializableDelegate();
  17. #if USE_REFEMIT
  18. public sealed class XmlDataContract : DataContract
  19. #else
  20. internal sealed partial class XmlDataContract : DataContract
  21. #endif
  22. {
  23. [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
  24. + " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
  25. [SecurityCritical]
  26. XmlDataContractCriticalHelper helper;
  27. [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
  28. Safe = "Doesn't leak anything.")]
  29. [SecuritySafeCritical]
  30. internal XmlDataContract()
  31. : base(new XmlDataContractCriticalHelper())
  32. {
  33. helper = base.Helper as XmlDataContractCriticalHelper;
  34. }
  35. [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
  36. Safe = "Doesn't leak anything.")]
  37. [SecuritySafeCritical]
  38. internal XmlDataContract(Type type)
  39. : base(new XmlDataContractCriticalHelper(type))
  40. {
  41. helper = base.Helper as XmlDataContractCriticalHelper;
  42. }
  43. internal override DataContractDictionary KnownDataContracts
  44. {
  45. [Fx.Tag.SecurityNote(Critical = "Fetches the critical KnownDataContracts property.",
  46. Safe = "KnownDataContracts only needs to be protected for write.")]
  47. [SecuritySafeCritical]
  48. get { return helper.KnownDataContracts; }
  49. [Fx.Tag.SecurityNote(Critical = "Sets the critical KnownDataContracts property.")]
  50. [SecurityCritical]
  51. set { helper.KnownDataContracts = value; }
  52. }
  53. internal XmlSchemaType XsdType
  54. {
  55. [Fx.Tag.SecurityNote(Critical = "Fetches the critical XsdType property.",
  56. Safe = "XsdType only needs to be protected for write.")]
  57. [SecuritySafeCritical]
  58. get { return helper.XsdType; }
  59. [Fx.Tag.SecurityNote(Critical = "Sets the critical XsdType property.")]
  60. [SecurityCritical]
  61. set { helper.XsdType = value; }
  62. }
  63. internal bool IsAnonymous
  64. {
  65. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsAnonymous property.",
  66. Safe = "IsAnonymous only needs to be protected for write.")]
  67. [SecuritySafeCritical]
  68. get { return helper.IsAnonymous; }
  69. }
  70. internal override bool HasRoot
  71. {
  72. [Fx.Tag.SecurityNote(Critical = "Fetches the critical HasRoot property.",
  73. Safe = "HasRoot only needs to be protected for write.")]
  74. [SecuritySafeCritical]
  75. get { return helper.HasRoot; }
  76. [Fx.Tag.SecurityNote(Critical = "Sets the critical HasRoot property.")]
  77. [SecurityCritical]
  78. set { helper.HasRoot = value; }
  79. }
  80. internal override XmlDictionaryString TopLevelElementName
  81. {
  82. [Fx.Tag.SecurityNote(Critical = "Fetches the critical TopLevelElementName property.",
  83. Safe = "TopLevelElementName only needs to be protected for write.")]
  84. [SecuritySafeCritical]
  85. get { return helper.TopLevelElementName; }
  86. [Fx.Tag.SecurityNote(Critical = "Sets the critical TopLevelElementName property.")]
  87. [SecurityCritical]
  88. set { helper.TopLevelElementName = value; }
  89. }
  90. internal override XmlDictionaryString TopLevelElementNamespace
  91. {
  92. [Fx.Tag.SecurityNote(Critical = "Fetches the critical TopLevelElementNamespace property.",
  93. Safe = "TopLevelElementNamespace only needs to be protected for write.")]
  94. [SecuritySafeCritical]
  95. get { return helper.TopLevelElementNamespace; }
  96. [Fx.Tag.SecurityNote(Critical = "Sets the critical TopLevelElementNamespace property.")]
  97. [SecurityCritical]
  98. set { helper.TopLevelElementNamespace = value; }
  99. }
  100. internal bool IsTopLevelElementNullable
  101. {
  102. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsTopLevelElementNullable property.",
  103. Safe = "IsTopLevelElementNullable only needs to be protected for write.")]
  104. [SecuritySafeCritical]
  105. get { return helper.IsTopLevelElementNullable; }
  106. [Fx.Tag.SecurityNote(Critical = "Sets the critical IsTopLevelElementNullable property.")]
  107. [SecurityCritical]
  108. set { helper.IsTopLevelElementNullable = value; }
  109. }
  110. internal bool IsTypeDefinedOnImport
  111. {
  112. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsTypeDefinedOnImport property.",
  113. Safe = "IsTypeDefinedOnImport only needs to be protected for write.")]
  114. [SecuritySafeCritical]
  115. get { return helper.IsTypeDefinedOnImport; }
  116. [Fx.Tag.SecurityNote(Critical = "Sets the critical IsTypeDefinedOnImport property.")]
  117. [SecurityCritical]
  118. set { helper.IsTypeDefinedOnImport = value; }
  119. }
  120. internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
  121. {
  122. [Fx.Tag.SecurityNote(Critical = "Fetches the critical CreateXmlSerializableDelegate property.",
  123. Safe = "CreateXmlSerializableDelegate only needs to be protected for write; initialized in getter if null.")]
  124. [SecuritySafeCritical]
  125. get
  126. {
  127. if (helper.CreateXmlSerializableDelegate == null)
  128. {
  129. lock (this)
  130. {
  131. if (helper.CreateXmlSerializableDelegate == null)
  132. {
  133. CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate();
  134. Thread.MemoryBarrier();
  135. helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable;
  136. }
  137. }
  138. }
  139. return helper.CreateXmlSerializableDelegate;
  140. }
  141. }
  142. internal override bool CanContainReferences
  143. {
  144. get { return false; }
  145. }
  146. internal override bool IsBuiltInDataContract
  147. {
  148. get
  149. {
  150. return UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray;
  151. }
  152. }
  153. [Fx.Tag.SecurityNote(Critical = "Holds all state used for for (de)serializing XML types."
  154. + " Since the data is cached statically, we lock down access to it.")]
  155. #if !NO_SECURITY_ATTRIBUTES
  156. [SecurityCritical(SecurityCriticalScope.Everything)]
  157. #endif
  158. class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper
  159. {
  160. DataContractDictionary knownDataContracts;
  161. bool isKnownTypeAttributeChecked;
  162. XmlDictionaryString topLevelElementName;
  163. XmlDictionaryString topLevelElementNamespace;
  164. bool isTopLevelElementNullable;
  165. bool isTypeDefinedOnImport;
  166. XmlSchemaType xsdType;
  167. bool hasRoot;
  168. CreateXmlSerializableDelegate createXmlSerializable;
  169. internal XmlDataContractCriticalHelper()
  170. {
  171. }
  172. internal XmlDataContractCriticalHelper(Type type)
  173. : base(type)
  174. {
  175. if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))
  176. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type))));
  177. if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
  178. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type))));
  179. XmlSchemaType xsdType;
  180. bool hasRoot;
  181. XmlQualifiedName stableName;
  182. SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot);
  183. this.StableName = stableName;
  184. this.XsdType = xsdType;
  185. this.HasRoot = hasRoot;
  186. XmlDictionary dictionary = new XmlDictionary();
  187. this.Name = dictionary.Add(StableName.Name);
  188. this.Namespace = dictionary.Add(StableName.Namespace);
  189. object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false);
  190. if (xmlRootAttributes == null || xmlRootAttributes.Length == 0)
  191. {
  192. if (hasRoot)
  193. {
  194. topLevelElementName = Name;
  195. topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace;
  196. isTopLevelElementNullable = true;
  197. }
  198. }
  199. else
  200. {
  201. if (hasRoot)
  202. {
  203. XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0];
  204. isTopLevelElementNullable = xmlRootAttribute.IsNullable;
  205. string elementName = xmlRootAttribute.ElementName;
  206. topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName));
  207. string elementNs = xmlRootAttribute.Namespace;
  208. topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs);
  209. }
  210. else
  211. {
  212. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType))));
  213. }
  214. }
  215. }
  216. internal override DataContractDictionary KnownDataContracts
  217. {
  218. get
  219. {
  220. if (!isKnownTypeAttributeChecked && UnderlyingType != null)
  221. {
  222. lock (this)
  223. {
  224. if (!isKnownTypeAttributeChecked)
  225. {
  226. knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
  227. Thread.MemoryBarrier();
  228. isKnownTypeAttributeChecked = true;
  229. }
  230. }
  231. }
  232. return knownDataContracts;
  233. }
  234. set { knownDataContracts = value; }
  235. }
  236. internal XmlSchemaType XsdType
  237. {
  238. get { return xsdType; }
  239. set { xsdType = value; }
  240. }
  241. internal bool IsAnonymous
  242. {
  243. get { return xsdType != null; }
  244. }
  245. internal override bool HasRoot
  246. {
  247. get { return hasRoot; }
  248. set { hasRoot = value; }
  249. }
  250. internal override XmlDictionaryString TopLevelElementName
  251. {
  252. get { return topLevelElementName; }
  253. set { topLevelElementName = value; }
  254. }
  255. internal override XmlDictionaryString TopLevelElementNamespace
  256. {
  257. get { return topLevelElementNamespace; }
  258. set { topLevelElementNamespace = value; }
  259. }
  260. internal bool IsTopLevelElementNullable
  261. {
  262. get { return isTopLevelElementNullable; }
  263. set { isTopLevelElementNullable = value; }
  264. }
  265. internal bool IsTypeDefinedOnImport
  266. {
  267. get { return isTypeDefinedOnImport; }
  268. set { isTypeDefinedOnImport = value; }
  269. }
  270. internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate
  271. {
  272. get { return createXmlSerializable; }
  273. set { createXmlSerializable = value; }
  274. }
  275. }
  276. ConstructorInfo GetConstructor()
  277. {
  278. Type type = UnderlyingType;
  279. if (type.IsValueType)
  280. return null;
  281. ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
  282. if (ctor == null)
  283. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));
  284. return ctor;
  285. }
  286. [Fx.Tag.SecurityNote(Critical = "Sets critical properties on XmlDataContract.")]
  287. [SecurityCritical]
  288. internal void SetTopLevelElementName(XmlQualifiedName elementName)
  289. {
  290. if (elementName != null)
  291. {
  292. XmlDictionary dictionary = new XmlDictionary();
  293. this.TopLevelElementName = dictionary.Add(elementName.Name);
  294. this.TopLevelElementNamespace = dictionary.Add(elementName.Namespace);
  295. }
  296. }
  297. #if !NO_DYNAMIC_CODEGEN
  298. [Fx.Tag.SecurityNote(Critical = "Calls CodeGenerator.BeginMethod which is SecurityCritical.",
  299. Safe = "Self-contained: returns the delegate to the generated IL but otherwise all IL generation is self-contained here.")]
  300. [SecuritySafeCritical]
  301. internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate()
  302. {
  303. Type type = this.UnderlyingType;
  304. CodeGenerator ilg = new CodeGenerator();
  305. bool memberAccessFlag = RequiresMemberAccessForCreate(null);
  306. try
  307. {
  308. ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag);
  309. }
  310. catch (SecurityException securityException)
  311. {
  312. if (memberAccessFlag && securityException.PermissionType.Equals(typeof(ReflectionPermission)))
  313. {
  314. RequiresMemberAccessForCreate(securityException);
  315. }
  316. else
  317. {
  318. throw;
  319. }
  320. }
  321. if (type.IsValueType)
  322. {
  323. System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value");
  324. ilg.Ldloca(local);
  325. ilg.InitObj(type);
  326. ilg.Ldloc(local);
  327. }
  328. else
  329. {
  330. ilg.New(GetConstructor());
  331. }
  332. ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable);
  333. ilg.Ret();
  334. return (CreateXmlSerializableDelegate)ilg.EndMethod();
  335. }
  336. #endif
  337. #if !NO_DYNAMIC_CODEGEN
  338. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Calculates whether this Xml type requires MemberAccessPermission for deserialization."
  339. + " Since this information is used to determine whether to give the generated code access"
  340. + " permissions to private members, any changes to the logic should be reviewed.")]
  341. bool RequiresMemberAccessForCreate(SecurityException securityException)
  342. {
  343. if (!IsTypeVisible(UnderlyingType))
  344. {
  345. if (securityException != null)
  346. {
  347. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  348. new SecurityException(SR.GetString(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)),
  349. securityException));
  350. }
  351. return true;
  352. }
  353. if (ConstructorRequiresMemberAccess(GetConstructor()))
  354. {
  355. if (securityException != null)
  356. {
  357. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  358. new SecurityException(SR.GetString(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)),
  359. securityException));
  360. }
  361. return true;
  362. }
  363. return false;
  364. }
  365. #endif
  366. internal override bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
  367. {
  368. if (IsEqualOrChecked(other, checkedContracts))
  369. return true;
  370. XmlDataContract dataContract = other as XmlDataContract;
  371. if (dataContract != null)
  372. {
  373. if (this.HasRoot != dataContract.HasRoot)
  374. return false;
  375. if (this.IsAnonymous)
  376. {
  377. return dataContract.IsAnonymous;
  378. }
  379. else
  380. {
  381. return (StableName.Name == dataContract.StableName.Name && StableName.Namespace == dataContract.StableName.Namespace);
  382. }
  383. }
  384. return false;
  385. }
  386. public override int GetHashCode()
  387. {
  388. return base.GetHashCode();
  389. }
  390. public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
  391. {
  392. if (context == null)
  393. XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj);
  394. else
  395. context.WriteIXmlSerializable(xmlWriter, obj);
  396. }
  397. public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
  398. {
  399. object o;
  400. if (context == null)
  401. {
  402. o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/);
  403. }
  404. else
  405. {
  406. o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/);
  407. context.AddNewObject(o);
  408. }
  409. xmlReader.ReadEndElement();
  410. return o;
  411. }
  412. }
  413. }