1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
12 #include "assembler.h"
16 #define FAIL_UNLESS(x, y) if (!(x)) { report->error y; return; }
18 /**************************************************************************/
19 void Assembler::StartNameSpace(__in __nullterminated char* name)
21 m_NSstack.PUSH(m_szNamespace);
23 unsigned L = (unsigned)strlen(m_szFullNS);
24 unsigned l = (unsigned)strlen(name);
25 if(L+l+1 >= m_ulFullNSLen)
27 char* pch = new char[((L+l)/MAX_NAMESPACE_LENGTH + 1)*MAX_NAMESPACE_LENGTH];
30 memcpy(pch,m_szFullNS,L+1);
33 m_ulFullNSLen = ((L+l)/MAX_NAMESPACE_LENGTH + 1)*MAX_NAMESPACE_LENGTH;
35 else report->error("Failed to reallocate the NameSpace buffer\n");
37 if(L) m_szFullNS[L] = NAMESPACE_SEPARATOR_CHAR;
39 memcpy(&m_szFullNS[L+1],m_szNamespace, l+1);
42 /**************************************************************************/
43 void Assembler::EndNameSpace()
45 char *p = &m_szFullNS[strlen(m_szFullNS)-strlen(m_szNamespace)];
46 if(p > m_szFullNS) p--;
48 delete [] m_szNamespace;
49 if((m_szNamespace = m_NSstack.POP())==NULL)
51 m_szNamespace = new char[2];
56 /**************************************************************************/
57 void Assembler::ClearImplList(void)
59 while(m_nImplList) m_crImplList[--m_nImplList] = mdTypeRefNil;
61 /**************************************************************************/
64 #pragma warning(disable:22008) // "Suppress PREfast warnings about integer overflow"
66 void Assembler::AddToImplList(mdToken tk)
68 if(m_nImplList+1 >= m_nImplListSize)
70 mdToken *ptr = new mdToken[m_nImplListSize + MAX_INTERFACES_IMPLEMENTED];
73 report->error("Failed to reallocate Impl List from %d to %d bytes\n",
74 m_nImplListSize*sizeof(mdToken),
75 (m_nImplListSize+MAX_INTERFACES_IMPLEMENTED)*sizeof(mdToken));
78 memcpy(ptr,m_crImplList,m_nImplList*sizeof(mdToken));
81 m_nImplListSize += MAX_INTERFACES_IMPLEMENTED;
83 m_crImplList[m_nImplList++] = tk;
84 m_crImplList[m_nImplList] = mdTypeRefNil;
90 void Assembler::ClearBoundList(void)
94 /**************************************************************************/
95 mdToken Assembler::ResolveClassRef(mdToken tkResScope, __in __nullterminated const char *pszFullClassName, Class** ppClass)
98 mdToken tkRet = mdTokenNil;
99 mdToken *ptkSpecial = NULL;
101 if(pszFullClassName == NULL) return mdTokenNil;
103 switch(strlen(pszFullClassName))
106 if(strcmp(pszFullClassName,"System.Enum")==0) ptkSpecial = &m_tkSysEnum;
109 if(strcmp(pszFullClassName,"System.Object")==0) ptkSpecial = &m_tkSysObject;
110 else if(strcmp(pszFullClassName,"System.String")==0) ptkSpecial = &m_tkSysString;
113 if(strcmp(pszFullClassName,"System.ValueType")==0) ptkSpecial = &m_tkSysValue;
116 if(ptkSpecial) // special token
118 if(*ptkSpecial) // already resolved
123 if(TypeFromToken(tkRet)==mdtTypeDef)
124 *ppClass = m_lstClass.PEEK(RidFromToken(tkRet)-1);
125 else *ppClass = NULL;
129 else // needs to be resolved
130 if(!m_fIsMscorlib) tkResScope = GetBaseAsmRef();
134 if((pClass = FindCreateClass(pszFullClassName)) != NULL) tkRet = pClass->m_cl;
138 tkRet = MakeTypeRef(tkResScope, pszFullClassName);
141 if(ppClass) *ppClass = pClass;
142 if(ptkSpecial) *ptkSpecial = tkRet;
146 class TypeSpecContainer
150 unsigned __int8 *ptr_;
152 // Hash the BinStr, just for speed of lookup
154 // The value we're looking for
157 // Constructor for a 'lookup' object
158 TypeSpecContainer(BinStr *typeSpec) :
159 ptr_(typeSpec->ptr()),
160 len_(typeSpec->length()),
161 hash_(typeSpec->length()),
164 for (unsigned i = 0; i < len_; i++)
165 hash_ = (hash_ * 257) ^ ((i + 1) * (ptr_[i] ^ 0xA5));
167 // Constructor for a 'permanent' object
168 // Don't bother re-hashing, since we will always have already constructed the lookup object
169 TypeSpecContainer(const TypeSpecContainer &t, mdToken tk) :
170 ptr_(new unsigned __int8[t.len_]),
175 _ASSERT(tk != mdTokenNil);
176 _ASSERT(t.token_ == mdTokenNil);
177 memcpy(ptr_, t.ptr_, len_);
181 if (token_ != mdTokenNil)
182 // delete any memory for a 'permanent' object
185 // this is the operator for a RBTREE
186 int ComparedTo(TypeSpecContainer *t) const
188 // If they don't hash the same, just diff the hashes
189 if (hash_ != t->hash_)
190 return hash_ - t->hash_;
192 return len_ - t->len_;
193 return memcmp(ptr_, t->ptr_, len_);
195 // The only public data we need
196 const mdToken Token() const { return token_; }
199 static RBTREE<TypeSpecContainer> typeSpecCache;
201 extern FIFO<char> TyParFixupList;
203 /**************************************************************************/
204 mdToken Assembler::ResolveTypeSpec(BinStr* typeSpec)
208 // It is safe to use the cache only if there are no pending fixups
209 if (TyParFixupList.COUNT() != 0)
211 if (FAILED(m_pEmitter->GetTokenFromTypeSpec(typeSpec->ptr(), typeSpec->length(), &tk)))
216 TypeSpecContainer tsc(typeSpec);
218 // GetTokenFromTypeSpec is a linear search through an unsorted list
219 // Instead of doing that all the time, look this thing up in a cache
220 TypeSpecContainer *res = typeSpecCache.FIND(&tsc);
224 // Verify that the cache is in sync with the master copy in metadata
227 m_pImporter->GetTypeSpecFromToken(res->Token(),(PCCOR_SIGNATURE*)&pSig,&cSig);
228 _ASSERTE(typeSpec->length() == cSig);
229 _ASSERTE(memcmp(typeSpec->ptr(), pSig, cSig) == 0);
235 if (FAILED(m_pEmitter->GetTokenFromTypeSpec(typeSpec->ptr(), typeSpec->length(), &tk)))
238 typeSpecCache.PUSH(new TypeSpecContainer(tsc, tk));
242 /**************************************************************************/
243 mdToken Assembler::GetAsmRef(__in __nullterminated const char* szName)
245 mdToken tkResScope = 0;
246 if(strcmp(szName,"*")==0) tkResScope = mdTokenNil;
249 tkResScope = m_pManifest->GetAsmRefTokByName(szName);
250 if(RidFromToken(tkResScope)==0)
252 // emit the AssemblyRef
253 // if it's not self, try to get attributes with Autodetect
254 unsigned L = (unsigned)strlen(szName)+1;
255 char *sz = new char[L];
259 AsmManAssembly *pAsmRef = m_pManifest->m_pCurAsmRef;
260 m_pManifest->StartAssembly(sz,NULL,0,TRUE);
261 if(RidFromToken(m_pManifest->GetAsmTokByName(szName))==0)
263 report->warn("Reference to undeclared extern assembly '%s'. Attempting autodetect\n",szName);
264 m_pManifest->SetAssemblyAutodetect();
266 m_pManifest->EndAssembly();
267 tkResScope = m_pManifest->GetAsmRefTokByName(szName);
268 m_pManifest->m_pCurAsmRef = pAsmRef;
271 report->error("\nOut of memory!\n");
277 mdToken Assembler::GetBaseAsmRef()
279 AsmManAssembly* sysRuntime = m_pManifest->GetAsmRefByAsmName("System.Runtime");
280 if(sysRuntime != NULL)
282 return GetAsmRef(sysRuntime->szAlias ? sysRuntime->szAlias : sysRuntime->szName);
285 AsmManAssembly* mscorlibAsm = m_pManifest->GetAsmRefByAsmName("mscorlib");
286 if(mscorlibAsm != NULL)
288 return GetAsmRef(mscorlibAsm->szAlias ? mscorlibAsm->szAlias : mscorlibAsm->szName);
291 AsmManAssembly* netstandardAsm = m_pManifest->GetAsmRefByAsmName("netstandard");
292 if (netstandardAsm != NULL)
294 return GetAsmRef(netstandardAsm->szAlias ? netstandardAsm->szAlias : netstandardAsm->szName);
297 return GetAsmRef("mscorlib");
300 mdToken Assembler::GetInterfaceImpl(mdToken tsClass, mdToken tsInterface)
302 mdToken result = mdTokenNil;
304 ULONG actualInterfaces;
305 mdInterfaceImpl impls;
307 while (SUCCEEDED(m_pImporter->EnumInterfaceImpls(&iiEnum, tsClass, &impls, 1, &actualInterfaces)))
309 if (actualInterfaces == 1)
311 mdToken classToken, interfaceToken;
312 if (FAILED(m_pImporter->GetInterfaceImplProps(impls, &classToken, &interfaceToken)))
314 if (classToken == tsClass && interfaceToken == tsInterface)
321 m_pImporter->CloseEnum(iiEnum);
325 /**************************************************************************/
326 mdToken Assembler::GetModRef(__in __nullterminated char* szName)
328 mdToken tkResScope = 0;
329 if(!strcmp(szName,m_szScopeName))
330 tkResScope = 1; // scope is "this module"
333 ImportDescriptor* pID;
335 tkResScope = mdModuleRefNil;
336 DWORD L = (DWORD)strlen(szName);
337 while((pID=m_ImportList.PEEK(i++)))
339 if(pID->dwDllName != L) continue;
340 if((L > 0) && (strcmp(pID->szDllName,szName)!=0)) continue;
341 tkResScope = pID->mrDll;
344 if(RidFromToken(tkResScope)==0)
345 report->error("Undefined module ref '%s'\n",szName);
349 /**************************************************************************/
350 mdToken Assembler::MakeTypeRef(mdToken tkResScope, LPCUTF8 pszFullClassName)
352 mdToken tkRet = mdTokenNil;
353 if(pszFullClassName && *pszFullClassName)
356 if((pc = strrchr(pszFullClassName,NESTING_SEP))) // scope: enclosing class
359 DWORD L = (DWORD)(pc-pszFullClassName);
360 if((szScopeName = new char[L+1]) != NULL)
362 memcpy(szScopeName,pszFullClassName,L);
364 tkResScope = MakeTypeRef(tkResScope,szScopeName);
365 delete [] szScopeName;
368 report->error("\nOut of memory!\n");
371 else pc = pszFullClassName;
374 // convert name to widechar
375 WszMultiByteToWideChar(g_uCodePage,0,pc,-1,wzUniBuf,dwUniBuf);
376 if(FAILED(m_pEmitter->DefineTypeRefByName(tkResScope, wzUniBuf, &tkRet))) tkRet = mdTokenNil;
381 /**************************************************************************/
383 DWORD Assembler::CheckClassFlagsIfNested(Class* pEncloser, DWORD attr)
385 DWORD wasAttr = attr;
386 if(pEncloser && (!IsTdNested(attr)))
389 report->error("Nested class has non-nested visibility (0x%08X)\n",attr);
392 attr &= ~tdVisibilityMask;
393 attr |= (IsTdPublic(wasAttr) ? tdNestedPublic : tdNestedPrivate);
394 report->warn("Nested class has non-nested visibility (0x%08X), changed to nested (0x%08X)\n",wasAttr,attr);
397 else if((pEncloser==NULL) && IsTdNested(attr))
400 report->error("Non-nested class has nested visibility (0x%08X)\n",attr);
403 attr &= ~tdVisibilityMask;
404 attr |= (IsTdNestedPublic(wasAttr) ? tdPublic : tdNotPublic);
405 report->warn("Non-nested class has nested visibility (0x%08X), changed to non-nested (0x%08X)\n",wasAttr,attr);
411 /**************************************************************************/
413 void Assembler::StartClass(__in __nullterminated char* name, DWORD attr, TyParList *typars)
415 Class *pEnclosingClass = m_pCurClass;
419 m_TyParList = typars;
421 if (m_pCurMethod != NULL)
423 report->error("Class cannot be declared within a method scope\n");
427 LL = pEnclosingClass->m_dwFQN+(ULONG)strlen(name)+2;
428 if((szFQN = new char[LL]))
429 sprintf_s(szFQN,LL,"%s%c%s",pEnclosingClass->m_szFQN,NESTING_SEP,name);
431 report->error("\nOut of memory!\n");
435 unsigned L = (unsigned)strlen(m_szFullNS);
436 unsigned LLL = (unsigned)strlen(name);
437 LL = L + LLL + (L ? 2 : 1);
438 if((szFQN = new char[LL]))
440 if(L) sprintf_s(szFQN,LL,"%s.%s",m_szFullNS,name);
441 else memcpy(szFQN,name,LL);
442 if(LL > MAX_CLASSNAME_LENGTH)
444 report->error("Full class name too long (%d characters, %d allowed).\n",LL-1,MAX_CLASSNAME_LENGTH-1);
448 report->error("\nOut of memory!\n");
450 if(szFQN == NULL) return;
454 tkThis = ResolveClassRef(1,szFQN,&m_pCurClass); // boils down to FindCreateClass(szFQN)
457 m_pCurClass = FindCreateClass(szFQN);
458 tkThis = m_pCurClass->m_cl;
460 if(m_pCurClass->m_bIsMaster)
462 m_pCurClass->m_Attr = CheckClassFlagsIfNested(pEnclosingClass, attr);
466 //m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&m_pCurClass->m_TyParBounds, &m_pCurClass->m_TyParNames, &m_pCurClass->m_TyParAttrs);
467 m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&(m_pCurClass->m_TyPars));
471 else m_pCurClass->m_NumTyPars = 0;
472 m_pCurClass->m_pEncloser = pEnclosingClass;
473 } // end if(old class) else
474 m_tkCurrentCVOwner = 0;
475 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
476 m_pCustomDescrList = &(m_pCurClass->m_CustDList);
478 m_ClassStack.PUSH(pEnclosingClass);
482 /**************************************************************************/
484 void Assembler::AddClass()
486 mdTypeRef crExtends = mdTypeRefNil;
487 BOOL bIsEnum = FALSE;
488 BOOL bIsValueType = FALSE;
490 if(m_pCurClass->m_bIsMaster)
492 DWORD attr = m_pCurClass->m_Attr;
493 if(!IsNilToken(m_crExtends))
496 if(IsTdInterface(attr)) report->error("Base class in interface\n");
497 bIsValueType = (m_crExtends == m_tkSysValue)&&(m_pCurClass->m_cl != m_tkSysEnum);
498 bIsEnum = (m_crExtends == m_tkSysEnum);
499 crExtends = m_crExtends;
503 bIsEnum = ((attr & 0x40000000) != 0);
504 bIsValueType = ((attr & 0x80000000) != 0);
507 if (m_fAutoInheritFromObject && (crExtends == mdTypeRefNil) && (!IsTdInterface(attr)))
509 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetBaseAsmRef();
510 crExtends = bIsEnum ?
511 ResolveClassRef(tkMscorlib,"System.Enum",NULL)
513 ResolveClassRef(tkMscorlib,"System.ValueType",NULL)
514 : ResolveClassRef(tkMscorlib, "System.Object",NULL));
516 m_pCurClass->m_Attr = attr;
517 m_pCurClass->m_crExtends = (m_pCurClass->m_cl == m_tkSysObject)? mdTypeRefNil : crExtends;
519 if ((m_pCurClass->m_dwNumInterfaces = m_nImplList) != NULL)
521 if(bIsEnum) report->error("Enum implementing interface(s)\n");
522 if((m_pCurClass->m_crImplements = new mdTypeRef[m_nImplList+1]) != NULL)
523 memcpy(m_pCurClass->m_crImplements, m_crImplList, (m_nImplList+1)*sizeof(mdTypeRef));
526 report->error("Failed to allocate Impl List for class '%s'\n", m_pCurClass->m_szFQN);
527 m_pCurClass->m_dwNumInterfaces = 0;
530 else m_pCurClass->m_crImplements = NULL;
533 if(!IsTdSealed(attr))
535 if(OnErrGo) report->error("Non-sealed value class\n");
538 report->warn("Non-sealed value class, made sealed\n");
539 m_pCurClass->m_Attr |= tdSealed;
543 m_pCurClass->m_bIsMaster = FALSE;
544 } // end if(old class) else
546 m_crExtends = mdTypeRefNil;
549 /**************************************************************************/
550 void Assembler::EndClass()
552 m_pCurClass = m_ClassStack.POP();
553 m_tkCurrentCVOwner = 0;
554 m_pCustomDescrList = m_CustomDescrListStack.POP();
557 /**************************************************************************/
558 void Assembler::SetPinvoke(BinStr* DllName, int Ordinal, BinStr* Alias, int Attrs)
560 if(m_pPInvoke) delete m_pPInvoke;
561 if(DllName->length())
563 if((m_pPInvoke = new PInvokeDescriptor))
566 ImportDescriptor* pID;
567 if((pID = EmitImport(DllName)))
569 m_pPInvoke->mrDll = pID->mrDll;
570 m_pPInvoke->szAlias = NULL;
574 if((m_pPInvoke->szAlias = new char[l+1]))
576 memcpy(m_pPInvoke->szAlias,Alias->ptr(),l);
577 m_pPInvoke->szAlias[l] = 0;
579 else report->error("\nOut of memory!\n");
581 m_pPInvoke->dwAttrs = (DWORD)Attrs;
587 report->error("PInvoke refers to undefined imported DLL\n");
591 report->error("Failed to allocate PInvokeDescriptor\n");
595 m_pPInvoke = NULL; // No DLL name, it's "local" (IJW) PInvoke
596 report->error("Local (embedded native) PInvoke method, the resulting PE file is unusable\n");
598 if(DllName) delete DllName;
599 if(Alias) delete Alias;
602 /**************************************************************************/
603 void Assembler::StartMethod(__in __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars)
605 if (m_pCurMethod != NULL)
607 report->error("Cannot declare a method '%s' within another method\n",name);
609 if (!m_fInitialisedMetaData)
611 if (FAILED(InitMetaData())) // impl. see WRITER.CPP
616 size_t namelen = strlen(name);
617 if(namelen >= MAX_CLASSNAME_LENGTH)
619 char c = name[MAX_CLASSNAME_LENGTH-1];
620 name[MAX_CLASSNAME_LENGTH-1] = 0;
621 report->error("Method '%s...' -- name too long (%d characters).\n",name,namelen);
622 name[MAX_CLASSNAME_LENGTH-1] = c;
624 if (!(flags & mdStatic))
625 *(sig->ptr()) |= IMAGE_CEE_CS_CALLCONV_HASTHIS;
626 else if(*(sig->ptr()) & (IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS))
628 if(OnErrGo) report->error("Method '%s' -- both static and instance\n", name);
631 report->warn("Method '%s' -- both static and instance, set to static\n", name);
632 *(sig->ptr()) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
636 if(!IsMdPrivateScope(flags))
639 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
640 DWORD L = (DWORD)strlen(name);
641 for(int j=0; (pMethod = pClass->m_MethodList.PEEK(j)); j++)
643 if( (pMethod->m_dwName == L) &&
644 (!strcmp(pMethod->m_szName,name)) &&
645 (pMethod->m_dwMethodCSig == sig->length()) &&
646 (!memcmp(pMethod->m_pMethodSig,sig->ptr(),sig->length()))
647 &&(!IsMdPrivateScope(pMethod->m_Attr)))
649 if(m_fTolerateDupMethods)
651 // reset for new body
652 pMethod->m_lstFixup.RESET(true);
653 //pMethod->m_lstLabel.RESET(true);
654 m_lstLabel.RESET(true);
655 pMethod->m_Locals.RESET(true);
656 delArgNameList(pMethod->m_firstArgName);
657 delArgNameList(pMethod->m_firstVarName);
658 pMethod->m_pCurrScope = &(pMethod->m_MainScope);
659 pMethod->m_pCurrScope->Reset();
660 pMethod->m_firstArgName = getArgNameList();
661 pMethod->m_dwNumExceptions = 0;
662 pMethod->m_dwNumEndfilters = 0;
663 if(pMethod->m_pRetMarshal) delete pMethod->m_pRetMarshal;
664 if(pMethod->m_pRetValue) delete pMethod->m_pRetValue;
666 pMethod->m_MethodImplDList.RESET(false); // ptrs in m_MethodImplDList are dups of those in Assembler
668 pMethod->m_CustomDescrList.RESET(true);
670 if(pMethod->m_fEntryPoint)
672 pMethod->m_fEntryPoint = FALSE;
673 m_fEntryPointPresent = FALSE;
676 if(pMethod->m_pbsBody)
678 // no need to remove relevant MemberRef Fixups from the Assembler list:
679 // their m_fNew flag is set to FALSE anyway.
680 // Just get rid of old method body
681 delete pMethod->m_pbsBody;
682 pMethod->m_pbsBody = NULL;
685 pMethod->m_fNewBody = TRUE;
686 m_pCurMethod = pMethod;
689 report->error("Duplicate method declaration\n");
694 if(m_pCurMethod == NULL)
698 if(IsMdAbstract(flags) && !IsTdAbstract(m_pCurClass->m_Attr))
700 report->error("Abstract method '%s' in non-abstract class '%s'\n",name,m_pCurClass->m_szFQN);
702 if(m_pCurClass->m_crExtends == m_tkSysEnum) report->error("Method in enum\n");
704 if(!strcmp(name,COR_CTOR_METHOD_NAME))
706 flags = (CorMethodAttr)(flags | mdSpecialName);
707 if(IsTdInterface(m_pCurClass->m_Attr)) report->error("Instance constructor in interface\n");
710 if(!IsMdStatic(flags))
712 if(IsTdInterface(m_pCurClass->m_Attr))
714 if(!IsMdPublic(flags)) report->error("Non-public instance method in interface\n");
715 if((!(IsMdVirtual(flags) && IsMdAbstract(flags))))
717 if(OnErrGo) report->error("Non-virtual, non-abstract instance method in interface\n");
720 report->warn("Non-virtual, non-abstract instance method in interface, set to such\n");
721 flags = (CorMethodAttr)(flags |mdVirtual | mdAbstract);
727 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
731 if(IsMdAbstract(flags))
733 if(OnErrGo) report->error("Global method '%s' can't be abstract\n",name);
736 report->warn("Global method '%s' can't be abstract, flag removed\n",name);
737 flags = (CorMethodAttr)(((int) flags) &~mdAbstract);
740 if(!IsMdStatic(flags))
742 if(OnErrGo) report->error("Non-static global method '%s'\n",name);
745 report->warn("Non-static global method '%s', made static\n",name);
746 flags = (CorMethodAttr)(flags | mdStatic);
747 *((BYTE*)(sig->ptr())) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
750 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
753 m_pCurMethod->SetIsGlobalMethod();
754 if (m_fInitialisedMetaData == FALSE) InitMetaData();
761 if(m_pCurMethod->m_firstArgName)
763 for(ARG_NAME_LIST *pAN=m_pCurMethod->m_firstArgName; pAN; pAN = pAN->pNext)
767 int k = m_pCurMethod->findArgNum(pAN->pNext,pAN->szName,pAN->dwName);
769 report->warn("Duplicate param name '%s' in method '%s'\n",pAN->szName,name);
774 m_pCurMethod->m_pRetMarshal = retMarshal;
775 m_pCurMethod->m_dwRetAttr = retAttr;
776 m_tkCurrentCVOwner = 0;
777 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
778 m_pCustomDescrList = &(m_pCurMethod->m_CustomDescrList);
779 m_pCurMethod->m_MainScope.dwStart = m_CurPC;
782 //m_pCurMethod->m_NumTyPars = typars->ToArray(&m_pCurMethod->m_TyParBounds,
783 //&m_pCurMethod->m_TyParNames, NULL);
784 m_pCurMethod->m_NumTyPars = typars->ToArray(&(m_pCurMethod->m_TyPars));
788 else m_pCurMethod->m_NumTyPars = 0;
790 else report->error("Failed to allocate Method class\n");
791 } // end if new method
794 /**************************************************************************/
795 void Assembler::EndMethod()
798 if(m_pCurMethod->m_pCurrScope != &(m_pCurMethod->m_MainScope))
800 report->error("Invalid lexical scope structure in method %s\n",m_pCurMethod->m_szName);
802 m_pCurMethod->m_pCurrScope->dwEnd = m_CurPC;
803 if (DoFixups(m_pCurMethod)) AddMethod(m_pCurMethod); //AddMethod - see ASSEM.CPP
806 report->error("Method '%s' compilation failed.\n",m_pCurMethod->m_szName);
808 //m_pCurMethod->m_lstLabel.RESET(true);
809 m_lstLabel.RESET(true);
810 m_tkCurrentCVOwner = 0;
811 m_pCustomDescrList = m_CustomDescrListStack.POP();
812 ResetForNextMethod(); // see ASSEM.CPP
814 /**************************************************************************/
815 /* rvaLabel is the optional label that indicates this field points at a particular RVA */
816 void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, __in __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset)
818 FieldDescriptor* pFD;
820 mdToken tkParent = mdTokenNil;
824 report->error("Field cannot be declared within a method\n");
826 if(strlen(name) >= MAX_CLASSNAME_LENGTH)
828 char c = name[MAX_CLASSNAME_LENGTH-1];
829 name[MAX_CLASSNAME_LENGTH-1] = 0;
830 report->error("Field '%s...' -- name too long (%d characters).\n",name,strlen(name));
831 name[MAX_CLASSNAME_LENGTH-1] = c;
834 if(sig && (sig->length() >= 2))
836 if(sig->ptr()[1] == ELEMENT_TYPE_VOID)
837 report->error("Illegal use of type 'void'\n");
842 tkParent = m_pCurClass->m_cl;
844 if(IsTdInterface(m_pCurClass->m_Attr))
846 if(!IsFdStatic(flags))
848 report->warn("Instance field in interface (CLS violation)\n");
849 if(!IsFdPublic(flags)) report->error("Non-public instance field in interface\n");
855 if(ulOffset != 0xFFFFFFFF)
857 report->warn("Offset in global field '%s' is ignored\n",name);
858 ulOffset = 0xFFFFFFFF;
860 if(!IsFdStatic(flags))
862 if(OnErrGo) report->error("Non-static global field\n");
865 report->warn("Non-static global field, made static\n");
866 flags = (CorFieldAttr)(flags | fdStatic);
870 pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
871 n = pClass->m_FieldDList.COUNT();
872 DWORD L = (DWORD)strlen(name);
873 for(i = 0; i < n; i++)
875 pFD = pClass->m_FieldDList.PEEK(i);
876 if((pFD->m_tdClass == tkParent)&&(L==pFD->m_dwName)&&(!strcmp(pFD->m_szName,name))
877 &&(pFD->m_pbsSig->length() == sig->length())
878 &&(memcmp(pFD->m_pbsSig->ptr(),sig->ptr(),sig->length())==0))
880 report->error("Duplicate field declaration: '%s'\n",name);
884 if (rvaLabel && !IsFdStatic(flags))
885 report->error("Only static fields can have 'at' clauses\n");
889 if((pFD = new FieldDescriptor))
891 pFD->m_tdClass = tkParent;
892 pFD->m_szName = name;
894 pFD->m_fdFieldTok = mdTokenNil;
895 if((pFD->m_ulOffset = ulOffset) != 0xFFFFFFFF) pClass->m_dwNumFieldsWithOffset++;
896 pFD->m_rvaLabel = rvaLabel;
898 pFD->m_pClass = pClass;
899 pFD->m_pbsValue = pVal;
900 pFD->m_pbsMarshal = m_pMarshal;
901 pFD->m_pPInvoke = m_pPInvoke;
902 pFD->m_dwAttr = flags;
904 m_tkCurrentCVOwner = 0;
905 m_pCustomDescrList = &(pFD->m_CustomDescrList);
907 pClass->m_FieldDList.PUSH(pFD);
908 pClass->m_fNewMembers = TRUE;
911 report->error("Failed to allocate Field Descriptor\n");
915 if(pVal) delete pVal;
916 if(m_pPInvoke) delete m_pPInvoke;
917 if(m_pMarshal) delete m_pMarshal;
924 BOOL Assembler::EmitField(FieldDescriptor* pFD)
926 WCHAR* wzFieldName=&wzUniBuf[0];
929 COR_SIGNATURE* mySig;
931 BYTE ValType = ELEMENT_TYPE_VOID;
932 void * pValue = NULL;
936 cSig = pFD->m_pbsSig->length();
937 mySig = (COR_SIGNATURE*)(pFD->m_pbsSig->ptr());
939 WszMultiByteToWideChar(g_uCodePage,0,pFD->m_szName,-1,wzFieldName,dwUniBuf); //int)cFieldNameLength);
940 if(IsFdPrivateScope(pFD->m_dwAttr))
942 WCHAR* p = wcsstr(wzFieldName,W("$PST04"));
946 if(pFD->m_pbsValue && pFD->m_pbsValue->length())
948 ValType = *(pFD->m_pbsValue->ptr());
949 lVal = pFD->m_pbsValue->length() - 1; // 1 is type byte
950 pValue = (void*)(pFD->m_pbsValue->ptr() + 1);
951 if(ValType == ELEMENT_TYPE_STRING)
953 //while(lVal % sizeof(WCHAR)) { pFD->m_pbsValue->appendInt8(0); lVal++; }
954 lVal /= sizeof(WCHAR);
956 #if defined(ALIGN_ACCESS) || BIGENDIAN
957 void* pValueTemp = _alloca(lVal * sizeof(WCHAR));
958 memcpy(pValueTemp, pValue, lVal * sizeof(WCHAR));
961 SwapStringLength((WCHAR*)pValue, lVal);
966 hr = m_pEmitter->DefineField(
979 report->error("Failed to define field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
984 //--------------------------------------------------------------------------------
985 if(IsFdPinvokeImpl(pFD->m_dwAttr)&&(pFD->m_pPInvoke))
987 if(pFD->m_pPInvoke->szAlias == NULL) pFD->m_pPInvoke->szAlias = pFD->m_szName;
988 if(FAILED(EmitPinvokeMap(mb,pFD->m_pPInvoke)))
990 report->error("Failed to define PInvoke map of .field '%s'\n",pFD->m_szName);
994 //--------------------------------------------------------------------------
995 if(pFD->m_pbsMarshal)
997 if(FAILED(hr = m_pEmitter->SetFieldMarshal (
998 mb, // [IN] given a fieldDef or paramDef token
999 (PCCOR_SIGNATURE)(pFD->m_pbsMarshal->ptr()), // [IN] native type specification
1000 pFD->m_pbsMarshal->length()))) // [IN] count of bytes of pvNativeType
1002 report->error("Failed to set field marshaling for '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
1006 //--------------------------------------------------------------------------------
1007 // Set the the RVA to a dummy value. later it will be fixed
1008 // up to be something correct, but if we don't emit something
1009 // the size of the meta-data will not be correct
1010 if (pFD->m_rvaLabel)
1012 m_fHaveFieldsWithRvas = TRUE;
1013 hr = m_pEmitter->SetFieldRVA(mb, 0xCCCCCCCC);
1016 report->error("Failed to set RVA for field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
1020 //--------------------------------------------------------------------------------
1021 EmitCustomAttributes(mb, &(pFD->m_CustomDescrList));
1024 pFD->m_fdFieldTok = mb;
1028 /**************************************************************************/
1029 void Assembler::EmitByte(int val)
1031 char ch = (char)val;
1032 //if((val < -128)||(val > 127))
1033 // report->warn("Emitting 0x%X as a byte: data truncated to 0x%X\n",(unsigned)val,(BYTE)ch);
1034 EmitBytes((BYTE *)&ch,1);
1037 /**************************************************************************/
1038 void Assembler::NewSEHDescriptor(void) //sets m_SEHD
1040 m_SEHDstack.PUSH(m_SEHD);
1041 m_SEHD = new SEH_Descriptor;
1042 if(m_SEHD == NULL) report->error("Failed to allocate SEH descriptor\n");
1044 /**************************************************************************/
1045 void Assembler::SetTryLabels(__in __nullterminated char * szFrom, __in __nullterminated char *szTo)
1048 Label *pLbl = m_pCurMethod->FindLabel(szFrom);
1051 m_SEHD->tryFrom = pLbl->m_PC;
1052 if((pLbl = m_pCurMethod->FindLabel(szTo))) m_SEHD->tryTo = pLbl->m_PC; //FindLabel: Method.CPP
1053 else report->error("Undefined 2nd label in 'try <label> to <label>'\n");
1055 else report->error("Undefined 1st label in 'try <label> to <label>'\n");
1057 /**************************************************************************/
1058 void Assembler::SetFilterLabel(__in __nullterminated char *szFilter)
1061 Label *pLbl = m_pCurMethod->FindLabel(szFilter);
1062 if(pLbl) m_SEHD->sehFilter = pLbl->m_PC;
1063 else report->error("Undefined label in 'filter <label>'\n");
1065 /**************************************************************************/
1066 void Assembler::SetCatchClass(mdToken catchClass)
1069 m_SEHD->cException = catchClass;
1072 /**************************************************************************/
1073 void Assembler::SetHandlerLabels(__in __nullterminated char *szHandlerFrom, __in __nullterminated char *szHandlerTo)
1076 Label *pLbl = m_pCurMethod->FindLabel(szHandlerFrom);
1079 m_SEHD->sehHandler = pLbl->m_PC;
1082 pLbl = m_pCurMethod->FindLabel(szHandlerTo);
1085 m_SEHD->sehHandlerTo = pLbl->m_PC;
1091 m_SEHD->sehHandlerTo = m_SEHD->sehHandler - 1;
1095 report->error("Undefined label in 'handler <label> to <label>'\n");
1097 /**************************************************************************/
1098 void Assembler::EmitTry(void) //enum CorExceptionFlag kind, char* beginLabel, char* endLabel, char* handleLabel, char* filterOrClass)
1102 bool isFilter=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FILTER),
1103 isFault=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FAULT),
1104 isFinally=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FINALLY);
1106 AddException(m_SEHD->tryFrom, m_SEHD->tryTo, m_SEHD->sehHandler, m_SEHD->sehHandlerTo,
1107 m_SEHD->cException, isFilter, isFault, isFinally);
1109 else report->error("Attempt to EmitTry with NULL SEH descriptor\n");
1111 /**************************************************************************/
1113 void Assembler::AddException(DWORD pcStart, DWORD pcEnd, DWORD pcHandler, DWORD pcHandlerTo, mdTypeRef crException, BOOL isFilter, BOOL isFault, BOOL isFinally)
1115 if (m_pCurMethod == NULL)
1117 report->error("Exceptions can be declared only when in a method scope\n");
1121 if (m_pCurMethod->m_dwNumExceptions >= m_pCurMethod->m_dwMaxNumExceptions)
1123 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *ptr =
1124 new COR_ILMETHOD_SECT_EH_CLAUSE_FAT[m_pCurMethod->m_dwMaxNumExceptions+MAX_EXCEPTIONS];
1127 report->error("Failed to reallocate SEH buffer\n");
1130 memcpy(ptr,m_pCurMethod->m_ExceptionList,m_pCurMethod->m_dwNumExceptions*sizeof(COR_ILMETHOD_SECT_EH_CLAUSE_FAT));
1131 delete [] m_pCurMethod->m_ExceptionList;
1132 m_pCurMethod->m_ExceptionList = ptr;
1133 m_pCurMethod->m_dwMaxNumExceptions += MAX_EXCEPTIONS;
1136 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *clause = &m_pCurMethod->m_ExceptionList[m_pCurMethod->m_dwNumExceptions];
1137 clause->SetTryOffset(pcStart);
1138 clause->SetTryLength(pcEnd - pcStart);
1139 clause->SetHandlerOffset(pcHandler);
1140 clause->SetHandlerLength(pcHandlerTo - pcHandler);
1141 clause->SetClassToken(crException);
1143 int flags = COR_ILEXCEPTION_CLAUSE_OFFSETLEN;
1145 flags |= COR_ILEXCEPTION_CLAUSE_FILTER;
1148 flags |= COR_ILEXCEPTION_CLAUSE_FAULT;
1151 flags |= COR_ILEXCEPTION_CLAUSE_FINALLY;
1153 clause->SetFlags((CorExceptionFlag)flags);
1155 m_pCurMethod->m_dwNumExceptions++;
1158 /**************************************************************************/
1159 void Assembler::EmitMaxStack(unsigned val)
1161 if(val > 0xFFFF) report->warn(".maxstack parameter exceeds 65535, truncated to %d\n",val&0xFFFF);
1162 if (m_pCurMethod) m_pCurMethod->m_MaxStack = val&0xFFFF;
1163 else report->error(".maxstack can be used only within a method scope\n");
1166 /**************************************************************************/
1167 void Assembler::EmitLocals(BinStr* sig)
1173 ARG_NAME_LIST *pAN, *pList= getArgNameList();
1177 for(pAN=pList; pAN; pAN = pAN->pNext)
1179 if(pAN->dwAttr == 0) pAN->dwAttr = m_pCurMethod->m_Locals.COUNT() +1;
1181 if((pVD = m_pCurMethod->m_Locals.PEEK(pAN->dwAttr)))
1185 report->warn("Local var slot %d is in use\n",pAN->dwAttr);
1187 if(pVD->pbsSig && ((pVD->pbsSig->length() != pAN->pSig->length()) ||
1188 (memcmp(pVD->pbsSig->ptr(),pAN->pSig->ptr(),pVD->pbsSig->length()))))
1190 report->error("Local var slot %d: type conflict\n",pAN->dwAttr);
1194 { // create new entry:
1195 for(unsigned n = m_pCurMethod->m_Locals.COUNT(); n <= pAN->dwAttr; n++)
1198 if(pVD != NULL) m_pCurMethod->m_Locals.PUSH(pVD);
1201 report->error("Out of memory allocating local var descriptor\n");
1207 pVD->dwSlot = pAN->dwAttr;
1208 pVD->pbsSig = pAN->pSig;
1209 pVD->bInScope = TRUE;
1211 if(pVD->pbsSig && (pVD->pbsSig->length() == 1))
1213 if(pVD->pbsSig->ptr()[0] == ELEMENT_TYPE_VOID)
1214 report->error("Illegal local var type: 'void'\n");
1216 m_pCurMethod->m_pCurrScope->pLocals =
1217 m_pCurMethod->catArgNameList(m_pCurMethod->m_pCurrScope->pLocals, pList);
1220 else report->error(".locals can be used only within a method scope\n");
1223 else report->error("Attempt to EmitLocals with NULL argument\n");
1226 /**************************************************************************/
1227 void Assembler::EmitEntryPoint()
1231 if(!m_fEntryPointPresent)
1233 if(IsMdStatic(m_pCurMethod->m_Attr))
1235 m_pCurMethod->m_fEntryPoint = TRUE;
1236 m_fEntryPointPresent = TRUE;
1238 else report->error("Non-static method as entry point\n");
1240 else report->error("Multiple .entrypoint declarations\n");
1242 else report->error(".entrypoint can be used only within a method scope\n");
1245 /**************************************************************************/
1246 void Assembler::EmitZeroInit()
1248 if (m_pCurMethod) m_pCurMethod->m_Flags |= CorILMethod_InitLocals;
1249 else report->error(".zeroinit can be used only within a method scope\n");
1252 /**************************************************************************/
1253 void Assembler::SetImplAttr(unsigned short attrval)
1257 if(IsMiNative(attrval)||IsMiOPTIL(attrval)||IsMiUnmanaged(attrval))
1258 report->error("Cannot compile native/unmanaged method\n");
1259 m_pCurMethod->m_wImplAttr = attrval;
1263 /**************************************************************************/
1264 void Assembler::EmitData(__in_opt void *buffer, unsigned len)
1269 HRESULT hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, len, 1, &ptr);
1272 report->error("Could not extend data section (out of memory?)");
1278 memcpy(ptr, buffer, len);
1282 memset(ptr, 0, len);
1287 /**************************************************************************/
1288 void Assembler::EmitDD(__in __nullterminated char *str)
1291 GlobalLabel *pLabel = FindGlobalLabel(str);
1294 HRESULT hr = m_pCeeFileGen->GetSectionDataLen(m_pCurSection, &loc);
1295 _ASSERTE(SUCCEEDED(hr));
1298 DWORD sizeofptr = (DWORD)((m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32) ? sizeof(DWORD) : sizeof(__int64));
1299 hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, sizeofptr, 1, (void**) &ptr);
1302 report->error("Could not extend data section (out of memory?)");
1307 dwAddr = pLabel->m_GlobalOffset;
1308 if (pLabel->m_Section != m_pGlobalDataSection) {
1309 report->error("For '&label', label must be in data section");
1310 m_State = STATE_FAIL;
1314 AddDeferredGlobalFixup(str, (BYTE*) ptr);
1316 hr = m_pCeeFileGen->AddSectionReloc(m_pCurSection, loc, m_pGlobalDataSection, srRelocHighLow);
1317 _ASSERTE(SUCCEEDED(hr));
1318 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
1320 report->error("Base relocations are emitted, while /STRIPRELOC option has been specified");
1322 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32)
1324 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1325 if (m_dwCeeFileFlags & ICEE_CREATE_MACHINE_I386)
1326 COR_SET_32BIT_REQUIRED(m_dwComImageFlags);
1331 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1332 *((__int64*)ptr) = (__int64)dwAddr;
1336 /**************************************************************************/
1337 GlobalLabel *Assembler::FindGlobalLabel(LPCUTF8 pszName)
1339 GlobalLabel lSearch(pszName,0,NULL), *pL;
1340 pL = m_lstGlobalLabel.FIND(&lSearch);
1341 lSearch.m_szName = NULL;
1343 //return m_lstGlobalLabel.FIND(pszName);
1346 /**************************************************************************/
1348 GlobalFixup *Assembler::AddDeferredGlobalFixup(__in __nullterminated char *pszLabel, BYTE* pReference)
1350 GlobalFixup *pNew = new GlobalFixup(pszLabel, (BYTE*) pReference);
1353 report->error("Failed to allocate global fixup\n");
1354 m_State = STATE_FAIL;
1357 m_lstGlobalFixup.PUSH(pNew);
1362 /**************************************************************************/
1363 void Assembler::AddDeferredILFixup(ILFixupType Kind)
1365 _ASSERTE(Kind != ilGlobal);
1366 AddDeferredILFixup(Kind, NULL);
1368 /**************************************************************************/
1370 void Assembler::AddDeferredILFixup(ILFixupType Kind,
1371 GlobalFixup *GFixup)
1373 ILFixup *pNew = new ILFixup(m_CurPC, Kind, GFixup);
1375 _ASSERTE(m_pCurMethod != NULL);
1378 report->error("Failed to allocate IL fixup\n");
1379 m_State = STATE_FAIL;
1382 m_pCurMethod->m_lstILFixup.PUSH(pNew);
1385 /**************************************************************************/
1386 void Assembler::EmitDataString(BinStr* str)
1391 DWORD DataLen = str->length();
1392 char *pb = (char*)(str->ptr());
1393 WCHAR *UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen] : &wzUniBuf[0];
1397 WszMultiByteToWideChar(g_uCodePage,0,pb,-1,UnicodeString,DataLen);
1398 EmitData(UnicodeString,DataLen*sizeof(WCHAR));
1399 if(DataLen >= dwUniBuf) delete [] UnicodeString;
1401 else report->error("\nOut of memory!\n");
1408 /**************************************************************************/
1409 unsigned Assembler::OpcodeLen(Instr* instr)
1411 return (m_fStdMapping ? OpcodeInfo[instr->opcode].Len : 3);
1413 /**************************************************************************/
1414 void Assembler::EmitOpcode(Instr* instr)
1416 if(m_fGeneratePDB &&
1417 ((instr->linenum != m_ulLastDebugLine)
1418 ||(instr->column != m_ulLastDebugColumn)
1419 ||(instr->linenum_end != m_ulLastDebugLineEnd)
1420 ||(instr->column_end != m_ulLastDebugColumnEnd)))
1424 LinePC *pLPC = new LinePC;
1427 pLPC->Line = instr->linenum;
1428 pLPC->Column = instr->column;
1429 pLPC->LineEnd = instr->linenum_end;
1430 pLPC->ColumnEnd = instr->column_end;
1432 pLPC->pWriter = instr->pWriter;
1433 m_pCurMethod->m_LinePCList.PUSH(pLPC);
1435 else report->error("\nOut of memory!\n");
1437 m_ulLastDebugLine = instr->linenum;
1438 m_ulLastDebugColumn = instr->column;
1439 m_ulLastDebugLineEnd = instr->linenum_end;
1440 m_ulLastDebugColumnEnd = instr->column_end;
1442 if(instr->opcode == CEE_ENDFILTER)
1446 if(m_pCurMethod->m_dwNumEndfilters >= m_pCurMethod->m_dwMaxNumEndfilters)
1448 DWORD *pdw = new DWORD[m_pCurMethod->m_dwMaxNumEndfilters+MAX_EXCEPTIONS];
1451 report->error("Failed to reallocate auxiliary SEH buffer\n");
1455 memcpy(pdw,m_pCurMethod->m_EndfilterOffsetList,m_pCurMethod->m_dwNumEndfilters*sizeof(DWORD));
1456 delete m_pCurMethod->m_EndfilterOffsetList;
1457 m_pCurMethod->m_EndfilterOffsetList = pdw;
1458 m_pCurMethod->m_dwMaxNumEndfilters += MAX_EXCEPTIONS;
1460 m_pCurMethod->m_EndfilterOffsetList[m_pCurMethod->m_dwNumEndfilters++] = m_CurPC+2;
1465 if (OpcodeInfo[instr->opcode].Len == 2)
1466 EmitByte(OpcodeInfo[instr->opcode].Std1);
1467 EmitByte(OpcodeInfo[instr->opcode].Std2);
1471 unsigned short us = (unsigned short)instr->opcode;
1473 EmitBytes((BYTE *)&us,2);
1478 /**************************************************************************/
1479 //void Assembler::OptimizeInstr(Instr* instr, int var)
1483 /**************************************************************************/
1484 unsigned Assembler::ShortOf(unsigned opcode)
1489 case CEE_LDARG: retcode=CEE_LDARG_S; break;
1490 case CEE_LDARGA: retcode=CEE_LDARGA_S; break;
1491 case CEE_STARG: retcode=CEE_STARG_S; break;
1493 case CEE_LDLOC: retcode=CEE_LDLOC_S; break;
1494 case CEE_LDLOCA: retcode=CEE_LDLOCA_S; break;
1495 case CEE_STLOC: retcode=CEE_STLOC_S; break;
1497 case CEE_BR: retcode=CEE_BR_S; break;
1498 case CEE_BRFALSE: retcode=CEE_BRFALSE_S; break;
1499 case CEE_BRTRUE: retcode=CEE_BRTRUE_S; break;
1500 case CEE_BEQ: retcode=CEE_BEQ_S; break;
1501 case CEE_BGE: retcode=CEE_BGE_S; break;
1502 case CEE_BGT: retcode=CEE_BGT_S; break;
1503 case CEE_BLE: retcode=CEE_BLE_S; break;
1504 case CEE_BLT: retcode=CEE_BLT_S; break;
1505 case CEE_BNE_UN: retcode=CEE_BNE_UN_S; break;
1506 case CEE_BGE_UN: retcode=CEE_BGE_UN_S; break;
1507 case CEE_BGT_UN: retcode=CEE_BGT_UN_S; break;
1508 case CEE_BLE_UN: retcode=CEE_BLE_UN_S; break;
1509 case CEE_BLT_UN: retcode=CEE_BLT_UN_S; break;
1510 case CEE_LEAVE: retcode=CEE_LEAVE_S; break;
1512 case CEE_LDC_I4: retcode=CEE_LDC_I4_S; break;
1513 case CEE_LDC_R8: retcode=CEE_LDC_R4; break;
1516 default: retcode = opcode; break;
1521 /**************************************************************************/
1522 void Assembler::EmitInstrVar(Instr* instr, int var)
1524 unsigned opc = instr->opcode;
1532 case CEE_LDARG_S: opc = CEE_LDARG_0 + var; break;
1535 case CEE_LDLOC_S: opc = CEE_LDLOC_0 + var; break;
1538 case CEE_STLOC_S: opc = CEE_STLOC_0 + var; break;
1542 if(opc != (unsigned) instr->opcode)
1544 instr->opcode = opc;
1551 opc = instr->opcode = ShortOf(opc);
1561 short sh = (short)var;
1562 EmitBytes((BYTE *)&sh,2);
1566 /**************************************************************************/
1567 void Assembler::EmitInstrVarByName(Instr* instr, __in __nullterminated char* label)
1569 int idx = -1, nArgVarFlag=0;
1570 switch(instr->opcode)
1588 DWORD L = (DWORD)strlen(label);
1589 if(nArgVarFlag == 1)
1591 idx = m_pCurMethod->findArgNum(m_pCurMethod->m_firstArgName,label,L);
1595 for(Scope* pSC = m_pCurMethod->m_pCurrScope; pSC; pSC=pSC->pSuperScope)
1597 idx = m_pCurMethod->findLocSlot(pSC->pLocals,label,L);
1601 if(idx >= 0) EmitInstrVar(instr,
1602 ((nArgVarFlag==0)||(m_pCurMethod->m_Attr & mdStatic))? idx : idx+1);
1603 else report->error("Undeclared identifier %s\n",label);
1606 report->error("Instructions can be used only when in a method scope\n");
1609 report->error("Named argument illegal for this instruction\n");
1611 instr->opcode = -1; // in case we got here with error
1614 /**************************************************************************/
1615 void Assembler::EmitInstrI(Instr* instr, int val)
1617 int opc = instr->opcode;
1620 if((val >= -1)&&(val <= 8))
1625 case CEE_LDC_I4_S: opc = CEE_LDC_I4_M1 + (val+1); break;
1629 if(opc != instr->opcode)
1631 instr->opcode = opc;
1636 if((-128 <= val)&&(val <= 127))
1638 opc = instr->opcode = ShortOf(opc);
1649 EmitBytes((BYTE *)&i,sizeof(int));
1653 /**************************************************************************/
1654 void Assembler::EmitInstrI8(Instr* instr, __int64* val)
1657 EmitBytes((BYTE *)val, sizeof(__int64));
1661 /**************************************************************************/
1662 void Assembler::EmitInstrR(Instr* instr, double* pval)
1664 unsigned opc = instr->opcode;
1668 float val = (float)*pval;
1669 EmitBytes((BYTE *)&val, sizeof(float));
1672 EmitBytes((BYTE *)pval, sizeof(double));
1675 /**************************************************************************/
1676 void Assembler::EmitInstrBrTarget(Instr* instr, __in __nullterminated char* label)
1678 Label * pLabel = m_pCurMethod->FindLabel(label);
1680 if (pLabel == NULL) // branching forward -- no optimization
1682 int pcrelsize = 1+(isShort(instr->opcode) ? 1 : 4); //size of the instruction plus argument
1683 AddDeferredFixup(label, m_pCurOutputPos+1,
1684 (m_CurPC + pcrelsize), pcrelsize-1);
1688 offset = pLabel->m_PC - m_CurPC;
1691 if((-128 <= offset-5)&&(offset-2 <= 127)) //need to take into account the argument size (worst cases)
1693 instr->opcode = ShortOf(instr->opcode);
1696 if(isShort(instr->opcode))
1699 if((-128 > offset)||(offset > 127))
1700 report->error("Offset too large for short branching instruction, truncated\n");
1706 int opc = instr->opcode;
1708 if(isShort(opc)) EmitByte(offset);
1709 else EmitBytes((BYTE *)&offset,4);
1711 /**************************************************************************/
1712 void Assembler::AddDeferredFixup(__in __nullterminated char *pszLabel, BYTE *pBytes, DWORD RelativeToPC, BYTE FixupSize)
1714 Fixup *pNew = new Fixup(pszLabel, pBytes, RelativeToPC, FixupSize);
1718 report->error("Failed to allocate deferred fixup\n");
1719 m_State = STATE_FAIL;
1722 m_pCurMethod->m_lstFixup.PUSH(pNew);
1724 /**************************************************************************/
1725 void Assembler::EmitInstrBrOffset(Instr* instr, int offset)
1727 unsigned opc=instr->opcode;
1730 if((-128 <= offset)&&(offset <= 127))
1732 opc = instr->opcode = ShortOf(opc);
1736 if(isShort(opc)) EmitByte(offset);
1740 EmitBytes((BYTE *)&i,4);
1744 /**************************************************************************/
1745 mdToken Assembler::MakeMemberRef(mdToken cr, __in __nullterminated char* pszMemberName, BinStr* sig)
1747 DWORD cSig = sig->length();
1748 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1749 mdToken mr = mdMemberRefNil;
1750 Class* pClass = NULL;
1751 if(cr == 0x00000001) cr = mdTokenNil; // Module -> nil for globals
1752 if(TypeFromToken(cr) == mdtTypeDef) pClass = m_lstClass.PEEK(RidFromToken(cr)-1);
1753 if((TypeFromToken(cr) == mdtTypeDef)||(cr == mdTokenNil))
1755 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1758 pMRD->m_tdClass = cr;
1759 pMRD->m_pClass = pClass;
1760 pMRD->m_szName = pszMemberName;
1761 pMRD->m_dwName = (DWORD)strlen(pszMemberName);
1762 pMRD->m_pSigBinStr = sig;
1763 pMRD->m_tkResolved = 0;
1764 if(*(sig->ptr())== IMAGE_CEE_CS_CALLCONV_FIELD)
1766 m_LocalFieldRefDList.PUSH(pMRD);
1767 mr = 0x98000000 | m_LocalFieldRefDList.COUNT();
1771 m_LocalMethodRefDList.PUSH(pMRD);
1772 mr = 0x99000000 | m_LocalMethodRefDList.COUNT();
1777 report->error("Failed to allocate MemberRef Descriptor\n");
1783 WszMultiByteToWideChar(g_uCodePage,0,pszMemberName,-1,wzUniBuf,dwUniBuf);
1785 if(cr == mdTokenNil) cr = mdTypeRefNil;
1786 if(TypeFromToken(cr) == mdtAssemblyRef)
1788 report->error("Cross-assembly global references are not supported ('%s')\n", pszMemberName);
1793 HRESULT hr = m_pEmitter->DefineMemberRef(cr, wzUniBuf, mySig, cSig, &mr);
1796 report->error("Unable to define member reference '%s'\n", pszMemberName);
1800 //if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,mr));
1801 delete pszMemberName;
1806 /**************************************************************************/
1807 void Assembler::SetMemberRefFixup(mdToken tk, unsigned opcode_len)
1811 switch(TypeFromToken(tk))
1816 if(m_pCurMethod != NULL)
1817 m_pCurMethod->m_LocalMemberRefFixupList.PUSH(
1818 new LocalMemberRefFixup(tk,(size_t)(m_CurPC + opcode_len)));
1824 /**************************************************************************/
1825 mdToken Assembler::MakeMethodSpec(mdToken tkParent, BinStr* sig)
1827 DWORD cSig = sig->length();
1828 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1829 mdMethodSpec mi = mdMethodSpecNil;
1830 if(TypeFromToken(tkParent) == 0x99000000) // Local MemberRef: postpone until resolved
1832 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1835 memset(pMRD,0,sizeof(MemberRefDescriptor));
1836 pMRD->m_tdClass = tkParent;
1837 pMRD->m_pSigBinStr = sig;
1838 m_MethodSpecList.PUSH(pMRD);
1839 mi = 0x9A000000 | m_MethodSpecList.COUNT();
1843 report->error("Failed to allocate MemberRef Descriptor\n");
1849 HRESULT hr = m_pEmitter->DefineMethodSpec(tkParent, mySig, cSig, &mi);
1852 report->error("Unable to define method instantiation");
1859 /**************************************************************************/
1860 void Assembler::EndEvent(void)
1862 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1863 if(m_pCurEvent->m_tkAddOn == 0)
1864 report->error("Event %s of class %s has no Add method. Event not emitted.",
1865 m_pCurEvent->m_szName,pClass->m_szFQN);
1866 else if(m_pCurEvent->m_tkRemoveOn == 0)
1867 report->error("Event %s of class %s has no Remove method. Event not emitted.",
1868 m_pCurEvent->m_szName,pClass->m_szFQN);
1871 pClass->m_EventDList.PUSH(m_pCurEvent);
1872 pClass->m_fNewMembers = TRUE;
1875 m_tkCurrentCVOwner = 0;
1876 m_pCustomDescrList = m_CustomDescrListStack.POP();
1879 void Assembler::ResetEvent(__inout_z __inout char* szName, mdToken typeSpec, DWORD dwAttr)
1881 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1883 char c = szName[MAX_CLASSNAME_LENGTH-1];
1884 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1885 report->error("Event '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1886 szName[MAX_CLASSNAME_LENGTH-1] = c;
1888 if((m_pCurEvent = new EventDescriptor))
1890 memset(m_pCurEvent,0,sizeof(EventDescriptor));
1891 m_pCurEvent->m_tdClass = m_pCurClass->m_cl;
1892 m_pCurEvent->m_szName = szName;
1893 m_pCurEvent->m_dwAttr = dwAttr;
1894 m_pCurEvent->m_tkEventType = typeSpec;
1895 m_pCurEvent->m_fNew = TRUE;
1896 m_tkCurrentCVOwner = 0;
1897 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1898 m_pCustomDescrList = &(m_pCurEvent->m_CustomDescrList);
1900 else report->error("Failed to allocate Event Descriptor\n");
1903 void Assembler::SetEventMethod(int MethodCode, mdToken tk)
1908 m_pCurEvent->m_tkAddOn = tk;
1911 m_pCurEvent->m_tkRemoveOn = tk;
1914 m_pCurEvent->m_tkFire = tk;
1917 m_pCurEvent->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
1921 /**************************************************************************/
1923 void Assembler::EndProp(void)
1925 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1926 pClass->m_PropDList.PUSH(m_pCurProp);
1927 pClass->m_fNewMembers = TRUE;
1929 m_tkCurrentCVOwner = 0;
1930 m_pCustomDescrList = m_CustomDescrListStack.POP();
1933 void Assembler::ResetProp(__inout_z __inout char * szName, BinStr* bsType, DWORD dwAttr, BinStr* pValue)
1935 DWORD cSig = bsType->length();
1936 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(bsType->ptr());
1938 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1940 char c = szName[MAX_CLASSNAME_LENGTH-1];
1941 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1942 report->error("Property '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1943 szName[MAX_CLASSNAME_LENGTH-1] = c;
1945 m_pCurProp = new PropDescriptor;
1946 if(m_pCurProp == NULL)
1948 report->error("Failed to allocate Property Descriptor\n");
1951 memset(m_pCurProp,0,sizeof(PropDescriptor));
1952 m_pCurProp->m_tdClass = m_pCurClass->m_cl;
1953 m_pCurProp->m_szName = szName;
1954 m_pCurProp->m_dwAttr = dwAttr;
1955 m_pCurProp->m_fNew = TRUE;
1957 m_pCurProp->m_pSig = new COR_SIGNATURE[cSig];
1958 if(m_pCurProp->m_pSig == NULL)
1960 report->error("\nOut of memory!\n");
1963 memcpy(m_pCurProp->m_pSig,mySig,cSig);
1964 m_pCurProp->m_dwCSig = cSig;
1966 if(pValue && pValue->length())
1968 BYTE* pch = pValue->ptr();
1969 m_pCurProp->m_dwCPlusTypeFlag = (DWORD)(*pch);
1970 m_pCurProp->m_cbValue = pValue->length() - 1;
1971 m_pCurProp->m_pValue = (PVOID)(pch+1);
1972 if(m_pCurProp->m_dwCPlusTypeFlag == ELEMENT_TYPE_STRING) m_pCurProp->m_cbValue /= sizeof(WCHAR);
1973 m_pCurProp->m_dwAttr |= prHasDefault;
1977 m_pCurProp->m_dwCPlusTypeFlag = ELEMENT_TYPE_VOID;
1978 m_pCurProp->m_pValue = NULL;
1979 m_pCurProp->m_cbValue = 0;
1981 m_tkCurrentCVOwner = 0;
1982 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1983 m_pCustomDescrList = &(m_pCurProp->m_CustomDescrList);
1986 void Assembler::SetPropMethod(int MethodCode, mdToken tk)
1991 m_pCurProp->m_tkSet = tk;
1994 m_pCurProp->m_tkGet = tk;
1997 m_pCurProp->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
2002 /**************************************************************************/
2003 void Assembler::EmitInstrStringLiteral(Instr* instr, BinStr* literal, BOOL ConvertToUnicode, BOOL Swap /*=FALSE*/)
2005 DWORD DataLen = literal->length(),L;
2006 unsigned __int8 *pb = literal->ptr();
2009 WCHAR *UnicodeString;
2012 //report->warn("Zero length string emitted\n");
2013 ConvertToUnicode = FALSE;
2015 if(ConvertToUnicode)
2017 UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen+1] : &wzUniBuf[0];
2018 literal->appendInt8(0);
2019 pb = literal->ptr();
2020 // convert string to Unicode
2021 L = UnicodeString ? WszMultiByteToWideChar(g_uCodePage,0,(char*)pb,-1,UnicodeString,DataLen+1) : 0;
2024 const char* sz=NULL;
2026 switch(dw=GetLastError())
2028 case ERROR_INSUFFICIENT_BUFFER: sz = "ERROR_INSUFFICIENT_BUFFER"; break;
2029 case ERROR_INVALID_FLAGS: sz = "ERROR_INVALID_FLAGS"; break;
2030 case ERROR_INVALID_PARAMETER: sz = "ERROR_INVALID_PARAMETER"; break;
2031 case ERROR_NO_UNICODE_TRANSLATION: sz = "ERROR_NO_UNICODE_TRANSLATION"; break;
2033 if(sz) report->error("Failed to convert string '%s' to Unicode: %s\n",(char*)pb,sz);
2034 else report->error("Failed to convert string '%s' to Unicode: error 0x%08X\n",(char*)pb,dw);
2044 literal->appendInt8(0);
2045 pb = literal->ptr();
2048 UnicodeString = (WCHAR*)pb;
2049 L = DataLen/sizeof(WCHAR);
2053 SwapStringLength(UnicodeString, L);
2056 // Add the string data to the metadata, which will fold dupes.
2057 hr = m_pEmitter->DefineUserString(
2064 report->error("Failed to add user string using DefineUserString, hr=0x%08x, data: '%S'\n",
2071 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,tk));
2073 EmitBytes((BYTE *)&tk,sizeof(mdToken));
2077 if(((void*)UnicodeString != (void*)pb)&&(DataLen >= dwUniBuf)) delete [] UnicodeString;
2078 instr->opcode = -1; // in case we got here with error
2081 /**************************************************************************/
2082 void Assembler::EmitInstrSig(Instr* instr, BinStr* sig)
2084 mdSignature MetadataToken;
2085 DWORD cSig = sig->length();
2086 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
2088 if (FAILED(m_pEmitter->GetTokenFromSig(mySig, cSig, &MetadataToken)))
2090 report->error("Unable to convert signature to metadata token.\n");
2096 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,MetadataToken));
2097 EmitBytes((BYTE *)&MetadataToken, sizeof(mdSignature));
2100 instr->opcode = -1; // in case we got here with error
2103 /**************************************************************************/
2104 void Assembler::EmitInstrSwitch(Instr* instr, Labels* targets)
2114 for(pLbls = targets, NumLabels = 0; pLbls; pLbls = pLbls->Next, NumLabels++);
2116 EmitBytes((BYTE *)&NumLabels,sizeof(int));
2117 DWORD PC_nextInstr = m_CurPC + 4*NumLabels;
2118 for(pLbls = targets; pLbls; pLbls = pLbls->Next)
2122 if((pLabel = m_pCurMethod->FindLabel(pLbls->Label)))
2124 offset = pLabel->m_PC - PC_nextInstr;
2125 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2129 // defer until we find the label
2130 AddDeferredFixup(pLbls->Label, m_pCurOutputPos, PC_nextInstr, 4 /* pcrelsize */ );
2132 pLbls->Label = NULL;
2133 if (m_fDisplayTraceOutput) report->msg("forward label %s\n", pLbls->Label);
2138 offset = (UINT)(UINT_PTR)pLbls->Label;
2139 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2141 EmitBytes((BYTE *)&offset, sizeof(UINT));
2146 /**************************************************************************/
2147 void Assembler::EmitLabel(__in __nullterminated char* label)
2149 _ASSERTE(m_pCurMethod);
2150 AddLabel(m_CurPC, label);
2152 /**************************************************************************/
2153 void Assembler::EmitDataLabel(__in __nullterminated char* label)
2155 AddGlobalLabel(label, m_pCurSection);
2158 /**************************************************************************/
2159 void Assembler::EmitBytes(BYTE *p, unsigned len)
2161 if(m_pCurOutputPos + len >= m_pEndOutputPos)
2163 size_t buflen = m_pEndOutputPos - m_pOutputBuffer;
2164 size_t newlen = buflen+(len/OUTPUT_BUFFER_INCREMENT + 1)*OUTPUT_BUFFER_INCREMENT;
2165 BYTE *pb = new BYTE[newlen];
2168 report->error("Failed to extend output buffer from %d to %d bytes. Aborting\n",
2172 size_t delta = pb - m_pOutputBuffer;
2175 GlobalFixup *pGSearch;
2176 for (i=0; (pSearch = m_pCurMethod->m_lstFixup.PEEK(i)); i++) pSearch->m_pBytes += delta;
2177 for (i=0; (pGSearch = m_lstGlobalFixup.PEEK(i)); i++) //need to move only those pointing to output buffer
2179 if((pGSearch->m_pReference >= m_pOutputBuffer)&&(pGSearch->m_pReference <= m_pEndOutputPos))
2180 pGSearch->m_pReference += delta;
2184 memcpy(pb,m_pOutputBuffer,m_CurPC);
2185 delete m_pOutputBuffer;
2186 m_pOutputBuffer = pb;
2187 m_pCurOutputPos = &m_pOutputBuffer[m_CurPC];
2188 m_pEndOutputPos = &m_pOutputBuffer[newlen];
2195 *m_pCurOutputPos = *p;
2198 SET_UNALIGNED_VAL16(m_pCurOutputPos, GET_UNALIGNED_16(p));
2201 SET_UNALIGNED_VAL32(m_pCurOutputPos, GET_UNALIGNED_32(p));
2204 SET_UNALIGNED_VAL64(m_pCurOutputPos, GET_UNALIGNED_64(p));
2211 m_pCurOutputPos += len;
2214 /**************************************************************************/
2215 BinStr* Assembler::EncodeSecAttr(__in __nullterminated char* szReflName, BinStr* pbsSecAttrBlob, unsigned nProps)
2219 // build the blob As BinStr
2220 unsigned L = (unsigned) strlen(szReflName);
2222 BinStr* pbsRet = new BinStr();
2223 // encode the Reflection name length
2224 cnt = CorSigCompressData(L, pbsRet->getBuff(5));
2225 pbsRet->remove(5 - cnt);
2227 if((pb = pbsRet->getBuff(L)) != NULL)
2228 memcpy(pb,szReflName,L);
2229 // find out the size of compressed nProps
2230 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2233 unsigned nSize = cnt + pbsSecAttrBlob->length();
2234 cnt = CorSigCompressData(nSize, pbsRet->getBuff(5));
2235 pbsRet->remove(5 - cnt);
2236 // actually encode nProps
2237 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2238 pbsRet->remove(5 - cnt);
2239 // append the props/values blob
2240 pbsRet->append(pbsSecAttrBlob);
2241 delete pbsSecAttrBlob;
2244 /**************************************************************************/
2245 void Assembler::EmitSecurityInfo(mdToken token,
2246 PermissionDecl* pPermissions,
2247 PermissionSetDecl* pPermissionSets)
2249 PermissionDecl *pPerm, *pPermNext;
2250 PermissionSetDecl *pPset, *pPsetNext;
2251 unsigned uCount = 0;
2252 COR_SECATTR *pAttrs;
2255 mdTypeRef tkTypeRef;
2258 DWORD dwErrorIndex = 0;
2262 for (pPerm = pPermissions; pPerm; pPerm = pPerm->m_Next)
2265 _ASSERTE(uCount > 0);
2266 // uCount is expected to be positive all the time. The if statement is here to please prefast.
2269 if((pAttrs = new COR_SECATTR[uCount])==NULL)
2271 report->error("\nOut of memory!\n");
2275 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetAsmRef("mscorlib");
2276 tkTypeRef = ResolveClassRef(tkMscorlib,"System.Security.Permissions.SecurityAction", NULL);
2277 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2278 pPermNext = pPerm->m_Next;
2280 pSig = new BinStr();
2281 pSig->appendInt8(IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS);
2282 pSig->appendInt8(1);
2283 pSig->appendInt8(ELEMENT_TYPE_VOID);
2284 pSig->appendInt8(ELEMENT_TYPE_VALUETYPE);
2285 uLength = CorSigCompressToken(tkTypeRef, pSig->getBuff(5));
2286 pSig->remove(5 - uLength);
2288 uLength = (unsigned)strlen(COR_CTOR_METHOD_NAME) + 1;
2289 if((szMemberName = new char[uLength]))
2291 memcpy(szMemberName, COR_CTOR_METHOD_NAME, uLength);
2292 pAttrs[i].tkCtor = MakeMemberRef(pPerm->m_TypeSpec, szMemberName, pSig);
2293 pAttrs[i].pCustomAttribute = (const void *)pPerm->m_Blob;
2294 pAttrs[i].cbCustomAttribute = pPerm->m_BlobLength;
2296 else report->error("\nOut of memory!\n");
2299 if (FAILED(m_pEmitter->DefineSecurityAttributeSet(token,
2304 _ASSERT(uCount >= dwErrorIndex);
2305 if (dwErrorIndex == uCount)
2307 report->error("Failed to define security attribute set for 0x%08X\n", token);
2311 report->error("Failed to define security attribute set for 0x%08X\n (error in permission %u)\n",
2312 token, uCount - dwErrorIndex);
2316 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2317 pPermNext = pPerm->m_Next;
2323 for (pPset = pPermissionSets; pPset; pPset = pPsetNext) {
2324 pPsetNext = pPset->m_Next;
2325 if(FAILED(m_pEmitter->DefinePermissionSet(token,
2327 pPset->m_Value->ptr(),
2328 pPset->m_Value->length(),
2330 report->error("Failed to define security permission set for 0x%08X\n", token);
2335 void Assembler::AddMethodImpl(mdToken tkImplementedTypeSpec, __in __nullterminated char* szImplementedName, BinStr* pImplementedSig,
2336 mdToken tkImplementingTypeSpec, __in_opt __nullterminated char* szImplementingName, BinStr* pImplementingSig)
2340 MethodImplDescriptor* pMID = new MethodImplDescriptor;
2341 pMID->m_fNew = TRUE;
2344 report->error("Failed to allocate MethodImpl Descriptor\n");
2347 pMID->m_tkDefiningClass = m_pCurClass->m_cl;
2348 if(szImplementingName) //called from class scope, overriding method specified
2350 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2351 pMID->m_tkImplementingMethod = MakeMemberRef(tkImplementingTypeSpec,szImplementingName,pImplementingSig);
2353 else //called from method scope, use current method as overriding
2357 if (pImplementedSig == NULL)
2359 pImplementedSig = new BinStr();
2360 memcpy(pImplementedSig->getBuff(m_pCurMethod->m_dwMethodCSig), m_pCurMethod->m_pMethodSig,m_pCurMethod->m_dwMethodCSig);
2362 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2363 pMID->m_tkImplementingMethod = 0;
2365 m_pCurMethod->m_MethodImplDList.PUSH(pMID); // copy goes to method's own list (ptr only)
2369 report->error("No overriding method specified");
2374 m_MethodImplDList.PUSH(pMID);
2377 report->error(".override directive outside class scope");
2379 // source file name paraphernalia
2380 void Assembler::SetSourceFileName(__in __nullterminated char* szName)
2386 if(strcmp(m_szSourceFileName,szName))
2388 strcpy_s(m_szSourceFileName,MAX_FILENAME_LENGTH*3+1,szName);
2389 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,m_wzSourceFileName,MAX_FILENAME_LENGTH);
2395 while((pDW = m_DocWriterList.PEEK(i++)) != NULL)
2397 if(!strcmp(szName,pDW->Name)) break;
2401 m_pSymDocument = pDW->pWriter;
2404 else if(m_pSymWriter)
2407 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,wzUniBuf,dwUniBuf);
2408 if(FAILED(hr=m_pSymWriter->DefineDocument(wzUniBuf,&m_guidLang,
2409 &m_guidLangVendor,&m_guidDoc,&m_pSymDocument)))
2411 m_pSymDocument = NULL;
2412 report->error("Failed to define a document writer");
2414 if((pDW = new DocWriter()) != NULL)
2417 pDW->pWriter = m_pSymDocument;
2418 m_DocWriterList.PUSH(pDW);
2422 report->error("Out of memory");
2426 else delete [] szName;
2428 else delete [] szName;
2430 else delete [] szName;
2433 void Assembler::SetSourceFileName(BinStr* pbsName)
2436 if(pbsName && (L = (ULONG)(pbsName->length())))
2438 pbsName->appendInt8(0);
2439 char* sz = new char[L+1];
2440 memcpy(sz,pbsName->ptr(),L+1);
2441 SetSourceFileName(sz);