aboutsummaryrefslogtreecommitdiff
path: root/runtime/VMProtect.Runtime/Loader.cs
blob: 8511045a0807884403d56fa12f23e5430756eefb (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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics;
using System.Reflection.Emit;

// ReSharper disable once CheckNamespace
namespace VMProtect
{
	[VMProtect.DeleteOnCompilation]
	enum MessageType
	{
		InitializationError,
		ProcNotFound,
		OrdinalNotFound,
		FileCorrupted,
		DebuggerFound,
		UnregisteredVersion,
		VirtualMachineFound
	}

	[VMProtect.DeleteOnCompilation]
	enum ErrorType
	{
		VIRTUAL_PROTECT_ERROR = 1,
		UNPACKER_ERROR = 2
	}

	[VMProtect.DeleteOnCompilation]
	enum LoaderOption
	{
		CHECK_PATCH = 0x1,
		CHECK_DEBUGGER = 0x2,
		CHECK_KERNEL_DEBUGGER = 0x4,
		EXIT_PROCESS = 0x8,
		CHECK_VIRTUAL_MACHINE = 0x10
	}

	[VMProtect.DeleteOnCompilation]
	enum FixupType
	{
		Absolute = 0,
		High = 1,
		Low = 2,
		HighLow = 3,
		Dir64 = 10
	}

	public static class Loader
	{
		public static object[] IAT;

		internal static bool FindFirmwareVendor(byte[] data)
		{
			for (var i = 0; i < data.Length; i++)
			{
				if (i + 3 < data.Length && data[i + 0] == 'Q' && data[i + 1] == 'E' && data[i + 2] == 'M' && data[i + 3] == 'U')
					return true;
				if (i + 8 < data.Length && data[i + 0] == 'M' && data[i + 1] == 'i' && data[i + 2] == 'c' && data[i + 3] == 'r' && data[i + 4] == 'o' && data[i + 5] == 's' && data[i + 6] == 'o' && data[i + 7] == 'f' && data[i + 8] == 't')
					return true;
				if (i + 6 < data.Length && data[i + 0] == 'i' && data[i + 1] == 'n' && data[i + 2] == 'n' && data[i + 3] == 'o' && data[i + 4] == 't' && data[i + 5] == 'e' && data[i + 6] == 'k')
					return true;
				if (i + 9 < data.Length && data[i + 0] == 'V' && data[i + 1] == 'i' && data[i + 2] == 'r' && data[i + 3] == 't' && data[i + 4] == 'u' && data[i + 5] == 'a' && data[i + 6] == 'l' && data[i + 7] == 'B' && data[i + 8] == 'o' && data[i + 9] == 'x')
					return true;
				if (i + 5 < data.Length && data[i + 0] == 'V' && data[i + 1] == 'M' && data[i + 2] == 'w' && data[i + 3] == 'a' && data[i + 4] == 'r' && data[i + 5] == 'e')
					return true;
				if (i + 8 < data.Length && data[i + 0] == 'P' && data[i + 1] == 'a' && data[i + 2] == 'r' && data[i + 3] == 'a' && data[i + 4] == 'l' && data[i + 5] == 'l' && data[i + 6] == 'e' && data[i + 7] == 'l' && data[i + 8] == 's')
					return true;
			}
			return false;
		}

		private static void ShowMessage(uint type, uint param = 0)
		{
			uint position;
			switch (type)
			{
				case (uint)MessageType.DebuggerFound:
					position = (uint)Faces.DEBUGGER_FOUND;
					break;
				case (uint)MessageType.VirtualMachineFound:
					position = (uint)Faces.VIRTUAL_MACHINE_FOUND;
					break;
				case (uint)MessageType.FileCorrupted:
					position = (uint)Faces.FILE_CORRUPTED;
					break;
				case (uint)MessageType.UnregisteredVersion:
					position = (uint)Faces.UNREGISTERED_VERSION;
					break;
				case (uint)MessageType.InitializationError:
					position = (uint)Faces.INITIALIZATION_ERROR;
					break;
				default:
					return;
			}

			long instance = Marshal.GetHINSTANCE(typeof(Loader).Module).ToInt64();
			String message = null;
			var buffer = new byte[1024];
			for (var pos = 0; pos < 512; pos++)
			{
				var c = (ushort)(Marshal.ReadInt16(new IntPtr(instance + position + pos * 2)) ^ (BitRotate.Left((uint)Faces.STRING_DECRYPT_KEY, pos) + pos));
				if (c == 0)
				{
					if (pos > 0)
						message = Encoding.Unicode.GetString(buffer, 0, pos * 2);
					break;
				}

				buffer[pos * 2] = (byte)c;
				buffer[pos * 2 + 1] = (byte)(c >> 8);
			}
			if (message != null)
			{
				if (type == (uint)MessageType.InitializationError)
					message = String.Format(message, param);
				Win32.ShowMessage(message, Assembly.GetExecutingAssembly().GetName().Name, MessageBoxButtons.OK, type == (uint)MessageType.UnregisteredVersion ? MessageBoxIcon.Warning : MessageBoxIcon.Error);
			}
		}

		internal static bool LzmaDecode(IntPtr dst, IntPtr src, byte[] properties, ref uint dstSize, out uint srcSize)
		{
			srcSize = 0;
			unsafe
			{
				using (
					var srcStream = new UnmanagedMemoryStream((byte*)src.ToPointer(), int.MaxValue, int.MaxValue, FileAccess.Read)
					)
				{
					using (
						var dstStream = new UnmanagedMemoryStream((byte*) dst.ToPointer(), dstSize, dstSize,
							FileAccess.Write))
					{
						try
						{
							var coder = new SevenZip.Compression.LZMA.Decoder();
							coder.SetDecoderProperties(properties);
							coder.Code(srcStream, dstStream, dstSize);
							dstStream.Flush();

							srcSize = (uint)srcStream.Position;
							dstSize = (uint)dstStream.Position;
						}
						catch (Exception)
						{
							return false;
						}

						return true;
					}
				}
			}
		}

		public static void Main()
		{
			if (GlobalData.LoaderStatus() != 0)
				return;

			var module = typeof(Loader).Module;
			long instance = Marshal.GetHINSTANCE(module).ToInt64();
			var options = (uint)Faces.LOADER_OPTIONS;
			GlobalData.SetIsPatchDetected(false);
			GlobalData.SetIsDebuggerDetected(false);
			GlobalData.SetLoaderCrcInfo((uint)Faces.LOADER_CRC_INFO);
			GlobalData.SetLoaderCrcSize((uint)Faces.LOADER_CRC_INFO_SIZE);
			GlobalData.SetLoaderCrcHash((uint)Faces.LOADER_CRC_INFO_HASH);
			GlobalData.SetServerDate(0);

			// detect a debugger
			if ((options & (uint)LoaderOption.CHECK_DEBUGGER) != 0)
			{
				if (Debugger.IsAttached || Debugger.IsLogging())
				{
					ShowMessage((uint)MessageType.DebuggerFound);
					Environment.Exit(1);
					return;
				}

				if (Win32.IsDebuggerPresent() || Win32.CheckRemoteDebuggerPresent())
				{
					ShowMessage((uint)MessageType.DebuggerFound);
					Environment.Exit(1);
					return;
				}

				Win32.NtSetInformationThread(Win32.CurrentThread, Win32.THREADINFOCLASS.ThreadHideFromDebugger, IntPtr.Zero, 0);
			}

			// check header and loader CRC
			var crcSize = (uint)Faces.LOADER_CRC_INFO_SIZE;
			if (crcSize != 0)
			{
				crcSize = (uint)Marshal.ReadInt32(new IntPtr(instance + crcSize));
				var crcPosition = (uint)Faces.LOADER_CRC_INFO;
				var crcCryptor = new CRCValueCryptor();
				bool isValid = true;
				var crcInfo = new byte[12];
				var crc32 = new CRC32();
				var crcHash = (uint)Marshal.ReadInt32(new IntPtr(instance + (uint)Faces.LOADER_CRC_INFO_HASH));
				if (crcHash != crc32.Hash(new IntPtr(instance + crcPosition), crcSize))
					isValid = false;
				for (var i = 0; i < crcSize; i += crcInfo.Length)
				{
					Marshal.Copy(new IntPtr(instance + crcPosition + i), crcInfo, 0, crcInfo.Length);
					uint address = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 0));
					uint size = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 4));
					uint hash = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 8));

					if (crc32.Hash(new IntPtr(instance + address), size) != hash)
						isValid = false;
				}

				if (!isValid)
				{
					if ((options & (uint)LoaderOption.CHECK_PATCH) != 0)
					{
						ShowMessage((uint)MessageType.FileCorrupted);
						Environment.Exit(1);
						return;
					}
					GlobalData.SetIsPatchDetected(true);
				}
			}

			// check file CRC
			crcSize = (uint)Faces.FILE_CRC_INFO_SIZE;
			if (crcSize != 0) //-V3022
			{
				crcSize = (uint)Marshal.ReadInt32(new IntPtr(instance + crcSize));
				var crcPosition = (uint)Faces.FILE_CRC_INFO;
				bool isValid = true;
				var file = Win32.OpenFile(Assembly.GetExecutingAssembly().Location, (uint)Win32.Values.GENERIC_READ, (uint)Win32.Values.FILE_SHARE_READ | (uint)Win32.Values.FILE_SHARE_WRITE);
				if (file != Win32.InvalidHandleValue)
				{
					var fileSize = Win32.GetFileSize(file, IntPtr.Zero);
					if (fileSize < (uint)Marshal.ReadInt32(new IntPtr(instance + crcPosition)))
						isValid = false;
					else
					{
						var map = Win32.CreateFileMapping(file, IntPtr.Zero, Win32.MemoryProtection.ReadOnly, 0, 0, null);
						if (map != Win32.NullHandle)
						{
							IntPtr baseAddress = Win32.MapViewOfFile(map, Win32.MapAccess.Read, 0, 0, IntPtr.Zero);
							if (baseAddress != IntPtr.Zero)
							{
								var crcInfo = new byte[12];
								var crc32 = new CRC32();
								var crcCryptor = new CRCValueCryptor();
								for (var i = 4; i < crcSize; i += crcInfo.Length)
								{
									Marshal.Copy(new IntPtr(instance + crcPosition + i), crcInfo, 0, crcInfo.Length);
									uint address = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 0));
									uint size = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 4));
									uint hash = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 8));

									if (crc32.Hash(new IntPtr(baseAddress.ToInt64() + address), size) != hash)
										isValid = false;
								}
								Win32.UnmapViewOfFile(baseAddress);
							}
							Win32.CloseHandle(map);
						}
					}
					Win32.CloseHandle(file);
				}

				if (!isValid)
				{
					if ((options & (uint)LoaderOption.CHECK_PATCH) != 0)
					{
						ShowMessage((uint)MessageType.FileCorrupted);
						Environment.Exit(1);
						return;
					}
					GlobalData.SetIsPatchDetected(true);
				}
			}

			// setup WRITABLE flag for memory pages
			var sectionSize = (uint)Faces.SECTION_INFO_SIZE;
			if (sectionSize != 0)
			{
				var sectionPos = (uint)Faces.SECTION_INFO;
				var sectionInfo = new byte[12];
				for (var i = 0; i < sectionSize; i += sectionInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + sectionPos + i), sectionInfo, 0, sectionInfo.Length);
					uint address = BitConverter.ToUInt32(sectionInfo, 0);
					uint size = BitConverter.ToUInt32(sectionInfo, 4);
					uint type = BitConverter.ToUInt32(sectionInfo, 8);

					Win32.MemoryProtection protect, old_protect;
					protect = ((type & (uint)Win32.SectionType.Execute) != 0) ? Win32.MemoryProtection.ExecuteReadWrite : Win32.MemoryProtection.ReadWrite;
					if (!Win32.VirtualProtect(new IntPtr(instance + address), new UIntPtr(size), protect, out old_protect))
					{
						ShowMessage((uint)MessageType.InitializationError, (uint)ErrorType.VIRTUAL_PROTECT_ERROR);
						Environment.Exit(1);
						return;
					}
					if (((uint)old_protect & ((uint)Win32.MemoryProtection.NoAccess | (uint)Win32.MemoryProtection.Guard)) != 0)
					{
						if ((options & (uint)LoaderOption.CHECK_DEBUGGER) != 0)
						{
							ShowMessage((uint)MessageType.DebuggerFound);
							Environment.Exit(1);
							return;
						}
						GlobalData.SetIsDebuggerDetected(true);
					}
				}
			}

			// unpack regions
			var packerSize = (uint)Faces.PACKER_INFO_SIZE;
			if (packerSize != 0)
			{
				int tlsIndex = 0;
				var tlsIndexPos = (uint)Faces.TLS_INDEX_INFO;
				if (tlsIndexPos != 0)
					tlsIndex = Marshal.ReadInt32(new IntPtr(instance + tlsIndexPos));

				var packerPos = (uint)Faces.PACKER_INFO;
				var packerInfo = new byte[8];
				Marshal.Copy(new IntPtr(instance + packerPos), packerInfo, 0, packerInfo.Length);
				uint src = BitConverter.ToUInt32(packerInfo, 0);
				uint dst = BitConverter.ToUInt32(packerInfo, 4);
				var properties = new byte[dst];
				Marshal.Copy(new IntPtr(instance + src), properties, 0, properties.Length);
				for (var i = packerInfo.Length; i < packerSize; i += packerInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + packerPos + i), packerInfo, 0, packerInfo.Length);
					src = BitConverter.ToUInt32(packerInfo, 0);
					dst = BitConverter.ToUInt32(packerInfo, 4);
					uint dstSize = int.MaxValue, srcSize;

					if (!LzmaDecode(new IntPtr(instance + dst), new IntPtr(instance + src), properties, ref dstSize, out srcSize))
					{
						ShowMessage((uint)MessageType.InitializationError, (uint)ErrorType.UNPACKER_ERROR);
						Environment.Exit(1);
						return;
					}
				}

				if (tlsIndexPos != 0)
					Marshal.WriteInt32(new IntPtr(instance + tlsIndexPos), tlsIndex);
			}

			// setup fixups
			long fileBase = (uint)Faces.FILE_BASE;
			long deltaBase = instance - fileBase;
			if (deltaBase != 0)
			{
				var fixupSize = (uint)Faces.FIXUP_INFO_SIZE;
				if (fixupSize != 0)
				{
					var fixupPos = (uint)Faces.FIXUP_INFO;
					var fixupInfo = new byte[8];
					uint blockSize = 0;
					for (uint i = 0; i < fixupSize; i += blockSize)
					{
						Marshal.Copy(new IntPtr(instance + fixupPos + i), fixupInfo, 0, fixupInfo.Length);
						uint address = BitConverter.ToUInt32(fixupInfo, 0);
						blockSize = BitConverter.ToUInt32(fixupInfo, 4);
						if (blockSize < fixupInfo.Length)
							break;

						var c = blockSize - fixupInfo.Length;
						var block = new byte[c];
						Marshal.Copy(new IntPtr(instance + fixupPos + i + fixupInfo.Length), block, 0, block.Length);
						for (var j = 0; j < c; j += 2)
						{
							ushort typeOffset = BitConverter.ToUInt16(block, j);
							var type = (typeOffset & 0xf);
							var ptr = new IntPtr(instance + address + (typeOffset >> 4));

							if (type == (uint)FixupType.HighLow)
							{
								int value = Marshal.ReadInt32(ptr);
								value += (int)deltaBase;
								Marshal.WriteInt32(ptr, value);
							}
							else if (type == (uint)FixupType.Dir64)
							{
								long value = Marshal.ReadInt64(ptr);
								value += deltaBase;
								Marshal.WriteInt64(ptr, value);
							}
							else if (type == (uint)FixupType.High)
							{
								short value = Marshal.ReadInt16(ptr);
								value += (short)(deltaBase >> 16);
								Marshal.WriteInt16(ptr, value);
							}
							else if (type == (uint)FixupType.Low)
							{
								short value = Marshal.ReadInt16(ptr);
								value += (short)deltaBase;
								Marshal.WriteInt16(ptr, value);
							}
						}
					}
				}
			}

			// setup IAT
			var iatSize = (uint)Faces.IAT_INFO_SIZE;
			if (iatSize != 0)
			{
				var iatPos = (uint)Faces.IAT_INFO;
				var iatInfo = new byte[12];
				for (var i = 0; i < iatSize; i += iatInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + iatPos + i), iatInfo, 0, iatInfo.Length);
					uint src = BitConverter.ToUInt32(iatInfo, 0);
					uint dst = BitConverter.ToUInt32(iatInfo, 4);
					uint size = BitConverter.ToUInt32(iatInfo, 8);

					var data = new byte[size];
					Marshal.Copy(new IntPtr(instance + src), data, 0, data.Length);
					Marshal.Copy(data, 0, new IntPtr(instance + dst), data.Length);
				}
			}

			// reset WRITABLE flag for memory pages
			if (sectionSize != 0) //-V3022
			{
				var sectionPos = (uint)Faces.SECTION_INFO;
				var sectionInfo = new byte[12];
				for (var i = 0; i < sectionSize; i += sectionInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + sectionPos + i), sectionInfo, 0, sectionInfo.Length);
					uint address = BitConverter.ToUInt32(sectionInfo, 0);
					uint size = BitConverter.ToUInt32(sectionInfo, 4);
					uint type = BitConverter.ToUInt32(sectionInfo, 8);

					Win32.MemoryProtection protect, old_protect;
					if ((type & (uint)Win32.SectionType.Read) != 0)
					{
						if ((type & (uint)Win32.SectionType.Write) != 0)
							protect = ((type & (uint)Win32.SectionType.Execute) != 0) ? Win32.MemoryProtection.ExecuteReadWrite : Win32.MemoryProtection.ReadWrite;
						else
							protect = ((type & (uint)Win32.SectionType.Execute) != 0) ? Win32.MemoryProtection.ExecuteRead : Win32.MemoryProtection.ReadOnly;
					}
					else
					{
						protect = ((type & (uint)Win32.SectionType.Execute) != 0) ? Win32.MemoryProtection.Execute : Win32.MemoryProtection.NoAccess;
					}
					if (!Win32.VirtualProtect(new IntPtr(instance + address), new UIntPtr(size), protect, out old_protect))
					{
						ShowMessage((uint)MessageType.InitializationError, (uint)ErrorType.VIRTUAL_PROTECT_ERROR);
						Environment.Exit(1);
					}
					if (((uint)old_protect & ((uint)Win32.MemoryProtection.NoAccess | (uint)Win32.MemoryProtection.Guard)) != 0)
					{
						if ((options & (uint)LoaderOption.CHECK_DEBUGGER) != 0)
						{
							ShowMessage((uint)MessageType.DebuggerFound);
							Environment.Exit(1);
							return;
						}
						GlobalData.SetIsDebuggerDetected(true);
					}
				}
			}

			// detect a virtual machine
			if ((options & (uint)LoaderOption.CHECK_VIRTUAL_MACHINE) != 0)
			{
				var info = CpuId.Invoke(1);
				if (((info[2] >> 31) & 1) != 0)
				{
					// hypervisor found
					bool isFound = true;
					// check Hyper-V root partition
					info = CpuId.Invoke(0x40000000);
					if (info[1] == 0x7263694d && info[2] == 0x666f736f && info[3] == 0x76482074) // "Microsoft Hv"
					{
						info = CpuId.Invoke(0x40000003);
						if ((info[1] & 1) != 0)
							isFound = false;
					}
					if (isFound)
					{
						ShowMessage((uint)MessageType.VirtualMachineFound);
						Environment.Exit(1);
						return;
					}
				}
				else
				{
					int size;
					uint tableSignature = (byte)'R' << 24 | (byte)'S' << 16 | (byte)'M' << 8 | (byte)'B';
					try
					{
						size = (int)Win32.EnumSystemFirmwareTables(tableSignature, IntPtr.Zero, 0);
					}
					catch (EntryPointNotFoundException) { size = 0; }

					if (size > 0)
					{
						IntPtr nativeBuffer = Marshal.AllocHGlobal(size);
						Win32.EnumSystemFirmwareTables(tableSignature, nativeBuffer, (uint)size);
						byte[] buffer = new byte[size];
						Marshal.Copy(nativeBuffer, buffer, 0, size);
						Marshal.FreeHGlobal(nativeBuffer);
						for (var i = 0; i < size / sizeof(uint); i += sizeof(uint))
						{
							uint tableId = BitConverter.ToUInt32(buffer, i);
							int dataSize = (int)Win32.GetSystemFirmwareTable(tableSignature, tableId, IntPtr.Zero, 0);
							if (dataSize > 0)
							{
								nativeBuffer = Marshal.AllocHGlobal(dataSize);
								Win32.GetSystemFirmwareTable(tableSignature, tableId, nativeBuffer, (uint)dataSize);
								byte[] data = new byte[dataSize];
								Marshal.Copy(nativeBuffer, data, 0, dataSize);
								Marshal.FreeHGlobal(nativeBuffer);
								if (FindFirmwareVendor(data))
								{
									ShowMessage((uint)MessageType.VirtualMachineFound);
									Environment.Exit(1);
									return;
								}
							}
						}
					}
				}
			}

			// check memory CRC
			crcSize = (uint)Faces.MEMORY_CRC_INFO_SIZE;
			if (crcSize != 0) //-V3022
			{
				var crcPosition = (uint)Faces.MEMORY_CRC_INFO;
				var crcCryptor = new CRCValueCryptor();
				bool isValid = true;
				var crcInfo = new byte[12];
				var crc32 = new CRC32();
				var crcHash = (uint)Faces.MEMORY_CRC_INFO_HASH;
				if (crcHash != crc32.Hash(new IntPtr(instance + crcPosition), crcSize))
					isValid = false;
				for (var i = 0; i < crcSize; i += crcInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + crcPosition + i), crcInfo, 0, crcInfo.Length);
					uint address = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 0));
					uint size = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 4));
					uint hash = crcCryptor.Decrypt(BitConverter.ToUInt32(crcInfo, 8));

					if (crc32.Hash(new IntPtr(instance + address), size) != hash)
						isValid = false;
				}

				if (!isValid)
				{
					if ((options & (uint)LoaderOption.CHECK_PATCH) != 0)
					{
						ShowMessage((uint)MessageType.FileCorrupted);
						Environment.Exit(1);
						return;
					}
					GlobalData.SetIsPatchDetected(true);
				}
			}

			GlobalData.SetSessionKey((uint)new Random().Next());

			if (!Core.Instance.Init(instance))
			{
				Environment.Exit(1);
				return;
			}

			// setup Import
			var importSize = (uint)Faces.IMPORT_INFO_SIZE;
			if (importSize != 0)
			{
				var importPos = (uint)Faces.IMPORT_INFO;
				var key = (uint)Faces.STRING_DECRYPT_KEY;
				var importInfo = new byte[12];
				object[] iat = new object[importSize / importInfo.Length];
				uint index = 0;
				for (var i = 0; i < importSize; i += importInfo.Length) //-V3022
				{
					Marshal.Copy(new IntPtr(instance + importPos + i), importInfo, 0, importInfo.Length);
					uint token = BitConverter.ToUInt32(importInfo, 0) ^ key;
					uint delegateToken = BitConverter.ToUInt32(importInfo, 4) ^ key;
					uint callType = BitConverter.ToUInt32(importInfo, 8);

					MethodBase method = null;
					FieldInfo field = null;
					try
					{
						if ((callType & 8) != 0)
							field = module.ResolveField((int)token);
						else
							method = module.ResolveMethod((int)token);
					}
					catch (Exception e)
					{
						Win32.ShowMessage(e.InnerException.Message, Assembly.GetExecutingAssembly().GetName().Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
						Environment.Exit(1);
						return;
					}

					var invoke = (MethodInfo)module.ResolveMethod((int)delegateToken);
					var delegateType = invoke.DeclaringType;
					object delegateObject;
					if (callType == 0 && method.IsStatic)
						delegateObject = Delegate.CreateDelegate(delegateType, (MethodInfo)method);
					else
					{
						ParameterInfo[] parameters = invoke.GetParameters();
						Type[] paramTypes = new Type[parameters.Length];
						for (var j = 0; j < paramTypes.Length; j++)
							paramTypes[j] = parameters[j].ParameterType;

						Type declType = (method != null) ? method.DeclaringType : field.DeclaringType;
						DynamicMethod dynamicMethod = new DynamicMethod("", invoke.ReturnType, paramTypes, (declType.IsInterface || declType.IsArray) ? delegateType : declType, true);
						DynamicILInfo dynamicInfo = dynamicMethod.GetDynamicILInfo();
						dynamicInfo.SetLocalSignature(new byte[] { 0x7, 0x0 });

						if (method != null)
						{
							parameters = method.GetParameters();
							int s = 0;
							if (paramTypes.Length > parameters.Length)
							{
								paramTypes[0] = method.DeclaringType;
								s = 1;
							}
							for (var j = 0; j < parameters.Length; j++)
								paramTypes[s + j] = parameters[j].ParameterType;
						}
						else
						{
							if (paramTypes.Length > 0)
								paramTypes[0] = field.DeclaringType;
						}

						var code = new byte[7 * paramTypes.Length + 6];
						int codePos = 0;
						int dynamicToken;
						for (var j = 0; j < paramTypes.Length; j++)
						{
							code[codePos++] = 0x0e; // Ldarg_s
							code[codePos++] = (byte)j;

							Type type = paramTypes[j];
							if ((type.IsClass || type.IsInterface) && !type.IsPointer && !type.IsByRef)
							{
								code[codePos++] = 0x74; // Castclass
								dynamicToken = dynamicInfo.GetTokenFor(type.TypeHandle);
								code[codePos++] = (byte)dynamicToken;
								code[codePos++] = (byte)(dynamicToken >> 8);
								code[codePos++] = (byte)(dynamicToken >> 16);
								code[codePos++] = (byte)(dynamicToken >> 24);
							}
							else
								codePos += 5;
						}

						switch (callType)
						{
							case 1:
								code[codePos++] = 0x73;  // Newobj
								break;
							case 2:
								code[codePos++] = 0x6f;  // Callvirt
								break;
							case 8:
								code[codePos++] = 0x7e;  // Ldsfld
								break;
							case 9:
								code[codePos++] = 0x7b;  // Ldfld
								break;
							default:
								code[codePos++] = 0x28;  // Call
								break;
						}
						dynamicToken = (method != null) ? dynamicInfo.GetTokenFor(method.MethodHandle) : dynamicInfo.GetTokenFor(field.FieldHandle);
						code[codePos++] = (byte)dynamicToken;
						code[codePos++] = (byte)(dynamicToken >> 8);
						code[codePos++] = (byte)(dynamicToken >> 16);
						code[codePos++] = (byte)(dynamicToken >> 24);

						code[codePos] = 0x2a; // Ret
						dynamicInfo.SetCode(code, paramTypes.Length + 1);

						delegateObject = dynamicMethod.CreateDelegate(delegateType);
					}
					iat[index++] = delegateObject;
				}
				IAT = iat;
			}

			ShowMessage((uint)MessageType.UnregisteredVersion);

			GlobalData.SetLoaderStatus(1);
		}
	}
}