Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AssemblyName.cs « reflect - github.com/mono/ikvm-fork.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 43c25e8d94ba7d6dd0f01ccf7ef6a5fb9bdf1a5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/*
  Copyright (C) 2009-2012 Jeroen Frijters

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  Jeroen Frijters
  jeroen@frijters.net
  
*/
using System;
using System.Globalization;
using System.Configuration.Assemblies;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using IKVM.Reflection.Reader;

namespace IKVM.Reflection
{
	public sealed class AssemblyName
#if !CORECLR
		: ICloneable
#endif
	{
		private string name;
		private string culture;
		private Version version;
		private byte[] publicKeyToken;
		private byte[] publicKey;
		private StrongNameKeyPair keyPair;
		private AssemblyNameFlags flags;
		private AssemblyHashAlgorithm hashAlgorithm;
		private AssemblyVersionCompatibility versionCompatibility = AssemblyVersionCompatibility.SameMachine;
		private string codeBase;
		internal byte[] hash;

		public AssemblyName()
		{
		}

		public AssemblyName(string assemblyName)
		{
			if (assemblyName == null)
			{
				throw new ArgumentNullException("assemblyName");
			}
			if (assemblyName == "")
			{
				throw new ArgumentException();
			}
			ParsedAssemblyName parsed;
			switch (Fusion.ParseAssemblyName(assemblyName, out parsed))
			{
				case ParseAssemblyResult.GenericError:
				case ParseAssemblyResult.DuplicateKey:
					throw new FileLoadException();
			}
			if (!ParseVersion(parsed.Version, parsed.Retargetable.HasValue, out version))
			{
				throw new FileLoadException();
			}
			name = parsed.Name;
			if (parsed.Culture != null)
			{
				if (parsed.Culture.Equals("neutral", StringComparison.OrdinalIgnoreCase))
				{
					culture = "";
				}
				else if (parsed.Culture == "")
				{
					throw new FileLoadException();
				}
				else
				{
					culture = new CultureInfo(parsed.Culture).Name;
				}
			}
			if (parsed.PublicKeyToken != null)
			{
				if (parsed.PublicKeyToken.Equals("null", StringComparison.OrdinalIgnoreCase))
				{
					publicKeyToken = Empty<byte>.Array;
				}
				else if (parsed.PublicKeyToken.Length != 16)
				{
					throw new FileLoadException();
				}
				else
				{
					publicKeyToken = ParseKey(parsed.PublicKeyToken);
				}
			}
			if (parsed.Retargetable.HasValue)
			{
				if (parsed.Culture == null || parsed.PublicKeyToken == null || version == null)
				{
					throw new FileLoadException();
				}
				if (parsed.Retargetable.Value)
				{
					flags |= AssemblyNameFlags.Retargetable;
				}
			}
			ProcessorArchitecture = parsed.ProcessorArchitecture;
			if (parsed.WindowsRuntime)
			{
				ContentType = AssemblyContentType.WindowsRuntime;
			}
		}

		private static byte[] ParseKey(string key)
		{
			if ((key.Length & 1) != 0)
			{
				throw new FileLoadException();
			}
			byte[] buf = new byte[key.Length / 2];
			for (int i = 0; i < buf.Length; i++)
			{
				buf[i] = (byte)(ParseHexDigit(key[i * 2]) * 16 + ParseHexDigit(key[i * 2 + 1]));
			}
			return buf;
		}

		private static int ParseHexDigit(char digit)
		{
			if (digit >= '0' && digit <= '9')
			{
				return digit - '0';
			}
			else
			{
				digit |= (char)0x20;
				if (digit >= 'a' && digit <= 'f')
				{
					return 10 + digit - 'a';
				}
				else
				{
					throw new FileLoadException();
				}
			}
		}

		public override string ToString()
		{
			return FullName;
		}

		public string Name
		{
			get { return name; }
			set { name = value; }
		}

		public CultureInfo CultureInfo
		{
			get { return culture == null ? null : new CultureInfo(culture); }
			set { culture = value == null ? null : value.Name; }
		}

		public string CultureName
		{
			get { return culture; }
		}

		internal string Culture
		{
			get { return culture; }
			set { culture = value; }
		}

		public Version Version
		{
			get { return version; }
			set { version = value; }
		}

		public StrongNameKeyPair KeyPair
		{
			get { return keyPair; }
			set { keyPair = value; }
		}

		public string CodeBase
		{
			get { return codeBase; }
			set { codeBase = value; }
		}

#if !CORECLR
		public string EscapedCodeBase
		{
			get
			{
				// HACK use the real AssemblyName to escape the codebase
				System.Reflection.AssemblyName tmp = new System.Reflection.AssemblyName();
				tmp.CodeBase = codeBase;
				return tmp.EscapedCodeBase;
			}
		}
#endif

		public ProcessorArchitecture ProcessorArchitecture
		{
			get { return (ProcessorArchitecture)(((int)flags & 0x70) >> 4); }
			set
			{
				if (value >= ProcessorArchitecture.None && value <= ProcessorArchitecture.Arm)
				{
					flags = (flags & ~(AssemblyNameFlags)0x70) | (AssemblyNameFlags)((int)value << 4);
				}
			}
		}

		public AssemblyNameFlags Flags
		{
			get { return flags & (AssemblyNameFlags)~0xEF0; }
			set { flags = (flags & (AssemblyNameFlags)0xEF0) | (value & (AssemblyNameFlags)~0xEF0); }
		}

		public AssemblyVersionCompatibility VersionCompatibility
		{
			get { return versionCompatibility; }
			set { versionCompatibility = value; }
		}

		public AssemblyContentType ContentType
		{
			get { return (AssemblyContentType)(((int)flags & 0xE00) >> 9); }
			set
			{
				if (value >= AssemblyContentType.Default && value <= AssemblyContentType.WindowsRuntime)
				{
					flags = (flags & ~(AssemblyNameFlags)0xE00) | (AssemblyNameFlags)((int)value << 9);
				}
			}
		}

		public byte[] GetPublicKey()
		{
			return publicKey;
		}

		public void SetPublicKey(byte[] publicKey)
		{
			this.publicKey = publicKey;
			flags = (flags & ~AssemblyNameFlags.PublicKey) | (publicKey == null ? 0 : AssemblyNameFlags.PublicKey);
		}

		public byte[] GetPublicKeyToken()
		{
			if (publicKeyToken == null && publicKey != null)
			{
				// note that GetPublicKeyToken() has a side effect in this case, because we retain this token even after the public key subsequently gets changed
				publicKeyToken = ComputePublicKeyToken(publicKey);
			}
			return publicKeyToken;
		}

		public void SetPublicKeyToken(byte[] publicKeyToken)
		{
			this.publicKeyToken = publicKeyToken;
		}

		public AssemblyHashAlgorithm HashAlgorithm
		{
			get { return hashAlgorithm; }
			set { hashAlgorithm = value; }
		}

		public byte[] __Hash
		{
			get { return hash; }
		}

		public string FullName
		{
			get
			{
				if (name == null)
				{
					return "";
				}
				ushort versionMajor = 0xFFFF;
				ushort versionMinor = 0xFFFF;
				ushort versionBuild = 0xFFFF;
				ushort versionRevision = 0xFFFF;
				if (version != null)
				{
					versionMajor = (ushort)version.Major;
					versionMinor = (ushort)version.Minor;
					versionBuild = (ushort)version.Build;
					versionRevision = (ushort)version.Revision;
				}
				byte[] publicKeyToken = this.publicKeyToken;
				if ((publicKeyToken == null || publicKeyToken.Length == 0) && publicKey != null)
				{
					publicKeyToken = ComputePublicKeyToken(publicKey);
				}
				return GetFullName(name, versionMajor, versionMinor, versionBuild, versionRevision, culture, publicKeyToken, (int)flags);
			}
		}

		internal static string GetFullName(string name, ushort versionMajor, ushort versionMinor, ushort versionBuild, ushort versionRevision, string culture, byte[] publicKeyToken, int flags)
		{
			StringBuilder sb = new StringBuilder();
			bool doubleQuotes = name.StartsWith(" ") || name.EndsWith(" ") || name.IndexOf('\'') != -1;
			bool singleQuotes = name.IndexOf('"') != -1;
			if (singleQuotes)
			{
				sb.Append('\'');
			}
			else if (doubleQuotes)
			{
				sb.Append('"');
			}
			if (name.IndexOf(',') != -1 || name.IndexOf('\\') != -1 || name.IndexOf('=') != -1 || (singleQuotes && name.IndexOf('\'') != -1))
			{
				for (int i = 0; i < name.Length; i++)
				{
					char c = name[i];
					if (c == ',' || c == '\\' || c == '=' || (singleQuotes && c == '\''))
					{
						sb.Append('\\');
					}
					sb.Append(c);
				}
			}
			else
			{
				sb.Append(name);
			}
			if (singleQuotes)
			{
				sb.Append('\'');
			}
			else if (doubleQuotes)
			{
				sb.Append('"');
			}
			if (versionMajor != 0xFFFF)
			{
				sb.Append(", Version=").Append(versionMajor);
				if (versionMinor != 0xFFFF)
				{
					sb.Append('.').Append(versionMinor);
					if (versionBuild != 0xFFFF)
					{
						sb.Append('.').Append(versionBuild);
						if (versionRevision != 0xFFFF)
						{
							sb.Append('.').Append(versionRevision);
						}
					}
				}
			}
			if (culture != null)
			{
				sb.Append(", Culture=").Append(culture == "" ? "neutral" : culture);
			}
			if (publicKeyToken != null)
			{
				sb.Append(", PublicKeyToken=");
				if (publicKeyToken.Length == 0)
				{
					sb.Append("null");
				}
				else
				{
					AppendPublicKey(sb, publicKeyToken);
				}
			}
			if ((flags & (int)AssemblyNameFlags.Retargetable) != 0)
			{
				sb.Append(", Retargetable=Yes");
			}
			if ((AssemblyContentType)((flags & 0xE00) >> 9) == AssemblyContentType.WindowsRuntime)
			{
				sb.Append(", ContentType=WindowsRuntime");
			}
			return sb.ToString();
		}

		internal static byte[] ComputePublicKeyToken(byte[] publicKey)
		{
			if (publicKey.Length == 0)
			{
				return publicKey;
			}
			byte[] hash = new SHA1Managed().ComputeHash(publicKey);
			byte[] token = new byte[8];
			for (int i = 0; i < token.Length; i++)
			{
				token[i] = hash[hash.Length - 1 - i];
			}
			return token;
		}

		internal static string ComputePublicKeyToken(string publicKey)
		{
			StringBuilder sb = new StringBuilder(16);
			AppendPublicKey(sb, ComputePublicKeyToken(ParseKey(publicKey)));
			return sb.ToString();
		}

		private static void AppendPublicKey(StringBuilder sb, byte[] publicKey)
		{
			for (int i = 0; i < publicKey.Length; i++)
			{
				sb.Append("0123456789abcdef"[publicKey[i] >> 4]);
				sb.Append("0123456789abcdef"[publicKey[i] & 0x0F]);
			}
		}

		public override bool Equals(object obj)
		{
			AssemblyName other = obj as AssemblyName;
			return other != null && other.FullName == this.FullName;
		}

		public override int GetHashCode()
		{
			return FullName.GetHashCode();
		}

		public object Clone()
		{
			AssemblyName copy = (AssemblyName)MemberwiseClone();
			copy.publicKey = Copy(publicKey);
			copy.publicKeyToken = Copy(publicKeyToken);
			return copy;
		}

		private static byte[] Copy(byte[] b)
		{
			return b == null || b.Length == 0 ? b : (byte[])b.Clone();
		}

#if !CORECLR
		public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition)
		{
			// HACK use the real AssemblyName to implement the (broken) ReferenceMatchesDefinition method
			return System.Reflection.AssemblyName.ReferenceMatchesDefinition(new System.Reflection.AssemblyName(reference.FullName), new System.Reflection.AssemblyName(definition.FullName));
		}
#endif

