-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathAppAssembler.cs
More file actions
1561 lines (1397 loc) · 69.6 KB
/
AppAssembler.cs
File metadata and controls
1561 lines (1397 loc) · 69.6 KB
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
//#define VMT_DEBUG
//#define COSMOSDEBUG
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
#if VMT_DEBUG
using System.Xml;
#endif
using Cosmos.Build.Common;
using IL2CPU.API;
using IL2CPU.API.Attribs;
using IL2CPU.Debug.Symbols;
using Cosmos.IL2CPU.Extensions;
using Cosmos.IL2CPU.ILOpCodes;
using Cosmos.IL2CPU.X86.IL;
using XSharp;
using XSharp.Assembler;
using XSharp.Assembler.x86;
using static XSharp.XSRegisters;
using Label = XSharp.Assembler.Label;
using Cosmos.IL2CPU.MethodAnalysis;
namespace Cosmos.IL2CPU
{
internal sealed class AppAssembler : IDisposable
{
public const string EndOfMethodLabelNameNormal = ".END__OF__METHOD_NORMAL";
public const string EndOfMethodLabelNameException = ".END__OF__METHOD_EXCEPTION";
private const string InitStringIDsLabel = "___INIT__STRINGS_TYPE_ID_S___";
private List<LOCAL_ARGUMENT_INFO> mLocals_Arguments_Infos = new();
private ILOp[] mILOpsLo = new ILOp[256];
private ILOp[] mILOpsHi = new ILOp[256];
public bool ShouldOptimize = false;
public DebugInfo DebugInfo { get; set; }
private TextWriter mLog;
private string mLogDir;
private string mOutputDir;
private Dictionary<string, ModuleDefinition> mLoadedModules = new Dictionary<string, ModuleDefinition>();
public TraceAssemblies TraceAssemblies;
public bool DebugEnabled = false;
public bool StackCorruptionDetection = false;
public StackCorruptionDetectionLevel StackCorruptionDetectionLevel;
public DebugMode DebugMode;
public bool IgnoreDebugStubAttribute;
public string TargetArchitecture;
private List<MethodIlOp> mSymbols = new List<MethodIlOp>();
private List<INT3Label> mINT3Labels = new List<INT3Label>();
private int incBinCounter = 0;
public readonly CosmosAssembler Assembler;
public AppAssembler(CosmosAssembler aAssembler, TextWriter aLog, string aLogDir, string aOutputDir)
{
Assembler = aAssembler;
mLog = aLog;
mLogDir = aLogDir;
mOutputDir = aOutputDir;
InitILOps();
}
public void Dispose()
{
mLog?.Dispose();
DebugInfo?.Dispose();
GC.SuppressFinalize(this);
}
private void MethodBegin(Il2cpuMethodInfo aMethod)
{
XS.Comment("---------------------------------------------------------");
XS.Comment("Assembly: " + aMethod.MethodBase.DeclaringType.Assembly.FullName);
XS.Comment("Type: " + aMethod.MethodBase.DeclaringType);
XS.Comment("Name: " + aMethod.MethodBase.Name);
XS.Comment("Plugged: " + (aMethod.PlugMethod == null ? "No" : "Yes"));
#region Document locals, arguments and return value
if (aMethod.MethodAssembler == null && !aMethod.IsInlineAssembler)
{
// the body of aMethod is getting emitted
var xLocals = aMethod.MethodBase.GetLocalVariables() ?? new List<LocalVariableInfo>();
for (int i = 0; i < xLocals.Count; i++)
{
XS.Comment(String.Format("Local {0} at EBP-{1}", i, ILOp.GetEBPOffsetForLocal(aMethod, i)));
}
var xIdxOffset = 0u;
if (!aMethod.MethodBase.IsStatic)
{
XS.Comment(String.Format("Argument[0] $this at EBP+{0}, size = {1}", X86.IL.Ldarg.GetArgumentDisplacement(aMethod, 0), ILOp.Align(ILOp.SizeOfType(aMethod.MethodBase.DeclaringType), 4)));
xIdxOffset++;
}
var xParams = aMethod.MethodBase.GetParameters();
var xParamCount = (ushort)xParams.Length;
for (ushort i = 0; i < xParamCount; i++)
{
var xOffset = X86.IL.Ldarg.GetArgumentDisplacement(aMethod, (ushort)(i + xIdxOffset));
var xSize = ILOp.SizeOfType(xParams[i].ParameterType);
// if last argument is 8 byte long, we need to add 4, so that debugger could read all 8 bytes from this variable in positiv direction
XS.Comment(String.Format("Argument[{3}] {0} at EBP+{1}, size = {2}", xParams[i].Name, xOffset, xSize, xIdxOffset + i));
}
var xMethodInfo = aMethod.MethodBase as MethodInfo;
if (xMethodInfo != null)
{
var xSize = ILOp.Align(ILOp.SizeOfType(xMethodInfo.ReturnType), 4);
XS.Comment(String.Format("Return size: {0}", xSize));
}
}
#endregion
// Issue label that is used for calls etc.
string xMethodLabel = ILOp.GetLabel(aMethod);
XS.Label(xMethodLabel);
// Alternative asm labels for the method
var xAsmLabelAttributes = aMethod.MethodBase.GetCustomAttributes<AsmLabel>();
foreach (var xAttribute in xAsmLabelAttributes)
{
XS.Label(xAttribute.Label);
}
// We could use same GUID as MethodLabelStart, but its better to keep GUIDs unique globaly for items
// so during debugging they can never be confused as to what they point to.
aMethod.DebugMethodUID = DebugInfo.CreateId;
// We issue a second label for GUID. This is increases label count, but for now we need a master label first.
// We issue a GUID label to reduce amount of work and time needed to construct debugging DB.
aMethod.DebugMethodLabelUID = DebugInfo.CreateId;
XS.Label("GUID_" + aMethod.DebugMethodLabelUID.ToString());
Label.LastFullLabel = "METHOD_" + aMethod.DebugMethodLabelUID.ToString();
if (DebugEnabled && StackCorruptionDetection)
{
// if StackCorruption detection is active, we're also going to emit a stack overflow detection
XS.Set(RAX, "Before_Kernel_Stack");
XS.Compare(RAX, RSP);
XS.Jump(ConditionalTestEnum.LessThan, ".StackOverflowCheck_End");
XS.ClearInterruptFlag();
// don't remove the call. It seems pointless, but we need it to retrieve the EIP value
XS.Call(".StackOverflowCheck_GetAddress");
XS.Label(".StackOverflowCheck_GetAddress");
XS.Exchange(BX, BX);
XS.Pop(RAX);
XS.Set(AsmMarker.Labels[AsmMarker.Type.DebugStub_CallerEIP], RAX, destinationIsIndirect: true);
XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_SendStackOverflowEvent]);
XS.Halt();
XS.Label(".StackOverflowCheck_End");
}
aMethod.EndMethodID = DebugInfo.CreateId;
if (aMethod.MethodBase.IsStatic && aMethod.MethodBase is ConstructorInfo)
{
XS.Comment("Static constructor. See if it has been called already, return if so.");
var xName = DataMember.FilterStringForIncorrectChars("CCTOR_CALLED__" + LabelName.GetFullName(aMethod.MethodBase.DeclaringType));
XS.DataMember(xName, 1, "db", "0");
XS.Compare(xName, 1, destinationIsIndirect: true, size: RegisterSize.Byte8);
XS.Jump(ConditionalTestEnum.Equal, ".BeforeQuickReturn");
XS.Set(xName, 1, destinationIsIndirect: true, size: RegisterSize.Byte8);
XS.Jump(".AfterCCTorAlreadyCalledCheck");
XS.Label(".BeforeQuickReturn");
XS.Set(RCX, 0);
XS.Return();
XS.Label(".AfterCCTorAlreadyCalledCheck");
}
XS.Push(RBP);
XS.Set(RBP, RSP);
if (aMethod.MethodAssembler == null && aMethod.PlugMethod == null && !aMethod.IsInlineAssembler)
{
// the body of aMethod is getting emitted
aMethod.LocalVariablesSize = 0;
var xLocals = aMethod.MethodBase.GetLocalVariables();
for (int i = 0; i < xLocals.Count; i++)
{
{
var xInfo = new LOCAL_ARGUMENT_INFO
{
METHODLABELNAME = xMethodLabel,
IsArgument = false,
INDEXINMETHOD = xLocals[i].LocalIndex,
NAME = "Local" + xLocals[i].LocalIndex,
OFFSET = 0 - (int)ILOp.GetEBPOffsetForLocalForDebugger(aMethod, i),
TYPENAME = xLocals[i].LocalType.FullName
};
mLocals_Arguments_Infos.Add(xInfo);
var xSize = ILOp.Align(ILOp.SizeOfType(xLocals[i].LocalType), 4);
XS.Comment(string.Format("Local {0}, Size {1}", i, xSize));
for (int j = 0; j < xSize / 4; j++) //TODO: Can this be done shorter?
{
XS.Push(0);
}
aMethod.LocalVariablesSize += xSize;
}
}
// debug info:
var xIdxOffset = 0u;
if (!aMethod.MethodBase.IsStatic)
{
mLocals_Arguments_Infos.Add(new LOCAL_ARGUMENT_INFO
{
METHODLABELNAME = xMethodLabel,
IsArgument = true,
NAME = "this:" + X86.IL.Ldarg.GetArgumentDisplacement(aMethod, 0),
INDEXINMETHOD = 0,
OFFSET = X86.IL.Ldarg.GetArgumentDisplacement(aMethod, 0),
TYPENAME = aMethod.MethodBase.DeclaringType.FullName
});
xIdxOffset++;
}
var xParams = aMethod.MethodBase.GetParameters();
var xParamCount = (ushort)xParams.Length;
for (ushort i = 0; i < xParamCount; i++)
{
var xOffset = X86.IL.Ldarg.GetArgumentDisplacement(aMethod, (ushort)(i + xIdxOffset));
// if last argument is 8 byte long, we need to add 4, so that debugger could read all 8 bytes from this variable in positiv direction
xOffset -= (int)ILOp.Align(ILOp.SizeOfType(xParams[i].ParameterType), 4) - 4;
mLocals_Arguments_Infos.Add(new LOCAL_ARGUMENT_INFO
{
METHODLABELNAME = xMethodLabel,
IsArgument = true,
INDEXINMETHOD = (int)(i + xIdxOffset),
NAME = xParams[i].Name,
OFFSET = xOffset,
TYPENAME = xParams[i].ParameterType.FullName
});
}
}
}
public DebugInfo.SequencePoint[] GenerateDebugSequencePoints(Il2cpuMethodInfo aMethod, DebugMode aDebugMode)
{
if (aDebugMode == DebugMode.Source)
{
// Would be nice to use xMethodSymbols.GetSourceStartEnd but we cant
// because its not implemented by the unmanaged code underneath.
DebugInfo.SequencePoint[] mSequences = DebugInfo.GetSequencePoints(aMethod.MethodBase, true);
if (mSequences.Length > 0)
{
DebugInfo.AddDocument(mSequences[0].Document);
var xMethod = new Method
{
ID = aMethod.DebugMethodUID,
TypeToken = aMethod.MethodBase.DeclaringType.GetMetadataToken(),
MethodToken = aMethod.MethodBase.MetadataToken,
LabelStartID = aMethod.DebugMethodLabelUID,
LabelEndID = aMethod.EndMethodID,
LabelCall = aMethod.MethodLabel
};
if (DebugInfo.AssemblyGUIDs.TryGetValue(aMethod.MethodBase.DeclaringType.Assembly, out var xAssemblyFileID))
{
xMethod.AssemblyFileID = xAssemblyFileID;
}
xMethod.DocumentID = DebugInfo.DocumentGUIDs[mSequences[0].Document.ToLower()];
xMethod.LineColStart = ((long)mSequences[0].LineStart << 32) + mSequences[0].ColStart;
xMethod.LineColEnd = ((long)mSequences[mSequences.Length - 1].LineEnd << 32) + mSequences[mSequences.Length - 1].ColEnd;
DebugInfo.AddMethod(xMethod);
}
return mSequences;
}
return new DebugInfo.SequencePoint[0];
}
private void MethodEnd(Il2cpuMethodInfo aMethod)
{
XS.Comment("End Method: " + aMethod.MethodBase.Name);
// Start end of method block
var xMethInfo = aMethod.MethodBase as MethodInfo;
var xMethodLabel = ILOp.GetLabel(aMethod);
XS.Label(xMethodLabel + EndOfMethodLabelNameNormal);
XS.Comment("Following code is for debugging. Adjust accordingly!");
XS.Set(R10, xMethodLabel + EndOfMethodLabelNameNormal, size: RegisterSize.Long64);
XS.Set(AsmMarker.Labels[AsmMarker.Type.Int_LastKnownAddress], R10, true);
XS.Set(RCX, 0);
// Determine size of return value
uint xReturnSize = 0;
if (xMethInfo != null)
{
xReturnSize = ILOp.Align(ILOp.SizeOfType(xMethInfo.ReturnType), 4);
}
var xTotalArgsSize = (from item in aMethod.MethodBase.GetParameters()
select (int)ILOp.Align(ILOp.SizeOfType(item.ParameterType), 4)).Sum();
if (!aMethod.MethodBase.IsStatic)
{
if (aMethod.MethodBase.DeclaringType.IsValueType)
{
xTotalArgsSize += 4; // only a reference is passed
}
else
{
xTotalArgsSize += (int)ILOp.Align(ILOp.SizeOfType(aMethod.MethodBase.DeclaringType), 4);
}
}
if (aMethod.PluggedMethod != null)
{
xReturnSize = 0;
xMethInfo = aMethod.PluggedMethod.MethodBase as MethodInfo;
if (xMethInfo != null)
{
xReturnSize = ILOp.Align(ILOp.SizeOfType(xMethInfo.ReturnType), 4);
}
xTotalArgsSize = (from item in aMethod.PluggedMethod.MethodBase.GetParameters()
select (int)ILOp.Align(ILOp.SizeOfType(item.ParameterType), 4)).Sum();
if (!aMethod.PluggedMethod.MethodBase.IsStatic)
{
if (aMethod.PluggedMethod.MethodBase.DeclaringType.IsValueType)
{
xTotalArgsSize += 4; // only a reference is passed
}
else
{
xTotalArgsSize += (int)ILOp.Align(ILOp.SizeOfType(aMethod.PluggedMethod.MethodBase.DeclaringType), 4);
}
}
}
if (xReturnSize > 0)
{
var xOffset = GetResultCodeOffset(xReturnSize, (uint)xTotalArgsSize);
// move return value
for (int i = 0; i < (int)(xReturnSize / 4); i++)
{
XS.Pop(RAX);
XS.Set(RBP, RAX, destinationDisplacement: (int)(xOffset + (i + 0) * 4));
}
}
// extra stack space is the space reserved for example when a "public static int TestMethod();" method is called, 4 bytes is pushed, to make room for result;
// Handle exception code here
var xLabelExc = xMethodLabel + EndOfMethodLabelNameException;
XS.Label(xLabelExc);
if (aMethod.MethodAssembler == null && aMethod.PlugMethod == null && !aMethod.IsInlineAssembler)
{
uint xLocalsSize = 0;
var xLocalInfos = aMethod.MethodBase.GetLocalVariables();
for (int j = xLocalInfos.Count - 1; j >= 0; j--)
{
xLocalsSize += ILOp.Align(ILOp.SizeOfType(xLocalInfos[j].LocalType), 4);
if (xLocalsSize >= 256)
{
XS.Add(RSP, 255);
xLocalsSize -= 255;
}
}
if (xLocalsSize > 0)
{
XS.Add(RSP, xLocalsSize);
}
}
if (DebugEnabled && StackCorruptionDetection)
{
// if debugstub is active, emit a stack corruption detection. at this point EBP and ESP should have the same value.
// if not, we should somehow break here.
XS.Set(RAX, RSP);
XS.Set(RBX, RBP);
XS.Compare(RAX, RBX);
XS.Jump(ConditionalTestEnum.Equal, xLabelExc + "__2");
XS.ClearInterruptFlag();
// don't remove the call. It seems pointless, but we need it to retrieve the EIP value
XS.Call(".MethodFooterStackCorruptionCheck_Break_on_location");
XS.Label(xLabelExc + ".MethodFooterStackCorruptionCheck_Break_on_location");
XS.Exchange(BX, BX);
XS.Pop(RCX);
XS.Push(RAX);
XS.Push(RBX);
XS.Set(AsmMarker.Labels[AsmMarker.Type.DebugStub_CallerEIP], RCX, destinationIsIndirect: true);
XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_SendSimpleNumber]);
XS.Add(RSP, 4);
XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_SendSimpleNumber]);
XS.Add(RSP, 4);
XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_SendStackCorruptedEvent]);
XS.Halt();
}
XS.Label(xLabelExc + "__2");
XS.Pop(RBP);
var xRetSize = xTotalArgsSize - (int)xReturnSize;
if (xRetSize < 0)
{
xRetSize = 0;
}
XS.Return((uint)xRetSize);
// Final, after all code. Points to op AFTER method.
XS.Label("GUID_" + aMethod.EndMethodID.ToString());
}
public void FinalizeDebugInfo()
{
DebugInfo.AddDocument(null, true);
DebugInfo.AddAssemblies(null, true);
DebugInfo.AddMethod(null, true);
DebugInfo.WriteAllLocalsArgumentsInfos(mLocals_Arguments_Infos);
DebugInfo.AddSymbols(mSymbols, true);
if (DebugInfo != null && DebugInfo.initConnection != null)
{
DebugInfo.AddINT3Labels(mINT3Labels, true);
}
}
public static uint GetResultCodeOffset(uint aResultSize, uint aTotalArgumentSize)
{
uint xOffset = 8;
if (aTotalArgumentSize > 0 && aTotalArgumentSize >= aResultSize)
{
xOffset += aTotalArgumentSize;
xOffset -= aResultSize;
}
return xOffset;
}
public void ProcessMethod(Il2cpuMethodInfo aMethod, List<ILOpCode> aOpCodes, PlugManager aPlugManager)
{
try
{
// We check this here and not scanner as when scanner makes these
// plugs may still have not yet been scanned that it will depend on.
// But by the time we make it here, they have to be resolved.
if (aMethod.Type == Il2cpuMethodInfo.TypeEnum.NeedsPlug && aMethod.PlugMethod == null)
{
throw new Exception("Method needs plug, but no plug was assigned.");
}
// todo: MtW: how to do this? we need some extra space.
// see ConstructLabel for extra info
if (aMethod.UID > 0x00FFFFFF)
{
throw new Exception("Too many methods.");
}
if (aPlugManager.DirectPlugMapping.ContainsKey(LabelName.GetFullName(aMethod.MethodBase, false)))
{
// we dont need the trampoline since we can always call the plug directly
return;
}
MethodBegin(aMethod);
mLog.WriteLine("Method '{0}', ID = '{1}'", aMethod.MethodBase.GetFullName(), aMethod.UID);
mLog.Flush();
if (aMethod.MethodAssembler != null)
{
var xAssembler = (AssemblerMethod)Activator.CreateInstance(aMethod.MethodAssembler);
xAssembler.AssembleNew(Assembler, aMethod.PluggedMethod);
}
else if (aMethod.IsInlineAssembler)
{
aMethod.MethodBase.Invoke(null, new object[aMethod.MethodBase.GetParameters().Length]);
}
else
{
AnalyseMethodOpCodes(aMethod, aOpCodes);
EmitInstructions(aMethod, aOpCodes, false);
}
MethodEnd(aMethod);
}
catch (Exception E)
{
throw new Exception("Error compiling method '" + aMethod.MethodBase.GetFullName() + "': " + E.ToString(), E);
}
}
public void AnalyseMethodOpCodes(Il2cpuMethodInfo aMethod, List<ILOpCode> aOpCodes)
{
var mSequences = GenerateDebugSequencePoints(aMethod, DebugMode);
CompilerHelpers.Debug($"AppAssembler: Method: {aMethod.MethodBase.GetFullName()}");
var method = new ILMethod(aOpCodes, mSequences);
method.Analyse();
}
private void EmitInstructions(Il2cpuMethodInfo aMethod, List<ILOpCode> aCurrentGroup, bool emitINT3)
{
foreach (var xOpCodeItem in aCurrentGroup.Select((value, i) => new { i, value }))
{
var xOpCode = xOpCodeItem.value;
var index = xOpCodeItem.i;
ushort xOpCodeVal = (ushort)xOpCode.OpCode;
ILOp xILOp;
if (xOpCodeVal <= 0xFF)
{
xILOp = mILOpsLo[xOpCodeVal];
}
else
{
xILOp = mILOpsHi[xOpCodeVal & 0xFF];
}
mLog.Flush();
int? xLocalsSize = null;
//calculate local size once
if (aMethod.MethodBase != null)
{
var xLocals = aMethod.MethodBase.GetLocalVariables();
xLocalsSize = (from item in xLocals
select (int)ILOp.Align(ILOp.SizeOfType(item.LocalType), 4)).Sum();
}
//Only emit INT3 as per conditions above...
BeforeOp(aMethod, xOpCode, emitINT3 && !(xILOp is Nop), out var INT3Emitted, true, xLocalsSize);
//Emit INT3 on the first non-NOP instruction immediately after a NOP
// - This is because TracePoints for NOP are automatically ignored in code called below this
XS.Comment(xILOp.ToString());
var xNextPosition = xOpCode.Position + 1;
#region Exception handling support code
_ExceptionRegionInfo xCurrentExceptionRegion = null;
// todo: add support for nested handlers using a stack or so..
foreach (_ExceptionRegionInfo xHandler in aMethod.MethodBase.GetExceptionRegionInfos())
{
if (xHandler.TryOffset > 0)
{
if (xHandler.TryOffset <= xNextPosition && xHandler.TryLength + xHandler.TryOffset > xNextPosition)
{
if (xCurrentExceptionRegion == null)
{
xCurrentExceptionRegion = xHandler;
continue;
}
else if (xHandler.TryOffset > xCurrentExceptionRegion.TryOffset && xHandler.TryLength + xHandler.TryOffset < xCurrentExceptionRegion.TryLength + xCurrentExceptionRegion.TryOffset)
{
// only replace if the current found handler is narrower
xCurrentExceptionRegion = xHandler;
continue;
}
}
}
if (xHandler.HandlerOffset > 0)
{
if (xHandler.HandlerOffset <= xNextPosition && xHandler.HandlerOffset + xHandler.HandlerLength > xNextPosition)
{
if (xCurrentExceptionRegion == null)
{
xCurrentExceptionRegion = xHandler;
continue;
}
else if (xHandler.HandlerOffset > xCurrentExceptionRegion.HandlerOffset && xHandler.HandlerOffset + xHandler.HandlerLength < xCurrentExceptionRegion.HandlerOffset + xCurrentExceptionRegion.HandlerLength)
{
// only replace if the current found handler is narrower
xCurrentExceptionRegion = xHandler;
continue;
}
}
}
if (xHandler.Kind.HasFlag(ExceptionRegionKind.Filter))
{
if (xHandler.FilterOffset > 0)
{
if (xHandler.FilterOffset <= xNextPosition)
{
if (xCurrentExceptionRegion == null)
{
xCurrentExceptionRegion = xHandler;
continue;
}
else if (xHandler.FilterOffset > xCurrentExceptionRegion.FilterOffset)
{
// only replace if the current found handler is narrower
xCurrentExceptionRegion = xHandler;
continue;
}
}
}
}
}
#endregion
var xNeedsExceptionPush = xCurrentExceptionRegion != null &&
((xCurrentExceptionRegion.HandlerOffset > 0 && xCurrentExceptionRegion.HandlerOffset == xOpCode.Position)
|| (xCurrentExceptionRegion.Kind.HasFlag(ExceptionRegionKind.Filter) && xCurrentExceptionRegion.FilterOffset > 0
&& xCurrentExceptionRegion.FilterOffset == xOpCode.Position))
&& xCurrentExceptionRegion.Kind == ExceptionRegionKind.Catch;
if (xNeedsExceptionPush)
{
XS.Push(LabelName.GetStaticFieldName(ExceptionHelperRefs.CurrentExceptionRef), true);
XS.Push(0);
}
xILOp.DebugEnabled = DebugEnabled;
try
{
xILOp.Execute(aMethod, xOpCode);
}
catch (Exception e)
{
throw new Exception($@"{aMethod.MethodLabel}: OpCodeIndex = {index}", e);
}
AfterOp(aMethod, xOpCode);
}
}
private void InitILOps()
{
InitILOps(typeof(ILOp));
}
private void InitILOps(Type aAssemblerBaseOp)
{
foreach (var xType in aAssemblerBaseOp.Assembly.GetExportedTypes())
{
if (xType.IsSubclassOf(aAssemblerBaseOp))
{
var xAttribs = xType.GetCustomAttributes<OpCodeAttribute>(false);
foreach (var xAttrib in xAttribs)
{
var xOpCode = (ushort)xAttrib.OpCode;
var xCtor = xType.GetConstructor(new[] { typeof(Assembler) });
var xILOp = (ILOp)xCtor.Invoke(new object[] { Assembler });
if (xOpCode <= 0xFF)
{
mILOpsLo[xOpCode] = xILOp;
}
else
{
mILOpsHi[xOpCode & 0xFF] = xILOp;
}
}
}
}
}
private static void Call(MethodBase aMethod)
{
XS.Call(LabelName.Get(aMethod));
}
private static _FieldInfo ResolveField(Il2cpuMethodInfo method, string fieldId, bool aOnlyInstance)
{
return ILOp.ResolveField(method.MethodBase.DeclaringType, fieldId, aOnlyInstance);
}
private void Ldarg(Il2cpuMethodInfo aMethod, int aIndex)
{
X86.IL.Ldarg.DoExecute(Assembler, aMethod, (ushort)aIndex);
}
private void Call(Il2cpuMethodInfo aMethod, Il2cpuMethodInfo aTargetMethod, string aNextLabel)
{
uint xSize = 0;
if (!(aTargetMethod.MethodBase.Name == "Invoke" && aTargetMethod.MethodBase.DeclaringType.Name == "DelegateImpl"))
{
xSize = X86.IL.Call.GetStackSizeToReservate(aTargetMethod.MethodBase);
}
else
{
xSize = X86.IL.Call.GetStackSizeToReservate(aMethod.MethodBase);
}
if (xSize > 0)
{
XS.Sub(RSP, xSize);
}
XS.Call(ILOp.GetLabel(aTargetMethod));
var xMethodInfo = aMethod.MethodBase as MethodInfo;
uint xReturnsize = 0;
if (xMethodInfo != null)
{
xReturnsize = ILOp.SizeOfType(((MethodInfo)aMethod.MethodBase).ReturnType);
}
ILOp.EmitExceptionLogic(Assembler, aMethod, null, true,
delegate ()
{
var xResultSize = xReturnsize;
if (xResultSize % 4 != 0)
{
xResultSize += 4 - xResultSize % 4;
}
for (int i = 0; i < xResultSize / 4; i++)
{
XS.Add(RSP, 4);
}
}, aNextLabel);
}
private void Ldflda(Il2cpuMethodInfo aMethod, _FieldInfo aFieldInfo)
{
X86.IL.Ldflda.DoExecute(Assembler, aMethod, aMethod.MethodBase.DeclaringType, aFieldInfo, false, false, aFieldInfo.DeclaringType);
}
private void Ldsflda(Il2cpuMethodInfo aMethod, _FieldInfo aFieldInfo)
{
X86.IL.Ldsflda.DoExecute(Assembler, aMethod, LabelName.GetStaticFieldName(aFieldInfo.Field), aMethod.MethodBase.DeclaringType, null);
}
public static byte[] AllocateEmptyArray(int aLength, int aElementSize, uint aArrayTypeID)
{
var xData = new byte[16 + aLength * aElementSize];
var xTemp = BitConverter.GetBytes(aArrayTypeID);
Array.Copy(xTemp, 0, xData, 0, 4);
xTemp = BitConverter.GetBytes((uint)ObjectUtils.InstanceTypeEnum.StaticEmbeddedArray);
Array.Copy(xTemp, 0, xData, 4, 4);
xTemp = BitConverter.GetBytes(aLength);
Array.Copy(xTemp, 0, xData, 8, 4);
xTemp = BitConverter.GetBytes(aElementSize);
Array.Copy(xTemp, 0, xData, 12, 4);
return xData;
}
public const string InitVMTCodeLabel = "___INIT__VMT__CODE____";
private static Type VTableType;
private static Type GCTableType;
public unsafe void GenerateVMTCode(HashSet<Type> aTypesSet, HashSet<MethodBase> aMethodsSet, PlugManager aPlugManager, Func<Type, uint> aGetTypeID, Func<MethodBase, uint> aGetMethodUID)
{
XS.Comment("---------------------------------------------------------");
XS.Label(InitVMTCodeLabel);
XS.Push(RBP);
XS.Set(RBP, RSP);
var xTypesFieldRef = VTablesImplRefs.VTablesImplDef.GetField("mTypes", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
string xTheName = LabelName.GetStaticFieldName(xTypesFieldRef);
DataMember xDataMember = (from item in XSharp.Assembler.Assembler.CurrentInstance.DataMembers
where item.Name == xTheName
select item).FirstOrDefault();
if (xDataMember != null)
{
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Remove(
(from item in XSharp.Assembler.Assembler.CurrentInstance.DataMembers
where item == xDataMember
select item).First());
}
var xGCTypesFieldRef = VTablesImplRefs.VTablesImplDef.GetField("gcTypes", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
string xGCArrayName = LabelName.GetStaticFieldName(xGCTypesFieldRef);
xDataMember = (from item in XSharp.Assembler.Assembler.CurrentInstance.DataMembers
where item.Name == xGCArrayName
select item).FirstOrDefault();
if (xDataMember != null)
{
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Remove(
(from item in XSharp.Assembler.Assembler.CurrentInstance.DataMembers
where item == xDataMember
select item).First());
}
uint xArrayTypeID = aGetTypeID(typeof(Array));
if (VTableType == null)
{
VTableType = CompilerEngine.TypeResolver.ResolveType("Cosmos.Core.VTable, Cosmos.Core", true);
GCTableType = CompilerEngine.TypeResolver.ResolveType("Cosmos.Core.GCTable, Cosmos.Core", true);
if (VTableType == null)
{
throw new Exception("Cannot resolve VTable struct in Cosmos.Core");
}
}
byte[] xData = AllocateEmptyArray(aTypesSet.Count, (int)ILOp.SizeOfType(VTableType), xArrayTypeID);
XS.DataMemberBytes(xTheName + "_Contents", xData);
XS.DataMember(xTheName, 1, "db", "0, 0, 0, 0, 0, 0, 0, 0");
XS.Set(R10, xTheName + "_Contents", sourceIsIndirect: true);
XS.Set(xTheName, R10, destinationIsIndirect: true, destinationDisplacement: 4);
xData = AllocateEmptyArray(aTypesSet.Count, (int)ILOp.SizeOfType(GCTableType), xArrayTypeID);
XS.DataMemberBytes(xGCArrayName + "_Contents", xData);
XS.DataMember(xGCArrayName, 1, "db", "0, 0, 0, 0, 0, 0, 0, 0");
XS.Set(R10, xGCArrayName + "_Contents", sourceIsIndirect: true);
XS.Set(xGCArrayName, R10, destinationIsIndirect: true, destinationDisplacement: 4);
#if VMT_DEBUG
using (var xVmtDebugOutput = XmlWriter.Create(
File.Create(Path.Combine(mLogDir, @"vmt_debug.xml")), new XmlWriterSettings() { Indent = true }))
{
xVmtDebugOutput.WriteStartDocument();
xVmtDebugOutput.WriteStartElement("VMT");
#endif
foreach (var xType in aTypesSet)
{
uint xTypeID = aGetTypeID(xType);
#if VMT_DEBUG
xVmtDebugOutput.WriteStartElement("Type");
xVmtDebugOutput.WriteAttributeString("TypeId", xTypeID.ToString());
if (xType.BaseType != null)
{
xVmtDebugOutput.WriteAttributeString("BaseTypeId", aGetTypeID(xType.BaseType).ToString());
}
xVmtDebugOutput.WriteAttributeString("Name", xType.FullName);
#endif
var xEmittedMethods = GetEmittedMethods(xType, aMethodsSet);
var xEmittedInterfaceMethods = GetEmittedInterfaceMethods(xType, aMethodsSet);
int? xBaseIndex = null;
if (xType.BaseType == null)
{
xBaseIndex = (int)xTypeID;
}
else
{
foreach (var item in aTypesSet)
{
if (item.ToString() == xType.BaseType.ToString())
{
xBaseIndex = (int)aGetTypeID(item);
break;
}
}
}
if (xBaseIndex == null)
{
throw new Exception("Base type not found!");
}
// Set type info
string xTypeName = $"{LabelName.GetFullName(xType)} ASM_IS__{xType.Assembly.GetName().Name}";
xTypeName = DataMember.FilterStringForIncorrectChars(xTypeName);
// Type ID
string xDataName = $"VMT__TYPE_ID_HOLDER__{xTypeName}";
XS.Comment(xType.FullName);
XS.Set(xDataName, (uint)xTypeID, destinationIsIndirect: true, size: RegisterSize.Long64);
XS.DataMember(xDataName, xTypeID);
XS.Push(xTypeID);
// Base Type ID
XS.Push((uint)xBaseIndex.Value);
// Size
XS.Push(ILOp.SizeOfType(xType));
// Interface Count
var xInterfaces = xType.GetInterfaces();
XS.Push((uint)xInterfaces.Length);
xData = AllocateEmptyArray(xInterfaces.Length, sizeof(uint), xArrayTypeID);
// Interface Indexes Array
xDataName = $"____SYSTEM____TYPE___{xTypeName}__InterfaceIndexesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
XS.Push(xDataName);
XS.Push(0);
// Method array
xData = AllocateEmptyArray(xEmittedMethods.Count, sizeof(uint), xArrayTypeID);
// Method Count
XS.Push((uint)xEmittedMethods.Count);
// Method Indexes Array
xDataName = $"____SYSTEM____TYPE___{xTypeName}__MethodIndexesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
XS.Push(xDataName);
XS.Push(0);
// Method Addresses Array
xDataName = $"____SYSTEM____TYPE___{xTypeName}__MethodAddressesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
XS.Push(xDataName);
XS.Push(0);
// Interface methods
xData = AllocateEmptyArray(xEmittedInterfaceMethods.Count, sizeof(uint), xArrayTypeID);
// Interface method count
XS.Push((uint)xEmittedInterfaceMethods.Count);
// Interface method indexes array
xDataName = $"____SYSTEM____TYPE___{xTypeName}__InterfaceMethodIndexesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
XS.Push(xDataName);
XS.Push(0);
// Target method indexes array
xDataName = $"____SYSTEM____TYPE___{xTypeName}__TargetMethodIndexesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
XS.Push(xDataName);
XS.Push(0);
// Full type name
xDataName = $"____SYSTEM____TYPE___{xTypeName}";
int xDataByteCount = Encoding.Unicode.GetByteCount($"{xType.FullName}, {xType.Assembly.FullName}");
xData = AllocateEmptyArray(xDataByteCount, 2, xArrayTypeID);
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, xData));
//GC Information
var fields = ILOp.GetFieldsInfo(xType, false);
var gcFieldCount = fields.Where(f => !f.FieldType.IsValueType || (!f.FieldType.IsPointer && !f.FieldType.IsEnum && !f.FieldType.IsPrimitive && !f.FieldType.IsByRef)).Count();
XS.Push((uint)gcFieldCount);
var gCFieldOffsets = AllocateEmptyArray(gcFieldCount, sizeof(uint), xArrayTypeID);
var gcFieldTypes = AllocateEmptyArray(gcFieldCount, sizeof(uint), xArrayTypeID);
uint pos = 4; // we cant overwrite the start of the array object
foreach (var field in fields)
{
if (!field.FieldType.IsValueType || (!field.FieldType.IsPointer && !field.FieldType.IsEnum && !field.FieldType.IsPrimitive && !field.FieldType.IsByRef))
{
#if VMT_DEBUG
xVmtDebugOutput.WriteStartElement("Field");
xVmtDebugOutput.WriteAttributeString("Name", field.FieldType.Name);
xVmtDebugOutput.WriteAttributeString("Id", aGetTypeID(field.FieldType).ToString());
xVmtDebugOutput.WriteAttributeString("Offset", Ldfld.GetFieldOffset(xType, field.Id).ToString());
xVmtDebugOutput.WriteEndElement();
#endif
var value = BitConverter.GetBytes(aGetTypeID(field.FieldType));
for (var i = 0; i < 4; i++)
{
gcFieldTypes[4 * pos + i] = value[i];
}
value = BitConverter.GetBytes(Ldfld.GetFieldOffset(xType, field.Id));
for (var i = 0; i < 4; i++)
{
gCFieldOffsets[4 * pos + i] = value[i];
}
pos++;
}
}
xDataName = $"____SYSTEM____TYPE___{xTypeName}__GCFieldOffsetArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, gCFieldOffsets));
XS.Push(xDataName);
XS.Push(0);
xDataName = $"____SYSTEM____TYPE___{xTypeName}__GCFieldTypesArray";
XSharp.Assembler.Assembler.CurrentInstance.DataMembers.Add(new DataMember(xDataName, gcFieldTypes));
XS.Push(xDataName);
XS.Push(0);
XS.Push((uint)(xType.IsValueType ? 1 : 0));
XS.Push((uint)(xType.IsValueType && !xType.IsByRef && !xType.IsPointer && !xType.IsPrimitive ? 1 : 0));
LdStr.PushString(Assembler, xType.Name);
LdStr.PushString(Assembler, xType.AssemblyQualifiedName);
Call(VTablesImplRefs.SetTypeInfoRef);
for (int j = 0; j < xInterfaces.Length; j++)
{
var xInterface = xInterfaces[j];
var xInterfaceTypeId = aGetTypeID(xInterface);
#if VMT_DEBUG
xVmtDebugOutput.WriteStartElement("Interface");
xVmtDebugOutput.WriteAttributeString("Id", xInterfaceTypeId.ToString());
xVmtDebugOutput.WriteAttributeString("Name", xInterface.GetFullName());
xVmtDebugOutput.WriteEndElement();
#endif
XS.Push(xTypeID);
XS.Push((uint)j);
XS.Push(xInterfaceTypeId);
Call(VTablesImplRefs.SetInterfaceInfoRef);
}
for (int j = 0; j < xEmittedMethods.Count; j++)
{
var xMethod = xEmittedMethods[j];
var xMethodUID = aGetMethodUID(xMethod);
var xAddress = ILOp.GetLabel(xMethod);
if (aPlugManager.DirectPlugMapping.TryGetValue(LabelName.GetFullName(xMethod, false), out MethodBase plug))
{
xAddress = ILOp.GetLabel(plug);
}
#if VMT_DEBUG
xVmtDebugOutput.WriteStartElement("Method");
xVmtDebugOutput.WriteAttributeString("Id", xMethodUID.ToString());
xVmtDebugOutput.WriteAttributeString("Name", xMethod.GetFullName());
xVmtDebugOutput.WriteEndElement();
#endif
if (!xType.IsInterface)
{
XS.Push(xTypeID);
XS.Push((uint)j);
XS.Push(xMethodUID);
if (xMethod.IsAbstract)
{
// abstract methods dont have bodies, oiw, are not emitted
XS.Push(0);
}
else
{
XS.Push(xAddress);
}
Call(VTablesImplRefs.SetMethodInfoRef);
}
}
for (int j = 0; j < xEmittedInterfaceMethods.Count; j++)
{
var xMethod = xEmittedInterfaceMethods.ElementAt(j);
var xInterfaceMethodUID = aGetMethodUID(xMethod.InterfaceMethod);
var xTargetMethodUID = aGetMethodUID(xMethod.TargetMethod);