Merge pull request #3335 from lambdageek/dev/system-reflection-assembly
[mono.git] / mcs / class / corlib / System.Reflection / AssemblyName.cs
1 //
2 // System.Reflection/AssemblyName.cs
3 //
4 // Authors:
5 //      Paolo Molaro (lupus@ximian.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
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
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;
38 using System.Text;
39 using System.Runtime.InteropServices;
40 using System.Runtime.CompilerServices;
41 using System.IO;
42
43 using Mono;
44 using Mono.Security;
45 using Mono.Security.Cryptography;
46
47 namespace System.Reflection {
48
49 // References:
50 // a.   Uniform Resource Identifiers (URI): Generic Syntax
51 //      http://www.ietf.org/rfc/rfc2396.txt
52
53         [ComVisible (true)]
54         [ComDefaultInterfaceAttribute (typeof (_AssemblyName))]
55         [Serializable]
56         [ClassInterfaceAttribute (ClassInterfaceType.None)]
57         [StructLayout (LayoutKind.Sequential)]
58 #if MOBILE
59         public sealed class AssemblyName  : ICloneable, ISerializable, IDeserializationCallback {
60 #else
61         public sealed class AssemblyName  : ICloneable, ISerializable, IDeserializationCallback, _AssemblyName {
62 #endif
63 #pragma warning disable 169
64                 #region Synch with object-internals.h
65                 string name;
66                 string codebase;
67                 int major, minor, build, revision;
68                 CultureInfo cultureinfo;
69                 AssemblyNameFlags flags;
70                 AssemblyHashAlgorithm hashalg;
71                 StrongNameKeyPair keypair;
72                 byte[] publicKey;
73                 byte[] keyToken;
74                 AssemblyVersionCompatibility versioncompat;
75                 Version version;
76                 ProcessorArchitecture processor_architecture = ProcessorArchitecture.None;
77                 #endregion
78 #pragma warning restore 169             
79
80                 AssemblyContentType contentType;
81                 public AssemblyName ()
82                 {
83                         // defaults
84                         versioncompat = AssemblyVersionCompatibility.SameMachine;
85                 }
86
87                 [MethodImpl (MethodImplOptions.InternalCall)]
88                 static extern bool ParseAssemblyName (IntPtr name, out MonoAssemblyName aname, out bool is_version_definited, out bool is_token_defined);
89
90                 public AssemblyName (string assemblyName)
91                 {
92                         if (assemblyName == null)
93                                 throw new ArgumentNullException ("assemblyName");
94                         if (assemblyName.Length < 1)
95                                 throw new ArgumentException ("assemblyName cannot have zero length.");
96
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.");
103                                 try {
104                                         unsafe {
105                                                 this.FillName (&nativeName, null, isVersionDefined, false, isTokenDefined);
106                                         }
107                                 } finally {
108                                         RuntimeMarshal.FreeAssemblyName (ref nativeName);
109                                 }
110                         }
111                 }
112                 
113                 [MonoLimitation ("Not used, as the values are too limited;  Mono supports more")]
114                 public ProcessorArchitecture ProcessorArchitecture {
115                         get {
116                                 return processor_architecture;
117                         }
118                         set {
119                                 processor_architecture = value;
120                         }
121                 }
122
123                 internal AssemblyName (SerializationInfo si, StreamingContext sc)
124                 {
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);
136                 }
137
138                 public string Name {
139                         get { return name; }
140                         set { name = value; }
141                 }
142
143                 public string CodeBase {
144                         get { return codebase; }
145                         set { codebase = value; }
146                 }
147
148                 public string EscapedCodeBase {
149                         get {
150                                 if (codebase == null)
151                                         return null;
152                                 return Uri.EscapeString (codebase, false, true, true);
153                         }
154                 }
155
156                 public CultureInfo CultureInfo {
157                         get { return cultureinfo; }
158                         set { cultureinfo = value; }
159                 }
160
161                 public AssemblyNameFlags Flags {
162                         get { return flags; }
163                         set { flags = value; }
164                 }
165
166                 public string FullName {
167                         get {
168                                 if (name == null)
169                                         return string.Empty;
170                                 StringBuilder fname = new StringBuilder ();
171                                 if (Char.IsWhiteSpace (name [0]))
172                                         fname.Append ("\"" + name + "\"");
173                                 else
174                                         fname.Append (name);
175                                 if (Version != null) {
176                                         fname.Append (", Version=");
177                                         fname.Append (Version.ToString ());
178                                 }
179                                 if (cultureinfo != null) {
180                                         fname.Append (", Culture=");
181                                         if (cultureinfo.LCID == CultureInfo.InvariantCulture.LCID)
182                                                 fname.Append ("neutral");
183                                         else
184                                                 fname.Append (cultureinfo.Name);
185                                 }
186                                 byte [] pub_tok = InternalGetPublicKeyToken ();
187                                 if (pub_tok != null) {
188                                         if (pub_tok.Length == 0)
189                                                 fname.Append (", PublicKeyToken=null");
190                                         else {
191                                                 fname.Append (", PublicKeyToken=");
192                                                 for (int i = 0; i < pub_tok.Length; i++)
193                                                         fname.Append (pub_tok[i].ToString ("x2"));
194                                         }
195                                 }
196
197                                 if ((Flags & AssemblyNameFlags.Retargetable) != 0)
198                                         fname.Append (", Retargetable=Yes");
199
200                                 return fname.ToString ();
201                         }
202                 }
203
204                 public AssemblyHashAlgorithm HashAlgorithm {
205                         get { return hashalg; }
206                         set { hashalg = value; }
207                 }
208
209                 public StrongNameKeyPair KeyPair {
210                         get { return keypair; }
211                         set { keypair = value; }
212                 }
213
214                 public Version Version {
215                         get {
216                                 return version;
217                         }
218
219                         set {
220                                 version = value;
221                                 if (value == null)
222                                         major = minor = build = revision = 0;
223                                 else {
224                                         major = value.Major;
225                                         minor = value.Minor;
226                                         build = value.Build;
227                                         revision = value.Revision;
228                                 }
229                         }
230                 }
231
232                 public AssemblyVersionCompatibility VersionCompatibility {
233                         get { return versioncompat; }
234                         set { versioncompat = value; }
235                 }
236                 
237                 public override string ToString ()
238                 {
239                         string name = FullName;
240                         return (name != null) ? name : base.ToString ();
241                 }
242
243                 public byte[] GetPublicKey()
244                 {
245                         return publicKey;
246                 }
247
248                 public byte[] GetPublicKeyToken ()
249                 {
250                         if (keyToken != null)
251                                 return keyToken;
252                         if (publicKey == null)
253                                 return null;
254
255                                 if (publicKey.Length == 0)
256                                         return EmptyArray<byte>.Value;
257
258                                 if (!IsPublicKeyValid)
259                                         throw new  SecurityException ("The public key is not valid.");
260
261                                 keyToken = ComputePublicKeyToken ();
262                                 return keyToken;
263                 }
264
265                 private bool IsPublicKeyValid {
266                         get {
267                                 // check for ECMA key
268                                 if (publicKey.Length == 16) {
269                                         int i = 0;
270                                         int sum = 0;
271                                         while (i < publicKey.Length)
272                                                 sum += publicKey [i++];
273                                         if (sum == 4)
274                                                 return true;
275                                 }
276
277                                 switch (publicKey [0]) {
278                                 case 0x00: // public key inside a header
279                                         if (publicKey.Length > 12 && publicKey [12] == 0x06) {
280 #if MOBILE
281                                                 return true;
282 #else
283                                                 try {
284                                                         CryptoConvert.FromCapiPublicKeyBlob (
285                                                                 publicKey, 12);
286                                                         return true;
287                                                 } catch (CryptographicException) {
288                                                 }
289 #endif
290                                         }
291                                         break;
292                                 case 0x06: // public key
293 #if MOBILE
294                                         return true;
295 #else
296                                         try {
297                                                 CryptoConvert.FromCapiPublicKeyBlob (publicKey);
298                                                 return true;
299                                         } catch (CryptographicException) {
300                                         }
301                                         break;                                  
302 #endif
303                                 case 0x07: // private key
304                                         break;
305                                 }
306
307                                 return false;
308                         }
309                 }
310
311                 private byte [] InternalGetPublicKeyToken ()
312                 {
313                         if (keyToken != null)
314                                 return keyToken;
315
316                         if (publicKey == null)
317                                 return null;
318
319                         if (publicKey.Length == 0)
320                                 return EmptyArray<byte>.Value;
321
322                         if (!IsPublicKeyValid)
323                                 throw new  SecurityException ("The public key is not valid.");
324
325                         return ComputePublicKeyToken ();
326                 }
327
328                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
329                 extern unsafe static void get_public_token (byte* token, byte* pubkey, int len);
330
331                 private unsafe byte [] ComputePublicKeyToken ()
332                 {
333                         byte [] token = new byte [8];
334                         fixed (byte* pkt = token)
335                         fixed (byte *pk = publicKey)
336                                 get_public_token (pkt, pk, publicKey.Length);
337                         return token;
338                 }
339
340                 public static bool ReferenceMatchesDefinition (AssemblyName reference, AssemblyName definition)
341                 {
342                         if (reference == null)
343                                 throw new ArgumentNullException ("reference");
344                         if (definition == null)
345                                 throw new ArgumentNullException ("definition");
346                         
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);
350                 }
351
352                 public void SetPublicKey (byte[] publicKey) 
353                 {
354                         if (publicKey == null)
355                                 flags ^= AssemblyNameFlags.PublicKey;
356                         else
357                                 flags |= AssemblyNameFlags.PublicKey;
358                         this.publicKey = publicKey;
359                 }
360
361                 public void SetPublicKeyToken (byte[] publicKeyToken) 
362                 {
363                         keyToken = publicKeyToken;
364                 }
365
366                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
367                 public void GetObjectData (SerializationInfo info, StreamingContext context)
368                 {
369                         if (info == null)
370                                 throw new ArgumentNullException ("info");
371
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);
384                 }
385
386                 public object Clone() 
387                 {
388                         AssemblyName an = new AssemblyName ();
389                         an.name = name;
390                         an.codebase = codebase;
391                         an.major = major;
392                         an.minor = minor;
393                         an.build = build;
394                         an.revision = revision;
395                         an.version = version;
396                         an.cultureinfo = cultureinfo;
397                         an.flags = flags;
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;
404                         return an;
405                 }
406
407                 public void OnDeserialization (object sender) 
408                 {
409                         Version = version;
410                 }
411
412                 public static AssemblyName GetAssemblyName (string assemblyFile) 
413                 {
414                         if (assemblyFile == null)
415                                 throw new ArgumentNullException ("assemblyFile");
416
417                         AssemblyName aname = new AssemblyName ();
418                         Assembly.InternalGetAssemblyName (Path.GetFullPath (assemblyFile), aname);
419                         return aname;
420                 }
421
422 #if !MOBILE
423                 void _AssemblyName.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
424                 {
425                         throw new NotImplementedException ();
426                 }
427
428                 void _AssemblyName.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
429                 {
430                         throw new NotImplementedException ();
431                 }
432
433                 void _AssemblyName.GetTypeInfoCount (out uint pcTInfo)
434                 {
435                         throw new NotImplementedException ();
436                 }
437
438                 void _AssemblyName.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
439                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
440                 {
441                         throw new NotImplementedException ();
442                 }
443 #endif
444
445                 public string CultureName {
446                         get {
447                                 return (cultureinfo == null)? null : cultureinfo.Name;
448                         }
449 #if NETSTANDARD
450                         set {
451                                 throw new NotImplementedException ();
452                         }
453 #endif
454                 }
455
456                 [ComVisibleAttribute(false)]
457                 public AssemblyContentType ContentType {
458                         get {
459                                 return contentType;
460                         }
461                         set {
462                                 contentType = value;
463                         }
464                 }
465
466                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
467                 static extern unsafe MonoAssemblyName* GetNativeName (IntPtr assembly_ptr);
468
469                 internal unsafe void FillName (MonoAssemblyName *native, string codeBase, bool addVersion, bool addPublickey, bool defaultToken)
470                 {
471                         this.name = RuntimeMarshal.PtrToUtf8String (native->name);
472
473                         this.major = native->major;
474                         this.minor = native->minor;
475                         this.build = native->build;
476                         this.revision = native->revision;
477
478                         this.flags = (AssemblyNameFlags)native->flags;
479
480                         this.hashalg = (AssemblyHashAlgorithm)native->hash_alg;
481
482                         this.versioncompat = AssemblyVersionCompatibility.SameMachine;
483                         this.processor_architecture = (ProcessorArchitecture)native->arch;
484
485                         if (addVersion)
486                                 this.version = new Version (this.major, this.minor, this.build, this.revision);
487
488                         this.codebase = codeBase;
489
490                         if (native->culture != IntPtr.Zero)
491                                 this.cultureinfo = CultureInfo.CreateCulture ( RuntimeMarshal.PtrToUtf8String (native->culture), false);
492
493                         if (native->public_key != IntPtr.Zero) {
494                                 this.publicKey = RuntimeMarshal.DecodeBlobArray (native->public_key);
495                                 this.flags |= AssemblyNameFlags.PublicKey;
496                         } else if (addPublickey) {
497                                 this.publicKey = EmptyArray<byte>.Value;
498                                 this.flags |= AssemblyNameFlags.PublicKey;
499                         }
500
501                         // MonoAssemblyName keeps the public key token as an hexadecimal string
502                         if (native->public_key_token [0] != 0) {
503                                 byte[] keyToken = new byte [8];
504                                 for (int i = 0, j = 0; i < 8; ++i) {
505                                         keyToken [i] = (byte)(RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]) << 4);
506                                         keyToken [i] |= (byte)RuntimeMarshal.AsciHexDigitValue (native->public_key_token [j++]);
507                                 }
508                                 this.keyToken = keyToken;
509                         } else if (defaultToken) {
510                                 this.keyToken = EmptyArray<byte>.Value;
511                         }
512                 }
513
514                 internal static AssemblyName Create (Assembly assembly, bool fillCodebase)
515                 {
516                         AssemblyName aname = new AssemblyName ();
517                         unsafe {
518                                 MonoAssemblyName *native = GetNativeName (assembly._mono_assembly);
519                                 aname.FillName (native, fillCodebase ? assembly.CodeBase : null, true, true, true);
520                         }
521                         return aname;
522                 }
523         }
524 }