2 // System.Reflection/AssemblyName.cs
5 // Paolo Molaro (lupus@ximian.com)
6 // Sebastien Pouliot <sebastien@ximian.com>
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)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
32 using System.Configuration.Assemblies;
33 using System.Globalization;
34 using System.Runtime.Serialization;
35 using System.Security;
36 using System.Security.Cryptography;
37 using System.Security.Permissions;
39 using System.Runtime.InteropServices;
40 using System.Runtime.CompilerServices;
45 using Mono.Security.Cryptography;
47 namespace System.Reflection {
50 // a. Uniform Resource Identifiers (URI): Generic Syntax
51 // http://www.ietf.org/rfc/rfc2396.txt
54 [ComDefaultInterfaceAttribute (typeof (_AssemblyName))]
56 [ClassInterfaceAttribute (ClassInterfaceType.None)]
57 [StructLayout (LayoutKind.Sequential)]
59 public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback {
61 public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback, _AssemblyName {
63 #pragma warning disable 169
64 #region Synch with object-internals.h
67 int major, minor, build, revision;
68 CultureInfo cultureinfo;
69 AssemblyNameFlags flags;
70 AssemblyHashAlgorithm hashalg;
71 StrongNameKeyPair keypair;
74 AssemblyVersionCompatibility versioncompat;
76 ProcessorArchitecture processor_architecture = ProcessorArchitecture.None;
78 #pragma warning restore 169
80 AssemblyContentType contentType;
81 public AssemblyName ()
84 versioncompat = AssemblyVersionCompatibility.SameMachine;
87 [MethodImpl (MethodImplOptions.InternalCall)]
88 static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined);
90 public AssemblyName (string assemblyName)
92 if (assemblyName == null)
93 throw new ArgumentNullException ("assemblyName");
94 if (assemblyName.Length < 1)
95 throw new ArgumentException ("assemblyName cannot have zero length.");
97 using (var name = RuntimeMarshal.MarshalString (assemblyName)) {
98 MonoAssemblyName nativeName;
99 bool isVersionDefined, isTokenDefined;
100 //ParseName free the name if it fails.
101 if (!ParseAssemblyName (name.Value, out nativeName, out isVersionDefined, out isTokenDefined))
102 throw new FileLoadException ("The assembly name is invalid.");
105 this.FillName (&nativeName, null, isVersionDefined, false, isTokenDefined);
108 RuntimeMarshal.FreeAssemblyName (ref nativeName);
113 [MonoLimitation ("Not used, as the values are too limited; Mono supports more")]
114 public ProcessorArchitecture ProcessorArchitecture {
116 return processor_architecture;
119 processor_architecture = value;
123 internal AssemblyName (SerializationInfo si, StreamingContext sc)
125 name = si.GetString ("_Name");
126 codebase = si.GetString ("_CodeBase");
127 version = (Version)si.GetValue ("_Version", typeof (Version));
128 publicKey = (byte[])si.GetValue ("_PublicKey", typeof (byte[]));
129 keyToken = (byte[])si.GetValue ("_PublicKeyToken", typeof (byte[]));
130 hashalg = (AssemblyHashAlgorithm)si.GetValue ("_HashAlgorithm", typeof (AssemblyHashAlgorithm));
131 keypair = (StrongNameKeyPair)si.GetValue ("_StrongNameKeyPair", typeof (StrongNameKeyPair));
132 versioncompat = (AssemblyVersionCompatibility)si.GetValue ("_VersionCompatibility", typeof (AssemblyVersionCompatibility));
133 flags = (AssemblyNameFlags)si.GetValue ("_Flags", typeof (AssemblyNameFlags));
134 int lcid = si.GetInt32 ("_CultureInfo");
135 if (lcid != -1) cultureinfo = new CultureInfo (lcid);
140 set { name = value; }
143 public string CodeBase {
144 get { return codebase; }
145 set { codebase = value; }
148 public string EscapedCodeBase {
150 if (codebase == null)
152 return Uri.EscapeString (codebase, false, true, true);
156 public CultureInfo CultureInfo {
157 get { return cultureinfo; }
158 set { cultureinfo = value; }
161 public AssemblyNameFlags Flags {
162 get { return flags; }
163 set { flags = value; }
166 public string FullName {
170 StringBuilder fname = new StringBuilder ();
171 if (Char.IsWhiteSpace (name [0]))
172 fname.Append ("\"" + name + "\"");
175 if (Version != null) {
176 fname.Append (", Version=");
177 fname.Append (Version.ToString ());
179 if (cultureinfo != null) {
180 fname.Append (", Culture=");
181 if (cultureinfo.LCID == CultureInfo.InvariantCulture.LCID)
182 fname.Append ("neutral");
184 fname.Append (cultureinfo.Name);
186 byte [] pub_tok = InternalGetPublicKeyToken ();
187 if (pub_tok != null) {
188 if (pub_tok.Length == 0)
189 fname.Append (", PublicKeyToken=null");
191 fname.Append (", PublicKeyToken=");
192 for (int i = 0; i < pub_tok.Length; i++)
193 fname.Append (pub_tok[i].ToString ("x2"));
197 if ((Flags & AssemblyNameFlags.Retargetable) != 0)
198 fname.Append (", Retargetable=Yes");
200 return fname.ToString ();
204 public AssemblyHashAlgorithm HashAlgorithm {
205 get { return hashalg; }
206 set { hashalg = value; }
209 public StrongNameKeyPair KeyPair {
210 get { return keypair; }
211 set { keypair = value; }
214 public Version Version {
222 major = minor = build = revision = 0;
227 revision = value.Revision;
232 public AssemblyVersionCompatibility VersionCompatibility {
233 get { return versioncompat; }
234 set { versioncompat = value; }
237 public override string ToString ()
239 string name = FullName;
240 return (name != null) ? name : base.ToString ();
243 public byte[] GetPublicKey()
248 public byte[] GetPublicKeyToken ()
250 if (keyToken != null)
252 if (publicKey == null)
255 if (publicKey.Length == 0)
256 return EmptyArray<byte>.Value;
258 if (!IsPublicKeyValid)
259 throw new SecurityException ("The public key is not valid.");
261 keyToken = ComputePublicKeyToken ();
265 private bool IsPublicKeyValid {
267 // check for ECMA key
268 if (publicKey.Length == 16) {
271 while (i < publicKey.Length)
272 sum += publicKey [i++];
277 switch (publicKey [0]) {
278 case 0x00: // public key inside a header
279 if (publicKey.Length > 12 && publicKey [12] == 0x06) {
284 CryptoConvert.FromCapiPublicKeyBlob (
287 } catch (CryptographicException) {
292 case 0x06: // public key
297 CryptoConvert.FromCapiPublicKeyBlob (publicKey);
299 } catch (CryptographicException) {
303 case 0x07: // private key
311 private byte [] InternalGetPublicKeyToken ()
313 if (keyToken != null)
316 if (publicKey == null)
319 if (publicKey.Length == 0)
320 return EmptyArray<byte>.Value;
322 if (!IsPublicKeyValid)
323 throw new SecurityException ("The public key is not valid.");
325 return ComputePublicKeyToken ();
328 [MethodImplAttribute (MethodImplOptions.InternalCall)]
329 extern unsafe static void get_public_token (byte* token, byte* pubkey, int len);
331 private unsafe byte [] ComputePublicKeyToken ()
333 byte [] token = new byte [8];
334 fixed (byte* pkt = token)
335 fixed (byte *pk = publicKey)
336 get_public_token (pkt, pk, publicKey.Length);
340 public static bool ReferenceMatchesDefinition (AssemblyName reference, AssemblyName definition)
342 if (reference == null)
343 throw new ArgumentNullException ("reference");
344 if (definition == null)
345 throw new ArgumentNullException ("definition");
347 // we only compare the simple assembly name to be consistent with MS .NET,
348 // which is the result of a bug in their implementation (see https://connect.microsoft.com/VisualStudio/feedback/details/752902)
349 return string.Equals (reference.Name, definition.Name, StringComparison.OrdinalIgnoreCase);
352 public void SetPublicKey (byte[] publicKey)
354 if (publicKey == null)
355 flags ^= AssemblyNameFlags.PublicKey;
357 flags |= AssemblyNameFlags.PublicKey;
358 this.publicKey = publicKey;
361 public void SetPublicKeyToken (byte[] publicKeyToken)
363 keyToken = publicKeyToken;
366 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
367 public void GetObjectData (SerializationInfo info, StreamingContext context)
370 throw new ArgumentNullException ("info");
372 info.AddValue ("_Name", name);
373 info.AddValue ("_PublicKey", publicKey);
374 info.AddValue ("_PublicKeyToken", keyToken);
375 info.AddValue ("_CultureInfo", cultureinfo != null ? cultureinfo.LCID : -1);
376 info.AddValue ("_CodeBase", codebase);
377 info.AddValue ("_Version", Version);
378 info.AddValue ("_HashAlgorithm", hashalg);
379 info.AddValue ("_HashAlgorithmForControl", AssemblyHashAlgorithm.None);
380 info.AddValue ("_StrongNameKeyPair", keypair);
381 info.AddValue ("_VersionCompatibility", versioncompat);
382 info.AddValue ("_Flags", flags);
383 info.AddValue ("_HashForControl", null);
386 public object Clone()
388 AssemblyName an = new AssemblyName ();
390 an.codebase = codebase;
394 an.revision = revision;
395 an.version = version;
396 an.cultureinfo = cultureinfo;
398 an.hashalg = hashalg;
399 an.keypair = keypair;
400 an.publicKey = publicKey;
401 an.keyToken = keyToken;
402 an.versioncompat = versioncompat;
403 an.processor_architecture = processor_architecture;
407 public void OnDeserialization (object sender)
412 public static AssemblyName GetAssemblyName (string assemblyFile)
414 if (assemblyFile == null)
415 throw new ArgumentNullException ("assemblyFile");
417 AssemblyName aname = new AssemblyName ();
418 Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), aname);
423 void _AssemblyName.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
425 throw new NotImplementedException ();
428 void _AssemblyName.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
430 throw new NotImplementedException ();
433 void _AssemblyName.GetTypeInfoCount (out uint pcTInfo)
435 throw new NotImplementedException ();
438 void _AssemblyName.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
439 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
441 throw new NotImplementedException ();
445 public string CultureName {
447 return (cultureinfo == null)? null : cultureinfo.Name;
450 throw new NotImplementedException ();
454 [ComVisibleAttribute(false)]
455 public AssemblyContentType ContentType {
464 [MethodImplAttribute (MethodImplOptions.InternalCall)]
465 static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assembly_ptr);
467 internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken)
469 this.name = RuntimeMarshal.PtrToUtf8String (native->name);
471 this.major = native->major;
472 this.minor = native->minor;
473 this.build = native->build;
474 this.revision = native->revision;
476 this.flags = (AssemblyNameFlags)native->flags;
478 this.hashalg = (AssemblyHashAlgorithm)native->hash_alg;
480 this.versioncompat = AssemblyVersionCompatibility.SameMachine;
481 this.processor_architecture = (ProcessorArchitecture)native->arch;
484 this.version = new Version (this.major, this.minor, this.build, this.revision);
486 this.codebase = codeBase;
488 if (native->culture != IntPtr.Zero)
489 this.cultureinfo = CultureInfo.CreateCulture ( RuntimeMarshal.PtrToUtf8String (native->culture), false);
491 if (native->public_key != IntPtr.Zero) {
492 this.publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key);
493 this.flags |= AssemblyNameFlags.PublicKey;
494 } else if (addPublickey) {
495 this.publicKey = EmptyArray<byte>.Value;
496 this.flags |= AssemblyNameFlags.PublicKey;
499 // MonoAssemblyName keeps the public key token as an hexadecimal string
500 if (native->public_key_token [0] != 0) {
501 byte[] keyToken = new byte [8];
502 for (int i = 0, j = 0; i < 8; ++i) {
503 keyToken [i] = (byte)(RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4);
504 keyToken [i] |= (byte)RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]);
506 this.keyToken = keyToken;
507 } else if (defaultToken) {
508 this.keyToken = EmptyArray<byte>.Value;
512 internal static AssemblyName Create (Assembly assembly, bool fillCodebase)
514 AssemblyName aname = new AssemblyName ();
516 MonoAssemblyName *native = GetNativeName (assembly._mono_assembly);
517 aname.FillName (native, fillCodebase ? assembly.CodeBase : null, true, true, true);