DataContract.cs 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.Runtime.Serialization
  5. {
  6. using System;
  7. using System.CodeDom;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Diagnostics.CodeAnalysis;
  11. using System.Globalization;
  12. using System.Reflection;
  13. using System.Runtime.CompilerServices;
  14. #if !NO_CONFIGURATION
  15. using System.Runtime.Serialization.Configuration;
  16. #endif
  17. using System.Runtime.Serialization.Diagnostics.Application;
  18. using System.Security;
  19. using System.Text;
  20. using System.Xml;
  21. using System.Xml.Schema;
  22. using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
  23. using System.Text.RegularExpressions;
  24. #if USE_REFEMIT
  25. public abstract class DataContract
  26. #else
  27. internal abstract class DataContract
  28. #endif
  29. {
  30. [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the type name. Statically cached and used from IL generated code.")]
  31. [SecurityCritical]
  32. XmlDictionaryString name;
  33. [Fx.Tag.SecurityNote(Critical = "XmlDictionaryString representing the type name. Statically cached and used from IL generated code.")]
  34. [SecurityCritical]
  35. XmlDictionaryString ns;
  36. [Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
  37. + " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
  38. [SecurityCritical]
  39. DataContractCriticalHelper helper;
  40. [Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
  41. Safe = "Doesn't leak anything.")]
  42. [SecuritySafeCritical]
  43. protected DataContract(DataContractCriticalHelper helper)
  44. {
  45. this.helper = helper;
  46. this.name = helper.Name;
  47. this.ns = helper.Namespace;
  48. }
  49. internal static DataContract GetDataContract(Type type)
  50. {
  51. return GetDataContract(type.TypeHandle, type, SerializationMode.SharedContract);
  52. }
  53. internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
  54. {
  55. int id = GetId(typeHandle);
  56. return GetDataContract(id, typeHandle, mode);
  57. }
  58. internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle, SerializationMode mode)
  59. {
  60. DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null);
  61. dataContract = dataContract.GetValidContract(mode);
  62. return dataContract;
  63. }
  64. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
  65. Safe = "Read only access.")]
  66. [SecuritySafeCritical]
  67. internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
  68. {
  69. return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type);
  70. }
  71. internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type, SerializationMode mode)
  72. {
  73. DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
  74. dataContract = dataContract.GetValidContract(mode);
  75. if (dataContract is ClassDataContract)
  76. {
  77. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.ClassDataContractReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(dataContract.UnderlyingType))));
  78. }
  79. return dataContract;
  80. }
  81. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
  82. Safe = "Read only access.")]
  83. [SecuritySafeCritical]
  84. internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
  85. {
  86. return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type);
  87. }
  88. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract .",
  89. Safe = "Read only access; doesn't modify any static information.")]
  90. [SecuritySafeCritical]
  91. internal static DataContract GetDataContractForInitialization(int id)
  92. {
  93. return DataContractCriticalHelper.GetDataContractForInitialization(id);
  94. }
  95. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up id for DataContract .",
  96. Safe = "Read only access; doesn't modify any static information.")]
  97. [SecuritySafeCritical]
  98. internal static int GetIdForInitialization(ClassDataContract classContract)
  99. {
  100. return DataContractCriticalHelper.GetIdForInitialization(classContract);
  101. }
  102. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up id assigned to a particular type.",
  103. Safe = "Read only access.")]
  104. [SecuritySafeCritical]
  105. internal static int GetId(RuntimeTypeHandle typeHandle)
  106. {
  107. return DataContractCriticalHelper.GetId(typeHandle);
  108. }
  109. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
  110. Safe = "Read only access.")]
  111. [SecuritySafeCritical]
  112. public static DataContract GetBuiltInDataContract(Type type)
  113. {
  114. return DataContractCriticalHelper.GetBuiltInDataContract(type);
  115. }
  116. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
  117. Safe = "Read only access.")]
  118. [SecuritySafeCritical]
  119. public static DataContract GetBuiltInDataContract(string name, string ns)
  120. {
  121. return DataContractCriticalHelper.GetBuiltInDataContract(name, ns);
  122. }
  123. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up DataContract.",
  124. Safe = "Read only access.")]
  125. [SecuritySafeCritical]
  126. public static DataContract GetBuiltInDataContract(string typeName)
  127. {
  128. return DataContractCriticalHelper.GetBuiltInDataContract(typeName);
  129. }
  130. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up string reference to use for a namespace string.",
  131. Safe = "Read only access.")]
  132. [SecuritySafeCritical]
  133. internal static string GetNamespace(string key)
  134. {
  135. return DataContractCriticalHelper.GetNamespace(key);
  136. }
  137. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to look up XmlDictionaryString for a string.",
  138. Safe = "Read only access.")]
  139. [SecuritySafeCritical]
  140. internal static XmlDictionaryString GetClrTypeString(string key)
  141. {
  142. return DataContractCriticalHelper.GetClrTypeString(key);
  143. }
  144. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical static cache to remove invalid DataContract if it has been added to cache.",
  145. Safe = "Doesn't leak any information.")]
  146. [SecuritySafeCritical]
  147. internal static void ThrowInvalidDataContractException(string message, Type type)
  148. {
  149. DataContractCriticalHelper.ThrowInvalidDataContractException(message, type);
  150. }
  151. #if USE_REFEMIT
  152. internal DataContractCriticalHelper Helper
  153. #else
  154. protected DataContractCriticalHelper Helper
  155. #endif
  156. {
  157. [Fx.Tag.SecurityNote(Critical = "holds instance of CriticalHelper which keeps state that is cached statically for serialization."
  158. + " Static fields are marked SecurityCritical or readonly to prevent"
  159. + " data from being modified or leaked to other components in appdomain.")]
  160. [SecurityCritical]
  161. get { return helper; }
  162. }
  163. internal Type UnderlyingType
  164. {
  165. [Fx.Tag.SecurityNote(Critical = "Fetches the critical UnderlyingType field.",
  166. Safe = "Get-only properties only needs to be protected for write.")]
  167. [SecuritySafeCritical]
  168. get { return helper.UnderlyingType; }
  169. }
  170. internal Type OriginalUnderlyingType
  171. {
  172. [Fx.Tag.SecurityNote(Critical = "Fetches the critical OriginalUnderlyingType property.",
  173. Safe = "OrginalUnderlyingType only needs to be protected for write.")]
  174. [SecuritySafeCritical]
  175. get { return helper.OriginalUnderlyingType; }
  176. }
  177. internal virtual bool IsBuiltInDataContract
  178. {
  179. [Fx.Tag.SecurityNote(Critical = "Fetches the critical isBuiltInDataContract property.",
  180. Safe = "isBuiltInDataContract only needs to be protected for write.")]
  181. [SecuritySafeCritical]
  182. get { return helper.IsBuiltInDataContract; }
  183. }
  184. internal Type TypeForInitialization
  185. {
  186. [Fx.Tag.SecurityNote(Critical = "Fetches the critical typeForInitialization property.",
  187. Safe = "typeForInitialization only needs to be protected for write.")]
  188. [SecuritySafeCritical]
  189. get { return helper.TypeForInitialization; }
  190. }
  191. public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
  192. {
  193. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
  194. }
  195. public virtual object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
  196. {
  197. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));
  198. }
  199. internal bool IsValueType
  200. {
  201. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsValueType property.",
  202. Safe = "IsValueType only needs to be protected for write.")]
  203. [SecuritySafeCritical]
  204. get { return helper.IsValueType; }
  205. [Fx.Tag.SecurityNote(Critical = "Sets the critical IsValueType property.")]
  206. [SecurityCritical]
  207. set { helper.IsValueType = value; }
  208. }
  209. internal bool IsReference
  210. {
  211. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsReference property.",
  212. Safe = "IsReference only needs to be protected for write.")]
  213. [SecuritySafeCritical]
  214. get { return helper.IsReference; }
  215. [Fx.Tag.SecurityNote(Critical = "Sets the critical IsReference property.")]
  216. [SecurityCritical]
  217. set { helper.IsReference = value; }
  218. }
  219. internal XmlQualifiedName StableName
  220. {
  221. [Fx.Tag.SecurityNote(Critical = "Fetches the critical StableName property.",
  222. Safe = "StableName only needs to be protected for write.")]
  223. [SecuritySafeCritical]
  224. get { return helper.StableName; }
  225. [Fx.Tag.SecurityNote(Critical = "Sets the critical StableName property.")]
  226. [SecurityCritical]
  227. set { helper.StableName = value; }
  228. }
  229. internal GenericInfo GenericInfo
  230. {
  231. [Fx.Tag.SecurityNote(Critical = "Fetches the critical GenericInfo property.",
  232. Safe = "GenericInfo only needs to be protected for write.")]
  233. [SecuritySafeCritical]
  234. get { return helper.GenericInfo; }
  235. [Fx.Tag.SecurityNote(Critical = "Sets the critical GenericInfo property.",
  236. Safe = "Protected for write if contract has underlyingType .")]
  237. [SecurityCritical]
  238. set { helper.GenericInfo = value; }
  239. }
  240. internal virtual DataContractDictionary KnownDataContracts
  241. {
  242. [Fx.Tag.SecurityNote(Critical = "Fetches the critical KnownDataContracts property.",
  243. Safe = "KnownDataContracts only needs to be protected for write.")]
  244. [SecuritySafeCritical]
  245. get { return helper.KnownDataContracts; }
  246. [Fx.Tag.SecurityNote(Critical = "Sets the critical KnownDataContracts property.")]
  247. [SecurityCritical]
  248. set { helper.KnownDataContracts = value; }
  249. }
  250. internal virtual bool IsISerializable
  251. {
  252. [Fx.Tag.SecurityNote(Critical = "Fetches the critical IsISerializable property.",
  253. Safe = "IsISerializable only needs to be protected for write.")]
  254. [SecuritySafeCritical]
  255. get { return helper.IsISerializable; }
  256. [Fx.Tag.SecurityNote(Critical = "Sets the critical IsISerializable property.")]
  257. [SecurityCritical]
  258. set { helper.IsISerializable = value; }
  259. }
  260. internal XmlDictionaryString Name
  261. {
  262. [Fx.Tag.SecurityNote(Critical = "Fetches the critical Name property.",
  263. Safe = "Name only needs to be protected for write.")]
  264. [SecuritySafeCritical]
  265. get { return this.name; }
  266. }
  267. public virtual XmlDictionaryString Namespace
  268. {
  269. [Fx.Tag.SecurityNote(Critical = "Fetches the critical Namespace property.",
  270. Safe = "Namespace only needs to be protected for write.")]
  271. [SecuritySafeCritical]
  272. get { return this.ns; }
  273. }
  274. internal virtual bool HasRoot
  275. {
  276. get { return true; }
  277. set { }
  278. }
  279. internal virtual XmlDictionaryString TopLevelElementName
  280. {
  281. [Fx.Tag.SecurityNote(Critical = "Fetches the critical Name property.",
  282. Safe = "Name only needs to be protected for write.")]
  283. [SecuritySafeCritical]
  284. get { return helper.TopLevelElementName; }
  285. [Fx.Tag.SecurityNote(Critical = "Sets the critical Name property.")]
  286. [SecurityCritical]
  287. set { helper.TopLevelElementName = value; }
  288. }
  289. internal virtual XmlDictionaryString TopLevelElementNamespace
  290. {
  291. [Fx.Tag.SecurityNote(Critical = "Fetches the critical Namespace property.",
  292. Safe = "Namespace only needs to be protected for write.")]
  293. [SecuritySafeCritical]
  294. get { return helper.TopLevelElementNamespace; }
  295. [Fx.Tag.SecurityNote(Critical = "Sets the critical Namespace property.")]
  296. [SecurityCritical]
  297. set { helper.TopLevelElementNamespace = value; }
  298. }
  299. internal virtual bool CanContainReferences
  300. {
  301. get { return true; }
  302. }
  303. internal virtual bool IsPrimitive
  304. {
  305. get { return false; }
  306. }
  307. internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
  308. {
  309. if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive)
  310. writer.WriteStartElement(Globals.SerPrefix, name, ns);
  311. else
  312. writer.WriteStartElement(name, ns);
  313. }
  314. internal virtual DataContract BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts)
  315. {
  316. return this;
  317. }
  318. internal virtual DataContract GetValidContract(SerializationMode mode)
  319. {
  320. return this;
  321. }
  322. internal virtual DataContract GetValidContract()
  323. {
  324. return this;
  325. }
  326. internal virtual bool IsValidContract(SerializationMode mode)
  327. {
  328. return true;
  329. }
  330. internal MethodInfo ParseMethod
  331. {
  332. [Fx.Tag.SecurityNote(Critical = "Fetches the critical ParseMethod field.",
  333. Safe = "Get-only properties only needs to be protected for write.")]
  334. [SecuritySafeCritical]
  335. get { return helper.ParseMethod; }
  336. }
  337. [Fx.Tag.SecurityNote(Critical = "Holds all state used for (de)serializing types."
  338. + " Since the data is cached statically, we lock down access to it.")]
  339. #if !NO_SECURITY_ATTRIBUTES
  340. [SecurityCritical(SecurityCriticalScope.Everything)]
  341. #endif
  342. #if USE_REFEMIT
  343. public class DataContractCriticalHelper
  344. #else
  345. protected class DataContractCriticalHelper
  346. #endif
  347. {
  348. static Dictionary<TypeHandleRef, IntRef> typeToIDCache;
  349. static DataContract[] dataContractCache;
  350. static int dataContractID;
  351. static Dictionary<Type, DataContract> typeToBuiltInContract;
  352. static Dictionary<XmlQualifiedName, DataContract> nameToBuiltInContract;
  353. static Dictionary<string, DataContract> typeNameToBuiltInContract;
  354. static Dictionary<string, string> namespaces;
  355. static Dictionary<string, XmlDictionaryString> clrTypeStrings;
  356. static XmlDictionary clrTypeStringsDictionary;
  357. static TypeHandleRef typeHandleRef = new TypeHandleRef();
  358. static object cacheLock = new object();
  359. static object createDataContractLock = new object();
  360. static object initBuiltInContractsLock = new object();
  361. static object namespacesLock = new object();
  362. static object clrTypeStringsLock = new object();
  363. readonly Type underlyingType;
  364. Type originalUnderlyingType;
  365. bool isReference;
  366. bool isValueType;
  367. XmlQualifiedName stableName;
  368. GenericInfo genericInfo;
  369. XmlDictionaryString name;
  370. XmlDictionaryString ns;
  371. [Fx.Tag.SecurityNote(Critical = "In deserialization, we initialize an object instance passing this Type to GetUninitializedObject method.")]
  372. Type typeForInitialization;
  373. MethodInfo parseMethod;
  374. bool parseMethodSet;
  375. static DataContractCriticalHelper()
  376. {
  377. typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer());
  378. dataContractCache = new DataContract[32];
  379. dataContractID = 0;
  380. }
  381. internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
  382. {
  383. DataContract dataContract = dataContractCache[id];
  384. if (dataContract == null)
  385. {
  386. dataContract = CreateDataContract(id, typeHandle, type);
  387. }
  388. else
  389. {
  390. return dataContract.GetValidContract();
  391. }
  392. return dataContract;
  393. }
  394. internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type)
  395. {
  396. DataContract dataContract = dataContractCache[id];
  397. if (dataContract == null)
  398. {
  399. dataContract = CreateGetOnlyCollectionDataContract(id, typeHandle, type);
  400. dataContractCache[id] = dataContract;
  401. }
  402. return dataContract;
  403. }
  404. internal static DataContract GetDataContractForInitialization(int id)
  405. {
  406. DataContract dataContract = dataContractCache[id];
  407. if (dataContract == null)
  408. {
  409. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
  410. }
  411. return dataContract;
  412. }
  413. internal static int GetIdForInitialization(ClassDataContract classContract)
  414. {
  415. int id = DataContract.GetId(classContract.TypeForInitialization.TypeHandle);
  416. if (id < dataContractCache.Length && ContractMatches(classContract, dataContractCache[id]))
  417. {
  418. return id;
  419. }
  420. for (int i = 0; i < DataContractCriticalHelper.dataContractID; i++)
  421. {
  422. if (ContractMatches(classContract, dataContractCache[i]))
  423. {
  424. return i;
  425. }
  426. }
  427. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
  428. }
  429. static bool ContractMatches(DataContract contract, DataContract cachedContract)
  430. {
  431. return (cachedContract != null && cachedContract.UnderlyingType == contract.UnderlyingType);
  432. }
  433. internal static int GetId(RuntimeTypeHandle typeHandle)
  434. {
  435. lock (cacheLock)
  436. {
  437. IntRef id;
  438. typeHandle = GetDataContractAdapterTypeHandle(typeHandle);
  439. typeHandleRef.Value = typeHandle;
  440. if (!typeToIDCache.TryGetValue(typeHandleRef, out id))
  441. {
  442. id = GetNextId();
  443. try
  444. {
  445. typeToIDCache.Add(new TypeHandleRef(typeHandle), id);
  446. }
  447. catch (Exception ex)
  448. {
  449. if (Fx.IsFatal(ex))
  450. {
  451. throw;
  452. }
  453. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
  454. }
  455. }
  456. return id.Value;
  457. }
  458. }
  459. // Assumed that this method is called under a lock
  460. static IntRef GetNextId()
  461. {
  462. int value = dataContractID++;
  463. if (value >= dataContractCache.Length)
  464. {
  465. int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue;
  466. if (newSize <= value)
  467. {
  468. Fx.Assert("DataContract cache overflow");
  469. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.DataContractCacheOverflow)));
  470. }
  471. Array.Resize<DataContract>(ref dataContractCache, newSize);
  472. }
  473. return new IntRef(value);
  474. }
  475. // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization
  476. static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
  477. {
  478. lock (createDataContractLock)
  479. {
  480. DataContract dataContract = dataContractCache[id];
  481. if (dataContract == null)
  482. {
  483. if (type == null)
  484. type = Type.GetTypeFromHandle(typeHandle);
  485. type = UnwrapNullableType(type);
  486. type = GetDataContractAdapterType(type);
  487. dataContract = GetBuiltInDataContract(type);
  488. if (dataContract == null)
  489. {
  490. if (type.IsArray)
  491. dataContract = new CollectionDataContract(type);
  492. else if (type.IsEnum)
  493. dataContract = new EnumDataContract(type);
  494. else if (type.IsGenericParameter)
  495. dataContract = new GenericParameterDataContract(type);
  496. else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
  497. dataContract = new XmlDataContract(type);
  498. else
  499. {
  500. //if (type.ContainsGenericParameters)
  501. // ThrowInvalidDataContractException(SR.GetString(SR.TypeMustNotBeOpenGeneric, type), type);
  502. if (type.IsPointer)
  503. type = Globals.TypeOfReflectionPointer;
  504. if (!CollectionDataContract.TryCreate(type, out dataContract))
  505. {
  506. if (type.IsSerializable || type.IsDefined(Globals.TypeOfDataContractAttribute, false) || ClassDataContract.IsNonAttributedTypeValidForSerialization(type))
  507. {
  508. dataContract = new ClassDataContract(type);
  509. }
  510. else
  511. {
  512. ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
  513. }
  514. }
  515. }
  516. }
  517. }
  518. dataContractCache[id] = dataContract;
  519. return dataContract;
  520. }
  521. }
  522. static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type)
  523. {
  524. DataContract dataContract = null;
  525. lock (createDataContractLock)
  526. {
  527. dataContract = dataContractCache[id];
  528. if (dataContract == null)
  529. {
  530. if (type == null)
  531. type = Type.GetTypeFromHandle(typeHandle);
  532. type = UnwrapNullableType(type);
  533. type = GetDataContractAdapterType(type);
  534. if (!CollectionDataContract.TryCreateGetOnlyCollectionDataContract(type, out dataContract))
  535. {
  536. ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
  537. }
  538. }
  539. }
  540. return dataContract;
  541. }
  542. // Any change to this method should be reflected in GetDataContractOriginalType
  543. internal static Type GetDataContractAdapterType(Type type)
  544. {
  545. // Replace the DataTimeOffset ISerializable type passed in with the internal DateTimeOffsetAdapter DataContract type.
  546. // DateTimeOffsetAdapter is used for serialization/deserialization purposes to bypass the ISerializable implementation
  547. // on DateTimeOffset; which does not work in partial trust and to ensure correct schema import/export scenarios.
  548. if (type == Globals.TypeOfDateTimeOffset)
  549. {
  550. return Globals.TypeOfDateTimeOffsetAdapter;
  551. }
  552. return type;
  553. }
  554. // Maps adapted types back to the original type
  555. // Any change to this method should be reflected in GetDataContractAdapterType
  556. internal static Type GetDataContractOriginalType(Type type)
  557. {
  558. if (type == Globals.TypeOfDateTimeOffsetAdapter)
  559. {
  560. return Globals.TypeOfDateTimeOffset;
  561. }
  562. return type;
  563. }
  564. static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHandle typeHandle)
  565. {
  566. if (Globals.TypeOfDateTimeOffset.TypeHandle.Equals(typeHandle))
  567. {
  568. return Globals.TypeOfDateTimeOffsetAdapter.TypeHandle;
  569. }
  570. return typeHandle;
  571. }
  572. [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typeToBuiltInContract", Justification = "No need to support type equivalence here.")]
  573. public static DataContract GetBuiltInDataContract(Type type)
  574. {
  575. if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type))
  576. type = Globals.TypeOfObject;
  577. lock (initBuiltInContractsLock)
  578. {
  579. if (typeToBuiltInContract == null)
  580. typeToBuiltInContract = new Dictionary<Type, DataContract>();
  581. DataContract dataContract = null;
  582. if (!typeToBuiltInContract.TryGetValue(type, out dataContract))
  583. {
  584. TryCreateBuiltInDataContract(type, out dataContract);
  585. typeToBuiltInContract.Add(type, dataContract);
  586. }
  587. return dataContract;
  588. }
  589. }
  590. public static DataContract GetBuiltInDataContract(string name, string ns)
  591. {
  592. lock (initBuiltInContractsLock)
  593. {
  594. if (nameToBuiltInContract == null)
  595. nameToBuiltInContract = new Dictionary<XmlQualifiedName, DataContract>();
  596. DataContract dataContract = null;
  597. XmlQualifiedName qname = new XmlQualifiedName(name, ns);
  598. if (!nameToBuiltInContract.TryGetValue(qname, out dataContract))
  599. {
  600. if (TryCreateBuiltInDataContract(name, ns, out dataContract))
  601. {
  602. nameToBuiltInContract.Add(qname, dataContract);
  603. }
  604. }
  605. return dataContract;
  606. }
  607. }
  608. public static DataContract GetBuiltInDataContract(string typeName)
  609. {
  610. if (!typeName.StartsWith("System.", StringComparison.Ordinal))
  611. return null;
  612. lock (initBuiltInContractsLock)
  613. {
  614. if (typeNameToBuiltInContract == null)
  615. typeNameToBuiltInContract = new Dictionary<string, DataContract>();
  616. DataContract dataContract = null;
  617. if (!typeNameToBuiltInContract.TryGetValue(typeName, out dataContract))
  618. {
  619. Type type = null;
  620. string name = typeName.Substring(7);
  621. if (name == "Char")
  622. type = typeof(Char);
  623. else if (name == "Boolean")
  624. type = typeof(Boolean);
  625. else if (name == "SByte")
  626. type = typeof(SByte);
  627. else if (name == "Byte")
  628. type = typeof(Byte);
  629. else if (name == "Int16")
  630. type = typeof(Int16);
  631. else if (name == "UInt16")
  632. type = typeof(UInt16);
  633. else if (name == "Int32")
  634. type = typeof(Int32);
  635. else if (name == "UInt32")
  636. type = typeof(UInt32);
  637. else if (name == "Int64")
  638. type = typeof(Int64);
  639. else if (name == "UInt64")
  640. type = typeof(UInt64);
  641. else if (name == "Single")
  642. type = typeof(Single);
  643. else if (name == "Double")
  644. type = typeof(Double);
  645. else if (name == "Decimal")
  646. type = typeof(Decimal);
  647. else if (name == "DateTime")
  648. type = typeof(DateTime);
  649. else if (name == "String")
  650. type = typeof(String);
  651. else if (name == "Byte[]")
  652. type = typeof(byte[]);
  653. else if (name == "Object")
  654. type = typeof(Object);
  655. else if (name == "TimeSpan")
  656. type = typeof(TimeSpan);
  657. else if (name == "Guid")
  658. type = typeof(Guid);
  659. else if (name == "Uri")
  660. type = typeof(Uri);
  661. else if (name == "Xml.XmlQualifiedName")
  662. type = typeof(XmlQualifiedName);
  663. else if (name == "Enum")
  664. type = typeof(Enum);
  665. else if (name == "ValueType")
  666. type = typeof(ValueType);
  667. else if (name == "Array")
  668. type = typeof(Array);
  669. else if (name == "Xml.XmlElement")
  670. type = typeof(XmlElement);
  671. else if (name == "Xml.XmlNode[]")
  672. type = typeof(XmlNode[]);
  673. if (type != null)
  674. TryCreateBuiltInDataContract(type, out dataContract);
  675. typeNameToBuiltInContract.Add(typeName, dataContract);
  676. }
  677. return dataContract;
  678. }
  679. }
  680. static public bool TryCreateBuiltInDataContract(Type type, out DataContract dataContract)
  681. {
  682. if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX
  683. {
  684. dataContract = null;
  685. return false;
  686. }
  687. dataContract = null;
  688. switch (Type.GetTypeCode(type))
  689. {
  690. case TypeCode.Boolean:
  691. dataContract = new BooleanDataContract();
  692. break;
  693. case TypeCode.Byte:
  694. dataContract = new UnsignedByteDataContract();
  695. break;
  696. case TypeCode.Char:
  697. dataContract = new CharDataContract();
  698. break;
  699. case TypeCode.DateTime:
  700. dataContract = new DateTimeDataContract();
  701. break;
  702. case TypeCode.Decimal:
  703. dataContract = new DecimalDataContract();
  704. break;
  705. case TypeCode.Double:
  706. dataContract = new DoubleDataContract();
  707. break;
  708. case TypeCode.Int16:
  709. dataContract = new ShortDataContract();
  710. break;
  711. case TypeCode.Int32:
  712. dataContract = new IntDataContract();
  713. break;
  714. case TypeCode.Int64:
  715. dataContract = new LongDataContract();
  716. break;
  717. case TypeCode.SByte:
  718. dataContract = new SignedByteDataContract();
  719. break;
  720. case TypeCode.Single:
  721. dataContract = new FloatDataContract();
  722. break;
  723. case TypeCode.String:
  724. dataContract = new StringDataContract();
  725. break;
  726. case TypeCode.UInt16:
  727. dataContract = new UnsignedShortDataContract();
  728. break;
  729. case TypeCode.UInt32:
  730. dataContract = new UnsignedIntDataContract();
  731. break;
  732. case TypeCode.UInt64:
  733. dataContract = new UnsignedLongDataContract();
  734. break;
  735. default:
  736. if (type == typeof(byte[]))
  737. dataContract = new ByteArrayDataContract();
  738. else if (type == typeof(object))
  739. dataContract = new ObjectDataContract();
  740. else if (type == typeof(Uri))
  741. dataContract = new UriDataContract();
  742. else if (type == typeof(XmlQualifiedName))
  743. dataContract = new QNameDataContract();
  744. else if (type == typeof(TimeSpan))
  745. dataContract = new TimeSpanDataContract();
  746. else if (type == typeof(Guid))
  747. dataContract = new GuidDataContract();
  748. else if (type == typeof(Enum) || type == typeof(ValueType))
  749. {
  750. dataContract = new SpecialTypeDataContract(type, DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace);
  751. }
  752. else if (type == typeof(Array))
  753. dataContract = new CollectionDataContract(type);
  754. else if (type == typeof(XmlElement) || type == typeof(XmlNode[]))
  755. dataContract = new XmlDataContract(type);
  756. break;
  757. }
  758. return dataContract != null;
  759. }
  760. static public bool TryCreateBuiltInDataContract(string name, string ns, out DataContract dataContract)
  761. {
  762. dataContract = null;
  763. if (ns == DictionaryGlobals.SchemaNamespace.Value)
  764. {
  765. if (DictionaryGlobals.BooleanLocalName.Value == name)
  766. dataContract = new BooleanDataContract();
  767. else if (DictionaryGlobals.SignedByteLocalName.Value == name)
  768. dataContract = new SignedByteDataContract();
  769. else if (DictionaryGlobals.UnsignedByteLocalName.Value == name)
  770. dataContract = new UnsignedByteDataContract();
  771. else if (DictionaryGlobals.ShortLocalName.Value == name)
  772. dataContract = new ShortDataContract();
  773. else if (DictionaryGlobals.UnsignedShortLocalName.Value == name)
  774. dataContract = new UnsignedShortDataContract();
  775. else if (DictionaryGlobals.IntLocalName.Value == name)
  776. dataContract = new IntDataContract();
  777. else if (DictionaryGlobals.UnsignedIntLocalName.Value == name)
  778. dataContract = new UnsignedIntDataContract();
  779. else if (DictionaryGlobals.LongLocalName.Value == name)
  780. dataContract = new LongDataContract();
  781. else if (DictionaryGlobals.integerLocalName.Value == name)
  782. dataContract = new IntegerDataContract();
  783. else if (DictionaryGlobals.positiveIntegerLocalName.Value == name)
  784. dataContract = new PositiveIntegerDataContract();
  785. else if (DictionaryGlobals.negativeIntegerLocalName.Value == name)
  786. dataContract = new NegativeIntegerDataContract();
  787. else if (DictionaryGlobals.nonPositiveIntegerLocalName.Value == name)
  788. dataContract = new NonPositiveIntegerDataContract();
  789. else if (DictionaryGlobals.nonNegativeIntegerLocalName.Value == name)
  790. dataContract = new NonNegativeIntegerDataContract();
  791. else if (DictionaryGlobals.UnsignedLongLocalName.Value == name)
  792. dataContract = new UnsignedLongDataContract();
  793. else if (DictionaryGlobals.FloatLocalName.Value == name)
  794. dataContract = new FloatDataContract();
  795. else if (DictionaryGlobals.DoubleLocalName.Value == name)
  796. dataContract = new DoubleDataContract();
  797. else if (DictionaryGlobals.DecimalLocalName.Value == name)
  798. dataContract = new DecimalDataContract();
  799. else if (DictionaryGlobals.DateTimeLocalName.Value == name)
  800. dataContract = new DateTimeDataContract();
  801. else if (DictionaryGlobals.StringLocalName.Value == name)
  802. dataContract = new StringDataContract();
  803. else if (DictionaryGlobals.timeLocalName.Value == name)
  804. dataContract = new TimeDataContract();
  805. else if (DictionaryGlobals.dateLocalName.Value == name)
  806. dataContract = new DateDataContract();
  807. else if (DictionaryGlobals.hexBinaryLocalName.Value == name)
  808. dataContract = new HexBinaryDataContract();
  809. else if (DictionaryGlobals.gYearMonthLocalName.Value == name)
  810. dataContract = new GYearMonthDataContract();
  811. else if (DictionaryGlobals.gYearLocalName.Value == name)
  812. dataContract = new GYearDataContract();
  813. else if (DictionaryGlobals.gMonthDayLocalName.Value == name)
  814. dataContract = new GMonthDayDataContract();
  815. else if (DictionaryGlobals.gDayLocalName.Value == name)
  816. dataContract = new GDayDataContract();
  817. else if (DictionaryGlobals.gMonthLocalName.Value == name)
  818. dataContract = new GMonthDataContract();
  819. else if (DictionaryGlobals.normalizedStringLocalName.Value == name)
  820. dataContract = new NormalizedStringDataContract();
  821. else if (DictionaryGlobals.tokenLocalName.Value == name)
  822. dataContract = new TokenDataContract();
  823. else if (DictionaryGlobals.languageLocalName.Value == name)
  824. dataContract = new LanguageDataContract();
  825. else if (DictionaryGlobals.NameLocalName.Value == name)
  826. dataContract = new NameDataContract();
  827. else if (DictionaryGlobals.NCNameLocalName.Value == name)
  828. dataContract = new NCNameDataContract();
  829. else if (DictionaryGlobals.XSDIDLocalName.Value == name)
  830. dataContract = new IDDataContract();
  831. else if (DictionaryGlobals.IDREFLocalName.Value == name)
  832. dataContract = new IDREFDataContract();
  833. else if (DictionaryGlobals.IDREFSLocalName.Value == name)
  834. dataContract = new IDREFSDataContract();
  835. else if (DictionaryGlobals.ENTITYLocalName.Value == name)
  836. dataContract = new ENTITYDataContract();
  837. else if (DictionaryGlobals.ENTITIESLocalName.Value == name)
  838. dataContract = new ENTITIESDataContract();
  839. else if (DictionaryGlobals.NMTOKENLocalName.Value == name)
  840. dataContract = new NMTOKENDataContract();
  841. else if (DictionaryGlobals.NMTOKENSLocalName.Value == name)
  842. dataContract = new NMTOKENDataContract();
  843. else if (DictionaryGlobals.ByteArrayLocalName.Value == name)
  844. dataContract = new ByteArrayDataContract();
  845. else if (DictionaryGlobals.ObjectLocalName.Value == name)
  846. dataContract = new ObjectDataContract();
  847. else if (DictionaryGlobals.TimeSpanLocalName.Value == name)
  848. dataContract = new XsDurationDataContract();
  849. else if (DictionaryGlobals.UriLocalName.Value == name)
  850. dataContract = new UriDataContract();
  851. else if (DictionaryGlobals.QNameLocalName.Value == name)
  852. dataContract = new QNameDataContract();
  853. }
  854. else if (ns == DictionaryGlobals.SerializationNamespace.Value)
  855. {
  856. if (DictionaryGlobals.TimeSpanLocalName.Value == name)
  857. dataContract = new TimeSpanDataContract();
  858. else if (DictionaryGlobals.GuidLocalName.Value == name)
  859. dataContract = new GuidDataContract();
  860. else if (DictionaryGlobals.CharLocalName.Value == name)
  861. dataContract = new CharDataContract();
  862. else if ("ArrayOfanyType" == name)
  863. dataContract = new CollectionDataContract(typeof(Array));
  864. }
  865. else if (ns == DictionaryGlobals.AsmxTypesNamespace.Value)
  866. {
  867. if (DictionaryGlobals.CharLocalName.Value == name)
  868. dataContract = new AsmxCharDataContract();
  869. else if (DictionaryGlobals.GuidLocalName.Value == name)
  870. dataContract = new AsmxGuidDataContract();
  871. }
  872. else if (ns == Globals.DataContractXmlNamespace)
  873. {
  874. if (name == "XmlElement")
  875. dataContract = new XmlDataContract(typeof(XmlElement));
  876. else if (name == "ArrayOfXmlNode")
  877. dataContract = new XmlDataContract(typeof(XmlNode[]));
  878. }
  879. return dataContract != null;
  880. }
  881. internal static string GetNamespace(string key)
  882. {
  883. lock (namespacesLock)
  884. {
  885. if (namespaces == null)
  886. namespaces = new Dictionary<string, string>();
  887. string value;
  888. if (namespaces.TryGetValue(key, out value))
  889. return value;
  890. try
  891. {
  892. namespaces.Add(key, key);
  893. }
  894. catch (Exception ex)
  895. {
  896. if (Fx.IsFatal(ex))
  897. {
  898. throw;
  899. }
  900. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
  901. }
  902. return key;
  903. }
  904. }
  905. internal static XmlDictionaryString GetClrTypeString(string key)
  906. {
  907. lock (clrTypeStringsLock)
  908. {
  909. if (clrTypeStrings == null)
  910. {
  911. clrTypeStringsDictionary = new XmlDictionary();
  912. clrTypeStrings = new Dictionary<string, XmlDictionaryString>();
  913. try
  914. {
  915. clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName, clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName));
  916. }
  917. catch (Exception ex)
  918. {
  919. if (Fx.IsFatal(ex))
  920. {
  921. throw;
  922. }
  923. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
  924. }
  925. }
  926. XmlDictionaryString value;
  927. if (clrTypeStrings.TryGetValue(key, out value))
  928. return value;
  929. value = clrTypeStringsDictionary.Add(key);
  930. try
  931. {
  932. clrTypeStrings.Add(key, value);
  933. }
  934. catch (Exception ex)
  935. {
  936. if (Fx.IsFatal(ex))
  937. {
  938. throw;
  939. }
  940. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
  941. }
  942. return value;
  943. }
  944. }
  945. internal static void ThrowInvalidDataContractException(string message, Type type)
  946. {
  947. if (type != null)
  948. {
  949. lock (cacheLock)
  950. {
  951. typeHandleRef.Value = GetDataContractAdapterTypeHandle(type.TypeHandle);
  952. try
  953. {
  954. typeToIDCache.Remove(typeHandleRef);
  955. }
  956. catch (Exception ex)
  957. {
  958. if (Fx.IsFatal(ex))
  959. {
  960. throw;
  961. }
  962. throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex);
  963. }
  964. }
  965. }
  966. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message));
  967. }
  968. internal DataContractCriticalHelper()
  969. {
  970. }
  971. internal DataContractCriticalHelper(Type type)
  972. {
  973. underlyingType = type;
  974. SetTypeForInitialization(type);
  975. isValueType = type.IsValueType;
  976. }
  977. internal Type UnderlyingType
  978. {
  979. get { return underlyingType; }
  980. }
  981. internal Type OriginalUnderlyingType
  982. {
  983. get
  984. {
  985. if (this.originalUnderlyingType == null)
  986. {
  987. this.originalUnderlyingType = GetDataContractOriginalType(this.underlyingType);
  988. }
  989. return this.originalUnderlyingType;
  990. }
  991. }
  992. internal virtual bool IsBuiltInDataContract
  993. {
  994. get
  995. {
  996. return false;
  997. }
  998. }
  999. internal Type TypeForInitialization
  1000. {
  1001. get { return this.typeForInitialization; }
  1002. }
  1003. [Fx.Tag.SecurityNote(Critical = "Sets the critical typeForInitialization property.",
  1004. Safe = "Validates input data, sets field correctly.")]
  1005. [SecuritySafeCritical]
  1006. void SetTypeForInitialization(Type classType)
  1007. {
  1008. if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false))
  1009. {
  1010. this.typeForInitialization = classType;
  1011. }
  1012. }
  1013. internal bool IsReference
  1014. {
  1015. get { return isReference; }
  1016. set
  1017. {
  1018. isReference = value;
  1019. }
  1020. }
  1021. internal bool IsValueType
  1022. {
  1023. get { return isValueType; }
  1024. set { isValueType = value; }
  1025. }
  1026. internal XmlQualifiedName StableName
  1027. {
  1028. get { return stableName; }
  1029. set { stableName = value; }
  1030. }
  1031. internal GenericInfo GenericInfo
  1032. {
  1033. get { return genericInfo; }
  1034. set { genericInfo = value; }
  1035. }
  1036. internal virtual DataContractDictionary KnownDataContracts
  1037. {
  1038. get { return null; }
  1039. set { /* do nothing */ }
  1040. }
  1041. internal virtual bool IsISerializable
  1042. {
  1043. get { return false; }
  1044. set { ThrowInvalidDataContractException(SR.GetString(SR.RequiresClassDataContractToSetIsISerializable)); }
  1045. }
  1046. internal XmlDictionaryString Name
  1047. {
  1048. get { return name; }
  1049. set { name = value; }
  1050. }
  1051. public XmlDictionaryString Namespace
  1052. {
  1053. get { return ns; }
  1054. set { ns = value; }
  1055. }
  1056. internal virtual bool HasRoot
  1057. {
  1058. get { return true; }
  1059. set { }
  1060. }
  1061. internal virtual XmlDictionaryString TopLevelElementName
  1062. {
  1063. get { return name; }
  1064. set { name = value; }
  1065. }
  1066. internal virtual XmlDictionaryString TopLevelElementNamespace
  1067. {
  1068. get { return ns; }
  1069. set { ns = value; }
  1070. }
  1071. internal virtual bool CanContainReferences
  1072. {
  1073. get { return true; }
  1074. }
  1075. internal virtual bool IsPrimitive
  1076. {
  1077. get { return false; }
  1078. }
  1079. internal MethodInfo ParseMethod
  1080. {
  1081. get
  1082. {
  1083. if (!parseMethodSet)
  1084. {
  1085. MethodInfo method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, null, new Type[] { Globals.TypeOfString }, null);
  1086. if (method != null && method.ReturnType == UnderlyingType)
  1087. {
  1088. parseMethod = method;
  1089. }
  1090. parseMethodSet = true;
  1091. }
  1092. return parseMethod; }
  1093. }
  1094. internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns)
  1095. {
  1096. if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive)
  1097. writer.WriteStartElement(Globals.SerPrefix, name, ns);
  1098. else
  1099. writer.WriteStartElement(name, ns);
  1100. }
  1101. internal void SetDataContractName(XmlQualifiedName stableName)
  1102. {
  1103. XmlDictionary dictionary = new XmlDictionary(2);
  1104. this.Name = dictionary.Add(stableName.Name);
  1105. this.Namespace = dictionary.Add(stableName.Namespace);
  1106. this.StableName = stableName;
  1107. }
  1108. internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString ns)
  1109. {
  1110. this.Name = name;
  1111. this.Namespace = ns;
  1112. this.StableName = CreateQualifiedName(name.Value, ns.Value);
  1113. }
  1114. internal void ThrowInvalidDataContractException(string message)
  1115. {
  1116. ThrowInvalidDataContractException(message, UnderlyingType);
  1117. }
  1118. }
  1119. static internal bool IsTypeSerializable(Type type)
  1120. {
  1121. return IsTypeSerializable(type, new Dictionary<Type, object>());
  1122. }
  1123. static bool IsTypeSerializable(Type type, Dictionary<Type, object> previousCollectionTypes)
  1124. {
  1125. Type itemType;
  1126. if (type.IsSerializable ||
  1127. type.IsDefined(Globals.TypeOfDataContractAttribute, false) ||
  1128. type.IsInterface ||
  1129. type.IsPointer ||
  1130. Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
  1131. {
  1132. return true;
  1133. }
  1134. if (CollectionDataContract.IsCollection(type, out itemType))
  1135. {
  1136. ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
  1137. if (IsTypeSerializable(itemType, previousCollectionTypes))
  1138. {
  1139. return true;
  1140. }
  1141. }
  1142. return (DataContract.GetBuiltInDataContract(type) != null || ClassDataContract.IsNonAttributedTypeValidForSerialization(type));
  1143. }
  1144. [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "previousCollectionTypes", Justification = "No need to support type equivalence here.")]
  1145. static void ValidatePreviousCollectionTypes(Type collectionType, Type itemType, Dictionary<Type, object> previousCollectionTypes)
  1146. {
  1147. previousCollectionTypes.Add(collectionType, collectionType);
  1148. while (itemType.IsArray)
  1149. {
  1150. itemType = itemType.GetElementType();
  1151. }
  1152. // Do a breadth first traversal of the generic type tree to
  1153. // produce the closure of all generic argument types and
  1154. // check that none of these is in the previousCollectionTypes
  1155. List<Type> itemTypeClosure = new List<Type>();
  1156. Queue<Type> itemTypeQueue = new Queue<Type>();
  1157. itemTypeQueue.Enqueue(itemType);
  1158. itemTypeClosure.Add(itemType);
  1159. while (itemTypeQueue.Count > 0)
  1160. {
  1161. itemType = itemTypeQueue.Dequeue();
  1162. if (previousCollectionTypes.ContainsKey(itemType))
  1163. {
  1164. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.RecursiveCollectionType, DataContract.GetClrTypeFullName(itemType))));
  1165. }
  1166. if (itemType.IsGenericType)
  1167. {
  1168. foreach (Type argType in itemType.GetGenericArguments())
  1169. {
  1170. if (!itemTypeClosure.Contains(argType))
  1171. {
  1172. itemTypeQueue.Enqueue(argType);
  1173. itemTypeClosure.Add(argType);
  1174. }
  1175. }
  1176. }
  1177. }
  1178. }
  1179. internal static Type UnwrapRedundantNullableType(Type type)
  1180. {
  1181. Type nullableType = type;
  1182. while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
  1183. {
  1184. nullableType = type;
  1185. type = type.GetGenericArguments()[0];
  1186. }
  1187. return nullableType;
  1188. }
  1189. internal static Type UnwrapNullableType(Type type)
  1190. {
  1191. while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
  1192. type = type.GetGenericArguments()[0];
  1193. return type;
  1194. }
  1195. static bool IsAlpha(char ch)
  1196. {
  1197. return (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z');
  1198. }
  1199. static bool IsDigit(char ch)
  1200. {
  1201. return (ch >= '0' && ch <= '9');
  1202. }
  1203. static bool IsAsciiLocalName(string localName)
  1204. {
  1205. if (localName.Length == 0)
  1206. return false;
  1207. if (!IsAlpha(localName[0]))
  1208. return false;
  1209. for (int i = 1; i < localName.Length; i++)
  1210. {
  1211. char ch = localName[i];
  1212. if (!IsAlpha(ch) && !IsDigit(ch))
  1213. return false;
  1214. }
  1215. return true;
  1216. }
  1217. static internal string EncodeLocalName(string localName)
  1218. {
  1219. if (IsAsciiLocalName(localName))
  1220. return localName;
  1221. if (IsValidNCName(localName))
  1222. return localName;
  1223. return XmlConvert.EncodeLocalName(localName);
  1224. }
  1225. internal static bool IsValidNCName(string name)
  1226. {
  1227. try
  1228. {
  1229. XmlConvert.VerifyNCName(name);
  1230. return true;
  1231. }
  1232. catch (XmlException)
  1233. {
  1234. return false;
  1235. }
  1236. }
  1237. internal static XmlQualifiedName GetStableName(Type type)
  1238. {
  1239. bool hasDataContract;
  1240. return GetStableName(type, out hasDataContract);
  1241. }
  1242. internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract)
  1243. {
  1244. return GetStableName(type, new Dictionary<Type, object>(), out hasDataContract);
  1245. }
  1246. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - Callers may need to depend on hasDataContract for a security decision."
  1247. + " hasDataContract must be calculated correctly."
  1248. + " GetStableName is factored into sub-methods so as to isolate the DataContractAttribute calculation and reduce SecurityCritical surface area.",
  1249. Safe = "Does not let caller influence hasDataContract calculation; no harm in leaking value.")]
  1250. static XmlQualifiedName GetStableName(Type type, Dictionary<Type, object> previousCollectionTypes, out bool hasDataContract)
  1251. {
  1252. type = UnwrapRedundantNullableType(type);
  1253. XmlQualifiedName stableName;
  1254. if (TryGetBuiltInXmlAndArrayTypeStableName(type, previousCollectionTypes, out stableName))
  1255. {
  1256. hasDataContract = false;
  1257. }
  1258. else
  1259. {
  1260. DataContractAttribute dataContractAttribute;
  1261. if (TryGetDCAttribute(type, out dataContractAttribute))
  1262. {
  1263. stableName = GetDCTypeStableName(type, dataContractAttribute);
  1264. hasDataContract = true;
  1265. }
  1266. else
  1267. {
  1268. stableName = GetNonDCTypeStableName(type, previousCollectionTypes);
  1269. hasDataContract = false;
  1270. }
  1271. }
  1272. return stableName;
  1273. }
  1274. static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute)
  1275. {
  1276. string name = null, ns = null;
  1277. if (dataContractAttribute.IsNameSetExplicitly)
  1278. {
  1279. name = dataContractAttribute.Name;
  1280. if (name == null || name.Length == 0)
  1281. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type))));
  1282. if (type.IsGenericType && !type.IsGenericTypeDefinition)
  1283. name = ExpandGenericParameters(name, type);
  1284. name = DataContract.EncodeLocalName(name);
  1285. }
  1286. else
  1287. name = GetDefaultStableLocalName(type);
  1288. if (dataContractAttribute.IsNamespaceSetExplicitly)
  1289. {
  1290. ns = dataContractAttribute.Namespace;
  1291. if (ns == null)
  1292. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidDataContractNamespace, DataContract.GetClrTypeFullName(type))));
  1293. CheckExplicitDataContractNamespaceUri(ns, type);
  1294. }
  1295. else
  1296. ns = GetDefaultDataContractNamespace(type);
  1297. return CreateQualifiedName(name, ns);
  1298. }
  1299. static XmlQualifiedName GetNonDCTypeStableName(Type type, Dictionary<Type, object> previousCollectionTypes)
  1300. {
  1301. string name = null, ns = null;
  1302. Type itemType;
  1303. CollectionDataContractAttribute collectionContractAttribute;
  1304. if (CollectionDataContract.IsCollection(type, out itemType))
  1305. {
  1306. ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
  1307. return GetCollectionStableName(type, itemType, previousCollectionTypes, out collectionContractAttribute);
  1308. }
  1309. name = GetDefaultStableLocalName(type);
  1310. // ensures that ContractNamespaceAttribute is honored when used with non-attributed types
  1311. if (ClassDataContract.IsNonAttributedTypeValidForSerialization(type))
  1312. {
  1313. ns = GetDefaultDataContractNamespace(type);
  1314. }
  1315. else
  1316. {
  1317. ns = GetDefaultStableNamespace(type);
  1318. }
  1319. return CreateQualifiedName(name, ns);
  1320. }
  1321. static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, Dictionary<Type, object> previousCollectionTypes, out XmlQualifiedName stableName)
  1322. {
  1323. stableName = null;
  1324. DataContract builtInContract = GetBuiltInDataContract(type);
  1325. if (builtInContract != null)
  1326. {
  1327. stableName = builtInContract.StableName;
  1328. }
  1329. else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))
  1330. {
  1331. bool hasRoot;
  1332. XmlSchemaType xsdType;
  1333. XmlQualifiedName xmlTypeStableName;
  1334. SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out xsdType, out hasRoot);
  1335. stableName = xmlTypeStableName;
  1336. }
  1337. else if (type.IsArray)
  1338. {
  1339. Type itemType = type.GetElementType();
  1340. ValidatePreviousCollectionTypes(type, itemType, previousCollectionTypes);
  1341. CollectionDataContractAttribute collectionContractAttribute;
  1342. stableName = GetCollectionStableName(type, itemType, previousCollectionTypes, out collectionContractAttribute);
  1343. }
  1344. return stableName != null;
  1345. }
  1346. [Fx.Tag.SecurityNote(Critical = "Marked SecurityCritical because callers may need to base security decisions on the presence (or absence) of the DC attribute.",
  1347. Safe = "Does not let caller influence calculation and the result is not a protected value.")]
  1348. [SecuritySafeCritical]
  1349. internal static bool TryGetDCAttribute(Type type, out DataContractAttribute dataContractAttribute)
  1350. {
  1351. dataContractAttribute = null;
  1352. object[] dataContractAttributes = type.GetCustomAttributes(Globals.TypeOfDataContractAttribute, false);
  1353. if (dataContractAttributes != null && dataContractAttributes.Length > 0)
  1354. {
  1355. #if DEBUG
  1356. if (dataContractAttributes.Length > 1)
  1357. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TooManyDataContracts, DataContract.GetClrTypeFullName(type))));
  1358. #endif
  1359. dataContractAttribute = (DataContractAttribute)dataContractAttributes[0];
  1360. }
  1361. return dataContractAttribute != null;
  1362. }
  1363. internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute collectionContractAttribute)
  1364. {
  1365. return GetCollectionStableName(type, itemType, new Dictionary<Type, object>(), out collectionContractAttribute);
  1366. }
  1367. static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, Dictionary<Type, object> previousCollectionTypes, out CollectionDataContractAttribute collectionContractAttribute)
  1368. {
  1369. string name, ns;
  1370. object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false);
  1371. if (collectionContractAttributes != null && collectionContractAttributes.Length > 0)
  1372. {
  1373. #if DEBUG
  1374. if (collectionContractAttributes.Length > 1)
  1375. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TooManyCollectionContracts, DataContract.GetClrTypeFullName(type))));
  1376. #endif
  1377. collectionContractAttribute = (CollectionDataContractAttribute)collectionContractAttributes[0];
  1378. if (collectionContractAttribute.IsNameSetExplicitly)
  1379. {
  1380. name = collectionContractAttribute.Name;
  1381. if (name == null || name.Length == 0)
  1382. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type))));
  1383. if (type.IsGenericType && !type.IsGenericTypeDefinition)
  1384. name = ExpandGenericParameters(name, type);
  1385. name = DataContract.EncodeLocalName(name);
  1386. }
  1387. else
  1388. name = GetDefaultStableLocalName(type);
  1389. if (collectionContractAttribute.IsNamespaceSetExplicitly)
  1390. {
  1391. ns = collectionContractAttribute.Namespace;
  1392. if (ns == null)
  1393. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidCollectionContractNamespace, DataContract.GetClrTypeFullName(type))));
  1394. CheckExplicitDataContractNamespaceUri(ns, type);
  1395. }
  1396. else
  1397. ns = GetDefaultDataContractNamespace(type);
  1398. }
  1399. else
  1400. {
  1401. collectionContractAttribute = null;
  1402. string arrayOfPrefix = Globals.ArrayPrefix + GetArrayPrefix(ref itemType);
  1403. bool hasDataContract;
  1404. XmlQualifiedName elementStableName = GetStableName(itemType, previousCollectionTypes, out hasDataContract);
  1405. name = arrayOfPrefix + elementStableName.Name;
  1406. ns = GetCollectionNamespace(elementStableName.Namespace);
  1407. }
  1408. return CreateQualifiedName(name, ns);
  1409. }
  1410. private static string GetArrayPrefix(ref Type itemType)
  1411. {
  1412. string arrayOfPrefix = string.Empty;
  1413. while (itemType.IsArray)
  1414. {
  1415. if (DataContract.GetBuiltInDataContract(itemType) != null)
  1416. break;
  1417. arrayOfPrefix += Globals.ArrayPrefix;
  1418. itemType = itemType.GetElementType();
  1419. }
  1420. return arrayOfPrefix;
  1421. }
  1422. internal XmlQualifiedName GetArrayTypeName(bool isNullable)
  1423. {
  1424. XmlQualifiedName itemName;
  1425. if (this.IsValueType && isNullable)
  1426. {
  1427. GenericInfo genericInfo = new GenericInfo(DataContract.GetStableName(Globals.TypeOfNullable), Globals.TypeOfNullable.FullName);
  1428. genericInfo.Add(new GenericInfo(this.StableName, null));
  1429. genericInfo.AddToLevel(0, 1);
  1430. itemName = genericInfo.GetExpandedStableName();
  1431. }
  1432. else
  1433. itemName = this.StableName;
  1434. string ns = GetCollectionNamespace(itemName.Namespace);
  1435. string name = Globals.ArrayPrefix + itemName.Name;
  1436. return new XmlQualifiedName(name, ns);
  1437. }
  1438. internal static string GetCollectionNamespace(string elementNs)
  1439. {
  1440. return IsBuiltInNamespace(elementNs) ? Globals.CollectionsNamespace : elementNs;
  1441. }
  1442. internal static XmlQualifiedName GetDefaultStableName(Type type)
  1443. {
  1444. return CreateQualifiedName(GetDefaultStableLocalName(type), GetDefaultStableNamespace(type));
  1445. }
  1446. static string GetDefaultStableLocalName(Type type)
  1447. {
  1448. if (type.IsGenericParameter)
  1449. return "{" + type.GenericParameterPosition + "}";
  1450. string typeName;
  1451. string arrayPrefix = null;
  1452. if (type.IsArray)
  1453. arrayPrefix = GetArrayPrefix(ref type);
  1454. if (type.DeclaringType == null)
  1455. typeName = type.Name;
  1456. else
  1457. {
  1458. int nsLen = (type.Namespace == null) ? 0 : type.Namespace.Length;
  1459. if (nsLen > 0)
  1460. nsLen++; //include the . following namespace
  1461. typeName = DataContract.GetClrTypeFullName(type).Substring(nsLen).Replace('+', '.');
  1462. }
  1463. if (arrayPrefix != null)
  1464. typeName = arrayPrefix + typeName;
  1465. if (type.IsGenericType)
  1466. {
  1467. StringBuilder localName = new StringBuilder();
  1468. StringBuilder namespaces = new StringBuilder();
  1469. bool parametersFromBuiltInNamespaces = true;
  1470. int iParam = typeName.IndexOf('[');
  1471. if (iParam >= 0)
  1472. typeName = typeName.Substring(0, iParam);
  1473. IList<int> nestedParamCounts = GetDataContractNameForGenericName(typeName, localName);
  1474. bool isTypeOpenGeneric = type.IsGenericTypeDefinition;
  1475. Type[] genParams = type.GetGenericArguments();
  1476. for (int i = 0; i < genParams.Length; i++)
  1477. {
  1478. Type genParam = genParams[i];
  1479. if (isTypeOpenGeneric)
  1480. localName.Append("{").Append(i).Append("}");
  1481. else
  1482. {
  1483. XmlQualifiedName qname = DataContract.GetStableName(genParam);
  1484. localName.Append(qname.Name);
  1485. namespaces.Append(" ").Append(qname.Namespace);
  1486. if (parametersFromBuiltInNamespaces)
  1487. parametersFromBuiltInNamespaces = IsBuiltInNamespace(qname.Namespace);
  1488. }
  1489. }
  1490. if (isTypeOpenGeneric)
  1491. localName.Append("{#}");
  1492. else if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces)
  1493. {
  1494. foreach (int count in nestedParamCounts)
  1495. namespaces.Insert(0, count).Insert(0, " ");
  1496. localName.Append(GetNamespacesDigest(namespaces.ToString()));
  1497. }
  1498. typeName = localName.ToString();
  1499. }
  1500. return DataContract.EncodeLocalName(typeName);
  1501. }
  1502. static string GetDefaultDataContractNamespace(Type type)
  1503. {
  1504. string clrNs = type.Namespace;
  1505. if (clrNs == null)
  1506. clrNs = String.Empty;
  1507. string ns = GetGlobalDataContractNamespace(clrNs, type.Module);
  1508. if (ns == null)
  1509. ns = GetGlobalDataContractNamespace(clrNs, type.Assembly);
  1510. if (ns == null)
  1511. ns = GetDefaultStableNamespace(type);
  1512. else
  1513. CheckExplicitDataContractNamespaceUri(ns, type);
  1514. return ns;
  1515. }
  1516. internal static IList<int> GetDataContractNameForGenericName(string typeName, StringBuilder localName)
  1517. {
  1518. List<int> nestedParamCounts = new List<int>();
  1519. for (int startIndex = 0, endIndex;;)
  1520. {
  1521. endIndex = typeName.IndexOf('`', startIndex);
  1522. if (endIndex < 0)
  1523. {
  1524. if (localName != null)
  1525. localName.Append(typeName.Substring(startIndex));
  1526. nestedParamCounts.Add(0);
  1527. break;
  1528. }
  1529. if (localName != null)
  1530. localName.Append(typeName.Substring(startIndex, endIndex - startIndex));
  1531. while ((startIndex = typeName.IndexOf('.', startIndex + 1, endIndex - startIndex - 1)) >= 0)
  1532. nestedParamCounts.Add(0);
  1533. startIndex = typeName.IndexOf('.', endIndex);
  1534. if (startIndex < 0)
  1535. {
  1536. nestedParamCounts.Add(Int32.Parse(typeName.Substring(endIndex + 1), CultureInfo.InvariantCulture));
  1537. break;
  1538. }
  1539. else
  1540. nestedParamCounts.Add(Int32.Parse(typeName.Substring(endIndex + 1, startIndex - endIndex - 1), CultureInfo.InvariantCulture));
  1541. }
  1542. if (localName != null)
  1543. localName.Append("Of");
  1544. return nestedParamCounts;
  1545. }
  1546. internal static bool IsBuiltInNamespace(string ns)
  1547. {
  1548. return (ns == Globals.SchemaNamespace || ns == Globals.SerializationNamespace);
  1549. }
  1550. internal static string GetDefaultStableNamespace(Type type)
  1551. {
  1552. if (type.IsGenericParameter)
  1553. return "{ns}";
  1554. return GetDefaultStableNamespace(type.Namespace);
  1555. }
  1556. internal static XmlQualifiedName CreateQualifiedName(string localName, string ns)
  1557. {
  1558. return new XmlQualifiedName(localName, GetNamespace(ns));
  1559. }
  1560. internal static string GetDefaultStableNamespace(string clrNs)
  1561. {
  1562. if (clrNs == null) clrNs = String.Empty;
  1563. return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri;
  1564. }
  1565. static void CheckExplicitDataContractNamespaceUri(string dataContractNs, Type type)
  1566. {
  1567. if (dataContractNs.Length > 0)
  1568. {
  1569. string trimmedNs = dataContractNs.Trim();
  1570. // Code similar to XmlConvert.ToUri (string.Empty is a valid uri but not " ")
  1571. if (trimmedNs.Length == 0 || trimmedNs.IndexOf("##", StringComparison.Ordinal) != -1)
  1572. ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceIsNotValid, dataContractNs), type);
  1573. dataContractNs = trimmedNs;
  1574. }
  1575. Uri uri;
  1576. if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri))
  1577. {
  1578. if (uri.ToString() == Globals.SerializationNamespace)
  1579. ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceReserved, Globals.SerializationNamespace), type);
  1580. }
  1581. else
  1582. ThrowInvalidDataContractException(SR.GetString(SR.DataContractNamespaceIsNotValid, dataContractNs), type);
  1583. }
  1584. internal static string GetClrTypeFullName(Type type)
  1585. {
  1586. return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? String.Format(CultureInfo.InvariantCulture, "{0}.{1}", type.Namespace, type.Name) : type.FullName;
  1587. }
  1588. internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom)
  1589. {
  1590. hasTypeForwardedFrom = false;
  1591. object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false);
  1592. if (typeAttributes != null && typeAttributes.Length > 0)
  1593. {
  1594. TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0];
  1595. hasTypeForwardedFrom = true;
  1596. return typeForwardedFromAttribute.AssemblyFullName;
  1597. }
  1598. else
  1599. {
  1600. return type.Assembly.FullName;
  1601. }
  1602. }
  1603. internal static string GetClrTypeFullNameUsingTypeForwardedFromAttribute(Type type)
  1604. {
  1605. if (type.IsArray)
  1606. {
  1607. return GetClrTypeFullNameForArray(type);
  1608. }
  1609. else
  1610. {
  1611. return GetClrTypeFullNameForNonArrayTypes(type);
  1612. }
  1613. }
  1614. static string GetClrTypeFullNameForArray(Type type)
  1615. {
  1616. return String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}",
  1617. GetClrTypeFullNameUsingTypeForwardedFromAttribute(type.GetElementType()), Globals.OpenBracket, Globals.CloseBracket);
  1618. }
  1619. static string GetClrTypeFullNameForNonArrayTypes(Type type)
  1620. {
  1621. if (!type.IsGenericType)
  1622. {
  1623. return DataContract.GetClrTypeFullName(type);
  1624. }
  1625. Type[] genericArguments = type.GetGenericArguments();
  1626. StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append(Globals.OpenBracket);
  1627. foreach (Type genericArgument in genericArguments)
  1628. {
  1629. bool hasTypeForwardedFrom;
  1630. builder.Append(Globals.OpenBracket).Append(GetClrTypeFullNameUsingTypeForwardedFromAttribute(genericArgument)).Append(Globals.Comma);
  1631. builder.Append(Globals.Space).Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom));
  1632. builder.Append(Globals.CloseBracket).Append(Globals.Comma);
  1633. }
  1634. //remove the last comma and close typename for generic with a close bracket
  1635. return builder.Remove(builder.Length - 1, 1).Append(Globals.CloseBracket).ToString();
  1636. }
  1637. internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns)
  1638. {
  1639. int nsEnd = fullTypeName.LastIndexOf('.');
  1640. if (nsEnd < 0)
  1641. {
  1642. ns = String.Empty;
  1643. localName = fullTypeName.Replace('+', '.');
  1644. }
  1645. else
  1646. {
  1647. ns = fullTypeName.Substring(0, nsEnd);
  1648. localName = fullTypeName.Substring(nsEnd + 1).Replace('+', '.');
  1649. }
  1650. int iParam = localName.IndexOf('[');
  1651. if (iParam >= 0)
  1652. localName = localName.Substring(0, iParam);
  1653. }
  1654. internal static void GetDefaultStableName(string fullTypeName, out string localName, out string ns)
  1655. {
  1656. CodeTypeReference typeReference = new CodeTypeReference(fullTypeName);
  1657. GetDefaultStableName(typeReference, out localName, out ns);
  1658. }
  1659. static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns)
  1660. {
  1661. string fullTypeName = typeReference.BaseType;
  1662. DataContract dataContract = GetBuiltInDataContract(fullTypeName);
  1663. if (dataContract != null)
  1664. {
  1665. localName = dataContract.StableName.Name;
  1666. ns = dataContract.StableName.Namespace;
  1667. return;
  1668. }
  1669. GetClrNameAndNamespace(fullTypeName, out localName, out ns);
  1670. if (typeReference.TypeArguments.Count > 0)
  1671. {
  1672. StringBuilder localNameBuilder = new StringBuilder();
  1673. StringBuilder argNamespacesBuilder = new StringBuilder();
  1674. bool parametersFromBuiltInNamespaces = true;
  1675. IList<int> nestedParamCounts = GetDataContractNameForGenericName(localName, localNameBuilder);
  1676. foreach (CodeTypeReference typeArg in typeReference.TypeArguments)
  1677. {
  1678. string typeArgName, typeArgNs;
  1679. GetDefaultStableName(typeArg, out typeArgName, out typeArgNs);
  1680. localNameBuilder.Append(typeArgName);
  1681. argNamespacesBuilder.Append(" ").Append(typeArgNs);
  1682. if (parametersFromBuiltInNamespaces)
  1683. parametersFromBuiltInNamespaces = IsBuiltInNamespace(typeArgNs);
  1684. }
  1685. if (nestedParamCounts.Count > 1 || !parametersFromBuiltInNamespaces)
  1686. {
  1687. foreach (int count in nestedParamCounts)
  1688. argNamespacesBuilder.Insert(0, count).Insert(0, " ");
  1689. localNameBuilder.Append(GetNamespacesDigest(argNamespacesBuilder.ToString()));
  1690. }
  1691. localName = localNameBuilder.ToString();
  1692. }
  1693. localName = DataContract.EncodeLocalName(localName);
  1694. ns = GetDefaultStableNamespace(ns);
  1695. }
  1696. internal static string GetDataContractNamespaceFromUri(string uriString)
  1697. {
  1698. return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString;
  1699. }
  1700. static string GetGlobalDataContractNamespace(string clrNs, ICustomAttributeProvider customAttribuetProvider)
  1701. {
  1702. object[] nsAttributes = customAttribuetProvider.GetCustomAttributes(typeof(ContractNamespaceAttribute), false);
  1703. string dataContractNs = null;
  1704. for (int i = 0; i < nsAttributes.Length; i++)
  1705. {
  1706. ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i];
  1707. string clrNsInAttribute = nsAttribute.ClrNamespace;
  1708. if (clrNsInAttribute == null)
  1709. clrNsInAttribute = String.Empty;
  1710. if (clrNsInAttribute == clrNs)
  1711. {
  1712. if (nsAttribute.ContractNamespace == null)
  1713. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.InvalidGlobalDataContractNamespace, clrNs)));
  1714. if (dataContractNs != null)
  1715. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.DataContractNamespaceAlreadySet, dataContractNs, nsAttribute.ContractNamespace, clrNs)));
  1716. dataContractNs = nsAttribute.ContractNamespace;
  1717. }
  1718. }
  1719. return dataContractNs;
  1720. }
  1721. private static string GetNamespacesDigest(string namespaces)
  1722. {
  1723. byte[] namespaceBytes = Encoding.UTF8.GetBytes(namespaces);
  1724. byte[] digestBytes = HashHelper.ComputeHash(namespaceBytes);
  1725. char[] digestChars = new char[24];
  1726. const int digestLen = 6;
  1727. int digestCharsLen = Convert.ToBase64CharArray(digestBytes, 0, digestLen, digestChars, 0);
  1728. StringBuilder digest = new StringBuilder();
  1729. for (int i = 0; i < digestCharsLen; i++)
  1730. {
  1731. char ch = digestChars[i];
  1732. switch (ch)
  1733. {
  1734. case '=':
  1735. break;
  1736. case '/':
  1737. digest.Append("_S");
  1738. break;
  1739. case '+':
  1740. digest.Append("_P");
  1741. break;
  1742. default:
  1743. digest.Append(ch);
  1744. break;
  1745. }
  1746. }
  1747. return digest.ToString();
  1748. }
  1749. private static string ExpandGenericParameters(string format, Type type)
  1750. {
  1751. GenericNameProvider genericNameProviderForType = new GenericNameProvider(type);
  1752. return ExpandGenericParameters(format, genericNameProviderForType);
  1753. }
  1754. internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider)
  1755. {
  1756. string digest = null;
  1757. StringBuilder typeName = new StringBuilder();
  1758. IList<int> nestedParameterCounts = genericNameProvider.GetNestedParameterCounts();
  1759. for (int i = 0; i < format.Length; i++)
  1760. {
  1761. char ch = format[i];
  1762. if (ch == '{')
  1763. {
  1764. i++;
  1765. int start = i;
  1766. for (; i < format.Length; i++)
  1767. if (format[i] == '}')
  1768. break;
  1769. if (i == format.Length)
  1770. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericNameBraceMismatch, format, genericNameProvider.GetGenericTypeName())));
  1771. if (format[start] == '#' && i == (start + 1))
  1772. {
  1773. if (nestedParameterCounts.Count > 1 || !genericNameProvider.ParametersFromBuiltInNamespaces)
  1774. {
  1775. if (digest == null)
  1776. {
  1777. StringBuilder namespaces = new StringBuilder(genericNameProvider.GetNamespaces());
  1778. foreach (int count in nestedParameterCounts)
  1779. namespaces.Insert(0, count).Insert(0, " ");
  1780. digest = GetNamespacesDigest(namespaces.ToString());
  1781. }
  1782. typeName.Append(digest);
  1783. }
  1784. }
  1785. else
  1786. {
  1787. int paramIndex;
  1788. if (!Int32.TryParse(format.Substring(start, i - start), out paramIndex) || paramIndex < 0 || paramIndex >= genericNameProvider.GetParameterCount())
  1789. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.GenericParameterNotValid, format.Substring(start, i - start), genericNameProvider.GetGenericTypeName(), genericNameProvider.GetParameterCount() - 1)));
  1790. typeName.Append(genericNameProvider.GetParameterName(paramIndex));
  1791. }
  1792. }
  1793. else
  1794. typeName.Append(ch);
  1795. }
  1796. return typeName.ToString();
  1797. }
  1798. static internal bool IsTypeNullable(Type type)
  1799. {
  1800. return !type.IsValueType ||
  1801. (type.IsGenericType &&
  1802. type.GetGenericTypeDefinition() == Globals.TypeOfNullable);
  1803. }
  1804. public static void ThrowTypeNotSerializable(Type type)
  1805. {
  1806. ThrowInvalidDataContractException(SR.GetString(SR.TypeNotSerializable, type), type);
  1807. }
  1808. #if !NO_CONFIGURATION
  1809. [Fx.Tag.SecurityNote(Critical = "configSection value is fetched under an elevation; need to protected access to it.")]
  1810. [SecurityCritical]
  1811. static DataContractSerializerSection configSection;
  1812. static DataContractSerializerSection ConfigSection
  1813. {
  1814. [Fx.Tag.SecurityNote(Critical = "Calls Security Critical method DataContractSerializerSection.UnsafeGetSection and stores result in"
  1815. + " SecurityCritical field configSection.")]
  1816. [SecurityCritical]
  1817. get
  1818. {
  1819. if (configSection == null)
  1820. configSection = DataContractSerializerSection.UnsafeGetSection();
  1821. return configSection;
  1822. }
  1823. }
  1824. #endif
  1825. internal static DataContractDictionary ImportKnownTypeAttributes(Type type)
  1826. {
  1827. DataContractDictionary knownDataContracts = null;
  1828. Dictionary<Type, Type> typesChecked = new Dictionary<Type, Type>();
  1829. ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts);
  1830. return knownDataContracts;
  1831. }
  1832. [SuppressMessage(FxCop.Category.Usage, "CA2301:EmbeddableTypesInContainersRule", MessageId = "typesChecked", Justification = "No need to support type equivalence here.")]
  1833. static void ImportKnownTypeAttributes(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary knownDataContracts)
  1834. {
  1835. if (TD.ImportKnownTypesStartIsEnabled())
  1836. {
  1837. TD.ImportKnownTypesStart();
  1838. }
  1839. while (type != null && DataContract.IsTypeSerializable(type))
  1840. {
  1841. if (typesChecked.ContainsKey(type))
  1842. return;
  1843. typesChecked.Add(type, type);
  1844. object[] knownTypeAttributes = type.GetCustomAttributes(Globals.TypeOfKnownTypeAttribute, false);
  1845. if (knownTypeAttributes != null)
  1846. {
  1847. KnownTypeAttribute kt;
  1848. bool useMethod = false, useType = false;
  1849. for (int i = 0; i < knownTypeAttributes.Length; ++i)
  1850. {
  1851. kt = (KnownTypeAttribute)knownTypeAttributes[i];
  1852. if (kt.Type != null)
  1853. {
  1854. if (useMethod)
  1855. {
  1856. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type);
  1857. }
  1858. CheckAndAdd(kt.Type, typesChecked, ref knownDataContracts);
  1859. useType = true;
  1860. }
  1861. else
  1862. {
  1863. if (useMethod || useType)
  1864. {
  1865. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type);
  1866. }
  1867. string methodName = kt.MethodName;
  1868. if (methodName == null)
  1869. {
  1870. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type);
  1871. }
  1872. if (methodName.Length == 0)
  1873. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type);
  1874. MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, Globals.EmptyTypeArray, null);
  1875. if (method == null)
  1876. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type);
  1877. if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType))
  1878. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type);
  1879. object types = method.Invoke(null, Globals.EmptyObjectArray);
  1880. if (types == null)
  1881. {
  1882. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type);
  1883. }
  1884. foreach (Type ty in (IEnumerable<Type>)types)
  1885. {
  1886. if (ty == null)
  1887. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.KnownTypeAttributeValidMethodTypes, DataContract.GetClrTypeFullName(type)), type);
  1888. CheckAndAdd(ty, typesChecked, ref knownDataContracts);
  1889. }
  1890. useMethod = true;
  1891. }
  1892. }
  1893. }
  1894. LoadKnownTypesFromConfig(type, typesChecked, ref knownDataContracts);
  1895. type = type.BaseType;
  1896. }
  1897. if (TD.ImportKnownTypesStopIsEnabled())
  1898. {
  1899. TD.ImportKnownTypesStop();
  1900. }
  1901. }
  1902. [Fx.Tag.SecurityNote(Critical = "Accesses SecurityCritical property ConfigSection.",
  1903. Safe = "Completely processes ConfigSection and only makes available the processed result."
  1904. + " The ConfigSection instance is not leaked.")]
  1905. [SecuritySafeCritical]
  1906. static void LoadKnownTypesFromConfig(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary knownDataContracts)
  1907. {
  1908. #if !NO_CONFIGURATION
  1909. // Pull known types from config
  1910. if (ConfigSection != null)
  1911. {
  1912. DeclaredTypeElementCollection elements = ConfigSection.DeclaredTypes;
  1913. Type rootType = type;
  1914. Type[] genArgs = null;
  1915. CheckRootTypeInConfigIsGeneric(type, ref rootType, ref genArgs);
  1916. DeclaredTypeElement elem = elements[rootType.AssemblyQualifiedName];
  1917. if (elem != null)
  1918. {
  1919. if (IsElemTypeNullOrNotEqualToRootType(elem.Type, rootType))
  1920. {
  1921. elem = null;
  1922. }
  1923. }
  1924. if (elem == null)
  1925. {
  1926. for (int i = 0; i < elements.Count; ++i)
  1927. {
  1928. if (IsCollectionElementTypeEqualToRootType(elements[i].Type, rootType))
  1929. {
  1930. elem = elements[i];
  1931. break;
  1932. }
  1933. }
  1934. }
  1935. if (elem != null)
  1936. {
  1937. for (int i = 0; i < elem.KnownTypes.Count; ++i)
  1938. {
  1939. Type knownType = elem.KnownTypes[i].GetType(elem.Type, genArgs);
  1940. if (knownType != null)
  1941. {
  1942. CheckAndAdd(knownType, typesChecked, ref knownDataContracts);
  1943. }
  1944. }
  1945. }
  1946. }
  1947. #endif
  1948. }
  1949. private static void CheckRootTypeInConfigIsGeneric(Type type, ref Type rootType, ref Type[] genArgs)
  1950. {
  1951. if (rootType.IsGenericType)
  1952. {
  1953. if (!rootType.ContainsGenericParameters)
  1954. {
  1955. genArgs = rootType.GetGenericArguments();
  1956. rootType = rootType.GetGenericTypeDefinition();
  1957. }
  1958. else
  1959. {
  1960. DataContract.ThrowInvalidDataContractException(SR.GetString(SR.TypeMustBeConcrete, type), type);
  1961. }
  1962. }
  1963. }
  1964. private static bool IsElemTypeNullOrNotEqualToRootType(string elemTypeName, Type rootType)
  1965. {
  1966. Type t = Type.GetType(elemTypeName, false);
  1967. if (t == null || !rootType.Equals(t))
  1968. {
  1969. return true;
  1970. }
  1971. return false;
  1972. }
  1973. private static bool IsCollectionElementTypeEqualToRootType(string collectionElementTypeName, Type rootType)
  1974. {
  1975. if (collectionElementTypeName.StartsWith(DataContract.GetClrTypeFullName(rootType), StringComparison.Ordinal))
  1976. {
  1977. Type t = Type.GetType(collectionElementTypeName, false);
  1978. if (t != null)
  1979. {
  1980. if (t.IsGenericType && !IsOpenGenericType(t))
  1981. {
  1982. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.KnownTypeConfigClosedGenericDeclared, collectionElementTypeName)));
  1983. }
  1984. else if (rootType.Equals(t))
  1985. {
  1986. return true;
  1987. }
  1988. }
  1989. }
  1990. return false;
  1991. }
  1992. [Fx.Tag.SecurityNote(Critical = "Fetches the critical dataContractAdapterType.",
  1993. Safe = "The critical dataContractAdapterType is only used for local comparison and is not leaked beyond this method.")]
  1994. [SecurityCritical, SecurityTreatAsSafe]
  1995. internal static void CheckAndAdd(Type type, Dictionary<Type, Type> typesChecked, ref DataContractDictionary nameToDataContractTable)
  1996. {
  1997. type = DataContract.UnwrapNullableType(type);
  1998. DataContract dataContract = DataContract.GetDataContract(type);
  1999. DataContract alreadyExistingContract;
  2000. if (nameToDataContractTable == null)
  2001. {
  2002. nameToDataContractTable = new DataContractDictionary();
  2003. }
  2004. else if (nameToDataContractTable.TryGetValue(dataContract.StableName, out alreadyExistingContract))
  2005. {
  2006. if (alreadyExistingContract.UnderlyingType != DataContractCriticalHelper.GetDataContractAdapterType(type))
  2007. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.DupContractInKnownTypes, type, alreadyExistingContract.UnderlyingType, dataContract.StableName.Namespace, dataContract.StableName.Name)));
  2008. return;
  2009. }
  2010. nameToDataContractTable.Add(dataContract.StableName, dataContract);
  2011. ImportKnownTypeAttributes(type, typesChecked, ref nameToDataContractTable);
  2012. }
  2013. static bool IsOpenGenericType(Type t)
  2014. {
  2015. Type[] args = t.GetGenericArguments();
  2016. for (int i = 0; i < args.Length; ++i)
  2017. if (!args[i].IsGenericParameter)
  2018. return false;
  2019. return true;
  2020. }
  2021. public sealed override bool Equals(object other)
  2022. {
  2023. if ((object)this == other)
  2024. return true;
  2025. return Equals(other, new Dictionary<DataContractPairKey, object>());
  2026. }
  2027. internal virtual bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
  2028. {
  2029. DataContract dataContract = other as DataContract;
  2030. if (dataContract != null)
  2031. {
  2032. return (StableName.Name == dataContract.StableName.Name && StableName.Namespace == dataContract.StableName.Namespace && IsReference == dataContract.IsReference);
  2033. }
  2034. return false;
  2035. }
  2036. internal bool IsEqualOrChecked(object other, Dictionary<DataContractPairKey, object> checkedContracts)
  2037. {
  2038. if ((object)this == other)
  2039. return true;
  2040. if (checkedContracts != null)
  2041. {
  2042. DataContractPairKey contractPairKey = new DataContractPairKey(this, other);
  2043. if (checkedContracts.ContainsKey(contractPairKey))
  2044. return true;
  2045. checkedContracts.Add(contractPairKey, null);
  2046. }
  2047. return false;
  2048. }
  2049. public override int GetHashCode()
  2050. {
  2051. return base.GetHashCode();
  2052. }
  2053. internal void ThrowInvalidDataContractException(string message)
  2054. {
  2055. ThrowInvalidDataContractException(message, UnderlyingType);
  2056. }
  2057. #if NO_DYNAMIC_CODEGEN
  2058. static internal bool IsTypeVisible(Type t)
  2059. {
  2060. return true;
  2061. }
  2062. #else
  2063. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
  2064. + " Since this information is used to determine whether to give the generated code access"
  2065. + " permissions to private members, any changes to the logic should be reviewed.")]
  2066. static internal bool IsTypeVisible(Type t)
  2067. {
  2068. // Generic parameters are always considered visible.
  2069. if (t.IsGenericParameter)
  2070. {
  2071. return true;
  2072. }
  2073. // The normal Type.IsVisible check requires all nested types to be IsNestedPublic.
  2074. // This does not comply with our convention where they can also have InternalsVisibleTo
  2075. // with our assembly. The following method performs a recursive walk back the declaring
  2076. // type hierarchy to perform this enhanced IsVisible check.
  2077. if (!IsTypeAndDeclaringTypeVisible(t))
  2078. {
  2079. return false;
  2080. }
  2081. // All generic argument types must also be visible.
  2082. // Nested types perform this test recursively for all their declaring types.
  2083. foreach (Type genericType in t.GetGenericArguments())
  2084. {
  2085. if (!IsTypeVisible(genericType))
  2086. {
  2087. return false;
  2088. }
  2089. }
  2090. return true;
  2091. }
  2092. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
  2093. + " Since this information is used to determine whether to give the generated code access"
  2094. + " permissions to private members, any changes to the logic should be reviewed.")]
  2095. static internal bool IsTypeAndDeclaringTypeVisible(Type t)
  2096. {
  2097. // Arrays, etc. must consider the underlying element type because the
  2098. // non-element type does not reflect the same type nesting. For example,
  2099. // MyClass[] would not show as a nested type, even when MyClass is nested.
  2100. if (t.HasElementType)
  2101. {
  2102. return IsTypeVisible(t.GetElementType());
  2103. }
  2104. // Nested types are not visible unless their declaring type is visible.
  2105. // Additionally, they must be either IsNestedPublic or in an assembly with InternalsVisibleTo this current assembly.
  2106. // Non-nested types must be public or have this same InternalsVisibleTo relation.
  2107. return t.IsNested
  2108. ? (t.IsNestedPublic || IsTypeVisibleInSerializationModule(t)) && IsTypeVisible(t.DeclaringType)
  2109. : t.IsPublic || IsTypeVisibleInSerializationModule(t);
  2110. }
  2111. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks constructor visibility to calculate if access to it requires MemberAccessPermission."
  2112. + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
  2113. + " Since this information is used to determine whether to give the generated code access"
  2114. + " permissions to private members, any changes to the logic should be reviewed.")]
  2115. static internal bool ConstructorRequiresMemberAccess(ConstructorInfo ctor)
  2116. {
  2117. return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor);
  2118. }
  2119. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks method visibility to calculate if access to it requires MemberAccessPermission."
  2120. + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
  2121. + " Since this information is used to determine whether to give the generated code access"
  2122. + " permissions to private members, any changes to the logic should be reviewed.")]
  2123. static internal bool MethodRequiresMemberAccess(MethodInfo method)
  2124. {
  2125. return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method);
  2126. }
  2127. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks field visibility to calculate if access to it requires MemberAccessPermission."
  2128. + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
  2129. + " Since this information is used to determine whether to give the generated code access"
  2130. + " permissions to private members, any changes to the logic should be reviewed.")]
  2131. static internal bool FieldRequiresMemberAccess(FieldInfo field)
  2132. {
  2133. return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field);
  2134. }
  2135. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks type visibility to calculate if access to it requires MemberAccessPermission."
  2136. + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
  2137. + " Since this information is used to determine whether to give the generated code access"
  2138. + " permissions to private members, any changes to the logic should be reviewed.")]
  2139. static bool IsTypeVisibleInSerializationModule(Type type)
  2140. {
  2141. return (type.Module.Equals(typeof(CodeGenerator).Module) || IsAssemblyFriendOfSerialization(type.Assembly)) && !type.IsNestedPrivate;
  2142. }
  2143. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission."
  2144. + " note: does local check for visibility, assuming that the declaring Type visibility has been checked."
  2145. + " Since this information is used to determine whether to give the generated code access"
  2146. + " permissions to private members, any changes to the logic should be reviewed.")]
  2147. static bool IsMemberVisibleInSerializationModule(MemberInfo member)
  2148. {
  2149. if (!IsTypeVisibleInSerializationModule(member.DeclaringType))
  2150. return false;
  2151. if (member is MethodInfo)
  2152. {
  2153. MethodInfo method = (MethodInfo)member;
  2154. return (method.IsAssembly || method.IsFamilyOrAssembly);
  2155. }
  2156. else if (member is FieldInfo)
  2157. {
  2158. FieldInfo field = (FieldInfo)member;
  2159. return (field.IsAssembly || field.IsFamilyOrAssembly) && IsTypeVisible(field.FieldType);
  2160. }
  2161. else if (member is ConstructorInfo)
  2162. {
  2163. ConstructorInfo constructor = (ConstructorInfo)member;
  2164. return (constructor.IsAssembly || constructor.IsFamilyOrAssembly);
  2165. }
  2166. return false;
  2167. }
  2168. [Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission."
  2169. + " Since this information is used to determine whether to give the generated code access"
  2170. + " permissions to private members, any changes to the logic should be reviewed.")]
  2171. internal static bool IsAssemblyFriendOfSerialization(Assembly assembly)
  2172. {
  2173. InternalsVisibleToAttribute[] internalsVisibleAttributes = (InternalsVisibleToAttribute[])assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), false);
  2174. foreach (InternalsVisibleToAttribute internalsVisibleAttribute in internalsVisibleAttributes)
  2175. {
  2176. string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName;
  2177. if (Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.SimpleSRSInternalsVisiblePattern) ||
  2178. Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.FullSRSInternalsVisiblePattern))
  2179. {
  2180. return true;
  2181. }
  2182. }
  2183. return false;
  2184. }
  2185. #endif
  2186. }
  2187. interface IGenericNameProvider
  2188. {
  2189. int GetParameterCount();
  2190. IList<int> GetNestedParameterCounts();
  2191. string GetParameterName(int paramIndex);
  2192. string GetNamespaces();
  2193. string GetGenericTypeName();
  2194. bool ParametersFromBuiltInNamespaces { get; }
  2195. }
  2196. class GenericNameProvider : IGenericNameProvider
  2197. {
  2198. string genericTypeName;
  2199. object[] genericParams; //Type or DataContract
  2200. IList<int> nestedParamCounts;
  2201. internal GenericNameProvider(Type type)
  2202. : this(DataContract.GetClrTypeFullName(type.GetGenericTypeDefinition()), type.GetGenericArguments())
  2203. {
  2204. }
  2205. internal GenericNameProvider(string genericTypeName, object[] genericParams)
  2206. {
  2207. this.genericTypeName = genericTypeName;
  2208. this.genericParams = new object[genericParams.Length];
  2209. genericParams.CopyTo(this.genericParams, 0);
  2210. string name, ns;
  2211. DataContract.GetClrNameAndNamespace(genericTypeName, out name, out ns);
  2212. this.nestedParamCounts = DataContract.GetDataContractNameForGenericName(name, null);
  2213. }
  2214. public int GetParameterCount()
  2215. {
  2216. return genericParams.Length;
  2217. }
  2218. public IList<int> GetNestedParameterCounts()
  2219. {
  2220. return nestedParamCounts;
  2221. }
  2222. public string GetParameterName(int paramIndex)
  2223. {
  2224. return GetStableName(paramIndex).Name;
  2225. }
  2226. public string GetNamespaces()
  2227. {
  2228. StringBuilder namespaces = new StringBuilder();
  2229. for (int j = 0; j < GetParameterCount(); j++)
  2230. namespaces.Append(" ").Append(GetStableName(j).Namespace);
  2231. return namespaces.ToString();
  2232. }
  2233. public string GetGenericTypeName()
  2234. {
  2235. return genericTypeName;
  2236. }
  2237. public bool ParametersFromBuiltInNamespaces
  2238. {
  2239. get
  2240. {
  2241. bool parametersFromBuiltInNamespaces = true;
  2242. for (int j = 0; j < GetParameterCount(); j++)
  2243. {
  2244. if (parametersFromBuiltInNamespaces)
  2245. parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(GetStableName(j).Namespace);
  2246. else
  2247. break;
  2248. }
  2249. return parametersFromBuiltInNamespaces;
  2250. }
  2251. }
  2252. XmlQualifiedName GetStableName(int i)
  2253. {
  2254. object o = genericParams[i];
  2255. XmlQualifiedName qname = o as XmlQualifiedName;
  2256. if (qname == null)
  2257. {
  2258. Type paramType = o as Type;
  2259. if (paramType != null)
  2260. genericParams[i] = qname = DataContract.GetStableName(paramType);
  2261. else
  2262. genericParams[i] = qname = ((DataContract)o).StableName;
  2263. }
  2264. return qname;
  2265. }
  2266. }
  2267. class GenericInfo : IGenericNameProvider
  2268. {
  2269. string genericTypeName;
  2270. XmlQualifiedName stableName;
  2271. List<GenericInfo> paramGenericInfos;
  2272. List<int> nestedParamCounts;
  2273. internal GenericInfo(XmlQualifiedName stableName, string genericTypeName)
  2274. {
  2275. this.stableName = stableName;
  2276. this.genericTypeName = genericTypeName;
  2277. this.nestedParamCounts = new List<int>();
  2278. this.nestedParamCounts.Add(0);
  2279. }
  2280. internal void Add(GenericInfo actualParamInfo)
  2281. {
  2282. if (paramGenericInfos == null)
  2283. paramGenericInfos = new List<GenericInfo>();
  2284. paramGenericInfos.Add(actualParamInfo);
  2285. }
  2286. internal void AddToLevel(int level, int count)
  2287. {
  2288. if (level >= nestedParamCounts.Count)
  2289. {
  2290. do
  2291. {
  2292. nestedParamCounts.Add((level == nestedParamCounts.Count) ? count : 0);
  2293. } while (level >= nestedParamCounts.Count);
  2294. }
  2295. else
  2296. nestedParamCounts[level] = nestedParamCounts[level] + count;
  2297. }
  2298. internal XmlQualifiedName GetExpandedStableName()
  2299. {
  2300. if (paramGenericInfos == null)
  2301. return stableName;
  2302. return new XmlQualifiedName(DataContract.EncodeLocalName(DataContract.ExpandGenericParameters(XmlConvert.DecodeName(stableName.Name), this)), stableName.Namespace);
  2303. }
  2304. internal string GetStableNamespace()
  2305. {
  2306. return stableName.Namespace;
  2307. }
  2308. internal XmlQualifiedName StableName
  2309. {
  2310. get { return stableName; }
  2311. }
  2312. internal IList<GenericInfo> Parameters
  2313. {
  2314. get { return paramGenericInfos; }
  2315. }
  2316. public int GetParameterCount()
  2317. {
  2318. return paramGenericInfos.Count;
  2319. }
  2320. public IList<int> GetNestedParameterCounts()
  2321. {
  2322. return nestedParamCounts;
  2323. }
  2324. public string GetParameterName(int paramIndex)
  2325. {
  2326. return paramGenericInfos[paramIndex].GetExpandedStableName().Name;
  2327. }
  2328. public string GetNamespaces()
  2329. {
  2330. StringBuilder namespaces = new StringBuilder();
  2331. for (int j = 0; j < paramGenericInfos.Count; j++)
  2332. namespaces.Append(" ").Append(paramGenericInfos[j].GetStableNamespace());
  2333. return namespaces.ToString();
  2334. }
  2335. public string GetGenericTypeName()
  2336. {
  2337. return genericTypeName;
  2338. }
  2339. public bool ParametersFromBuiltInNamespaces
  2340. {
  2341. get
  2342. {
  2343. bool parametersFromBuiltInNamespaces = true;
  2344. for (int j = 0; j < paramGenericInfos.Count; j++)
  2345. {
  2346. if (parametersFromBuiltInNamespaces)
  2347. parametersFromBuiltInNamespaces = DataContract.IsBuiltInNamespace(paramGenericInfos[j].GetStableNamespace());
  2348. else
  2349. break;
  2350. }
  2351. return parametersFromBuiltInNamespaces;
  2352. }
  2353. }
  2354. }
  2355. internal class DataContractPairKey
  2356. {
  2357. object object1;
  2358. object object2;
  2359. public DataContractPairKey(object object1, object object2)
  2360. {
  2361. this.object1 = object1;
  2362. this.object2 = object2;
  2363. }
  2364. public override bool Equals(object other)
  2365. {
  2366. DataContractPairKey otherKey = other as DataContractPairKey;
  2367. if (otherKey == null)
  2368. return false;
  2369. return ((otherKey.object1 == object1 && otherKey.object2 == object2) || (otherKey.object1 == object2 && otherKey.object2 == object1));
  2370. }
  2371. public override int GetHashCode()
  2372. {
  2373. return object1.GetHashCode() ^ object2.GetHashCode();
  2374. }
  2375. }
  2376. class TypeHandleRefEqualityComparer : IEqualityComparer<TypeHandleRef>
  2377. {
  2378. public bool Equals(TypeHandleRef x, TypeHandleRef y)
  2379. {
  2380. return x.Value.Equals(y.Value);
  2381. }
  2382. public int GetHashCode(TypeHandleRef obj)
  2383. {
  2384. return obj.Value.GetHashCode();
  2385. }
  2386. }
  2387. class TypeHandleRef
  2388. {
  2389. RuntimeTypeHandle value;
  2390. public TypeHandleRef()
  2391. {
  2392. }
  2393. public TypeHandleRef(RuntimeTypeHandle value)
  2394. {
  2395. this.value = value;
  2396. }
  2397. public RuntimeTypeHandle Value
  2398. {
  2399. get
  2400. {
  2401. return this.value;
  2402. }
  2403. set
  2404. {
  2405. this.value = value;
  2406. }
  2407. }
  2408. }
  2409. class IntRef
  2410. {
  2411. int value;
  2412. public IntRef(int value)
  2413. {
  2414. this.value = value;
  2415. }
  2416. public int Value
  2417. {
  2418. get
  2419. {
  2420. return this.value;
  2421. }
  2422. }
  2423. }
  2424. }