-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathCompiler.cs
1528 lines (1338 loc) · 67.5 KB
/
Compiler.cs
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PROJECT: Atomix Development
* LICENSE: BSD 3-Clause (LICENSE.md)
* PURPOSE: Compiler entrypoint
* PROGRAMMERS: Aman Priyadarshi ([email protected])
*/
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using Emit = System.Reflection.Emit;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Atomixilc.IL;
using Atomixilc.Machine;
using Atomixilc.Attributes;
using Atomixilc.Machine.x86;
using Atomixilc.IL.CodeType;
namespace Atomixilc
{
internal class Compiler
{
/// <summary>
/// Compiler Configurations
/// </summary>
Options Config;
/// <summary>
/// Input Assembly Entrypoint from which Kernel should be loaded
/// </summary>
Type Entrypoint;
/// <summary>
/// ILCode to Compiler's MSIL Implementation mapping
/// </summary>
Dictionary<ILCode, MSIL> ILCodes;
/// <summary>
/// IL byte code to OpCode Type mapping
/// </summary>
Dictionary<short, Emit.OpCode> OpCode;
/// <summary>
/// MethodBase (override Implementation) to target method's label mapping
/// </summary>
Dictionary<MethodBase, string> Plugs;
/// <summary>
/// Unique ID to Methodbase (Implementaion) mapping
/// </summary>
Dictionary<string, MethodBase> Labels;
/// <summary>
/// Compiler Scanner Queue
/// </summary>
Queue<object> ScanQ;
/// <summary>
/// Compiler Processed Item set
/// </summary>
HashSet<object> FinishedQ;
/// <summary>
/// Processed String Entries set
/// </summary>
HashSet<string> StringTable;
/// <summary>
/// Exportable MethodInfo from ELF Image
/// </summary>
HashSet<MethodInfo> Globals;
/// <summary>
/// External Symbols
/// </summary>
HashSet<MethodBase> Externals;
/// <summary>
/// Inherit methods
/// </summary>
HashSet<MethodInfo> Virtuals;
/// <summary>
/// Processed Code blocks
/// </summary>
List<FunctionalBlock> CodeSegment;
/// <summary>
/// Processed Bss Entries
/// </summary>
Dictionary<string, Type> ZeroSegment;
/// <summary>
/// Processed Data Entries
/// </summary>
Dictionary<string, AsmData> DataSegment;
/// <summary>
/// Compiler Constructor
/// </summary>
/// <param name="aCompilerOptions">Configurations</param>
internal Compiler(Options aCompilerOptions)
{
Config = aCompilerOptions;
PrepareEnvironment();
}
/// <summary>
/// Initialise variables and load MSIL, OpCode, ByteCode mappings
/// </summary>
internal void PrepareEnvironment()
{
var ExecutingAssembly = Assembly.GetExecutingAssembly();
ILCodes = new Dictionary<ILCode, MSIL>();
Plugs = new Dictionary<MethodBase, string>();
Labels = new Dictionary<string, MethodBase>();
ScanQ = new Queue<object>();
FinishedQ = new HashSet<object>();
Virtuals = new HashSet<MethodInfo>();
Globals = new HashSet<MethodInfo>();
Externals = new HashSet<MethodBase>();
OpCode = new Dictionary<short, Emit.OpCode>();
ZeroSegment = new Dictionary<string, Type>();
DataSegment = new Dictionary<string, AsmData>();
CodeSegment = new List<FunctionalBlock>();
StringTable = new HashSet<string>();
/* load OpCode <-> MSIL Implementation mapping */
var types = ExecutingAssembly.GetTypes();
foreach (var type in types)
{
var ILattributes = type.GetCustomAttributes<ILImplAttribute>();
foreach (var attrib in ILattributes)
{
Verbose.Message("[MSIL] {0}", type.ToString());
ILCodes.Add(attrib.OpCode, (MSIL)Activator.CreateInstance(type));
}
}
/* load byte code to OpCode type mapping */
var ilOpcodes = typeof(Emit.OpCodes).GetFields(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
foreach (var xField in ilOpcodes)
{
var xOpCode = (Emit.OpCode)xField.GetValue(null);
Verbose.Message("[OpCode] {0} [0x{1}]", xOpCode, xOpCode.Value.ToString("X4"));
OpCode.Add(xOpCode.Value, xOpCode);
}
}
/// <summary>
/// Clean previous session of compiler and execute new compilation stage
/// </summary>
internal void Execute()
{
/* clean up mess we've created in last session :P */
ScanQ.Clear();
Globals.Clear();
Virtuals.Clear();
Externals.Clear();
FinishedQ.Clear();
ZeroSegment.Clear();
DataSegment.Clear();
CodeSegment.Clear();
StringTable.Clear();
/* so much mess around :P */
Helper.DataSegment.Clear();
Helper.ZeroSegment.Clear();
Helper.cachedFieldLabel.Clear();
Helper.cachedMethodLabel.Clear();
Helper.cachedResolvedStringLabel.Clear();
Entrypoint = null;
/* Anyways, time to scan our new Assembly */
ScanInputAssembly(out Entrypoint);
/* why on earth somebody would do this mistake
* but you never know, what is going in a programmer's brain :P
* they sometime really don't know what they are doing :P
*/
if (Entrypoint == null)
throw new Exception("No input entrypoint found");
/* Anyways, I am adding all these kind of exceptions throughout the compiler
* because I know, sometime I act very stupid
*/
var main = Entrypoint.GetMethod("main");
if (main == null)
throw new Exception("No main function found");
/* I will be speechless if somebody asked me why to Enqueue main function :P */
ScanQ.Enqueue(main);
IncludePlugAndLibrary();
/* The real work :D kidding :P */
while (ScanQ.Count != 0)
{
var ScanObject = ScanQ.Dequeue();
if (FinishedQ.Contains(ScanObject))
continue;
/* while writing this code, I though there could be a lot of ways
* to write this branch, but hey what is the most beautiful way?
* now look below, Isn't it look beautiful? full of symmetry
* Thanks me later :P
*/
/* Some serious stuff :p
* Though ScanQ Enqueue Objects but compiler assume it only of these three types
*/
var method = ScanObject as MethodBase;
if (method != null)
{
Verbose.Message("Scanning Method : {0}", method.FullName());
ScanMethod(method);
continue;
}
var type = ScanObject as Type;
if (type != null)
{
Verbose.Message("Scanning Type : {0}", type.FullName);
ScanType(type);
continue;
}
var field = ScanObject as FieldInfo;
if (field != null)
{
Verbose.Message("Scanning Field : {0}", field.FullName());
ProcessFieldInfo(field);
continue;
}
throw new Exception(string.Format("Invalid Object in Queue of type '{0}'", ScanObject.GetType()));
}
}
/// <summary>
/// Flush Compiler output
/// </summary>
internal void Flush()
{
FlushVTables();
FlushStringTable();
/* Hack? Issue: #55 */
if (Verbose.ErrorCounter > 0)
Verbose.Error("Errors: {0}", Verbose.ErrorCounter);
switch (Config.TargetPlatform)
{
case Architecture.x86:
Flushx86();
break;
default:
throw new Exception("Unsupported Flush Platform");
}
}
/// <summary>
/// Flush method targeting x86 arch only
/// </summary>
private void Flushx86()
{
using (var SW = new StreamWriter(Config.OutputFile))
{
var attrib = Entrypoint.GetCustomAttribute<EntrypointAttribute>();
if (attrib == null)
throw new Exception("Internal compiler error");
/* Assembly header */
SW.WriteLine("global entrypoint");
SW.WriteLine(string.Format("entrypoint equ {0}", attrib.Entrypoint));
/* Global Symbols */
foreach (var global in Globals)
SW.WriteLine(string.Format("global {0}", global.FullName()));
SW.WriteLine();
/* External Symbols */
foreach (var method in Externals)
SW.WriteLine(string.Format("extern {0}", method.FullName()));
SW.WriteLine();
/* BSS Section */
SW.WriteLine("section .bss");
foreach (var bssEntry in Helper.ZeroSegment)
SW.WriteLine(string.Format("{0} resb {1}", bssEntry.Key, bssEntry.Value));
/* BSS - Global Variable Section */
var bssEntries = ZeroSegment.ToList();
bssEntries.Sort((x, y) => y.Value.IsClass.CompareTo(x.Value.IsClass));
int index = 0, count = bssEntries.Count;
/* GC Root Start */
SW.WriteLine(Helper.GC_Root_Start + ":");
for (; index < count; index++)
{
var entry = bssEntries[index];
int size = Helper.GetTypeSize(entry.Value, Config.TargetPlatform);
if (!entry.Value.IsClass)
break;
SW.WriteLine(string.Format("{0} resb {1}", entry.Key, size));
}
SW.WriteLine(Helper.GC_Root_End + ":");
/* GC Root End */
for (; index < count; index++)
{
var entry = bssEntries[index];
int size = Helper.GetTypeSize(entry.Value, Config.TargetPlatform, true);// align it
SW.WriteLine(string.Format("{0} resb {1}", entry.Key, size));
}
/* End of Global Variables Section */
SW.WriteLine();
/* Data Section */
SW.WriteLine("section .data");
foreach (var dataEntry in Helper.DataSegment)
SW.WriteLine(dataEntry);
foreach (var dataEntry in DataSegment)
SW.WriteLine(dataEntry.Value);
SW.WriteLine();
/* Code Section */
SW.WriteLine("section .text");
foreach (var block in CodeSegment)
{
var xbody = block.Body;
foreach (var code in xbody)
{
/* Some styping and indentation thing, because I love beautiful code :P */
if (!(code is Label))
SW.Write(" ");
else
SW.WriteLine();
/* Is this a call by label name?
* yes, replace label with original label name
*/
if (code is Call)
{
var xCall = (Call)code;
if (xCall.IsLabel)
{
xCall.IsLabel = false;
xCall.DestinationRef = Labels[xCall.DestinationRef].FullName();
}
}
SW.WriteLine(code);
}
/* some more styling */
SW.WriteLine();
}
SW.WriteLine(Helper.Compiler_End + ":");
SW.Flush();
SW.Close();
}
}
/// <summary>
/// Flush string table, create data entries for all discovered strings
/// </summary>
private void FlushStringTable()
{
var encoding = Encoding.Unicode;
foreach(var str in StringTable)
{
int count = encoding.GetByteCount(str);
var data = new byte[count + 0x10];
/* String Entry
* |string_type_id| : typeof(string).GetHashCode()
* |"0x1"| : object identifier ID "0x1" : object, "0x2" : array
* |entry_size| : total memory length in bytes
* |string_length| : string length in characters
* |char_0| : data entry
* |char_1|
* ...
*/
Array.Copy(BitConverter.GetBytes(typeof(string).GetHashCode()), 0, data, 0, 4);
Array.Copy(BitConverter.GetBytes(0x1), 0, data, 4, 4);
Array.Copy(BitConverter.GetBytes(data.Length), 0, data, 8, 4);
Array.Copy(BitConverter.GetBytes(str.Length), 0, data, 12, 4);
Array.Copy(encoding.GetBytes(str), 0, data, 16, count);
var label = Helper.GetResolvedStringLabel(str);
DataSegment.Add(label, new AsmData(label, data));
}
}
/// <summary>
/// FlushVTable to create a lookup table in datasegment
/// </summary>
private void FlushVTables()
{
/* VTables are implemented based on the idea of lookup tables
* Structure:
* |next_block_offset| : points to next block offset
* |method_uid| : MethodBase UID
* |method_address||type_id| : MethodInfo Address and DeclaringType ID
* |method_address||type_id|
* |method_address||type_id|
* |"0"| : End of this block
* |next_block_offset|
* |method_uid|
* |method_address||type_id|
* |method_address||type_id|
* |method_address||type_id|
* |"0"|
* |"0"| : End of VTable
*/
var count = new Dictionary<int, int>();
var tables = new List<KeyValuePair<int, MethodInfo> >();
foreach(var method in Virtuals)
{
var baseDef = method.GetBaseDefinition();
if (!baseDef.IsAbstract)
continue;
int UID = baseDef.GetHashCode();
if (count.ContainsKey(UID))
count[UID]++;
else
count.Add(UID, 1);
tables.Add(new KeyValuePair<int, MethodInfo>(UID, method));
}
tables.Sort((x, y) => x.Key.CompareTo(y.Key));
var methodgroup = count.ToList();
methodgroup.Sort((x, y) => x.Key.CompareTo(y.Key));
int index = 0;
List<string> data = new List<string>();
foreach(var methodgroupitem in methodgroup)
{
var offset = (methodgroupitem.Value * 2) + 3;
data.Add(offset.ToString()); // methods count
data.Add(methodgroupitem.Key.ToString()); // method UID
for (; index < tables.Count; index++)
{
var item = tables[index];
if (item.Key != methodgroupitem.Key)
break;
data.Add(item.Value.FullName()); // method address
data.Add(item.Value.DeclaringType.GetHashCode().ToString()); // type ID
}
data.Add("0");
}
data.Add("0");
DataSegment.Add(Helper.VTable_Flush, new AsmData(Helper.VTable_Flush, data.ToArray()));
}
/// <summary>
/// Include Compiler Provided Libraries
/// </summary>
internal void IncludePlugAndLibrary()
{
/* Hey, I know what you are thinking
* this code doesn't look good, right?
* But you don't know how it feels to debug the whole compiler continously for 3 days
* that much of debugging completely drain your skills :P
* don't mess up this code, and move forward
*/
ScanQ.Enqueue(typeof(Lib.Libc));
ScanQ.Enqueue(typeof(Lib.VTable));
ScanQ.Enqueue(typeof(Lib.Memory));
ScanQ.Enqueue(typeof(Lib.Native));
ScanQ.Enqueue(typeof(Lib.Plugs.ArrayImpl));
ScanQ.Enqueue(typeof(Lib.Plugs.StringImpl));
ScanQ.Enqueue(typeof(Lib.Plugs.ExceptionImpl));
ScanQ.Enqueue(typeof(Lib.Plugs.BitConverterImpl));
foreach (var plug in Plugs)
ScanQ.Enqueue(plug.Key);
foreach (var label in Labels)
ScanQ.Enqueue(label.Value);
}
/// <summary>
/// Scan Input assembly for entrypoint, plugs/labels
/// </summary>
/// <param name="Entrypoint"></param>
internal void ScanInputAssembly(out Type Entrypoint)
{
var InputAssembly = Assembly.LoadFile(Config.InputFiles[0]);
var types = InputAssembly.GetTypes();
Entrypoint = null;
Plugs.Clear();
Labels.Clear();
foreach (var type in types)
{
var entrypointattrib = type.GetCustomAttribute<EntrypointAttribute>();
if (entrypointattrib != null && entrypointattrib.Platform == Config.TargetPlatform)
{
if (Entrypoint != null)
throw new Exception("Multiple Entrypoint with same target platform");
Entrypoint = type;
}
var methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
foreach (var method in methods)
{
/* look for plugs */
var plugattrib = method.GetCustomAttribute<PlugAttribute>();
if (plugattrib != null && plugattrib.Platform == Config.TargetPlatform)
{
if (Plugs.ContainsValue(plugattrib.TargetLabel))
throw new Exception(string.Format("Multiple plugs with same target label '{0}'", plugattrib.TargetLabel));
Verbose.Message("[Plug] {0} : {1}", plugattrib.TargetLabel, method.FullName());
method.AddPlug(plugattrib.TargetLabel);
Plugs.Add(method, plugattrib.TargetLabel);
}
/* look for labels */
var labelattrib = method.GetCustomAttribute<LabelAttribute>();
if (labelattrib != null)
{
if (Labels.ContainsKey(labelattrib.RefLabel))
throw new Exception(string.Format("Multiple labels with same Ref label '{0}'", labelattrib.RefLabel));
Verbose.Message("[Label] {0} : {1}", labelattrib.RefLabel, method.FullName());
Labels.Add(labelattrib.RefLabel, method);
}
}
}
}
/// <summary>
/// Scan type for constructors, plugs, labels and virtuals
/// </summary>
/// <param name="type"></param>
internal void ScanType(Type type)
{
if (type.BaseType != null)
ScanQ.Enqueue(type.BaseType);
/* Scan for constructors */
var constructors = type.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var ctor in constructors)
{
if (ctor.DeclaringType != type)
continue;
ScanQ.Enqueue(ctor);
}
/* Scan for plugs/labels */
var methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
foreach (var method in methods)
{
/* You might ask, why I am scanning plugs/labels again (ScanInputAssembly already doing this)
* well the reason is, ScanInputAssembly is called for scanning input assembly only
* but we are inserting compiler implementations too in build process
* they might also have plugs/labels
*/
/* scan plugs */
var plugattrib = method.GetCustomAttribute<PlugAttribute>();
if (plugattrib != null && !Plugs.ContainsKey(method))
{
ScanQ.Enqueue(method);
method.AddPlug(plugattrib.TargetLabel);
Plugs.Add(method, plugattrib.TargetLabel);
Verbose.Message("[Plug] {0} : {1}", plugattrib.TargetLabel, method.FullName());
}
/* scan labels */
var labelattrib = method.GetCustomAttribute<LabelAttribute>();
if (labelattrib != null && !Labels.ContainsKey(labelattrib.RefLabel))
{
ScanQ.Enqueue(method);
Labels.Add(labelattrib.RefLabel, method);
Verbose.Message("[Label] {0} : {1}", labelattrib.RefLabel, method.FullName());
}
}
/* Scan for virtual methods */
methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var method in methods)
{
var basedefination = method.GetBaseDefinition();
if (Virtuals.Contains(method) ||
!basedefination.IsAbstract ||
method.DeclaringType.IsAbstract ||
basedefination.DeclaringType == method.DeclaringType)
continue;
Virtuals.Add(method);
ScanQ.Enqueue(method);
}
FinishedQ.Add(type);
}
/// <summary>
/// Scan Method and process if recognized format
/// </summary>
/// <param name="method">Method function</param>
internal void ScanMethod(MethodBase method)
{
FunctionalBlock block = null;
/* Hey? Is this label exportable? */
if (!Helper.RestrictedAssembly.Contains(method.DeclaringType.Assembly.GetName().Name)
&& method.IsPublic
&& method.DeclaringType.IsVisible
&& (method as MethodInfo) != null)
Globals.Add((MethodInfo)method);
/* Wow! Is it somekind of special method? :P */
/* Assembly method */
if (method.GetCustomAttribute<AssemblyAttribute>() != null)
ProcessAssemblyMethod(method, ref block);
/* Dll Import? Dynamic external function */
else if (method.GetCustomAttribute<DllImportAttribute>() != null)
ProcessExternMethod(method, ref block);
/* Is this a delegate? wow! */
else if (typeof(Delegate).IsAssignableFrom(method.DeclaringType))
ProcessDelegate(method, ref block);
/* lol, sorry It was just a normal method :P */
else
ProcessMethod(method, ref block);
/* no function body? great! You're dead for me now */
if (block != null)
CodeSegment.Add(block);
/* I am not going to treat you again :P */
FinishedQ.Add(method);
}
/// <summary>
/// Process Assembly attributed function
/// </summary>
/// <param name="method">method function</param>
/// <param name="block">code block</param>
internal void ProcessAssemblyMethod(MethodBase method, ref FunctionalBlock block)
{
var attrib = method.GetCustomAttribute<AssemblyAttribute>();
/* bwahahha, though this method is being called by ScanMethod only so, this attrib should not be null!
* but I really don't myself when I am coding sleepless
*/
if (attrib == null)
throw new Exception("Invalid call to ProcessAssemblyMethod");
if (attrib.CalliHeader == false && method.GetCustomAttribute<NoExceptionAttribute>() == null)
Verbose.Error("NoException Attribute not present '{0}' CalliHeader == false", method.FullName());
/* I am sure captain that we have discovered something, can we have our new functional block? */
block = new FunctionalBlock(method.FullName(), Config.TargetPlatform, CallingConvention.StdCall);
/* Instructions capturing ON! */
Instruction.Block = block;
/* Function entry label */
new Label(method.FullName());
/* Some assembly method don't really need a calliHeader -- Optimization thing */
if (attrib.CalliHeader)
EmitHeader(block, method, 0);
/* This is the simplest method processing, all you have to do is, execute that function
* Instruction will be created and captured by Instruction.Block hence our fucntions block
*/
try
{
method.Invoke(null, new object[method.GetParameters().Length]);
}
catch (Exception e)
{
throw new Exception(string.Format("Exception occured while invoking assembly function '{0}' => {1}", method.FullName(), e.ToString()));
}
/* No header so no footer :P */
if (attrib.CalliHeader)
EmitFooter(block, method);
/* this isn't necessary, but again I can't take bet on my sleepless coding :P */
Instruction.Block = null;
}
/// <summary>
/// Process dynamic loadable methods
/// </summary>
/// <param name="method"></param>
/// <param name="block"></param>
internal void ProcessExternMethod(MethodBase method, ref FunctionalBlock block)
{
var attrib = method.GetCustomAttribute<DllImportAttribute>();
if (attrib == null)
throw new Exception("Invalid call to ProcessExternMethod");
Externals.Add(method);
Verbose.Message("Extern Method Found '{0}'", method.FullName());
}
/// <summary>
/// Process and Add fieldInfo data/entry
/// </summary>
/// <param name="fieldInfo"></param>
internal void ProcessFieldInfo(FieldInfo fieldInfo)
{
var name = fieldInfo.FullName();
/* simply add this to BSS segment with given size */
InsertData(name, fieldInfo.FieldType);
FinishedQ.Add(fieldInfo);
}
/// <summary>
/// Helper function to add data to BSS segment
/// </summary>
/// <param name="name"></param>
/// <param name="size"></param>
internal void InsertData(string name, Type fieldtype)
{
/* Again I can't take bet on my stupidity */
if (ZeroSegment.ContainsKey(name))
{
if (ZeroSegment[name] != fieldtype)
/* please log, if I did some stupidity */
Verbose.Error("Two different type for same field label '{0}' : '{1}' '{2}'", name, ZeroSegment[name], fieldtype.Name);
return;
}
ZeroSegment.Add(name, fieldtype);
}
/// <summary>
/// Process Delegates
/// </summary>
/// <param name="method"></param>
/// <param name="block"></param>
internal void ProcessDelegate(MethodBase method, ref FunctionalBlock block)
{
/* This is difficult to explain :p believe me, I wasted a lot of time in designing and optimizing this stuff :P
* But I am going to explain it :P hahaha ready? scroll down!
*/
/* two important methods are implemented, "constructor" and "invoke" */
if (method.Name == ".ctor")
{
/* constructor */
block = new FunctionalBlock(method.FullName(), Config.TargetPlatform, CallingConvention.StdCall);
Instruction.Block = block;
/* method signature: void.ctor(System.Object, IntPtr)
* because this is non-static method, original signature would be : void.ctor(memory, System.Object, IntPtr)
* memory points to just allocated memory for this delegate, so we can use it to store info
* 0xC byte size metadata -- added by compiler
* [memory + 0xC] := IntPtr
* [memory + 0x10] := System.Object
*/
new Label(method.FullName());
EmitHeader(block, method, 0);
new Mov { DestinationReg = Register.EAX, SourceReg = Register.EBP, SourceDisplacement = 0x10, SourceIndirect = true };
new Mov { DestinationReg = Register.EDX, SourceReg = Register.EBP, SourceDisplacement = 0x8, SourceIndirect = true };
// [Memory + 0xC] := Intptr
new Mov { DestinationReg = Register.EAX, DestinationDisplacement = 0xC, DestinationIndirect = true, SourceReg = Register.EDX };
new Mov { DestinationReg = Register.EDX, SourceReg = Register.EBP, SourceDisplacement = 0xC, SourceIndirect = true };
// [Memory + 0x10] := Object
new Mov { DestinationReg = Register.EAX, DestinationDisplacement = 0x10, DestinationIndirect = true, SourceReg = Register.EDX };
EmitFooter(block, method);
Instruction.Block = null;
}
else if (method.Name == "Invoke")
{
block = new FunctionalBlock(method.FullName(), Config.TargetPlatform, CallingConvention.StdCall);
Instruction.Block = block;
/* Ah! I really can't explain this :P It was so difficult to write
* method signature : void Invoke(memory, params ...)
* check if System.Object [memory + 0x10] is null or not
* if null, simply call Intptr [memory + 0xC] after pushing params on to the stack
* if not null, first push System.Object [memory + 0x10] then push push params and then call Intptr [memory + 0xC]
*/
// Return-Type Invoke(params)
new Label(method.FullName());
int ESPOffset = 4;
var xparams = method.GetParameters();
foreach (var par in xparams)
ESPOffset += Helper.GetTypeSize(par.ParameterType, Config.TargetPlatform, true);
new Mov { DestinationReg = Register.EAX, SourceReg = Register.ESP, SourceDisplacement = ESPOffset, SourceIndirect = true };
new Add { DestinationReg = Register.EAX, SourceRef = "0xC" };
new Cmp { DestinationReg = Register.EAX, DestinationDisplacement = 0x4, DestinationIndirect = true, SourceRef = "0x0" };
new Jmp { Condition = ConditionalJump.JNE, DestinationRef = ".push_object_ref" };
new Pop { DestinationReg = Register.EDX };
new Mov { DestinationReg = Register.ESP, DestinationDisplacement = ESPOffset - 4, DestinationIndirect = true, SourceReg = Register.EDX };
new Call { DestinationRef = "[EAX]" };
new Ret { Offset = 0 };
new Label(".push_object_ref");
new Push { DestinationReg = Register.EAX, DestinationDisplacement = 0x4, DestinationIndirect = true };
for (int i = ESPOffset; i > 4; i -= 4)
new Push { DestinationReg = Register.ESP, DestinationDisplacement = ESPOffset, DestinationIndirect = true };
new Call { DestinationRef = "[EAX]" };
new Ret { Offset = (byte)ESPOffset };
Instruction.Block = null;
}
else
{
/* wohooo! Aman didn't implement you. just go to hell! :P */
Verbose.Error("Unimplemented delegate function '{0}'", method.Name);
}
}
/// <summary>
/// Process normal method body
/// </summary>
/// <param name="method"></param>
/// <param name="block"></param>
internal void ProcessMethod(MethodBase method, ref FunctionalBlock block)
{
var Body = method.GetMethodBody();
if (Body == null)
{
/* wow! you don't have a body? Great! */
Verbose.Warning("Body == null");
return;
}
var MethodName = method.FullName();
/* You are not allowed sir! if you have been implemented by a plug */
if (Plugs.ContainsValue(MethodName) && !Plugs.ContainsKey(method))
return;
/* Some dark magic is happening below; I a not going to explain everything :p */
var parameters = method.GetParameters();
foreach(var param in parameters)
{
ScanQ.Enqueue(param.ParameterType);
}
var localvars = Body.LocalVariables;
int bodySize = 0;
foreach(var localvar in localvars)
{
bodySize += Helper.GetTypeSize(localvar.LocalType, Config.TargetPlatform, true);
ScanQ.Enqueue(localvar.LocalType);
}
block = new FunctionalBlock(MethodName, Config.TargetPlatform, CallingConvention.StdCall);
Instruction.Block = block;
new Label(method.FullName());
if (method.IsStatic && method is ConstructorInfo)
{
/* Is static? Is constructor? hey you can't be called more than once */
EmitConstructor(block, method);
}
EmitHeader(block, method, bodySize);
var ReferencedPositions = new HashSet<int>();
var xOpCodes = EmitOpCodes(method, ReferencedPositions).ToDictionary(IL => IL.Position);
var ILQueue = new Queue<int>();
ILQueue.Enqueue(0);
var ILBlocks = new Dictionary<int, FunctionalBlock>();
var Optimizer = new Optimizer(Config, ILQueue);
while(ILQueue.Count != 0)
{
int index = ILQueue.Dequeue();
/* Create room for new IL and add it to Blocks List */
var xOp = xOpCodes[index];
if (xOp == null) continue;
xOpCodes[index] = null;
var tempBlock = new FunctionalBlock(null, Config.TargetPlatform, CallingConvention.StdCall);
Instruction.Block = tempBlock;
ILBlocks.Add(xOp.Position, tempBlock);
/* scan inline OpCodes, maybe we get some treasure */
if (xOp is OpMethod)
/* Wow! I found a method, Lucky me :P */
ScanQ.Enqueue(((OpMethod)xOp).Value);
else if (xOp is OpType)
/* Wow! I found a Type, Great! xD */
ScanQ.Enqueue(((OpType)xOp).Value);
else if (xOp is OpField)
{
/* Wow! I found a field, Cool */
var xOpField = ((OpField)xOp).Value;
ScanQ.Enqueue(xOpField.DeclaringType);
if (xOpField.IsStatic)
ScanQ.Enqueue(xOpField);
}
else if (xOp is OpToken)
{
/* Ah! I found a toek, Thanks :) */
var xOpToken = (OpToken)xOp;
if (xOpToken.IsType)
ScanQ.Enqueue(xOpToken.ValueType);
else if (xOpToken.IsField)
{
ScanQ.Enqueue(xOpToken.ValueField.DeclaringType);
if (xOpToken.ValueField.IsStatic)
ScanQ.Enqueue(xOpToken.ValueField);
}
}
else if (xOp is OpString)
{
/* Please! no more treasure :P */
var xOpStr = (OpString)xOp;
StringTable.Add(xOpStr.Value);
}
/* Thank god, It's over xD */
/* Add label to branch/refernced locations */
if (ReferencedPositions.Contains(xOp.Position))
new Label(Helper.GetLabel(xOp.Position));
/* Load state of dynamic state */
Optimizer.LoadStack(xOp.Position);
if (xOp.NeedHandler)
{
/* sir You asked me load execption object onto the stack? sure sir! */
EmitExceptionHandler(block, method);
Optimizer.vStack.Push(new StackItem(typeof(Exception)));
}
/* darkest magic of all time */
MSIL ILHandler = null;
ILCodes.TryGetValue(xOp.ILCode, out ILHandler);
if (ILHandler == null)
{
/* please I can't implement more IL code */
new Comment(string.Format("Unimplemented ILCode '{0}'", xOp.ILCode));
Verbose.Error("Unimplemented ILCode '{0}'", xOp.ILCode);
}
else
{
new Comment(string.Format("[{0}] : {1} => {2}", xOp.ILCode.ToString(), xOp.ToString(), Optimizer.vStack.Count));
/* yayaya! I found one that is already implement. I am lucky, right? I should buy a lottery ticket :P */
ILHandler.Execute(Config, xOp, method, Optimizer);
}
}
/* Add minor blocks to main block */
var ILKeys = ILBlocks.Keys.ToList();
ILKeys.Sort();
foreach (var pos in ILKeys)
block.Body.AddRange(ILBlocks[pos].Body);
/* revert to original main block */
Instruction.Block = block;
EmitFooter(block, method);