AssemblyName.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. //
  2. // System.Reflection/AssemblyName.cs
  3. //
  4. // Authors:
  5. // Paolo Molaro ([email protected])
  6. // Sebastien Pouliot <[email protected]>
  7. //
  8. // (C) 2001 Ximian, Inc. http://www.ximian.com
  9. // Portions (C) 2002 Motus Technologies Inc. (http://www.motus.com)
  10. // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System.Configuration.Assemblies;
  32. using System.Globalization;
  33. using System.Runtime.Serialization;
  34. using System.Security;
  35. using System.Security.Cryptography;
  36. using System.Security.Permissions;
  37. using System.Text;
  38. using System.Runtime.InteropServices;
  39. using System.Runtime.CompilerServices;
  40. using System.IO;
  41. using Mono;
  42. using Mono.Security;
  43. using Mono.Security.Cryptography;
  44. namespace System.Reflection {
  45. // References:
  46. // a. Uniform Resource Identifiers (URI): Generic Syntax
  47. // http://www.ietf.org/rfc/rfc2396.txt
  48. [ComVisible (true)]
  49. [ComDefaultInterfaceAttribute (typeof (_AssemblyName))]
  50. [Serializable]
  51. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  52. [StructLayout (LayoutKind.Sequential)]
  53. #if MOBILE
  54. public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback {
  55. #else
  56. public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback, _AssemblyName {
  57. #endif
  58. #pragma warning disable 169
  59. #region Synch with object-internals.h
  60. string name;
  61. string codebase;
  62. int major, minor, build, revision;
  63. CultureInfo cultureinfo;
  64. AssemblyNameFlags flags;
  65. AssemblyHashAlgorithm hashalg;
  66. StrongNameKeyPair keypair;
  67. byte[] publicKey;
  68. byte[] keyToken;
  69. AssemblyVersionCompatibility versioncompat;
  70. Version version;
  71. ProcessorArchitecture processor_architecture = ProcessorArchitecture.None;
  72. #endregion
  73. #pragma warning restore 169
  74. AssemblyContentType contentType;
  75. public AssemblyName ()
  76. {
  77. // defaults
  78. versioncompat = AssemblyVersionCompatibility.SameMachine;
  79. }
  80. [MethodImpl (MethodImplOptions.InternalCall)]
  81. static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined);
  82. public AssemblyName (string assemblyName)
  83. {
  84. if (assemblyName == null)
  85. throw new ArgumentNullException ("assemblyName");
  86. if (assemblyName.Length < 1)
  87. throw new ArgumentException ("assemblyName cannot have zero length.");
  88. using (var name = RuntimeMarshal.MarshalString (assemblyName)) {
  89. MonoAssemblyName nativeName;
  90. bool isVersionDefined, isTokenDefined;
  91. //ParseName free the name if it fails.
  92. if (!ParseAssemblyName (name.Value, out nativeName, out isVersionDefined, out isTokenDefined))
  93. throw new FileLoadException ("The assembly name is invalid.");
  94. try {
  95. unsafe {
  96. this.FillName (&nativeName, null, isVersionDefined, false, isTokenDefined);
  97. }
  98. } finally {
  99. RuntimeMarshal.FreeAssemblyName (ref nativeName);
  100. }
  101. }
  102. }
  103. [MonoLimitation ("Not used, as the values are too limited; Mono supports more")]
  104. public ProcessorArchitecture ProcessorArchitecture {
  105. get {
  106. return processor_architecture;
  107. }
  108. set {
  109. processor_architecture = value;
  110. }
  111. }
  112. internal AssemblyName (SerializationInfo si, StreamingContext sc)
  113. {
  114. name = si.GetString ("_Name");
  115. codebase = si.GetString ("_CodeBase");
  116. version = (Version)si.GetValue ("_Version", typeof (Version));
  117. publicKey = (byte[])si.GetValue ("_PublicKey", typeof (byte[]));
  118. keyToken = (byte[])si.GetValue ("_PublicKeyToken", typeof (byte[]));
  119. hashalg = (AssemblyHashAlgorithm)si.GetValue ("_HashAlgorithm", typeof (AssemblyHashAlgorithm));
  120. keypair = (StrongNameKeyPair)si.GetValue ("_StrongNameKeyPair", typeof (StrongNameKeyPair));
  121. versioncompat = (AssemblyVersionCompatibility)si.GetValue ("_VersionCompatibility", typeof (AssemblyVersionCompatibility));
  122. flags = (AssemblyNameFlags)si.GetValue ("_Flags", typeof (AssemblyNameFlags));
  123. int lcid = si.GetInt32 ("_CultureInfo");
  124. if (lcid != -1) cultureinfo = new CultureInfo (lcid);
  125. }
  126. public string Name {
  127. get { return name; }
  128. set { name = value; }
  129. }
  130. public string CodeBase {
  131. get { return codebase; }
  132. set { codebase = value; }
  133. }
  134. public string EscapedCodeBase {
  135. get {
  136. if (codebase == null)
  137. return null;
  138. return Uri.EscapeString (codebase, false, true, true);
  139. }
  140. }
  141. public CultureInfo CultureInfo {
  142. get { return cultureinfo; }
  143. set { cultureinfo = value; }
  144. }
  145. public AssemblyNameFlags Flags {
  146. get { return flags; }
  147. set { flags = value; }
  148. }
  149. public string FullName {
  150. get {
  151. if (name == null)
  152. return string.Empty;
  153. StringBuilder fname = new StringBuilder ();
  154. if (Char.IsWhiteSpace (name [0]))
  155. fname.Append ("\"" + name + "\"");
  156. else
  157. fname.Append (name);
  158. if (Version != null) {
  159. fname.Append (", Version=");
  160. fname.Append (Version.ToString ());
  161. }
  162. if (cultureinfo != null) {
  163. fname.Append (", Culture=");
  164. if (cultureinfo.LCID == CultureInfo.InvariantCulture.LCID)
  165. fname.Append ("neutral");
  166. else
  167. fname.Append (cultureinfo.Name);
  168. }
  169. byte [] pub_tok = InternalGetPublicKeyToken ();
  170. if (pub_tok != null) {
  171. if (pub_tok.Length == 0)
  172. fname.Append (", PublicKeyToken=null");
  173. else {
  174. fname.Append (", PublicKeyToken=");
  175. for (int i = 0; i < pub_tok.Length; i++)
  176. fname.Append (pub_tok[i].ToString ("x2"));
  177. }
  178. }
  179. if ((Flags & AssemblyNameFlags.Retargetable) != 0)
  180. fname.Append (", Retargetable=Yes");
  181. return fname.ToString ();
  182. }
  183. }
  184. public AssemblyHashAlgorithm HashAlgorithm {
  185. get { return hashalg; }
  186. set { hashalg = value; }
  187. }
  188. public StrongNameKeyPair KeyPair {
  189. get { return keypair; }
  190. set { keypair = value; }
  191. }
  192. public Version Version {
  193. get {
  194. return version;
  195. }
  196. set {
  197. version = value;
  198. if (value == null)
  199. major = minor = build = revision = 0;
  200. else {
  201. major = value.Major;
  202. minor = value.Minor;
  203. build = value.Build;
  204. revision = value.Revision;
  205. }
  206. }
  207. }
  208. public AssemblyVersionCompatibility VersionCompatibility {
  209. get { return versioncompat; }
  210. set { versioncompat = value; }
  211. }
  212. public override string ToString ()
  213. {
  214. string name = FullName;
  215. return (name != null) ? name : base.ToString ();
  216. }
  217. public byte[] GetPublicKey()
  218. {
  219. return publicKey;
  220. }
  221. public byte[] GetPublicKeyToken ()
  222. {
  223. if (keyToken != null)
  224. return keyToken;
  225. if (publicKey == null)
  226. return null;
  227. if (publicKey.Length == 0)
  228. return EmptyArray<byte>.Value;
  229. if (!IsPublicKeyValid)
  230. throw new SecurityException ("The public key is not valid.");
  231. keyToken = ComputePublicKeyToken ();
  232. return keyToken;
  233. }
  234. private bool IsPublicKeyValid {
  235. get {
  236. // check for ECMA key
  237. if (publicKey.Length == 16) {
  238. int i = 0;
  239. int sum = 0;
  240. while (i < publicKey.Length)
  241. sum += publicKey [i++];
  242. if (sum == 4)
  243. return true;
  244. }
  245. switch (publicKey [0]) {
  246. case 0x00: // public key inside a header
  247. if (publicKey.Length > 12 && publicKey [12] == 0x06) {
  248. #if MOBILE
  249. return true;
  250. #else
  251. try {
  252. CryptoConvert.FromCapiPublicKeyBlob (
  253. publicKey, 12);
  254. return true;
  255. } catch (CryptographicException) {
  256. }
  257. #endif
  258. }
  259. break;
  260. case 0x06: // public key
  261. #if MOBILE
  262. return true;
  263. #else
  264. try {
  265. CryptoConvert.FromCapiPublicKeyBlob (publicKey);
  266. return true;
  267. } catch (CryptographicException) {
  268. }
  269. break;
  270. #endif
  271. case 0x07: // private key
  272. break;
  273. }
  274. return false;
  275. }
  276. }
  277. private byte [] InternalGetPublicKeyToken ()
  278. {
  279. if (keyToken != null)
  280. return keyToken;
  281. if (publicKey == null)
  282. return null;
  283. if (publicKey.Length == 0)
  284. return EmptyArray<byte>.Value;
  285. if (!IsPublicKeyValid)
  286. throw new SecurityException ("The public key is not valid.");
  287. return ComputePublicKeyToken ();
  288. }
  289. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  290. extern unsafe static void get_public_token (byte* token, byte* pubkey, int len);
  291. private unsafe byte [] ComputePublicKeyToken ()
  292. {
  293. byte [] token = new byte [8];
  294. fixed (byte* pkt = token)
  295. fixed (byte *pk = publicKey)
  296. get_public_token (pkt, pk, publicKey.Length);
  297. return token;
  298. }
  299. public static bool ReferenceMatchesDefinition (AssemblyName reference, AssemblyName definition)
  300. {
  301. if (reference == null)
  302. throw new ArgumentNullException ("reference");
  303. if (definition == null)
  304. throw new ArgumentNullException ("definition");
  305. // we only compare the simple assembly name to be consistent with MS .NET,
  306. // which is the result of a bug in their implementation (see https://connect.microsoft.com/VisualStudio/feedback/details/752902)
  307. return string.Equals (reference.Name, definition.Name, StringComparison.OrdinalIgnoreCase);
  308. }
  309. public void SetPublicKey (byte[] publicKey)
  310. {
  311. if (publicKey == null)
  312. flags ^= AssemblyNameFlags.PublicKey;
  313. else
  314. flags |= AssemblyNameFlags.PublicKey;
  315. this.publicKey = publicKey;
  316. }
  317. public void SetPublicKeyToken (byte[] publicKeyToken)
  318. {
  319. keyToken = publicKeyToken;
  320. }
  321. [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
  322. public void GetObjectData (SerializationInfo info, StreamingContext context)
  323. {
  324. if (info == null)
  325. throw new ArgumentNullException ("info");
  326. info.AddValue ("_Name", name);
  327. info.AddValue ("_PublicKey", publicKey);
  328. info.AddValue ("_PublicKeyToken", keyToken);
  329. info.AddValue ("_CultureInfo", cultureinfo != null ? cultureinfo.LCID : -1);
  330. info.AddValue ("_CodeBase", codebase);
  331. info.AddValue ("_Version", Version);
  332. info.AddValue ("_HashAlgorithm", hashalg);
  333. info.AddValue ("_HashAlgorithmForControl", AssemblyHashAlgorithm.None);
  334. info.AddValue ("_StrongNameKeyPair", keypair);
  335. info.AddValue ("_VersionCompatibility", versioncompat);
  336. info.AddValue ("_Flags", flags);
  337. info.AddValue ("_HashForControl", null);
  338. }
  339. public object Clone()
  340. {
  341. AssemblyName an = new AssemblyName ();
  342. an.name = name;
  343. an.codebase = codebase;
  344. an.major = major;
  345. an.minor = minor;
  346. an.build = build;
  347. an.revision = revision;
  348. an.version = version;
  349. an.cultureinfo = cultureinfo;
  350. an.flags = flags;
  351. an.hashalg = hashalg;
  352. an.keypair = keypair;
  353. an.publicKey = publicKey;
  354. an.keyToken = keyToken;
  355. an.versioncompat = versioncompat;
  356. an.processor_architecture = processor_architecture;
  357. return an;
  358. }
  359. public void OnDeserialization (object sender)
  360. {
  361. Version = version;
  362. }
  363. public static AssemblyName GetAssemblyName (string assemblyFile)
  364. {
  365. if (assemblyFile == null)
  366. throw new ArgumentNullException ("assemblyFile");
  367. AssemblyName aname = new AssemblyName ();
  368. Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), aname);
  369. return aname;
  370. }
  371. #if !MOBILE
  372. void _AssemblyName.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  373. {
  374. throw new NotImplementedException ();
  375. }
  376. void _AssemblyName.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  377. {
  378. throw new NotImplementedException ();
  379. }
  380. void _AssemblyName.GetTypeInfoCount (out uint pcTInfo)
  381. {
  382. throw new NotImplementedException ();
  383. }
  384. void _AssemblyName.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  385. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  386. {
  387. throw new NotImplementedException ();
  388. }
  389. #endif
  390. public string CultureName {
  391. get {
  392. return (cultureinfo == null)? null : cultureinfo.Name;
  393. }
  394. #if NETSTANDARD
  395. set {
  396. throw new NotImplementedException ();
  397. }
  398. #endif
  399. }
  400. [ComVisibleAttribute(false)]
  401. public AssemblyContentType ContentType {
  402. get {
  403. return contentType;
  404. }
  405. set {
  406. contentType = value;
  407. }
  408. }
  409. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  410. static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assembly_ptr);
  411. internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken)
  412. {
  413. this.name = RuntimeMarshal.PtrToUtf8String (native->name);
  414. this.major = native->major;
  415. this.minor = native->minor;
  416. this.build = native->build;
  417. this.revision = native->revision;
  418. this.flags = (AssemblyNameFlags)native->flags;
  419. this.hashalg = (AssemblyHashAlgorithm)native->hash_alg;
  420. this.versioncompat = AssemblyVersionCompatibility.SameMachine;
  421. this.processor_architecture = (ProcessorArchitecture)native->arch;
  422. if (addVersion)
  423. this.version = new Version (this.major, this.minor, this.build, this.revision);
  424. this.codebase = codeBase;
  425. if (native->culture != IntPtr.Zero)
  426. this.cultureinfo = CultureInfo.CreateCulture ( RuntimeMarshal.PtrToUtf8String (native->culture), false);
  427. if (native->public_key != IntPtr.Zero) {
  428. this.publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key);
  429. this.flags |= AssemblyNameFlags.PublicKey;
  430. } else if (addPublickey) {
  431. this.publicKey = EmptyArray<byte>.Value;
  432. this.flags |= AssemblyNameFlags.PublicKey;
  433. }
  434. // MonoAssemblyName keeps the public key token as an hexadecimal string
  435. if (native->public_key_token [0] != 0) {
  436. byte[] keyToken = new byte [8];
  437. for (int i = 0, j = 0; i < 8; ++i) {
  438. keyToken [i] = (byte)(RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4);
  439. keyToken [i] |= (byte)RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]);
  440. }
  441. this.keyToken = keyToken;
  442. } else if (defaultToken) {
  443. this.keyToken = EmptyArray<byte>.Value;
  444. }
  445. }
  446. internal static AssemblyName Create (Assembly assembly, bool fillCodebase)
  447. {
  448. AssemblyName aname = new AssemblyName ();
  449. unsafe {
  450. MonoAssemblyName *native = GetNativeName (assembly._mono_assembly);
  451. aname.FillName (native, fillCodebase ? assembly.CodeBase : null, true, true, true);
  452. }
  453. return aname;
  454. }
  455. }
  456. }