summaryrefslogtreecommitdiff
path: root/external/ikvm/reflect/Fusion.cs
blob: dafb60e4fff1dc482de772550deb660689cbbd00 (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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/*
  Copyright (C) 2010-2012 Jeroen Frijters
  Copyright (C) 2011 Marek Safar

  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.Runtime.InteropServices;
using System.Text;

namespace IKVM.Reflection
{
	struct ParsedAssemblyName
	{
		internal string Name;
		internal Version Version;
		internal string Culture;
		internal string PublicKeyToken;
		internal bool? Retargetable;
		internal ProcessorArchitecture ProcessorArchitecture;
		internal bool HasPublicKey;
		internal bool WindowsRuntime;
	}

	enum ParseAssemblyResult
	{
		OK,
		GenericError,
		DuplicateKey,
	}

	static class Fusion
	{
		internal static bool CompareAssemblyIdentityNative(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)
		{
			bool equivalent;
			Marshal.ThrowExceptionForHR(CompareAssemblyIdentity(assemblyIdentity1, unified1, assemblyIdentity2, unified2, out equivalent, out result));
			return equivalent;
		}

		[DllImport("fusion", CharSet = CharSet.Unicode)]
		private static extern int CompareAssemblyIdentity(string pwzAssemblyIdentity1, bool fUnified1, string pwzAssemblyIdentity2, bool fUnified2, out bool pfEquivalent, out AssemblyComparisonResult pResult);

		// internal for use by mcs
		internal static bool CompareAssemblyIdentityPure(string assemblyIdentity1, bool unified1, string assemblyIdentity2, bool unified2, out AssemblyComparisonResult result)
		{
			ParsedAssemblyName name1;
			ParsedAssemblyName name2;

			ParseAssemblyResult r = ParseAssemblyName(assemblyIdentity1, out name1);
			if (r != ParseAssemblyResult.OK || (r = ParseAssemblyName(assemblyIdentity2, out name2)) != ParseAssemblyResult.OK)
			{
				result = AssemblyComparisonResult.NonEquivalent;
				switch (r)
				{
					case ParseAssemblyResult.DuplicateKey:
						throw new System.IO.FileLoadException();
					case ParseAssemblyResult.GenericError:
					default:
						throw new ArgumentException();
				}
			}

			bool partial = IsPartial(name1);

			if ((partial && unified1) || IsPartial(name2))
			{
				result = AssemblyComparisonResult.NonEquivalent;
				throw new ArgumentException();
			}
			if (!name1.Name.Equals(name2.Name, StringComparison.InvariantCultureIgnoreCase))
			{
				result = AssemblyComparisonResult.NonEquivalent;
				return false;
			}
			if (name1.Name.Equals("mscorlib", StringComparison.InvariantCultureIgnoreCase))
			{
				result = AssemblyComparisonResult.EquivalentFullMatch;
				return true;
			}
			if (partial && name1.Culture == null)
			{
			}
			else if (!name1.Culture.Equals(name2.Culture, StringComparison.InvariantCultureIgnoreCase))
			{
				result = AssemblyComparisonResult.NonEquivalent;
				return false;
			}
			if (IsStrongNamed(name2))
			{
				if (partial && name1.PublicKeyToken == null)
				{
				}
				else if (name1.PublicKeyToken != name2.PublicKeyToken)
				{
					if (HasPclRuntimeRemapping (name1, name2)) {
						result = AssemblyComparisonResult.EquivalentFXUnified;
						return true;
					}
					result = AssemblyComparisonResult.NonEquivalent;
					return false;
				}
				if (partial && name1.Version == null)
				{
					result = AssemblyComparisonResult.EquivalentPartialMatch;
					return true;
				}
				else if (IsFrameworkAssembly(name2) || IsFacadeAssembly(name2))
				{
					result = partial ? AssemblyComparisonResult.EquivalentPartialFXUnified : AssemblyComparisonResult.EquivalentFXUnified;
					return true;
				}
				else if (name1.Version.Revision == -1 || name2.Version.Revision == -1)
				{
					result = AssemblyComparisonResult.NonEquivalent;
					throw new ArgumentException();
				}
				else if (name1.Version < name2.Version)
				{
					if (unified2)
					{
						result = partial ? AssemblyComparisonResult.EquivalentPartialUnified : AssemblyComparisonResult.EquivalentUnified;
						return true;
					}
					else
					{
						result = partial ? AssemblyComparisonResult.NonEquivalentPartialVersion : AssemblyComparisonResult.NonEquivalentVersion;
						return false;
					}
				}
				else if (name1.Version > name2.Version)
				{
					if (unified1)
					{
						result = partial ? AssemblyComparisonResult.EquivalentPartialUnified : AssemblyComparisonResult.EquivalentUnified;
						return true;
					}
					else
					{
						result = partial ? AssemblyComparisonResult.NonEquivalentPartialVersion : AssemblyComparisonResult.NonEquivalentVersion;
						return false;
					}
				}
				else
				{
					result = partial ? AssemblyComparisonResult.EquivalentPartialMatch : AssemblyComparisonResult.EquivalentFullMatch;
					return true;
				}
			}
			else if (IsStrongNamed(name1))
			{
				result = AssemblyComparisonResult.NonEquivalent;
				return false;
			}
			else
			{
				result = partial ? AssemblyComparisonResult.EquivalentPartialWeakNamed : AssemblyComparisonResult.EquivalentWeakNamed;
				return true;
			}
		}

		#region PCL Runtime Remapping

		// keep this in sync with the key_remap_table in mono/metadata/assembly.c

		const string SILVERLIGHT_KEY = "7cec85d7bea7798e";
		const string WINFX_KEY = "31bf3856ad364e35";
		const string ECMA_KEY = "b77a5c561934e089";
		const string MSFINAL_KEY = "b03f5f7f11d50a3a";

		static readonly string[,] key_remap_table = new string[,] {
			{ "Microsoft.CSharp", WINFX_KEY, MSFINAL_KEY },
			{ "System", SILVERLIGHT_KEY, ECMA_KEY },
			{ "System.ComponentModel.Composition", WINFX_KEY, ECMA_KEY },
			{ "System.ComponentModel.DataAnnotations", "ddd0da4d3e678217", WINFX_KEY },
			{ "System.Core", SILVERLIGHT_KEY, ECMA_KEY },
			// FIXME: MS uses MSFINAL_KEY for .NET 4.5
			{ "System.Net", SILVERLIGHT_KEY, MSFINAL_KEY },
			{ "System.Numerics", WINFX_KEY, MSFINAL_KEY },
			{ "System.Runtime.Serialization", SILVERLIGHT_KEY, ECMA_KEY },
			{ "System.ServiceModel", WINFX_KEY, ECMA_KEY },
			{ "System.ServiceModel.Web", SILVERLIGHT_KEY, WINFX_KEY },
			{ "System.Windows", SILVERLIGHT_KEY, MSFINAL_KEY },
			{ "System.Xml", SILVERLIGHT_KEY, ECMA_KEY },
			{ "System.Xml.Linq", WINFX_KEY, ECMA_KEY },
			{ "System.Xml.Serialization", WINFX_KEY, ECMA_KEY }
		};

		static bool HasPclRuntimeRemapping(ParsedAssemblyName name1, ParsedAssemblyName name2)
		{
			if (name1.Name != name2.Name)
				return false;

			for (int i = 0; i < key_remap_table.GetLength (0); i++) {
				if (!name1.Name.Equals (key_remap_table [i,0]))
					continue;
				if (name1.PublicKeyToken.Equals (key_remap_table [i, 1]) &&
				    name2.PublicKeyToken.Equals (key_remap_table [i, 2]))
					return true;
			}

			return false;
		}

		#endregion

		static bool IsFrameworkAssembly(ParsedAssemblyName name)
		{
			// A list of FX assemblies which require some form of remapping
			// When 4.0 + 1 version  is release, assemblies introduced in v4.0
			// will have to be added
			switch (name.Name)
			{
				case "System":
				case "System.Core":
				case "System.Data":
				case "System.Data.DataSetExtensions":
				case "System.Data.Linq":
				case "System.Data.OracleClient":
				case "System.Data.Services":
				case "System.Data.Services.Client":
				case "System.IdentityModel":
				case "System.IdentityModel.Selectors":
				case "System.Runtime.Remoting":
				case "System.Runtime.Serialization":
				case "System.ServiceModel":
				case "System.Transactions":
				case "System.Windows.Forms":
				case "System.Xml":
				case "System.Xml.Linq":
					return name.PublicKeyToken == "b77a5c561934e089";

				case "System.Configuration":
				case "System.Configuration.Install":
				case "System.Design":
				case "System.DirectoryServices":
				case "System.Drawing":
				case "System.Drawing.Design":
				case "System.EnterpriseServices":
				case "System.Management":
				case "System.Messaging":
				case "System.Runtime.Serialization.Formatters.Soap":
				case "System.Security":
				case "System.ServiceProcess":
				case "System.Web":
				case "System.Web.Mobile":
				case "System.Web.Services":
					return name.PublicKeyToken == "b03f5f7f11d50a3a";

				case "System.ComponentModel.DataAnnotations":
				case "System.ServiceModel.Web":
				case "System.Web.Abstractions":
				case "System.Web.Extensions":
				case "System.Web.Extensions.Design":
				case "System.Web.DynamicData":
				case "System.Web.Routing":
					return name.PublicKeyToken == "31bf3856ad364e35";
			}

			return false;
		}

		static bool IsFacadeAssembly (ParsedAssemblyName name)
		{
			switch (name.Name) {
			case "System.Collections":
			case "System.Collections.Concurrent":
			case "System.ComponentModel":
			case "System.ComponentModel.Annotations":
			case "System.ComponentModel.EventBasedAsync":
			case "System.Diagnostics.Contracts":
			case "System.Diagnostics.Debug":
			case "System.Diagnostics.Tools":
			case "System.Dynamic.Runtime":
			case "System.Globalization":
			case "System.IO":
			case "System.Linq":
			case "System.Linq.Expressions":
			case "System.Linq.Parallel":
			case "System.Linq.Queryable":
			case "System.Net.NetworkInformation":
			case "System.Net.Primitives":
			case "System.Net.Requests":
			case "System.ObjectModel":
			case "System.Reflection":
			case "System.Reflection.Extensions":
			case "System.Reflection.Primitives":
			case "System.Resources.ResourceManager":
			case "System.Runtime":
			case "System.Runtime.Extensions":
			case "System.Runtime.InteropServices":
			case "System.Runtime.Numerics":
			case "System.Runtime.Serialization.Json":
			case "System.Runtime.Serialization.Primitives":
			case "System.Runtime.Serialization.Xml":
			case "System.Security.Principal":
			case "System.ServiceModel.Http":
			case "System.ServiceModel.Primitives":
			case "System.Text.Encoding":
			case "System.Text.Encoding.Extensions":
			case "System.Text.RegularExpressions":
			case "System.Threading":
			case "System.Threading.Tasks":
			case "System.Threading.Tasks.Parallel":
			case "System.Xml.ReaderWriter":
			case "System.Xml.XDocument":
			case "System.Xml.XmlSerializer":
				return name.PublicKeyToken == "b03f5f7f11d50a3a";
			default:
				return false;
			}
		}

		internal static ParseAssemblyResult ParseAssemblySimpleName(string fullName, out int pos, out string simpleName)
		{
			StringBuilder sb = new StringBuilder();
			pos = 0;
			simpleName = null;
			while (pos < fullName.Length && char.IsWhiteSpace(fullName[pos]))
			{
				pos++;
			}
			char quoteOrComma = ',';
			if (pos < fullName.Length && (fullName[pos] == '\"' || fullName[pos] == '\''))
			{
				quoteOrComma = fullName[pos++];
			}
			while (pos < fullName.Length)
			{
				char ch = fullName[pos++];
				if (ch == '\\')
				{
					if (pos == fullName.Length)
					{
						return ParseAssemblyResult.GenericError;
					}
					ch = fullName[pos++];
					if (ch == '\\')
					{
						return ParseAssemblyResult.GenericError;
					}
				}
				else if (ch == quoteOrComma)
				{
					if (ch != ',')
					{
						while (pos != fullName.Length)
						{
							ch = fullName[pos++];
							if (ch == ',')
							{
								break;
							}
							if (!char.IsWhiteSpace(ch))
							{
								return ParseAssemblyResult.GenericError;
							}
						}
					}
					break;
				}
				else if (ch == '=' || (quoteOrComma == ',' && (ch == '\'' || ch == '"')))
				{
					return ParseAssemblyResult.GenericError;
				}
				sb.Append(ch);
			}
			simpleName = sb.ToString().Trim();
			if (simpleName.Length == 0)
			{
				return ParseAssemblyResult.GenericError;
			}
			if (pos == fullName.Length && fullName[fullName.Length - 1] == ',')
			{
				return ParseAssemblyResult.GenericError;
			}
			return ParseAssemblyResult.OK;
		}

		internal static ParseAssemblyResult ParseAssemblyName(string fullName, out ParsedAssemblyName parsedName)
		{
			parsedName = new ParsedAssemblyName();
			int pos;
			ParseAssemblyResult res = ParseAssemblySimpleName(fullName, out pos, out parsedName.Name);
			if (res != ParseAssemblyResult.OK || pos == fullName.Length)
			{
				return res;
			}
			else
			{
				System.Collections.Generic.Dictionary<string, string> unknownAttributes = null;
				bool hasProcessorArchitecture = false;
				bool hasContentType = false;
				string[] parts = fullName.Substring(pos).Split(',');
				for (int i = 0; i < parts.Length; i++)
				{
					string[] kv = parts[i].Split('=');
					if (kv.Length != 2)
					{
						return ParseAssemblyResult.GenericError;
					}
					switch (kv[0].Trim().ToLowerInvariant())
					{
						case "version":
							if (parsedName.Version != null)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							if (!ParseVersion(kv[1].Trim(), out parsedName.Version))
							{
								return ParseAssemblyResult.GenericError;
							}
							break;
						case "culture":
							if (parsedName.Culture != null)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							if (!ParseCulture(kv[1].Trim(), out parsedName.Culture))
							{
								return ParseAssemblyResult.GenericError;
							}
							break;
						case "publickeytoken":
							if (parsedName.PublicKeyToken != null)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							if (!ParsePublicKeyToken(kv[1].Trim(), out parsedName.PublicKeyToken))
							{
								return ParseAssemblyResult.GenericError;
							}
							break;
						case "publickey":
							if (parsedName.PublicKeyToken != null)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							if (!ParsePublicKey(kv[1].Trim(), out parsedName.PublicKeyToken))
							{
								return ParseAssemblyResult.GenericError;
							}
							parsedName.HasPublicKey = true;
							break;
						case "retargetable":
							if (parsedName.Retargetable.HasValue)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							switch (kv[1].Trim().ToLowerInvariant())
							{
								case "yes":
									parsedName.Retargetable = true;
									break;
								case "no":
									parsedName.Retargetable = false;
									break;
								default:
									return ParseAssemblyResult.GenericError;
							}
							break;
						case "processorarchitecture":
							if (hasProcessorArchitecture)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							hasProcessorArchitecture = true;
							switch (kv[1].Trim().ToLowerInvariant())
							{
								case "none":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.None;
									break;
								case "msil":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.MSIL;
									break;
								case "x86":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.X86;
									break;
								case "ia64":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.IA64;
									break;
								case "amd64":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.Amd64;
									break;
								case "arm":
									parsedName.ProcessorArchitecture = ProcessorArchitecture.Arm;
									break;
								default:
									return ParseAssemblyResult.GenericError;
							}
							break;
						case "contenttype":
							if (hasContentType)
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							hasContentType = true;
							if (kv[1].Trim().ToLowerInvariant() != "windowsruntime")
							{
								return ParseAssemblyResult.GenericError;
							}
							parsedName.WindowsRuntime = true;
							break;
						default:
							if (kv[1].Trim() == "")
							{
								return ParseAssemblyResult.GenericError;
							}
							if (unknownAttributes == null)
							{
								unknownAttributes = new System.Collections.Generic.Dictionary<string, string>();
							}
							if (unknownAttributes.ContainsKey(kv[0].Trim().ToLowerInvariant()))
							{
								return ParseAssemblyResult.DuplicateKey;
							}
							unknownAttributes.Add(kv[0].Trim().ToLowerInvariant(), null);
							break;
					}
				}
			}
			return ParseAssemblyResult.OK;
		}

		private static bool ParseVersion(string str, out Version version)
		{
			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], System.Globalization.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], System.Globalization.NumberStyles.Integer, null, out major)
				&& ushort.TryParse(parts[1], System.Globalization.NumberStyles.Integer, null, out minor)
				&& (parts.Length <= 2 || parts[2] == "" || ushort.TryParse(parts[2], System.Globalization.NumberStyles.Integer, null, out build))
				&& (parts.Length <= 3 || parts[3] == "" || (parts[2] != "" && ushort.TryParse(parts[3], System.Globalization.NumberStyles.Integer, null, out revision))))
			{
				if (parts.Length == 4 && parts[3] != "" && parts[2] != "")
				{
					version = new Version(major, minor, build, revision);
				}
				else if (parts.Length == 3 && parts[2] != "")
				{
					version = new Version(major, minor, build);
				}
				else
				{
					version = new Version(major, minor);
				}
				return true;
			}
			version = null;
			return false;
		}

		private static bool ParseCulture(string str, out string culture)
		{
			if (str == null)
			{
				culture = null;
				return false;
			}
			culture = str;
			return true;
		}

		private static bool ParsePublicKeyToken(string str, out string publicKeyToken)
		{
			if (str == null)
			{
				publicKeyToken = null;
				return false;
			}
			publicKeyToken = str.ToLowerInvariant();
			return true;
		}

		private static bool ParsePublicKey(string str, out string publicKeyToken)
		{
			if (str == null)
			{
				publicKeyToken = null;
				return false;
			}
			publicKeyToken = AssemblyName.ComputePublicKeyToken(str);
			return true;
		}

		private static bool IsPartial(ParsedAssemblyName name)
		{
			return name.Version == null || name.Culture == null || name.PublicKeyToken == null;
		}

		private static bool IsStrongNamed(ParsedAssemblyName name)
		{
			return name.PublicKeyToken != null && name.PublicKeyToken != "null";
		}
	}
}