		public static AssemblyName GetAssemblyName(string path)
		{
			try
			{
				path = Path.GetFullPath(path);
				using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					ModuleReader module = new ModuleReader(null, null, fs, path, false);
					if (module.Assembly == null)
					{
						throw new BadImageFormatException("Module does not contain a manifest");
					}
					return module.Assembly.GetName();
				}
			}
			catch (IOException x)
			{
				throw new FileNotFoundException(x.Message, x);
			}
			catch (UnauthorizedAccessException x)
			{
				throw new FileNotFoundException(x.Message, x);
			}
		}

		internal AssemblyNameFlags RawFlags
		{
			get { return flags; }
			set { flags = value; }
		}

		private static bool ParseVersion(string str, bool mustBeComplete, out Version version)
		{
			if (str == null)
			{
				version = null;
				return true;
			}
			string[] parts = str.Split('.');
			if (parts.Length < 2 || parts.Length > 4)
			{
				version = null;
				ushort dummy;
				// if the version consists of a single integer, it is invalid, but not invalid enough to fail the parse of the whole assembly name
				return parts.Length == 1 && ushort.TryParse(parts[0], NumberStyles.Integer, null, out dummy);
			}
			if (parts[0] == "" || parts[1] == "")
			{
				// this is a strange scenario, the version is invalid, but not invalid enough to fail the parse of the whole assembly name
				version = null;
				return true;
			}
			ushort major, minor, build = 65535, revision = 65535;
			if (ushort.TryParse(parts[0], NumberStyles.Integer, null, out major)
				&& ushort.TryParse(parts[1], NumberStyles.Integer, null, out minor)
				&& (parts.Length <= 2 || parts[2] == "" || ushort.TryParse(parts[2], NumberStyles.Integer, null, out build))
				&& (parts.Length <= 3 || parts[3] == "" || (parts[2] != "" && ushort.TryParse(parts[3], NumberStyles.Integer, null, out revision))))
			{
				if (mustBeComplete && (parts.Length < 4 || parts[2] == "" || parts[3] == ""))
				{
					version = null;
				}
				else if (major == 65535 || minor == 65535)
				{
					version = null;
				}
				else
				{
					version = new Version(major, minor, build, revision);
				}
				return true;
			}
			version = null;
			return false;
		}
	}
}