AssemblyName.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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.Text;
  37. using System.Runtime.InteropServices;
  38. using System.Runtime.CompilerServices;
  39. using System.IO;
  40. using Mono;
  41. #if !MOBILE && !NETCORE
  42. using Mono.Security.Cryptography;
  43. #endif
  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. #if !NETCORE
  50. [ComDefaultInterfaceAttribute (typeof (_AssemblyName))]
  51. [ClassInterfaceAttribute (ClassInterfaceType.None)]
  52. #endif
  53. [Serializable]
  54. [StructLayout (LayoutKind.Sequential)]
  55. #if MOBILE || NETCORE
  56. public sealed partial class AssemblyName : ICloneable, ISerializable, IDeserializationCallback {
  57. #else
  58. public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback, _AssemblyName {
  59. #endif
  60. #pragma warning disable 169
  61. #region Synch with object-internals.h
  62. string name;
  63. string codebase;
  64. int major, minor, build, revision;
  65. CultureInfo cultureinfo;
  66. AssemblyNameFlags flags;
  67. AssemblyHashAlgorithm hashalg;
  68. StrongNameKeyPair keypair;
  69. byte[] publicKey;
  70. byte[] keyToken;
  71. AssemblyVersionCompatibility versioncompat;
  72. Version version;
  73. ProcessorArchitecture processor_architecture = ProcessorArchitecture.None;
  74. #endregion
  75. #pragma warning restore 169
  76. AssemblyContentType contentType;
  77. public AssemblyName ()
  78. {
  79. // defaults
  80. versioncompat = AssemblyVersionCompatibility.SameMachine;
  81. }
  82. [MethodImpl (MethodImplOptions.InternalCall)]
  83. static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined);
  84. public AssemblyName (string assemblyName)
  85. {
  86. if (assemblyName == null)
  87. throw new ArgumentNullException ("assemblyName");
  88. if (assemblyName.Length < 1)
  89. throw new ArgumentException ("assemblyName cannot have zero length.");
  90. using (var name = RuntimeMarshal.MarshalString (assemblyName)) {
  91. MonoAssemblyName nativeName;
  92. bool isVersionDefined, isTokenDefined;
  93. //ParseName free the name if it fails.
  94. if (!ParseAssemblyName (name.Value, out nativeName, out isVersionDefined, out isTokenDefined))
  95. throw new FileLoadException ("The assembly name is invalid.");
  96. try {
  97. unsafe {
  98. this.FillName (&nativeName, null, isVersionDefined, false, isTokenDefined, false);
  99. }
  100. } finally {
  101. RuntimeMarshal.FreeAssemblyName (ref nativeName, false);
  102. }
  103. }
  104. }
  105. public ProcessorArchitecture ProcessorArchitecture {
  106. get {
  107. return processor_architecture;
  108. }
  109. set {
  110. processor_architecture = value;
  111. }
  112. }
  113. internal AssemblyName (SerializationInfo si, StreamingContext sc)
  114. {
  115. name = si.GetString ("_Name");
  116. codebase = si.GetString ("_CodeBase");
  117. version = (Version)si.GetValue ("_Version", typeof (Version));
  118. publicKey = (byte[])si.GetValue ("_PublicKey", typeof (byte[]));
  119. keyToken = (byte[])si.GetValue ("_PublicKeyToken", typeof (byte[]));
  120. hashalg = (AssemblyHashAlgorithm)si.GetValue ("_HashAlgorithm", typeof (AssemblyHashAlgorithm));
  121. keypair = (StrongNameKeyPair)si.GetValue ("_StrongNameKeyPair", typeof (StrongNameKeyPair));
  122. versioncompat = (AssemblyVersionCompatibility)si.GetValue ("_VersionCompatibility", typeof (AssemblyVersionCompatibility));
  123. flags = (AssemblyNameFlags)si.GetValue ("_Flags", typeof (AssemblyNameFlags));
  124. int lcid = si.GetInt32 ("_CultureInfo");
  125. if (lcid != -1) cultureinfo = new CultureInfo (lcid);
  126. }
  127. public string Name {
  128. get { return name; }
  129. set { name = value; }
  130. }
  131. public string CodeBase {
  132. get { return codebase; }
  133. set { codebase = value; }
  134. }
  135. public string EscapedCodeBase {
  136. get {
  137. if (codebase == null)
  138. return null;
  139. #if NETCORE
  140. throw new NotImplementedException ();
  141. #else
  142. return Mono.Security.Uri.EscapeString (codebase, false, true, true);
  143. #endif
  144. }
  145. }
  146. public CultureInfo CultureInfo {
  147. get { return cultureinfo; }
  148. set { cultureinfo = value; }
  149. }
  150. public AssemblyNameFlags Flags {
  151. get { return flags; }
  152. set { flags = value; }
  153. }
  154. public string FullName {
  155. get {
  156. if (name == null)
  157. return string.Empty;
  158. StringBuilder fname = new StringBuilder ();
  159. if (Char.IsWhiteSpace (name [0]))
  160. fname.Append ("\"" + name + "\"");
  161. else
  162. fname.Append (name);
  163. if (Version != null) {
  164. fname.Append (", Version=");
  165. fname.Append (Version.ToString ());
  166. }
  167. if (cultureinfo != null) {
  168. fname.Append (", Culture=");
  169. if (cultureinfo.LCID == CultureInfo.InvariantCulture.LCID)
  170. fname.Append ("neutral");
  171. else
  172. fname.Append (cultureinfo.Name);
  173. }
  174. byte [] pub_tok = InternalGetPublicKeyToken ();
  175. if (pub_tok != null) {
  176. if (pub_tok.Length == 0)
  177. fname.Append (", PublicKeyToken=null");
  178. else {
  179. fname.Append (", PublicKeyToken=");
  180. for (int i = 0; i < pub_tok.Length; i++)
  181. fname.Append (pub_tok[i].ToString ("x2"));
  182. }
  183. }
  184. if ((Flags & AssemblyNameFlags.Retargetable) != 0)
  185. fname.Append (", Retargetable=Yes");
  186. return fname.ToString ();
  187. }
  188. }
  189. public AssemblyHashAlgorithm HashAlgorithm {
  190. get { return hashalg; }
  191. set { hashalg = value; }
  192. }
  193. public StrongNameKeyPair KeyPair {
  194. get { return keypair; }
  195. set { keypair = value; }
  196. }
  197. public Version Version {
  198. get {
  199. return version;
  200. }
  201. set {
  202. version = value;
  203. if (value == null)
  204. major = minor = build = revision = 0;
  205. else {
  206. major = value.Major;
  207. minor = value.Minor;
  208. build = value.Build;
  209. revision = value.Revision;
  210. }
  211. }
  212. }
  213. public AssemblyVersionCompatibility VersionCompatibility {
  214. get { return versioncompat; }
  215. set { versioncompat = value; }
  216. }
  217. public override string ToString ()
  218. {
  219. string name = FullName;
  220. return (name != null) ? name : base.ToString ();
  221. }
  222. public byte[] GetPublicKey()
  223. {
  224. return publicKey;
  225. }
  226. public byte[] GetPublicKeyToken ()
  227. {
  228. if (keyToken != null)
  229. return keyToken;
  230. if (publicKey == null)
  231. return null;
  232. if (publicKey.Length == 0)
  233. return EmptyArray<byte>.Value;
  234. if (!IsPublicKeyValid)
  235. throw new SecurityException ("The public key is not valid.");
  236. keyToken = ComputePublicKeyToken ();
  237. return keyToken;
  238. }
  239. private bool IsPublicKeyValid {
  240. get {
  241. // check for ECMA key
  242. if (publicKey.Length == 16) {
  243. int i = 0;
  244. int sum = 0;
  245. while (i < publicKey.Length)
  246. sum += publicKey [i++];
  247. if (sum == 4)
  248. return true;
  249. }
  250. switch (publicKey [0]) {
  251. case 0x00: // public key inside a header
  252. if (publicKey.Length > 12 && publicKey [12] == 0x06) {
  253. #if MOBILE || NETCORE
  254. return true;
  255. #else
  256. try {
  257. CryptoConvert.FromCapiPublicKeyBlob (
  258. publicKey, 12);
  259. return true;
  260. } catch (CryptographicException) {
  261. }
  262. #endif
  263. }
  264. break;
  265. case 0x06: // public key
  266. #if MOBILE || NETCORE
  267. return true;
  268. #else
  269. try {
  270. CryptoConvert.FromCapiPublicKeyBlob (publicKey);
  271. return true;
  272. } catch (CryptographicException) {
  273. }
  274. break;
  275. #endif
  276. case 0x07: // private key
  277. break;
  278. }
  279. return false;
  280. }
  281. }
  282. private byte [] InternalGetPublicKeyToken ()
  283. {
  284. if (keyToken != null)
  285. return keyToken;
  286. if (publicKey == null)
  287. return null;
  288. if (publicKey.Length == 0)
  289. return EmptyArray<byte>.Value;
  290. if (!IsPublicKeyValid)
  291. throw new SecurityException ("The public key is not valid.");
  292. return ComputePublicKeyToken ();
  293. }
  294. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  295. extern unsafe static void get_public_token (byte* token, byte* pubkey, int len);
  296. private unsafe byte [] ComputePublicKeyToken ()
  297. {
  298. byte [] token = new byte [8];
  299. fixed (byte* pkt = token)
  300. fixed (byte *pk = publicKey)
  301. get_public_token (pkt, pk, publicKey.Length);
  302. return token;
  303. }
  304. public static bool ReferenceMatchesDefinition (AssemblyName reference, AssemblyName definition)
  305. {
  306. if (reference == null)
  307. throw new ArgumentNullException ("reference");
  308. if (definition == null)
  309. throw new ArgumentNullException ("definition");
  310. // we only compare the simple assembly name to be consistent with MS .NET,
  311. // which is the result of a bug in their implementation (see https://connect.microsoft.com/VisualStudio/feedback/details/752902)
  312. return string.Equals (reference.Name, definition.Name, StringComparison.OrdinalIgnoreCase);
  313. }
  314. public void SetPublicKey (byte[] publicKey)
  315. {
  316. if (publicKey == null)
  317. flags ^= AssemblyNameFlags.PublicKey;
  318. else
  319. flags |= AssemblyNameFlags.PublicKey;
  320. this.publicKey = publicKey;
  321. }
  322. public void SetPublicKeyToken (byte[] publicKeyToken)
  323. {
  324. keyToken = publicKeyToken;
  325. }
  326. public void GetObjectData (SerializationInfo info, StreamingContext context)
  327. {
  328. if (info == null)
  329. throw new ArgumentNullException ("info");
  330. info.AddValue ("_Name", name);
  331. info.AddValue ("_PublicKey", publicKey);
  332. info.AddValue ("_PublicKeyToken", keyToken);
  333. info.AddValue ("_CultureInfo", cultureinfo != null ? cultureinfo.LCID : -1);
  334. info.AddValue ("_CodeBase", codebase);
  335. info.AddValue ("_Version", Version);
  336. info.AddValue ("_HashAlgorithm", hashalg);
  337. info.AddValue ("_HashAlgorithmForControl", AssemblyHashAlgorithm.None);
  338. info.AddValue ("_StrongNameKeyPair", keypair);
  339. info.AddValue ("_VersionCompatibility", versioncompat);
  340. info.AddValue ("_Flags", flags);
  341. info.AddValue ("_HashForControl", null);
  342. }
  343. public object Clone()
  344. {
  345. AssemblyName an = new AssemblyName ();
  346. an.name = name;
  347. an.codebase = codebase;
  348. an.major = major;
  349. an.minor = minor;
  350. an.build = build;
  351. an.revision = revision;
  352. an.version = version;
  353. an.cultureinfo = cultureinfo;
  354. an.flags = flags;
  355. an.hashalg = hashalg;
  356. an.keypair = keypair;
  357. an.publicKey = publicKey;
  358. an.keyToken = keyToken;
  359. an.versioncompat = versioncompat;
  360. an.processor_architecture = processor_architecture;
  361. return an;
  362. }
  363. public void OnDeserialization (object sender)
  364. {
  365. Version = version;
  366. }
  367. public static AssemblyName GetAssemblyName (string assemblyFile)
  368. {
  369. if (assemblyFile == null)
  370. throw new ArgumentNullException ("assemblyFile");
  371. AssemblyName aname = new AssemblyName ();
  372. unsafe {
  373. Mono.MonoAssemblyName nativeName;
  374. string codebase;
  375. Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), out nativeName, out codebase);
  376. try {
  377. aname.FillName (&nativeName, codebase, true, false, true, false);
  378. } finally {
  379. RuntimeMarshal.FreeAssemblyName (ref nativeName, false);
  380. }
  381. }
  382. return aname;
  383. }
  384. #if !MOBILE && !NETCORE
  385. void _AssemblyName.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  386. {
  387. throw new NotImplementedException ();
  388. }
  389. void _AssemblyName.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  390. {
  391. throw new NotImplementedException ();
  392. }
  393. void _AssemblyName.GetTypeInfoCount (out uint pcTInfo)
  394. {
  395. throw new NotImplementedException ();
  396. }
  397. void _AssemblyName.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  398. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  399. {
  400. throw new NotImplementedException ();
  401. }
  402. #endif
  403. public string CultureName {
  404. get {
  405. return (cultureinfo == null)? null : cultureinfo.Name;
  406. }
  407. set {
  408. if (value == null)
  409. cultureinfo = null;
  410. else
  411. cultureinfo = new CultureInfo (value);
  412. }
  413. }
  414. [ComVisibleAttribute(false)]
  415. public AssemblyContentType ContentType {
  416. get {
  417. return contentType;
  418. }
  419. set {
  420. contentType = value;
  421. }
  422. }
  423. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  424. static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assembly_ptr);
  425. internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken, bool assemblyRef)
  426. {
  427. this.name = RuntimeMarshal.PtrToUtf8String (native->name);
  428. this.major = native->major;
  429. this.minor = native->minor;
  430. this.build = native->build;
  431. this.revision = native->revision;
  432. this.flags = (AssemblyNameFlags)native->flags;
  433. this.hashalg = (AssemblyHashAlgorithm)native->hash_alg;
  434. this.versioncompat = AssemblyVersionCompatibility.SameMachine;
  435. this.processor_architecture = (ProcessorArchitecture)native->arch;
  436. if (addVersion)
  437. this.version = new Version (this.major, this.minor, this.build, this.revision);
  438. this.codebase = codeBase;
  439. if (native->culture != IntPtr.Zero)
  440. this.cultureinfo = CultureInfo.CreateCulture ( RuntimeMarshal.PtrToUtf8String (native->culture), assemblyRef);
  441. if (native->public_key != IntPtr.Zero) {
  442. this.publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key);
  443. this.flags |= AssemblyNameFlags.PublicKey;
  444. } else if (addPublickey) {
  445. this.publicKey = EmptyArray<byte>.Value;
  446. this.flags |= AssemblyNameFlags.PublicKey;
  447. }
  448. // MonoAssemblyName keeps the public key token as an hexadecimal string
  449. if (native->public_key_token [0] != 0) {
  450. byte[] keyToken = new byte [8];
  451. for (int i = 0, j = 0; i < 8; ++i) {
  452. keyToken [i] = (byte)(RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4);
  453. keyToken [i] |= (byte)RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]);
  454. }
  455. this.keyToken = keyToken;
  456. } else if (defaultToken) {
  457. this.keyToken = EmptyArray<byte>.Value;
  458. }
  459. }
  460. internal static AssemblyName Create (Assembly assembly, bool fillCodebase)
  461. {
  462. AssemblyName aname = new AssemblyName ();
  463. unsafe {
  464. MonoAssemblyName *native = GetNativeName (assembly.MonoAssembly);
  465. aname.FillName (native, fillCodebase ? assembly.CodeBase : null, true, true, true, false);
  466. }
  467. return aname;
  468. }
  469. }
  470. }