forked from https-github-com-Surachai-kent/runtime
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathassem.cpp
More file actions
1532 lines (1334 loc) · 50.7 KB
/
assem.cpp
File metadata and controls
1532 lines (1334 loc) · 50.7 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: assem.cpp
//
//
// COM+ IL assembler
//
#include "ilasmpch.h"
#define INITGUID
#define DECLARE_DATA
#include "assembler.h"
void indexKeywords(Indx* indx); // defined in asmparse.y
unsigned int g_uCodePage = CP_ACP;
unsigned int g_uConsoleCP = CP_ACP;
char g_szSourceFileName[MAX_FILENAME_LENGTH*3];
WCHAR wzUniBuf[dwUniBuf]; // Unicode conversion global buffer
Assembler::Assembler()
{
m_pDisp = NULL;
m_pEmitter = NULL;
m_pImporter = NULL;
char* pszFQN = new char[16];
strcpy_s(pszFQN,16,"<Module>");
m_pModuleClass = new Class(pszFQN);
m_lstClass.PUSH(m_pModuleClass);
m_hshClass.PUSH(m_pModuleClass);
m_pModuleClass->m_cl = mdTokenNil;
m_pModuleClass->m_bIsMaster = FALSE;
m_fStdMapping = FALSE;
m_fDisplayTraceOutput= FALSE;
m_fTolerateDupMethods = FALSE;
m_pCurOutputPos = NULL;
m_CurPC = 0; // PC offset in method
m_pCurMethod = NULL;
m_pCurClass = NULL;
m_pCurEvent = NULL;
m_pCurProp = NULL;
m_wzMetadataVersion = NULL;
m_wMSVmajor = 0xFFFF;
m_wMSVminor = 0xFFFF;
m_wSSVersionMajor = 4;
m_wSSVersionMinor = 0;
m_fAppContainer = FALSE;
m_fHighEntropyVA = FALSE;
m_pCeeFileGen = NULL;
m_pCeeFile = 0;
m_pManifest = NULL;
m_pCustomDescrList = NULL;
m_pGlobalDataSection = NULL;
m_pILSection = NULL;
m_pTLSSection = NULL;
m_fDidCoInitialise = FALSE;
m_fDLL = FALSE;
m_fEntryPointPresent = FALSE;
m_fHaveFieldsWithRvas = FALSE;
m_fFoldCode = FALSE;
m_dwMethodsFolded = 0;
m_szScopeName[0] = 0;
m_crExtends = mdTypeDefNil;
m_nImplList = 0;
m_TyParList = NULL;
m_SEHD = NULL;
m_firstArgName = NULL;
m_lastArgName = NULL;
m_szNamespace = new char[2];
m_szNamespace[0] = 0;
m_NSstack.PUSH(m_szNamespace);
m_szFullNS = new char[MAX_NAMESPACE_LENGTH];
memset(m_szFullNS,0,MAX_NAMESPACE_LENGTH);
m_ulFullNSLen = MAX_NAMESPACE_LENGTH;
m_State = STATE_OK;
m_fInitialisedMetaData = FALSE;
m_fAutoInheritFromObject = TRUE;
m_ulLastDebugLine = 0xFFFFFFFF;
m_ulLastDebugColumn = 0xFFFFFFFF;
m_ulLastDebugLineEnd = 0xFFFFFFFF;
m_ulLastDebugColumnEnd = 0xFFFFFFFF;
m_dwIncludeDebugInfo = 0;
m_fGeneratePDB = FALSE;
m_fIsMscorlib = FALSE;
m_fOptimize = FALSE;
m_tkSysObject = 0;
m_tkSysString = 0;
m_tkSysValue = 0;
m_tkSysEnum = 0;
m_pVTable = NULL;
m_pMarshal = NULL;
m_pPInvoke = NULL;
m_fReportProgress = TRUE;
m_tkCurrentCVOwner = 1; // module
m_pOutputBuffer = NULL;
m_dwSubsystem = (DWORD)-1;
m_dwComImageFlags = COMIMAGE_FLAGS_ILONLY;
m_dwFileAlignment = 0;
m_stBaseAddress = 0;
m_stSizeOfStackReserve = 0;
m_dwCeeFileFlags = ICEE_CREATE_FILE_PURE_IL;
g_szSourceFileName[0] = 0;
m_guidLang = CorSym_LanguageType_ILAssembly;
m_guidLangVendor = CorSym_LanguageVendor_Microsoft;
m_guidDoc = CorSym_DocumentType_Text;
for(int i=0; i<INSTR_POOL_SIZE; i++) m_Instr[i].opcode = -1;
m_wzResourceFile = NULL;
m_wzKeySourceName = NULL;
OnErrGo = false;
bClock = NULL;
m_pbsMD = NULL;
m_pOutputBuffer = new BYTE[OUTPUT_BUFFER_SIZE];
m_pCurOutputPos = m_pOutputBuffer;
m_pEndOutputPos = m_pOutputBuffer + OUTPUT_BUFFER_SIZE;
m_crImplList = new mdTypeRef[MAX_INTERFACES_IMPLEMENTED];
m_nImplListSize = MAX_INTERFACES_IMPLEMENTED;
m_pManifest = new AsmMan((void*)this);
dummyClass = new Class(NULL);
indexKeywords(&indxKeywords);
m_pPortablePdbWriter = NULL;
}
Assembler::~Assembler()
{
if(m_pbsMD) delete m_pbsMD;
if(m_pMarshal) delete m_pMarshal;
if(m_pManifest) delete m_pManifest;
if(m_pPInvoke) delete m_pPInvoke;
if(m_pVTable) delete m_pVTable;
m_lstGlobalLabel.RESET(true);
m_lstGlobalFixup.RESET(true);
m_hshClass.RESET(false);
m_lstClass.RESET(true);
while((m_ClassStack.POP()));
while(m_CustomDescrListStack.POP());
m_pCurClass = NULL;
dummyClass->m_szFQN = NULL;
delete dummyClass;
if (m_pOutputBuffer) delete [] m_pOutputBuffer;
if (m_crImplList) delete [] m_crImplList;
if (m_TyParList) delete m_TyParList;
if (m_pCeeFileGen != NULL) {
if (m_pCeeFile)
m_pCeeFileGen->DestroyCeeFile(&m_pCeeFile);
DestroyICeeFileGen(&m_pCeeFileGen);
m_pCeeFileGen = NULL;
}
while((m_szNamespace = m_NSstack.POP())) ;
delete [] m_szFullNS;
m_MethodBodyList.RESET(true);
m_TypeDefDList.RESET(true);
if (m_pImporter != NULL)
{
m_pImporter->Release();
m_pImporter = NULL;
}
if (m_pEmitter != NULL)
{
m_pEmitter->Release();
m_pEmitter = NULL;
}
if (m_pPortablePdbWriter != NULL)
{
delete m_pPortablePdbWriter;
m_pPortablePdbWriter = NULL;
}
if (m_pDisp != NULL)
{
m_pDisp->Release();
m_pDisp = NULL;
}
}
BOOL Assembler::Init(BOOL generatePdb)
{
if (m_pCeeFileGen != NULL) {
if (m_pCeeFile)
m_pCeeFileGen->DestroyCeeFile(&m_pCeeFile);
DestroyICeeFileGen(&m_pCeeFileGen);
m_pCeeFileGen = NULL;
}
if (FAILED(CreateICeeFileGen(&m_pCeeFileGen))) return FALSE;
if (FAILED(m_pCeeFileGen->CreateCeeFileEx(&m_pCeeFile,(ULONG)m_dwCeeFileFlags))) return FALSE;
if (FAILED(m_pCeeFileGen->GetSectionCreate(m_pCeeFile, ".il", sdReadOnly, &m_pILSection))) return FALSE;
if (FAILED(m_pCeeFileGen->GetSectionCreate (m_pCeeFile, ".sdata", sdReadWrite, &m_pGlobalDataSection))) return FALSE;
if (FAILED(m_pCeeFileGen->GetSectionCreate (m_pCeeFile, ".tls", sdReadWrite, &m_pTLSSection))) return FALSE;
m_fGeneratePDB = generatePdb;
return TRUE;
}
void Assembler::SetDLL(BOOL IsDll)
{
HRESULT OK;
OK = m_pCeeFileGen->SetDllSwitch(m_pCeeFile, IsDll);
_ASSERTE(SUCCEEDED(OK));
m_fDLL = IsDll;
}
void Assembler::ResetArgNameList()
{
if(m_firstArgName) delArgNameList(m_firstArgName);
m_firstArgName = NULL;
m_lastArgName = NULL;
}
void Assembler::ResetForNextMethod()
{
ResetArgNameList();
m_CurPC = 0;
m_pCurOutputPos = m_pOutputBuffer;
m_State = STATE_OK;
m_pCurMethod = NULL;
}
void Assembler::ResetLineNumbers()
{
// reset line number information
m_ulLastDebugLine = 0xFFFFFFFF;
m_ulLastDebugColumn = 0xFFFFFFFF;
m_ulLastDebugLineEnd = 0xFFFFFFFF;
m_ulLastDebugColumnEnd = 0xFFFFFFFF;
}
BOOL Assembler::AddMethod(Method *pMethod)
{
BOOL fIsInterface=FALSE, fIsImport=FALSE;
ULONG PEFileOffset=0;
_ASSERTE(m_pCeeFileGen != NULL);
if (pMethod == NULL)
{
report->error("pMethod == NULL");
return FALSE;
}
if(pMethod->m_pClass != NULL)
{
fIsInterface = IsTdInterface(pMethod->m_pClass->m_Attr);
fIsImport = IsTdImport(pMethod->m_pClass->m_Attr);
}
if(m_CurPC)
{
char sz[1024];
sz[0] = 0;
if(fIsImport) strcat_s(sz,1024," imported");
if(IsMdAbstract(pMethod->m_Attr)) strcat_s(sz,1024," abstract");
if(IsMdPinvokeImpl(pMethod->m_Attr)) strcat_s(sz,1024," pinvoke");
if(!IsMiIL(pMethod->m_wImplAttr)) strcat_s(sz,1024," non-IL");
if(IsMiRuntime(pMethod->m_wImplAttr)) strcat_s(sz,1024," runtime-supplied");
if(IsMiInternalCall(pMethod->m_wImplAttr)) strcat_s(sz,1024," an internal call");
if(strlen(sz))
{
report->error("Method cannot have body if it is%s\n",sz);
}
}
else // method has no body
{
if(fIsImport || IsMdAbstract(pMethod->m_Attr) || IsMdPinvokeImpl(pMethod->m_Attr)
|| IsMiRuntime(pMethod->m_wImplAttr) || IsMiInternalCall(pMethod->m_wImplAttr)) return TRUE;
if(OnErrGo)
{
report->error("Method has no body\n");
return TRUE;
}
else
{
report->warn("Method has no body, 'ret' emitted\n");
Instr* pIns = GetInstr();
if(pIns)
{
memset(pIns,0,sizeof(Instr));
pIns->opcode = CEE_RET;
EmitOpcode(pIns);
}
}
}
if(pMethod->m_Locals.COUNT()) pMethod->m_LocalsSig=0x11000001; // placeholder, the real token 2b defined in EmitMethod
COR_ILMETHOD_FAT fatHeader;
fatHeader.SetFlags(pMethod->m_Flags);
fatHeader.SetMaxStack(pMethod->m_MaxStack);
fatHeader.SetLocalVarSigTok(pMethod->m_LocalsSig);
fatHeader.SetCodeSize(m_CurPC);
bool moreSections = (pMethod->m_dwNumExceptions != 0);
// if max stack is specified <8, force fat header, otherwise (with tiny header) it will default to 8
if((fatHeader.GetMaxStack() < 8)&&(fatHeader.GetLocalVarSigTok()==0)&&(fatHeader.GetCodeSize()<64)&&(!moreSections))
fatHeader.SetFlags(fatHeader.GetFlags() | CorILMethod_InitLocals); //forces fat header but does nothing else, since LocalVarSigTok==0
unsigned codeSize = m_CurPC;
unsigned codeSizeAligned = codeSize;
if (moreSections)
codeSizeAligned = (codeSizeAligned + 3) & ~3; // to insure EH section aligned
unsigned headerSize = COR_ILMETHOD::Size(&fatHeader, moreSections);
unsigned ehSize = COR_ILMETHOD_SECT_EH::Size(pMethod->m_dwNumExceptions, pMethod->m_ExceptionList);
unsigned totalSize = headerSize + codeSizeAligned + ehSize;
BYTE* outBuff;
BYTE* endbuf;
BinStr* pbsBody;
if((pbsBody = new BinStr())==NULL) return FALSE;
if((outBuff = pbsBody->getBuff(totalSize))==NULL) return FALSE;
endbuf = &outBuff[totalSize];
// Emit the header
outBuff += COR_ILMETHOD::Emit(headerSize, &fatHeader, moreSections, outBuff);
pMethod->m_pCode = outBuff;
pMethod->m_headerOffset= PEFileOffset;
pMethod->m_methodOffset= PEFileOffset + headerSize;
pMethod->m_CodeSize = codeSize;
// Emit the code
if (codeSizeAligned)
{
memset(outBuff,0,codeSizeAligned);
memcpy(outBuff, m_pOutputBuffer, codeSize);
outBuff += codeSizeAligned;
}
if(pMethod->m_dwNumExceptions)
{
// Validate the eh
COR_ILMETHOD_SECT_EH_CLAUSE_FAT* pEx;
DWORD TryEnd,HandlerEnd, dwEx, dwEf;
for(dwEx = 0, pEx = pMethod->m_ExceptionList; dwEx < pMethod->m_dwNumExceptions; dwEx++, pEx++)
{
if(pEx->GetTryOffset() > m_CurPC) // i.e., pMethod->m_CodeSize
{
report->error("Invalid SEH clause #%d: Try block starts beyond code size\n",dwEx+1);
}
TryEnd = pEx->GetTryOffset()+pEx->GetTryLength();
if(TryEnd > m_CurPC)
{
report->error("Invalid SEH clause #%d: Try block ends beyond code size\n",dwEx+1);
}
if(pEx->GetHandlerOffset() > m_CurPC)
{
report->error("Invalid SEH clause #%d: Handler block starts beyond code size\n",dwEx+1);
}
HandlerEnd = pEx->GetHandlerOffset()+pEx->GetHandlerLength();
if(HandlerEnd > m_CurPC)
{
report->error("Invalid SEH clause #%d: Handler block ends beyond code size\n",dwEx+1);
}
if(pEx->Flags & COR_ILEXCEPTION_CLAUSE_FILTER)
{
if(!((pEx->GetFilterOffset() >= TryEnd)||(pEx->GetTryOffset() >= HandlerEnd)))
{
report->error("Invalid SEH clause #%d: Try and Filter/Handler blocks overlap\n",dwEx+1);
}
for(dwEf = 0; dwEf < pMethod->m_dwNumEndfilters; dwEf++)
{
if(pMethod->m_EndfilterOffsetList[dwEf] == pEx->GetHandlerOffset()) break;
}
if(dwEf >= pMethod->m_dwNumEndfilters)
{
report->error("Invalid SEH clause #%d: Filter block separated from Handler, or not ending with endfilter\n",dwEx+1);
}
}
else
if(!((pEx->GetHandlerOffset() >= TryEnd)||(pEx->GetTryOffset() >= HandlerEnd)))
{
report->error("Invalid SEH clause #%d: Try and Handler blocks overlap\n",dwEx+1);
}
}
// Emit the eh
outBuff += COR_ILMETHOD_SECT_EH::Emit(ehSize, pMethod->m_dwNumExceptions,
pMethod->m_ExceptionList, false, outBuff);
}
_ASSERTE(outBuff == endbuf);
pMethod->m_pbsBody = pbsBody;
LocalMemberRefFixup* pMRF;
while((pMRF = pMethod->m_LocalMemberRefFixupList.POP()))
{
pMRF->offset += (size_t)(pMethod->m_pCode);
m_LocalMemberRefFixupList.PUSH(pMRF); // transfer MRF to assembler's list
}
if(m_fReportProgress)
{
if (pMethod->IsGlobalMethod())
report->msg("Assembled global method %s\n", pMethod->m_szName);
else report->msg("Assembled method %s::%s\n", pMethod->m_pClass->m_szFQN,
pMethod->m_szName);
}
return TRUE;
}
BOOL Assembler::EmitMethodBody(Method* pMethod, BinStr* pbsOut)
{
HRESULT hr = S_OK;
if(pMethod)
{
BinStr* pbsBody = pMethod->m_pbsBody;
unsigned totalSize;
if(pbsBody && (totalSize = pbsBody->length()))
{
unsigned headerSize = pMethod->m_methodOffset-pMethod->m_headerOffset;
MethodBody* pMB = NULL;
// ----------emit locals signature-------------------
unsigned uLocals;
if((uLocals = pMethod->m_Locals.COUNT()))
{
VarDescr* pVD;
BinStr* pbsSig = new BinStr();
unsigned cnt;
DWORD cSig;
const COR_SIGNATURE* mySig;
pbsSig->appendInt8(IMAGE_CEE_CS_CALLCONV_LOCAL_SIG);
cnt = CorSigCompressData(uLocals,pbsSig->getBuff(5));
pbsSig->remove(5-cnt);
for(cnt = 0; (pVD = pMethod->m_Locals.PEEK(cnt)); cnt++)
{
if(pVD->pbsSig) pbsSig->append(pVD->pbsSig);
else
{
report->error("Undefined type of local var slot %d in method %s\n",cnt,pMethod->m_szName);
pbsSig->appendInt8(ELEMENT_TYPE_I4);
}
}
cSig = pbsSig->length();
mySig = (const COR_SIGNATURE *)(pbsSig->ptr());
if (cSig > 1) // non-empty signature
{
hr = m_pEmitter->GetTokenFromSig(mySig, cSig, &pMethod->m_LocalsSig);
_ASSERTE(SUCCEEDED(hr));
}
delete pbsSig;
COR_ILMETHOD_FAT* pFH; // Fat header guaranteed, because there are local vars
pFH = (COR_ILMETHOD_FAT*)(pMethod->m_pbsBody->ptr());
pFH->SetLocalVarSigTok(pMethod->m_LocalsSig);
}
if(m_fFoldCode)
{
for(int k=0; (pMB = m_MethodBodyList.PEEK(k)) != NULL; k++)
{
if((pMB->pbsBody->length() == totalSize)
&& (memcmp(pMB->pbsBody->ptr(), pbsBody->ptr(),totalSize)==0))
break;
}
if(pMB)
{
pMethod->m_headerOffset= pMB->RVA;
pMethod->m_methodOffset= pMB->RVA + headerSize;
pMethod->m_pCode = pMB->pCode;
delete pbsBody;
pMethod->m_pbsBody = NULL;
m_dwMethodsFolded++;
}
}
if(pMB == NULL)
{
BYTE* outBuff;
unsigned align = (headerSize == 1)? 1 : 4;
ULONG PEFileOffset, methodRVA;
if (FAILED(m_pCeeFileGen->GetSectionBlock (m_pILSection, totalSize,
align, (void **) &outBuff))) return FALSE;
memcpy(outBuff,pbsBody->ptr(),totalSize);
// The offset where we start, (not where the alignment bytes start!
if (FAILED(m_pCeeFileGen->GetSectionDataLen (m_pILSection, &PEFileOffset)))
return FALSE;
PEFileOffset -= totalSize;
pMethod->m_pCode = outBuff + headerSize;
pMethod->m_headerOffset= PEFileOffset;
pMethod->m_methodOffset= PEFileOffset + headerSize;
DoDeferredILFixups(pMethod);
m_pCeeFileGen->GetMethodRVA(m_pCeeFile, PEFileOffset,&methodRVA);
pMethod->m_headerOffset= methodRVA;
pMethod->m_methodOffset= methodRVA + headerSize;
if(m_fFoldCode)
{
if((pMB = new MethodBody)==NULL) return FALSE;
pMB->pbsBody = pbsBody;
pMB->RVA = methodRVA;
pMB->pCode = pMethod->m_pCode;
m_MethodBodyList.PUSH(pMB);
}
//else
// delete pbsBody;
//pMethod->m_pbsBody = NULL;
}
m_pEmitter->SetRVA(pMethod->m_Tok,pMethod->m_headerOffset);
}
if (m_fGeneratePDB)
{
if (FAILED(m_pPortablePdbWriter->DefineSequencePoints(pMethod)))
return FALSE;
if (FAILED(m_pPortablePdbWriter->DefineLocalScope(pMethod)))
return FALSE;
}
return TRUE;
}
else return FALSE;
}
ImportDescriptor* Assembler::EmitImport(BinStr* DllName)
{
int i = 0, l = 0;
ImportDescriptor* pID;
char* sz=NULL;
if(DllName) l = DllName->length(); // No zero terminator here!
if(l)
{
sz = (char*)DllName->ptr();
while((pID=m_ImportList.PEEK(i++)))
{
if((pID->dwDllName== (DWORD) l)&& !memcmp(pID->szDllName,sz,l)) return pID;
}
}
else
{
while((pID=m_ImportList.PEEK(i++)))
{
if(pID->dwDllName==0) return pID;
}
}
if((pID = new ImportDescriptor(sz,l)))
{
m_ImportList.PUSH(pID);
pID->mrDll = TokenFromRid(m_ImportList.COUNT(),mdtModuleRef);
return pID;
}
else report->error("Failed to allocate import descriptor\n");
return NULL;
}
void Assembler::EmitImports()
{
WCHAR* wzDllName=&wzUniBuf[0];
ImportDescriptor* pID;
int i;
mdToken tk;
for(i=0; (pID = m_ImportList.PEEK(i)); i++)
{
WszMultiByteToWideChar(g_uCodePage,0,pID->szDllName,-1,wzDllName,dwUniBuf-1);
if(FAILED(m_pEmitter->DefineModuleRef( // S_OK or error.
wzDllName, // [IN] DLL name
&tk))) // [OUT] returned
report->error("Failed to define module ref '%s'\n",pID->szDllName);
else
_ASSERTE(tk == pID->mrDll);
}
}
HRESULT Assembler::EmitPinvokeMap(mdToken tk, PInvokeDescriptor* pDescr)
{
WCHAR* wzAlias=&wzUniBuf[0];
if(pDescr->szAlias) WszMultiByteToWideChar(g_uCodePage,0,pDescr->szAlias,-1,wzAlias,dwUniBuf-1);
return m_pEmitter->DefinePinvokeMap( // Return code.
tk, // [IN] FieldDef, MethodDef or MethodImpl.
pDescr->dwAttrs, // [IN] Flags used for mapping.
(LPCWSTR)wzAlias, // [IN] Import name.
pDescr->mrDll); // [IN] ModuleRef token for the target DLL.
}
BOOL Assembler::EmitMethod(Method *pMethod)
{
// Emit the metadata for a method definition
BOOL fSuccess = FALSE;
WCHAR* wzMemberName=&wzUniBuf[0];
BOOL fIsInterface;
DWORD cSig;
ULONG methodRVA = 0;
mdMethodDef MethodToken;
mdTypeDef ClassToken = mdTypeDefNil;
char *pszMethodName;
COR_SIGNATURE *mySig;
_ASSERTE((m_pCeeFileGen != NULL) && (pMethod != NULL));
fIsInterface = ((pMethod->m_pClass != NULL) && IsTdInterface(pMethod->m_pClass->m_Attr));
pszMethodName = pMethod->m_szName;
mySig = pMethod->m_pMethodSig;
cSig = pMethod->m_dwMethodCSig;
// If this is an instance method, make certain the signature says so
if (!(pMethod->m_Attr & mdStatic))
*mySig |= IMAGE_CEE_CS_CALLCONV_HASTHIS;
ClassToken = (pMethod->IsGlobalMethod())? mdTokenNil
: pMethod->m_pClass->m_cl;
// Convert name to UNICODE
WszMultiByteToWideChar(g_uCodePage,0,pszMethodName,-1,wzMemberName,dwUniBuf-1);
if(IsMdPrivateScope(pMethod->m_Attr))
{
WCHAR* p = wcsstr(wzMemberName,W("$PST06"));
if(p) *p = 0;
}
if (FAILED(m_pEmitter->DefineMethod(ClassToken, // parent class
wzMemberName, // member name
pMethod->m_Attr & ~mdReservedMask, // member attributes
mySig, // member signature
cSig,
methodRVA, // RVA
pMethod->m_wImplAttr, // implflags
&MethodToken)))
{
report->error("Failed to define method '%s'\n",pszMethodName);
goto exit;
}
pMethod->m_Tok = MethodToken;
//--------------------------------------------------------------------------------
// the only way to set mdRequireSecObject:
if(pMethod->m_Attr & mdRequireSecObject)
{
mdToken tkPseudoClass;
if(FAILED(m_pEmitter->DefineTypeRefByName(1, COR_REQUIRES_SECOBJ_ATTRIBUTE, &tkPseudoClass)))
report->error("Unable to define type reference '%s'\n", COR_REQUIRES_SECOBJ_ATTRIBUTE_ANSI);
else
{
mdToken tkPseudoCtor;
BYTE bSig[3] = {IMAGE_CEE_CS_CALLCONV_HASTHIS,0,ELEMENT_TYPE_VOID};
if(FAILED(m_pEmitter->DefineMemberRef(tkPseudoClass, W(".ctor"), (PCCOR_SIGNATURE)bSig, 3, &tkPseudoCtor)))
report->error("Unable to define member reference '%s::.ctor'\n", COR_REQUIRES_SECOBJ_ATTRIBUTE_ANSI);
else DefineCV(new CustomDescr(MethodToken,tkPseudoCtor,NULL));
}
}
if (pMethod->m_NumTyPars)
{
ULONG i;
mdToken tkNil = mdTokenNil;
mdGenericParam tkGP = mdTokenNil;
for(i = 0; i < pMethod->m_NumTyPars; i++)
{
if (FAILED(m_pEmitter->DefineGenericParam(MethodToken, i, pMethod->m_TyPars[i].Attrs(), pMethod->m_TyPars[i].Name(), 0, &tkNil, &tkGP)))
{
report->error("Unable to define generic param: %s'\n", pMethod->m_TyPars[i].Name());
}
else
{
pMethod->m_TyPars[i].Token(tkGP);
EmitCustomAttributes(tkGP, pMethod->m_TyPars[i].CAList());
}
}
EmitGenericParamConstraints(pMethod->m_NumTyPars, pMethod->m_TyPars, pMethod->m_Tok, &(pMethod->m_GPCList));
}
//--------------------------------------------------------------------------------
EmitSecurityInfo(MethodToken,
pMethod->m_pPermissions,
pMethod->m_pPermissionSets);
//--------------------------------------------------------------------------------
if (pMethod->m_fEntryPoint)
{
if (FAILED(m_pCeeFileGen->SetEntryPoint(m_pCeeFile, MethodToken)))
{
report->error("Failed to set entry point for method '%s'\n",pszMethodName);
goto exit;
}
}
//--------------------------------------------------------------------------------
if(IsMdPinvokeImpl(pMethod->m_Attr))
{
if(pMethod->m_pPInvoke)
{
HRESULT hr;
if(pMethod->m_pPInvoke->szAlias == NULL) pMethod->m_pPInvoke->szAlias = pszMethodName;
hr = EmitPinvokeMap(MethodToken,pMethod->m_pPInvoke);
if(pMethod->m_pPInvoke->szAlias == pszMethodName) pMethod->m_pPInvoke->szAlias = NULL;
if(FAILED(hr))
{
report->error("Failed to set PInvoke map for method '%s'\n",pszMethodName);
goto exit;
}
}
}
{ // add parameters to metadata
void const *pValue=NULL;
ULONG cbValue;
DWORD dwCPlusTypeFlag=0;
mdParamDef pdef;
WCHAR* wzParName=&wzUniBuf[0];
char* szPhonyName=(char*)&wzUniBuf[dwUniBuf >> 1];
if(pMethod->m_dwRetAttr || pMethod->m_pRetMarshal || pMethod->m_RetCustDList.COUNT())
{
if(pMethod->m_pRetValue)
{
dwCPlusTypeFlag= (DWORD)*(pMethod->m_pRetValue->ptr());
pValue = (void const *)(pMethod->m_pRetValue->ptr()+1);
cbValue = pMethod->m_pRetValue->length()-1;
if(dwCPlusTypeFlag == ELEMENT_TYPE_STRING)
{
cbValue /= sizeof(WCHAR);
#if BIGENDIAN
void* pValueTemp = _alloca(cbValue * sizeof(WCHAR));
memcpy(pValueTemp, pValue, cbValue * sizeof(WCHAR));
pValue = pValueTemp;
SwapStringLength((WCHAR*)pValue, cbValue);
#endif
}
}
else
{
pValue = NULL;
cbValue = (ULONG)-1;
dwCPlusTypeFlag=0;
}
m_pEmitter->DefineParam(MethodToken,0,NULL,pMethod->m_dwRetAttr,dwCPlusTypeFlag,pValue,cbValue,&pdef);
if(pMethod->m_pRetMarshal)
{
if(FAILED(m_pEmitter->SetFieldMarshal (
pdef, // [IN] given a fieldDef or paramDef token
(PCCOR_SIGNATURE)(pMethod->m_pRetMarshal->ptr()), // [IN] native type specification
pMethod->m_pRetMarshal->length()))) // [IN] count of bytes of pvNativeType
report->error("Failed to set param marshaling for return\n");
}
EmitCustomAttributes(pdef, &(pMethod->m_RetCustDList));
}
for(ARG_NAME_LIST *pAN=pMethod->m_firstArgName; pAN; pAN = pAN->pNext)
{
if(pAN->nNum >= 65535)
{
report->error("Method '%s': Param.sequence number (%d) exceeds 65535, unable to define parameter\n",pszMethodName,pAN->nNum+1);
continue;
}
if(pAN->dwName) strcpy_s(szPhonyName,dwUniBuf >> 1,pAN->szName);
else sprintf_s(szPhonyName,(dwUniBuf >> 1),"A_%d",pAN->nNum);
WszMultiByteToWideChar(g_uCodePage,0,szPhonyName,-1,wzParName,dwUniBuf >> 1);
if(pAN->pValue)
{
dwCPlusTypeFlag= (DWORD)*(pAN->pValue->ptr());
pValue = (void const *)(pAN->pValue->ptr()+1);
cbValue = pAN->pValue->length()-1;
if(dwCPlusTypeFlag == ELEMENT_TYPE_STRING)
{
cbValue /= sizeof(WCHAR);
#if BIGENDIAN
void* pValueTemp = _alloca(cbValue * sizeof(WCHAR));
memcpy(pValueTemp, pValue, cbValue * sizeof(WCHAR));
pValue = pValueTemp;
SwapStringLength((WCHAR*)pValue, cbValue);
#endif
}
}
else
{
pValue = NULL;
cbValue = (ULONG)-1;
dwCPlusTypeFlag=0;
}
m_pEmitter->DefineParam(MethodToken,pAN->nNum+1,wzParName,pAN->dwAttr,dwCPlusTypeFlag,pValue,cbValue,&pdef);
if(pAN->pMarshal)
{
if(FAILED(m_pEmitter->SetFieldMarshal (
pdef, // [IN] given a fieldDef or paramDef token
(PCCOR_SIGNATURE)(pAN->pMarshal->ptr()), // [IN] native type specification
pAN->pMarshal->length()))) // [IN] count of bytes of pvNativeType
report->error("Failed to set param marshaling for '%s'\n",pAN->szName);
}
EmitCustomAttributes(pdef, &(pAN->CustDList));
}
}
fSuccess = TRUE;
//--------------------------------------------------------------------------------
// Update method implementations for this method
{
MethodImplDescriptor* pMID;
int i;
for(i=0;(pMID = pMethod->m_MethodImplDList.PEEK(i));i++)
{
pMID->m_tkImplementingMethod = MethodToken;
// don't delete it here, it's still in the general list
}
}
//--------------------------------------------------------------------------------
EmitCustomAttributes(MethodToken, &(pMethod->m_CustomDescrList));
exit:
if (fSuccess == FALSE) m_State = STATE_FAIL;
return fSuccess;
}
BOOL Assembler::EmitMethodImpls()
{
MethodImplDescriptor* pMID;
BOOL ret = TRUE;
int i;
for(i=0; (pMID = m_MethodImplDList.PEEK(i)); i++)
{
pMID->m_tkImplementingMethod = ResolveLocalMemberRef(pMID->m_tkImplementingMethod);
pMID->m_tkImplementedMethod = ResolveLocalMemberRef(pMID->m_tkImplementedMethod);
if(FAILED(m_pEmitter->DefineMethodImpl( pMID->m_tkDefiningClass,
pMID->m_tkImplementingMethod,
pMID->m_tkImplementedMethod)))
{
report->error("Failed to define Method Implementation");
ret = FALSE;
}
pMID->m_fNew = FALSE;
}// end while
return ret;
}
mdToken Assembler::ResolveLocalMemberRef(mdToken tok)
{
if(TypeFromToken(tok) == 0x99000000)
{
tok = RidFromToken(tok);
if(tok) tok = m_LocalMethodRefDList.PEEK(tok-1)->m_tkResolved;
}
else if(TypeFromToken(tok) == 0x98000000)
{
tok = RidFromToken(tok);
if(tok) tok = m_LocalFieldRefDList.PEEK(tok-1)->m_tkResolved;
}
return tok;
}
BOOL Assembler::EmitEvent(EventDescriptor* pED)
{
mdMethodDef mdAddOn=mdMethodDefNil,
mdRemoveOn=mdMethodDefNil,
mdFire=mdMethodDefNil,
*mdOthers;
int nOthers;
WCHAR* wzMemberName=&wzUniBuf[0];
if(!pED) return FALSE;
WszMultiByteToWideChar(g_uCodePage,0,pED->m_szName,-1,wzMemberName,dwUniBuf-1);
mdAddOn = ResolveLocalMemberRef(pED->m_tkAddOn);
if(TypeFromToken(mdAddOn) != mdtMethodDef)
{
report->error("Invalid Add method of event '%s'\n",pED->m_szName);
return FALSE;
}
mdRemoveOn = ResolveLocalMemberRef(pED->m_tkRemoveOn);
if(TypeFromToken(mdRemoveOn) != mdtMethodDef)
{
report->error("Invalid Remove method of event '%s'\n",pED->m_szName);
return FALSE;
}
mdFire = ResolveLocalMemberRef(pED->m_tkFire);
if((RidFromToken(mdFire)!=0)&&(TypeFromToken(mdFire) != mdtMethodDef))
{
report->error("Invalid Fire method of event '%s'\n",pED->m_szName);
return FALSE;
}
nOthers = pED->m_tklOthers.COUNT();
mdOthers = new mdMethodDef[nOthers+1];
if(mdOthers == NULL)
{
report->error("Failed to allocate Others array for event descriptor\n");
nOthers = 0;
}
for(int j=0; j < nOthers; j++)
{
mdOthers[j] = ResolveLocalMemberRef((mdToken)(UINT_PTR)(pED->m_tklOthers.PEEK(j))); // @WARNING: casting down from 'mdToken*' to 'mdToken'
}
mdOthers[nOthers] = mdMethodDefNil; // like null-terminator
if(FAILED(m_pEmitter->DefineEvent( pED->m_tdClass,
wzMemberName,
pED->m_dwAttr,
pED->m_tkEventType,
mdAddOn,
mdRemoveOn,
mdFire,
mdOthers,
&(pED->m_edEventTok))))
{
report->error("Failed to define event '%s'.\n",pED->m_szName);
delete [] mdOthers;
return FALSE;
}
EmitCustomAttributes(pED->m_edEventTok, &(pED->m_CustomDescrList));
return TRUE;
}
BOOL Assembler::EmitProp(PropDescriptor* pPD)
{
mdMethodDef mdSet, mdGet, *mdOthers;
int nOthers;
WCHAR* wzMemberName=&wzUniBuf[0];
if(!pPD) return FALSE;
WszMultiByteToWideChar(g_uCodePage,0,pPD->m_szName,-1,wzMemberName,dwUniBuf-1);
mdSet = ResolveLocalMemberRef(pPD->m_tkSet);
if((RidFromToken(mdSet)!=0)&&(TypeFromToken(mdSet) != mdtMethodDef))
{
report->error("Invalid Set method of property '%s'\n",pPD->m_szName);
return FALSE;
}
mdGet = ResolveLocalMemberRef(pPD->m_tkGet);
if((RidFromToken(mdGet)!=0)&&(TypeFromToken(mdGet) != mdtMethodDef))
{
report->error("Invalid Get method of property '%s'\n",pPD->m_szName);
return FALSE;
}
nOthers = pPD->m_tklOthers.COUNT();
mdOthers = new mdMethodDef[nOthers+1];
if(mdOthers == NULL)
{
report->error("Failed to allocate Others array for prop descriptor\n");
nOthers = 0;
}
for(int j=0; j < nOthers; j++)
{
mdOthers[j] = ResolveLocalMemberRef((mdToken)(UINT_PTR)(pPD->m_tklOthers.PEEK(j))); // @WARNING: casting down from 'mdToken*' to 'mdToken'
if((RidFromToken(mdOthers[j])!=0)&&(TypeFromToken(mdOthers[j]) != mdtMethodDef))
{
report->error("Invalid Other method of property '%s'\n",pPD->m_szName);
delete [] mdOthers;