-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathassembler.cpp
2753 lines (2561 loc) · 93.2 KB
/
assembler.cpp
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: assembler.cpp
//
//
#include "ilasmpch.h"
#include "assembler.h"
#include "binstr.h"
#include "nvpair.h"
#define FAIL_UNLESS(x, y) if (!(x)) { report->error y; return; }
/**************************************************************************/
void Assembler::StartNameSpace(_In_ __nullterminated char* name)
{
m_NSstack.PUSH(m_szNamespace);
m_szNamespace = name;
unsigned L = (unsigned)strlen(m_szFullNS);
unsigned l = (unsigned)strlen(name);
if(L+l+1 >= m_ulFullNSLen)
{
char* pch = new char[((L+l)/MAX_NAMESPACE_LENGTH + 1)*MAX_NAMESPACE_LENGTH];
if(pch)
{
memcpy(pch,m_szFullNS,L+1);
delete [] m_szFullNS;
m_szFullNS = pch;
m_ulFullNSLen = ((L+l)/MAX_NAMESPACE_LENGTH + 1)*MAX_NAMESPACE_LENGTH;
}
else report->error("Failed to reallocate the NameSpace buffer\n");
}
if(L) m_szFullNS[L] = NAMESPACE_SEPARATOR_CHAR;
else L = 0xFFFFFFFF;
memcpy(&m_szFullNS[L+1],m_szNamespace, l+1);
}
/**************************************************************************/
void Assembler::EndNameSpace()
{
char *p = &m_szFullNS[strlen(m_szFullNS)-strlen(m_szNamespace)];
if(p > m_szFullNS) p--;
*p = 0;
delete [] m_szNamespace;
if((m_szNamespace = m_NSstack.POP())==NULL)
{
m_szNamespace = new char[2];
m_szNamespace[0] = 0;
}
}
/**************************************************************************/
void Assembler::ClearImplList(void)
{
while(m_nImplList) m_crImplList[--m_nImplList] = mdTypeRefNil;
}
/**************************************************************************/
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:22008) // "Suppress PREfast warnings about integer overflow"
#endif
void Assembler::AddToImplList(mdToken tk)
{
if(m_nImplList+1 >= m_nImplListSize)
{
mdToken *ptr = new mdToken[m_nImplListSize + MAX_INTERFACES_IMPLEMENTED];
if(ptr == NULL)
{
report->error("Failed to reallocate Impl List from %d to %d bytes\n",
m_nImplListSize*sizeof(mdToken),
(m_nImplListSize+MAX_INTERFACES_IMPLEMENTED)*sizeof(mdToken));
return;
}
memcpy(ptr,m_crImplList,m_nImplList*sizeof(mdToken));
delete m_crImplList;
m_crImplList = ptr;
m_nImplListSize += MAX_INTERFACES_IMPLEMENTED;
}
m_crImplList[m_nImplList++] = tk;
m_crImplList[m_nImplList] = mdTypeRefNil;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
void Assembler::ClearBoundList(void)
{
m_TyParList = NULL;
}
/**************************************************************************/
mdToken Assembler::ResolveClassRef(mdToken tkResScope, _In_ __nullterminated const char *pszFullClassName, Class** ppClass)
{
Class *pClass = NULL;
mdToken tkRet = mdTokenNil;
mdToken *ptkSpecial = NULL;
if(pszFullClassName == NULL) return mdTokenNil;
switch(strlen(pszFullClassName))
{
case 11:
if(strcmp(pszFullClassName,"System.Enum")==0) ptkSpecial = &m_tkSysEnum;
break;
case 13:
if(strcmp(pszFullClassName,"System.Object")==0) ptkSpecial = &m_tkSysObject;
else if(strcmp(pszFullClassName,"System.String")==0) ptkSpecial = &m_tkSysString;
break;
case 16:
if(strcmp(pszFullClassName,"System.ValueType")==0) ptkSpecial = &m_tkSysValue;
break;
}
if(ptkSpecial) // special token
{
if(*ptkSpecial) // already resolved
{
tkRet = *ptkSpecial;
if(ppClass)
{
if(TypeFromToken(tkRet)==mdtTypeDef)
*ppClass = m_lstClass.PEEK(RidFromToken(tkRet)-1);
else *ppClass = NULL;
}
return tkRet;
}
else // needs to be resolved
if(!m_fIsMscorlib) tkResScope = GetBaseAsmRef();
}
if(tkResScope == 1)
{
if((pClass = FindCreateClass(pszFullClassName)) != NULL) tkRet = pClass->m_cl;
}
else
{
tkRet = MakeTypeRef(tkResScope, pszFullClassName);
pClass = NULL;
}
if(ppClass) *ppClass = pClass;
if(ptkSpecial) *ptkSpecial = tkRet;
return tkRet;
}
class TypeSpecContainer
{
private:
// Contain a BinStr
uint8_t *ptr_;
unsigned len_;
// Hash the BinStr, just for speed of lookup
unsigned hash_;
// The value we're looking for
mdToken token_;
public:
// Constructor for a 'lookup' object
TypeSpecContainer(BinStr *typeSpec) :
ptr_(typeSpec->ptr()),
len_(typeSpec->length()),
hash_(typeSpec->length()),
token_(mdTokenNil)
{
for (unsigned i = 0; i < len_; i++)
hash_ = (hash_ * 257) ^ ((i + 1) * (ptr_[i] ^ 0xA5));
}
// Constructor for a 'permanent' object
// Don't bother re-hashing, since we will always have already constructed the lookup object
TypeSpecContainer(const TypeSpecContainer &t, mdToken tk) :
ptr_(new uint8_t[t.len_]),
len_(t.len_),
hash_(t.hash_),
token_(tk)
{
_ASSERT(tk != mdTokenNil);
_ASSERT(t.token_ == mdTokenNil);
memcpy(ptr_, t.ptr_, len_);
}
~TypeSpecContainer()
{
if (token_ != mdTokenNil)
// delete any memory for a 'permanent' object
delete[] ptr_;
}
// this is the operator for a RBTREE
int ComparedTo(TypeSpecContainer *t) const
{
// If they don't hash the same, just diff the hashes
if (hash_ != t->hash_)
return hash_ - t->hash_;
if (len_ != t->len_)
return len_ - t->len_;
return memcmp(ptr_, t->ptr_, len_);
}
// The only public data we need
mdToken Token() const { return token_; }
};
static RBTREE<TypeSpecContainer> typeSpecCache;
extern FIFO<char> TyParFixupList;
/**************************************************************************/
mdToken Assembler::ResolveTypeSpec(BinStr* typeSpec)
{
mdToken tk;
// It is safe to use the cache only if there are no pending fixups
if (TyParFixupList.COUNT() != 0)
{
if (FAILED(m_pEmitter->GetTokenFromTypeSpec(typeSpec->ptr(), typeSpec->length(), &tk)))
return mdTokenNil;
return tk;
}
TypeSpecContainer tsc(typeSpec);
// GetTokenFromTypeSpec is a linear search through an unsorted list
// Instead of doing that all the time, look this thing up in a cache
TypeSpecContainer *res = typeSpecCache.FIND(&tsc);
if (res != NULL)
{
#ifdef _DEBUG
// Verify that the cache is in sync with the master copy in metadata
PCOR_SIGNATURE pSig;
ULONG cSig;
m_pImporter->GetTypeSpecFromToken(res->Token(),(PCCOR_SIGNATURE*)&pSig,&cSig);
_ASSERTE(typeSpec->length() == cSig);
_ASSERTE(memcmp(typeSpec->ptr(), pSig, cSig) == 0);
#endif
return res->Token();
}
if (FAILED(m_pEmitter->GetTokenFromTypeSpec(typeSpec->ptr(), typeSpec->length(), &tk)))
return mdTokenNil;
typeSpecCache.PUSH(new TypeSpecContainer(tsc, tk));
return tk;
}
/**************************************************************************/
mdToken Assembler::GetAsmRef(_In_ __nullterminated const char* szName)
{
mdToken tkResScope = 0;
if(strcmp(szName,"*")==0) tkResScope = mdTokenNil;
else
{
tkResScope = m_pManifest->GetAsmRefTokByName(szName);
if(RidFromToken(tkResScope)==0)
{
// emit the AssemblyRef
// if it's not self, try to get attributes with Autodetect
size_t L = strlen(szName)+1;
char *sz = new char[L];
if(sz)
{
memcpy(sz,szName,L);
AsmManAssembly *pAsmRef = m_pManifest->m_pCurAsmRef;
m_pManifest->StartAssembly(sz,NULL,0,TRUE);
if(RidFromToken(m_pManifest->GetAsmTokByName(szName))==0)
{
report->warn("Reference to undeclared extern assembly '%s'. Attempting autodetect\n",szName);
m_pManifest->SetAssemblyAutodetect();
}
m_pManifest->EndAssembly();
tkResScope = m_pManifest->GetAsmRefTokByName(szName);
m_pManifest->m_pCurAsmRef = pAsmRef;
}
else
report->error("\nOut of memory!\n");
}
}
return tkResScope;
}
mdToken Assembler::GetBaseAsmRef()
{
// First we check for "System.Private.CoreLib" as the base or System assembly
//
AsmManAssembly* coreLibAsm = m_pManifest->GetAsmRefByAsmName("System.Private.CoreLib");
if(coreLibAsm != NULL)
{
return GetAsmRef(coreLibAsm->szAlias ? coreLibAsm->szAlias : coreLibAsm->szName);
}
AsmManAssembly* sysRuntime = m_pManifest->GetAsmRefByAsmName("System.Runtime");
if(sysRuntime != NULL)
{
return GetAsmRef(sysRuntime->szAlias ? sysRuntime->szAlias : sysRuntime->szName);
}
AsmManAssembly* mscorlibAsm = m_pManifest->GetAsmRefByAsmName("mscorlib");
if(mscorlibAsm != NULL)
{
return GetAsmRef(mscorlibAsm->szAlias ? mscorlibAsm->szAlias : mscorlibAsm->szName);
}
AsmManAssembly* netstandardAsm = m_pManifest->GetAsmRefByAsmName("netstandard");
if (netstandardAsm != NULL)
{
return GetAsmRef(netstandardAsm->szAlias ? netstandardAsm->szAlias : netstandardAsm->szName);
}
return GetAsmRef("mscorlib");
}
mdToken Assembler::GetInterfaceImpl(mdToken tsClass, mdToken tsInterface)
{
mdToken result = mdTokenNil;
HCORENUM iiEnum = 0;
ULONG actualInterfaces;
mdInterfaceImpl impls;
while (SUCCEEDED(m_pImporter->EnumInterfaceImpls(&iiEnum, tsClass, &impls, 1, &actualInterfaces)))
{
if (actualInterfaces == 1)
{
mdToken classToken, interfaceToken;
if (FAILED(m_pImporter->GetInterfaceImplProps(impls, &classToken, &interfaceToken)))
break;
if (classToken == tsClass && interfaceToken == tsInterface)
{
result = impls;
break;
}
}
}
m_pImporter->CloseEnum(iiEnum);
return result;
}
/**************************************************************************/
mdToken Assembler::GetModRef(_In_ __nullterminated char* szName)
{
mdToken tkResScope = 0;
if(!strcmp(szName,m_szScopeName))
tkResScope = 1; // scope is "this module"
else
{
ImportDescriptor* pID;
int i = 0;
tkResScope = mdModuleRefNil;
DWORD L = (DWORD)strlen(szName);
while((pID=m_ImportList.PEEK(i++)))
{
if(pID->dwDllName != L) continue;
if((L > 0) && (strcmp(pID->szDllName,szName)!=0)) continue;
tkResScope = pID->mrDll;
break;
}
if(RidFromToken(tkResScope)==0)
report->error("Undefined module ref '%s'\n",szName);
}
return tkResScope;
}
/**************************************************************************/
mdToken Assembler::MakeTypeRef(mdToken tkResScope, LPCUTF8 pszFullClassName)
{
mdToken tkRet = mdTokenNil;
if(pszFullClassName && *pszFullClassName)
{
LPCUTF8 pc;
if((pc = strrchr(pszFullClassName,NESTING_SEP))) // scope: enclosing class
{
LPUTF8 szScopeName;
DWORD L = (DWORD)(pc-pszFullClassName);
if((szScopeName = new char[L+1]) != NULL)
{
memcpy(szScopeName,pszFullClassName,L);
szScopeName[L] = 0;
tkResScope = MakeTypeRef(tkResScope,szScopeName);
delete [] szScopeName;
}
else
report->error("\nOut of memory!\n");
pc++;
}
else pc = pszFullClassName;
if(*pc)
{
// convert name to widechar
MultiByteToWideChar(g_uCodePage,0,pc,-1,wzUniBuf,dwUniBuf);
if(FAILED(m_pEmitter->DefineTypeRefByName(tkResScope, wzUniBuf, &tkRet))) tkRet = mdTokenNil;
}
}
return tkRet;
}
/**************************************************************************/
DWORD Assembler::CheckClassFlagsIfNested(Class* pEncloser, DWORD attr)
{
DWORD wasAttr = attr;
if(pEncloser && (!IsTdNested(attr)))
{
if(OnErrGo)
report->error("Nested class has non-nested visibility (0x%08X)\n",attr);
else
{
attr &= ~tdVisibilityMask;
attr |= (IsTdPublic(wasAttr) ? tdNestedPublic : tdNestedPrivate);
report->warn("Nested class has non-nested visibility (0x%08X), changed to nested (0x%08X)\n",wasAttr,attr);
}
}
else if((pEncloser==NULL) && IsTdNested(attr))
{
if(OnErrGo)
report->error("Non-nested class has nested visibility (0x%08X)\n",attr);
else
{
attr &= ~tdVisibilityMask;
attr |= (IsTdNestedPublic(wasAttr) ? tdPublic : tdNotPublic);
report->warn("Non-nested class has nested visibility (0x%08X), changed to non-nested (0x%08X)\n",wasAttr,attr);
}
}
return attr;
}
/**************************************************************************/
void Assembler::StartClass(_In_ __nullterminated char* name, DWORD attr, TyParList *typars)
{
Class *pEnclosingClass = m_pCurClass;
char *szFQN;
size_t LL;
m_TyParList = typars;
if (m_pCurMethod != NULL)
{
report->error("Class cannot be declared within a method scope\n");
}
if(pEnclosingClass)
{
LL = pEnclosingClass->m_dwFQN+strlen(name)+2;
if((szFQN = new char[LL]) != nullptr)
sprintf_s(szFQN,LL,"%s%c%s",pEnclosingClass->m_szFQN,NESTING_SEP,name);
else
report->error("\nOut of memory!\n");
}
else
{
size_t L = strlen(m_szFullNS);
size_t LLL = strlen(name);
LL = L + LLL + (L ? 2 : 1);
if((szFQN = new char[LL]) != nullptr)
{
if(L) sprintf_s(szFQN,LL,"%s.%s",m_szFullNS,name);
else memcpy(szFQN,name,LL);
if(LL > MAX_CLASSNAME_LENGTH)
{
report->error("Full class name too long (%zd characters, %d allowed).\n",LL-1,MAX_CLASSNAME_LENGTH-1);
}
}
else
report->error("\nOut of memory!\n");
}
if(szFQN == NULL) return;
mdToken tkThis;
if(m_fIsMscorlib)
tkThis = ResolveClassRef(1,szFQN,&m_pCurClass); // boils down to FindCreateClass(szFQN)
else
{
m_pCurClass = FindCreateClass(szFQN);
tkThis = m_pCurClass->m_cl;
}
if(m_pCurClass->m_bIsMaster)
{
m_pCurClass->m_Attr = CheckClassFlagsIfNested(pEnclosingClass, attr);
if (m_TyParList)
{
m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&(m_pCurClass->m_TyPars));
delete m_TyParList;
m_TyParList = NULL;
RecordTypeConstraints(&m_pCurClass->m_GPCList, m_pCurClass->m_NumTyPars, m_pCurClass->m_TyPars);
}
else m_pCurClass->m_NumTyPars = 0;
m_pCurClass->m_pEncloser = pEnclosingClass;
} // end if(old class) else
m_tkCurrentCVOwner = 0;
m_CustomDescrListStack.PUSH(m_pCustomDescrList);
m_pCustomDescrList = &(m_pCurClass->m_CustDList);
m_ClassStack.PUSH(pEnclosingClass);
ClearBoundList();
}
/**************************************************************************/
void Assembler::AddClass()
{
mdTypeRef crExtends = mdTypeRefNil;
BOOL bIsEnum = FALSE;
BOOL bIsValueType = FALSE;
if(m_pCurClass->m_bIsMaster)
{
DWORD attr = m_pCurClass->m_Attr;
if(!IsNilToken(m_crExtends))
{
// has a superclass
if(IsTdInterface(attr)) report->error("Base class in interface\n");
bIsValueType = (m_crExtends == m_tkSysValue)&&(m_pCurClass->m_cl != m_tkSysEnum);
bIsEnum = (m_crExtends == m_tkSysEnum);
crExtends = m_crExtends;
}
else
{
bIsEnum = ((attr & 0x40000000) != 0);
bIsValueType = ((attr & 0x80000000) != 0);
}
attr &= 0x3FFFFFFF;
if (m_fAutoInheritFromObject && (crExtends == mdTypeRefNil) && (!IsTdInterface(attr)))
{
mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetBaseAsmRef();
crExtends = bIsEnum ?
ResolveClassRef(tkMscorlib,"System.Enum",NULL)
:( bIsValueType ?
ResolveClassRef(tkMscorlib,"System.ValueType",NULL)
: ResolveClassRef(tkMscorlib, "System.Object",NULL));
}
m_pCurClass->m_Attr = attr;
m_pCurClass->m_crExtends = (m_pCurClass->m_cl == m_tkSysObject)? mdTypeRefNil : crExtends;
if ((m_pCurClass->m_dwNumInterfaces = m_nImplList) != 0)
{
if(bIsEnum) report->error("Enum implementing interface(s)\n");
if((m_pCurClass->m_crImplements = new mdTypeRef[m_nImplList+1]) != NULL)
memcpy(m_pCurClass->m_crImplements, m_crImplList, (m_nImplList+1)*sizeof(mdTypeRef));
else
{
report->error("Failed to allocate Impl List for class '%s'\n", m_pCurClass->m_szFQN);
m_pCurClass->m_dwNumInterfaces = 0;
}
}
else m_pCurClass->m_crImplements = NULL;
if(bIsValueType)
{
if(!IsTdSealed(attr))
{
if(OnErrGo) report->error("Non-sealed value class\n");
else
{
report->warn("Non-sealed value class, made sealed\n");
m_pCurClass->m_Attr |= tdSealed;
}
}
}
m_pCurClass->m_bIsMaster = FALSE;
} // end if(old class) else
ClearImplList();
m_crExtends = mdTypeRefNil;
}
/**************************************************************************/
void Assembler::EndClass()
{
m_pCurClass = m_ClassStack.POP();
m_tkCurrentCVOwner = 0;
m_pCustomDescrList = m_CustomDescrListStack.POP();
}
/**************************************************************************/
void Assembler::SetPinvoke(BinStr* DllName, int Ordinal, BinStr* Alias, int Attrs)
{
if(m_pPInvoke) delete m_pPInvoke;
if(DllName->length())
{
if((m_pPInvoke = new PInvokeDescriptor))
{
unsigned l;
ImportDescriptor* pID;
if((pID = EmitImport(DllName)))
{
m_pPInvoke->mrDll = pID->mrDll;
m_pPInvoke->szAlias = NULL;
if(Alias)
{
l = Alias->length();
if((m_pPInvoke->szAlias = new char[l+1]))
{
memcpy(m_pPInvoke->szAlias,Alias->ptr(),l);
m_pPInvoke->szAlias[l] = 0;
}
else report->error("\nOut of memory!\n");
}
m_pPInvoke->dwAttrs = (DWORD)Attrs;
}
else
{
delete m_pPInvoke;
m_pPInvoke = NULL;
report->error("PInvoke refers to undefined imported DLL\n");
}
}
else
report->error("Failed to allocate PInvokeDescriptor\n");
}
else
{
m_pPInvoke = NULL; // No DLL name, it's "local" (IJW) PInvoke
report->error("Local (embedded native) PInvoke method, the resulting PE file is unusable\n");
}
if(DllName) delete DllName;
if(Alias) delete Alias;
}
/**************************************************************************/
void Assembler::StartMethod(_In_ __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars)
{
if (m_pCurMethod != NULL)
{
report->error("Cannot declare a method '%s' within another method\n",name);
}
if (!m_fInitialisedMetaData)
{
if (FAILED(InitMetaData())) // impl. see WRITER.CPP
{
_ASSERTE(0);
}
}
size_t namelen = strlen(name);
if(namelen >= MAX_CLASSNAME_LENGTH)
{
char c = name[MAX_CLASSNAME_LENGTH-1];
name[MAX_CLASSNAME_LENGTH-1] = 0;
report->error("Method '%s...' -- name too long (%zd characters).\n",name,namelen);
name[MAX_CLASSNAME_LENGTH-1] = c;
}
if (!(flags & mdStatic))
*(sig->ptr()) |= IMAGE_CEE_CS_CALLCONV_HASTHIS;
else if(*(sig->ptr()) & (IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS))
{
if(OnErrGo) report->error("Method '%s' -- both static and instance\n", name);
else
{
report->warn("Method '%s' -- both static and instance, set to static\n", name);
*(sig->ptr()) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
}
}
if(!IsMdPrivateScope(flags))
{
Method* pMethod;
Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
DWORD L = (DWORD)strlen(name);
for(int j=0; (pMethod = pClass->m_MethodList.PEEK(j)); j++)
{
if( (pMethod->m_dwName == L) &&
(!strcmp(pMethod->m_szName,name)) &&
(pMethod->m_dwMethodCSig == sig->length()) &&
(!memcmp(pMethod->m_pMethodSig,sig->ptr(),sig->length()))
&&(!IsMdPrivateScope(pMethod->m_Attr)))
{
if(m_fTolerateDupMethods)
{
// reset for new body
pMethod->m_lstFixup.RESET(true);
//pMethod->m_lstLabel.RESET(true);
m_lstLabel.RESET(true);
pMethod->m_Locals.RESET(true);
delArgNameList(pMethod->m_firstArgName);
delArgNameList(pMethod->m_firstVarName);
pMethod->m_pCurrScope = &(pMethod->m_MainScope);
pMethod->m_pCurrScope->Reset();
pMethod->m_firstArgName = getArgNameList();
pMethod->m_dwNumExceptions = 0;
pMethod->m_dwNumEndfilters = 0;
if(pMethod->m_pRetMarshal) delete pMethod->m_pRetMarshal;
if(pMethod->m_pRetValue) delete pMethod->m_pRetValue;
pMethod->m_MethodImplDList.RESET(false); // ptrs in m_MethodImplDList are dups of those in Assembler
pMethod->m_CustomDescrList.RESET(true);
if(pMethod->m_fEntryPoint)
{
pMethod->m_fEntryPoint = FALSE;
m_fEntryPointPresent = FALSE;
}
if(pMethod->m_pbsBody)
{
// no need to remove relevant MemberRef Fixups from the Assembler list:
// their m_fNew flag is set to FALSE anyway.
// Just get rid of old method body
delete pMethod->m_pbsBody;
pMethod->m_pbsBody = NULL;
}
pMethod->m_fNewBody = TRUE;
m_pCurMethod = pMethod;
}
else
report->error("Duplicate method declaration\n");
break;
}
}
}
if(m_pCurMethod == NULL)
{
if(m_pCurClass)
{ // instance method
if(IsMdAbstract(flags) && !IsTdAbstract(m_pCurClass->m_Attr))
{
report->error("Abstract method '%s' in non-abstract class '%s'\n",name,m_pCurClass->m_szFQN);
}
if(m_pCurClass->m_crExtends == m_tkSysEnum) report->error("Method in enum\n");
if(!strcmp(name,COR_CTOR_METHOD_NAME))
{
flags = (CorMethodAttr)(flags | mdSpecialName);
if(IsTdInterface(m_pCurClass->m_Attr)) report->error("Instance constructor in interface\n");
}
m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
}
else
{
if(IsMdAbstract(flags))
{
if(OnErrGo) report->error("Global method '%s' can't be abstract\n",name);
else
{
report->warn("Global method '%s' can't be abstract, flag removed\n",name);
flags = (CorMethodAttr)(((int) flags) &~mdAbstract);
}
}
if(!IsMdStatic(flags))
{
if(OnErrGo) report->error("Non-static global method '%s'\n",name);
else
{
report->warn("Non-static global method '%s', made static\n",name);
flags = (CorMethodAttr)(flags | mdStatic);
*((BYTE*)(sig->ptr())) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
}
}
m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
if (m_pCurMethod)
{
m_pCurMethod->SetIsGlobalMethod();
if (m_fInitialisedMetaData == FALSE) InitMetaData();
}
}
if(m_pCurMethod)
{
if(!OnErrGo)
{
if(m_pCurMethod->m_firstArgName)
{
for(ARG_NAME_LIST *pAN=m_pCurMethod->m_firstArgName; pAN; pAN = pAN->pNext)
{
if(pAN->dwName)
{
int k = m_pCurMethod->findArgNum(pAN->pNext,pAN->szName,pAN->dwName);
if(k >= 0)
report->warn("Duplicate param name '%s' in method '%s'\n",pAN->szName,name);
}
}
}
}
m_pCurMethod->m_pRetMarshal = retMarshal;
m_pCurMethod->m_dwRetAttr = retAttr;
m_tkCurrentCVOwner = 0;
m_CustomDescrListStack.PUSH(m_pCustomDescrList);
m_pCustomDescrList = &(m_pCurMethod->m_CustomDescrList);
m_pCurMethod->m_MainScope.dwStart = m_CurPC;
if (typars)
{
m_pCurMethod->m_NumTyPars = typars->ToArray(&(m_pCurMethod->m_TyPars));
delete typars;
m_TyParList = NULL;
RecordTypeConstraints(&m_pCurMethod->m_GPCList, m_pCurMethod->m_NumTyPars, m_pCurMethod->m_TyPars);
}
else m_pCurMethod->m_NumTyPars = 0;
}
else report->error("Failed to allocate Method class\n");
} // end if new method
}
/**************************************************************************/
void Assembler::EndMethod()
{
if(m_pCurMethod->m_pCurrScope != &(m_pCurMethod->m_MainScope))
{
report->error("Invalid lexical scope structure in method %s\n",m_pCurMethod->m_szName);
}
m_pCurMethod->m_pCurrScope->dwEnd = m_CurPC;
if (DoFixups(m_pCurMethod)) AddMethod(m_pCurMethod); //AddMethod - see ASSEM.CPP
else
{
report->error("Method '%s' compilation failed.\n",m_pCurMethod->m_szName);
}
//m_pCurMethod->m_lstLabel.RESET(true);
m_lstLabel.RESET(true);
m_tkCurrentCVOwner = 0;
m_pCustomDescrList = m_CustomDescrListStack.POP();
ResetForNextMethod(); // see ASSEM.CPP
}
/**************************************************************************/
/* rvaLabel is the optional label that indicates this field points at a particular RVA */
void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, _In_ __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset)
{
FieldDescriptor* pFD;
ULONG i,n;
mdToken tkParent = mdTokenNil;
Class* pClass;
if (m_pCurMethod)
report->error("Field cannot be declared within a method\n");
size_t namelen = strlen(name);
if(namelen >= MAX_CLASSNAME_LENGTH)
{
char c = name[MAX_CLASSNAME_LENGTH-1];
name[MAX_CLASSNAME_LENGTH-1] = 0;
report->error("Field '%s...' -- name too long (%zd characters).\n",name,namelen);
name[MAX_CLASSNAME_LENGTH-1] = c;
}
if(sig && (sig->length() >= 2))
{
if(sig->ptr()[1] == ELEMENT_TYPE_VOID)
report->error("Illegal use of type 'void'\n");
}
if (m_pCurClass)
{
tkParent = m_pCurClass->m_cl;
if(IsTdInterface(m_pCurClass->m_Attr))
{
if(!IsFdStatic(flags))
{
report->warn("Instance field in interface (CLS violation)\n");
if(!IsFdPublic(flags)) report->error("Non-public instance field in interface\n");
}
}
}
else
{
if(ulOffset != 0xFFFFFFFF)
{
report->warn("Offset in global field '%s' is ignored\n",name);
ulOffset = 0xFFFFFFFF;
}
if(!IsFdStatic(flags))
{
if(OnErrGo) report->error("Non-static global field\n");
else
{
report->warn("Non-static global field, made static\n");
flags = (CorFieldAttr)(flags | fdStatic);
}
}
}
pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
n = pClass->m_FieldDList.COUNT();
DWORD L = (DWORD)strlen(name);
for(i = 0; i < n; i++)
{
pFD = pClass->m_FieldDList.PEEK(i);
if((pFD->m_tdClass == tkParent)&&(L==pFD->m_dwName)&&(!strcmp(pFD->m_szName,name))
&&(pFD->m_pbsSig->length() == sig->length())
&&(memcmp(pFD->m_pbsSig->ptr(),sig->ptr(),sig->length())==0))
{
report->error("Duplicate field declaration: '%s'\n",name);
break;
}
}
if (rvaLabel && !IsFdStatic(flags))
report->error("Only static fields can have 'at' clauses\n");
if(i >= n)
{
if((pFD = new FieldDescriptor))
{
pFD->m_tdClass = tkParent;
pFD->m_szName = name;
pFD->m_dwName = L;
pFD->m_fdFieldTok = mdTokenNil;
if((pFD->m_ulOffset = ulOffset) != 0xFFFFFFFF) pClass->m_dwNumFieldsWithOffset++;
pFD->m_rvaLabel = rvaLabel;
pFD->m_pbsSig = sig;
pFD->m_pClass = pClass;
pFD->m_pbsValue = pVal;
pFD->m_pbsMarshal = m_pMarshal;
pFD->m_pPInvoke = m_pPInvoke;
pFD->m_dwAttr = flags;
m_tkCurrentCVOwner = 0;
m_pCustomDescrList = &(pFD->m_CustomDescrList);
pClass->m_FieldDList.PUSH(pFD);
pClass->m_fNewMembers = TRUE;
}
else
report->error("Failed to allocate Field Descriptor\n");
}
else
{
if(pVal) delete pVal;
if(m_pPInvoke) delete m_pPInvoke;
if(m_pMarshal) delete m_pMarshal;
delete name;
}
m_pPInvoke = NULL;
m_pMarshal = NULL;
}
BOOL Assembler::EmitField(FieldDescriptor* pFD)
{
WCHAR* wzFieldName=&wzUniBuf[0];
HRESULT hr;
DWORD cSig;
COR_SIGNATURE* mySig;
mdFieldDef mb;
BYTE ValType = ELEMENT_TYPE_VOID;
void * pValue = NULL;
unsigned lVal = 0;
BOOL ret = TRUE;
cSig = pFD->m_pbsSig->length();
mySig = (COR_SIGNATURE*)(pFD->m_pbsSig->ptr());
MultiByteToWideChar(g_uCodePage,0,pFD->m_szName,-1,wzFieldName,dwUniBuf); //int)cFieldNameLength);
if(IsFdPrivateScope(pFD->m_dwAttr))
{
WCHAR* p = (WCHAR*)u16_strstr(wzFieldName,W("$PST04"));
if(p) *p = W('\0');
}
if(pFD->m_pbsValue && pFD->m_pbsValue->length())
{
ValType = *(pFD->m_pbsValue->ptr());
lVal = pFD->m_pbsValue->length() - 1; // 1 is type byte
pValue = (void*)(pFD->m_pbsValue->ptr() + 1);
if(ValType == ELEMENT_TYPE_STRING)
{
//while(lVal % sizeof(WCHAR)) { pFD->m_pbsValue->appendInt8(0); lVal++; }
lVal /= sizeof(WCHAR);
#if defined(ALIGN_ACCESS) || BIGENDIAN
void* pValueTemp = _alloca(lVal * sizeof(WCHAR));
memcpy(pValueTemp, pValue, lVal * sizeof(WCHAR));
pValue = pValueTemp;
SwapStringLength((WCHAR*)pValue, lVal);
#endif
}
}
hr = m_pEmitter->DefineField(
pFD->m_tdClass,
wzFieldName,
pFD->m_dwAttr,
mySig,
cSig,
ValType,
pValue,
lVal,
&mb
);
if (FAILED(hr))
{
report->error("Failed to define field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
ret = FALSE;
}
else
{
//--------------------------------------------------------------------------------
if(IsFdPinvokeImpl(pFD->m_dwAttr)&&(pFD->m_pPInvoke))
{
if(pFD->m_pPInvoke->szAlias == NULL) pFD->m_pPInvoke->szAlias = pFD->m_szName;
if(FAILED(EmitPinvokeMap(mb,pFD->m_pPInvoke)))
{
report->error("Failed to define PInvoke map of .field '%s'\n",pFD->m_szName);
ret = FALSE;
}
}
//--------------------------------------------------------------------------
if(pFD->m_pbsMarshal)
{
if(FAILED(hr = m_pEmitter->SetFieldMarshal (
mb, // [IN] given a fieldDef or paramDef token
(PCCOR_SIGNATURE)(pFD->m_pbsMarshal->ptr()), // [IN] native type specification
pFD->m_pbsMarshal->length()))) // [IN] count of bytes of pvNativeType
{
report->error("Failed to set field marshaling for '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
ret = FALSE;
}
}
//--------------------------------------------------------------------------------
// Set the RVA to a dummy value. later it will be fixed
// up to be something correct, but if we don't emit something
// the size of the meta-data will not be correct
if (pFD->m_rvaLabel)
{