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 if(RidFromToken(m_pManifest->GetAsmRefTokByName("System.Runtime")) != 0)
281 return GetAsmRef("System.Runtime");
284 return GetAsmRef("mscorlib");
287 mdToken Assembler::GetInterfaceImpl(mdToken tsClass, mdToken tsInterface)
289 mdToken result = mdTokenNil;
291 ULONG actualInterfaces;
292 mdInterfaceImpl impls;
294 while (SUCCEEDED(m_pImporter->EnumInterfaceImpls(&iiEnum, tsClass, &impls, 1, &actualInterfaces)))
296 if (actualInterfaces == 1)
298 mdToken classToken, interfaceToken;
299 if (FAILED(m_pImporter->GetInterfaceImplProps(impls, &classToken, &interfaceToken)))
301 if (classToken == tsClass && interfaceToken == tsInterface)
308 m_pImporter->CloseEnum(iiEnum);
312 /**************************************************************************/
313 mdToken Assembler::GetModRef(__in __nullterminated char* szName)
315 mdToken tkResScope = 0;
316 if(!strcmp(szName,m_szScopeName))
317 tkResScope = 1; // scope is "this module"
320 ImportDescriptor* pID;
322 tkResScope = mdModuleRefNil;
323 DWORD L = (DWORD)strlen(szName);
324 while((pID=m_ImportList.PEEK(i++)))
326 if(pID->dwDllName != L) continue;
327 if((L > 0) && (strcmp(pID->szDllName,szName)!=0)) continue;
328 tkResScope = pID->mrDll;
331 if(RidFromToken(tkResScope)==0)
332 report->error("Undefined module ref '%s'\n",szName);
336 /**************************************************************************/
337 mdToken Assembler::MakeTypeRef(mdToken tkResScope, LPCUTF8 pszFullClassName)
339 mdToken tkRet = mdTokenNil;
340 if(pszFullClassName && *pszFullClassName)
343 if((pc = strrchr(pszFullClassName,NESTING_SEP))) // scope: enclosing class
346 DWORD L = (DWORD)(pc-pszFullClassName);
347 if((szScopeName = new char[L+1]) != NULL)
349 memcpy(szScopeName,pszFullClassName,L);
351 tkResScope = MakeTypeRef(tkResScope,szScopeName);
352 delete [] szScopeName;
355 report->error("\nOut of memory!\n");
358 else pc = pszFullClassName;
361 // convert name to widechar
362 WszMultiByteToWideChar(g_uCodePage,0,pc,-1,wzUniBuf,dwUniBuf);
363 if(FAILED(m_pEmitter->DefineTypeRefByName(tkResScope, wzUniBuf, &tkRet))) tkRet = mdTokenNil;
368 /**************************************************************************/
370 DWORD Assembler::CheckClassFlagsIfNested(Class* pEncloser, DWORD attr)
372 DWORD wasAttr = attr;
373 if(pEncloser && (!IsTdNested(attr)))
376 report->error("Nested class has non-nested visibility (0x%08X)\n",attr);
379 attr &= ~tdVisibilityMask;
380 attr |= (IsTdPublic(wasAttr) ? tdNestedPublic : tdNestedPrivate);
381 report->warn("Nested class has non-nested visibility (0x%08X), changed to nested (0x%08X)\n",wasAttr,attr);
384 else if((pEncloser==NULL) && IsTdNested(attr))
387 report->error("Non-nested class has nested visibility (0x%08X)\n",attr);
390 attr &= ~tdVisibilityMask;
391 attr |= (IsTdNestedPublic(wasAttr) ? tdPublic : tdNotPublic);
392 report->warn("Non-nested class has nested visibility (0x%08X), changed to non-nested (0x%08X)\n",wasAttr,attr);
398 /**************************************************************************/
400 void Assembler::StartClass(__in __nullterminated char* name, DWORD attr, TyParList *typars)
402 Class *pEnclosingClass = m_pCurClass;
406 m_TyParList = typars;
408 if (m_pCurMethod != NULL)
410 report->error("Class cannot be declared within a method scope\n");
414 LL = pEnclosingClass->m_dwFQN+(ULONG)strlen(name)+2;
415 if((szFQN = new char[LL]))
416 sprintf_s(szFQN,LL,"%s%c%s",pEnclosingClass->m_szFQN,NESTING_SEP,name);
418 report->error("\nOut of memory!\n");
422 unsigned L = (unsigned)strlen(m_szFullNS);
423 unsigned LLL = (unsigned)strlen(name);
424 LL = L + LLL + (L ? 2 : 1);
425 if((szFQN = new char[LL]))
427 if(L) sprintf_s(szFQN,LL,"%s.%s",m_szFullNS,name);
428 else memcpy(szFQN,name,LL);
429 if(LL > MAX_CLASSNAME_LENGTH)
431 report->error("Full class name too long (%d characters, %d allowed).\n",LL-1,MAX_CLASSNAME_LENGTH-1);
435 report->error("\nOut of memory!\n");
437 if(szFQN == NULL) return;
441 tkThis = ResolveClassRef(1,szFQN,&m_pCurClass); // boils down to FindCreateClass(szFQN)
444 m_pCurClass = FindCreateClass(szFQN);
445 tkThis = m_pCurClass->m_cl;
447 if(m_pCurClass->m_bIsMaster)
449 m_pCurClass->m_Attr = CheckClassFlagsIfNested(pEnclosingClass, attr);
453 //m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&m_pCurClass->m_TyParBounds, &m_pCurClass->m_TyParNames, &m_pCurClass->m_TyParAttrs);
454 m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&(m_pCurClass->m_TyPars));
458 else m_pCurClass->m_NumTyPars = 0;
459 m_pCurClass->m_pEncloser = pEnclosingClass;
460 } // end if(old class) else
461 m_tkCurrentCVOwner = 0;
462 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
463 m_pCustomDescrList = &(m_pCurClass->m_CustDList);
465 m_ClassStack.PUSH(pEnclosingClass);
469 /**************************************************************************/
471 void Assembler::AddClass()
473 mdTypeRef crExtends = mdTypeRefNil;
474 BOOL bIsEnum = FALSE;
475 BOOL bIsValueType = FALSE;
477 if(m_pCurClass->m_bIsMaster)
479 DWORD attr = m_pCurClass->m_Attr;
480 if(!IsNilToken(m_crExtends))
483 if(IsTdInterface(attr)) report->error("Base class in interface\n");
484 bIsValueType = (m_crExtends == m_tkSysValue)&&(m_pCurClass->m_cl != m_tkSysEnum);
485 bIsEnum = (m_crExtends == m_tkSysEnum);
486 crExtends = m_crExtends;
490 bIsEnum = ((attr & 0x40000000) != 0);
491 bIsValueType = ((attr & 0x80000000) != 0);
494 if (m_fAutoInheritFromObject && (crExtends == mdTypeRefNil) && (!IsTdInterface(attr)))
496 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetBaseAsmRef();
497 crExtends = bIsEnum ?
498 ResolveClassRef(tkMscorlib,"System.Enum",NULL)
500 ResolveClassRef(tkMscorlib,"System.ValueType",NULL)
501 : ResolveClassRef(tkMscorlib, "System.Object",NULL));
503 m_pCurClass->m_Attr = attr;
504 m_pCurClass->m_crExtends = (m_pCurClass->m_cl == m_tkSysObject)? mdTypeRefNil : crExtends;
506 if ((m_pCurClass->m_dwNumInterfaces = m_nImplList) != NULL)
508 if(bIsEnum) report->error("Enum implementing interface(s)\n");
509 if((m_pCurClass->m_crImplements = new mdTypeRef[m_nImplList+1]) != NULL)
510 memcpy(m_pCurClass->m_crImplements, m_crImplList, (m_nImplList+1)*sizeof(mdTypeRef));
513 report->error("Failed to allocate Impl List for class '%s'\n", m_pCurClass->m_szFQN);
514 m_pCurClass->m_dwNumInterfaces = 0;
517 else m_pCurClass->m_crImplements = NULL;
520 if(!IsTdSealed(attr))
522 if(OnErrGo) report->error("Non-sealed value class\n");
525 report->warn("Non-sealed value class, made sealed\n");
526 m_pCurClass->m_Attr |= tdSealed;
530 m_pCurClass->m_bIsMaster = FALSE;
531 } // end if(old class) else
533 m_crExtends = mdTypeRefNil;
536 /**************************************************************************/
537 void Assembler::EndClass()
539 m_pCurClass = m_ClassStack.POP();
540 m_tkCurrentCVOwner = 0;
541 m_pCustomDescrList = m_CustomDescrListStack.POP();
544 /**************************************************************************/
545 void Assembler::SetPinvoke(BinStr* DllName, int Ordinal, BinStr* Alias, int Attrs)
547 if(m_pPInvoke) delete m_pPInvoke;
548 if(DllName->length())
550 if((m_pPInvoke = new PInvokeDescriptor))
553 ImportDescriptor* pID;
554 if((pID = EmitImport(DllName)))
556 m_pPInvoke->mrDll = pID->mrDll;
557 m_pPInvoke->szAlias = NULL;
561 if((m_pPInvoke->szAlias = new char[l+1]))
563 memcpy(m_pPInvoke->szAlias,Alias->ptr(),l);
564 m_pPInvoke->szAlias[l] = 0;
566 else report->error("\nOut of memory!\n");
568 m_pPInvoke->dwAttrs = (DWORD)Attrs;
574 report->error("PInvoke refers to undefined imported DLL\n");
578 report->error("Failed to allocate PInvokeDescriptor\n");
582 m_pPInvoke = NULL; // No DLL name, it's "local" (IJW) PInvoke
583 report->error("Local (embedded native) PInvoke method, the resulting PE file is unusable\n");
585 if(DllName) delete DllName;
586 if(Alias) delete Alias;
589 /**************************************************************************/
590 void Assembler::StartMethod(__in __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars)
592 if (m_pCurMethod != NULL)
594 report->error("Cannot declare a method '%s' within another method\n",name);
596 if (!m_fInitialisedMetaData)
598 if (FAILED(InitMetaData())) // impl. see WRITER.CPP
603 size_t namelen = strlen(name);
604 if(namelen >= MAX_CLASSNAME_LENGTH)
606 char c = name[MAX_CLASSNAME_LENGTH-1];
607 name[MAX_CLASSNAME_LENGTH-1] = 0;
608 report->error("Method '%s...' -- name too long (%d characters).\n",name,namelen);
609 name[MAX_CLASSNAME_LENGTH-1] = c;
611 if (!(flags & mdStatic))
612 *(sig->ptr()) |= IMAGE_CEE_CS_CALLCONV_HASTHIS;
613 else if(*(sig->ptr()) & (IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS))
615 if(OnErrGo) report->error("Method '%s' -- both static and instance\n", name);
618 report->warn("Method '%s' -- both static and instance, set to static\n", name);
619 *(sig->ptr()) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
623 if(!IsMdPrivateScope(flags))
626 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
627 DWORD L = (DWORD)strlen(name);
628 for(int j=0; (pMethod = pClass->m_MethodList.PEEK(j)); j++)
630 if( (pMethod->m_dwName == L) &&
631 (!strcmp(pMethod->m_szName,name)) &&
632 (pMethod->m_dwMethodCSig == sig->length()) &&
633 (!memcmp(pMethod->m_pMethodSig,sig->ptr(),sig->length()))
634 &&(!IsMdPrivateScope(pMethod->m_Attr)))
636 if(m_fTolerateDupMethods)
638 // reset for new body
639 pMethod->m_lstFixup.RESET(true);
640 //pMethod->m_lstLabel.RESET(true);
641 m_lstLabel.RESET(true);
642 pMethod->m_Locals.RESET(true);
643 delArgNameList(pMethod->m_firstArgName);
644 delArgNameList(pMethod->m_firstVarName);
645 pMethod->m_pCurrScope = &(pMethod->m_MainScope);
646 pMethod->m_pCurrScope->Reset();
647 pMethod->m_firstArgName = getArgNameList();
648 pMethod->m_dwNumExceptions = 0;
649 pMethod->m_dwNumEndfilters = 0;
650 if(pMethod->m_pRetMarshal) delete pMethod->m_pRetMarshal;
651 if(pMethod->m_pRetValue) delete pMethod->m_pRetValue;
653 pMethod->m_MethodImplDList.RESET(false); // ptrs in m_MethodImplDList are dups of those in Assembler
655 pMethod->m_CustomDescrList.RESET(true);
657 if(pMethod->m_fEntryPoint)
659 pMethod->m_fEntryPoint = FALSE;
660 m_fEntryPointPresent = FALSE;
663 if(pMethod->m_pbsBody)
665 // no need to remove relevant MemberRef Fixups from the Assembler list:
666 // their m_fNew flag is set to FALSE anyway.
667 // Just get rid of old method body
668 delete pMethod->m_pbsBody;
669 pMethod->m_pbsBody = NULL;
672 pMethod->m_fNewBody = TRUE;
673 m_pCurMethod = pMethod;
676 report->error("Duplicate method declaration\n");
681 if(m_pCurMethod == NULL)
685 if(IsMdAbstract(flags) && !IsTdAbstract(m_pCurClass->m_Attr))
687 report->error("Abstract method '%s' in non-abstract class '%s'\n",name,m_pCurClass->m_szFQN);
689 if(m_pCurClass->m_crExtends == m_tkSysEnum) report->error("Method in enum\n");
691 if(!strcmp(name,COR_CTOR_METHOD_NAME))
693 flags = (CorMethodAttr)(flags | mdSpecialName);
694 if(IsTdInterface(m_pCurClass->m_Attr)) report->error("Instance constructor in interface\n");
697 if(!IsMdStatic(flags))
699 if(IsTdInterface(m_pCurClass->m_Attr))
701 if(!IsMdPublic(flags)) report->error("Non-public instance method in interface\n");
702 if((!(IsMdVirtual(flags) && IsMdAbstract(flags))))
704 if(OnErrGo) report->error("Non-virtual, non-abstract instance method in interface\n");
707 report->warn("Non-virtual, non-abstract instance method in interface, set to such\n");
708 flags = (CorMethodAttr)(flags |mdVirtual | mdAbstract);
714 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
718 if(IsMdAbstract(flags))
720 if(OnErrGo) report->error("Global method '%s' can't be abstract\n",name);
723 report->warn("Global method '%s' can't be abstract, flag removed\n",name);
724 flags = (CorMethodAttr)(((int) flags) &~mdAbstract);
727 if(!IsMdStatic(flags))
729 if(OnErrGo) report->error("Non-static global method '%s'\n",name);
732 report->warn("Non-static global method '%s', made static\n",name);
733 flags = (CorMethodAttr)(flags | mdStatic);
734 *((BYTE*)(sig->ptr())) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
737 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
740 m_pCurMethod->SetIsGlobalMethod();
741 if (m_fInitialisedMetaData == FALSE) InitMetaData();
748 if(m_pCurMethod->m_firstArgName)
750 for(ARG_NAME_LIST *pAN=m_pCurMethod->m_firstArgName; pAN; pAN = pAN->pNext)
754 int k = m_pCurMethod->findArgNum(pAN->pNext,pAN->szName,pAN->dwName);
756 report->warn("Duplicate param name '%s' in method '%s'\n",pAN->szName,name);
761 m_pCurMethod->m_pRetMarshal = retMarshal;
762 m_pCurMethod->m_dwRetAttr = retAttr;
763 m_tkCurrentCVOwner = 0;
764 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
765 m_pCustomDescrList = &(m_pCurMethod->m_CustomDescrList);
766 m_pCurMethod->m_MainScope.dwStart = m_CurPC;
769 //m_pCurMethod->m_NumTyPars = typars->ToArray(&m_pCurMethod->m_TyParBounds,
770 //&m_pCurMethod->m_TyParNames, NULL);
771 m_pCurMethod->m_NumTyPars = typars->ToArray(&(m_pCurMethod->m_TyPars));
775 else m_pCurMethod->m_NumTyPars = 0;
777 else report->error("Failed to allocate Method class\n");
778 } // end if new method
781 /**************************************************************************/
782 void Assembler::EndMethod()
785 if(m_pCurMethod->m_pCurrScope != &(m_pCurMethod->m_MainScope))
787 report->error("Invalid lexical scope structure in method %s\n",m_pCurMethod->m_szName);
789 m_pCurMethod->m_pCurrScope->dwEnd = m_CurPC;
790 if (DoFixups(m_pCurMethod)) AddMethod(m_pCurMethod); //AddMethod - see ASSEM.CPP
793 report->error("Method '%s' compilation failed.\n",m_pCurMethod->m_szName);
795 //m_pCurMethod->m_lstLabel.RESET(true);
796 m_lstLabel.RESET(true);
797 m_tkCurrentCVOwner = 0;
798 m_pCustomDescrList = m_CustomDescrListStack.POP();
799 ResetForNextMethod(); // see ASSEM.CPP
801 /**************************************************************************/
802 /* rvaLabel is the optional label that indicates this field points at a particular RVA */
803 void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, __in __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset)
805 FieldDescriptor* pFD;
807 mdToken tkParent = mdTokenNil;
811 report->error("Field cannot be declared within a method\n");
813 if(strlen(name) >= MAX_CLASSNAME_LENGTH)
815 char c = name[MAX_CLASSNAME_LENGTH-1];
816 name[MAX_CLASSNAME_LENGTH-1] = 0;
817 report->error("Field '%s...' -- name too long (%d characters).\n",name,strlen(name));
818 name[MAX_CLASSNAME_LENGTH-1] = c;
821 if(sig && (sig->length() >= 2))
823 if(sig->ptr()[1] == ELEMENT_TYPE_VOID)
824 report->error("Illegal use of type 'void'\n");
829 tkParent = m_pCurClass->m_cl;
831 if(IsTdInterface(m_pCurClass->m_Attr))
833 if(!IsFdStatic(flags))
835 report->warn("Instance field in interface (CLS violation)\n");
836 if(!IsFdPublic(flags)) report->error("Non-public instance field in interface\n");
842 if(ulOffset != 0xFFFFFFFF)
844 report->warn("Offset in global field '%s' is ignored\n",name);
845 ulOffset = 0xFFFFFFFF;
847 if(!IsFdStatic(flags))
849 if(OnErrGo) report->error("Non-static global field\n");
852 report->warn("Non-static global field, made static\n");
853 flags = (CorFieldAttr)(flags | fdStatic);
857 pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
858 n = pClass->m_FieldDList.COUNT();
859 DWORD L = (DWORD)strlen(name);
860 for(i = 0; i < n; i++)
862 pFD = pClass->m_FieldDList.PEEK(i);
863 if((pFD->m_tdClass == tkParent)&&(L==pFD->m_dwName)&&(!strcmp(pFD->m_szName,name))
864 &&(pFD->m_pbsSig->length() == sig->length())
865 &&(memcmp(pFD->m_pbsSig->ptr(),sig->ptr(),sig->length())==0))
867 report->error("Duplicate field declaration: '%s'\n",name);
871 if (rvaLabel && !IsFdStatic(flags))
872 report->error("Only static fields can have 'at' clauses\n");
876 if((pFD = new FieldDescriptor))
878 pFD->m_tdClass = tkParent;
879 pFD->m_szName = name;
881 pFD->m_fdFieldTok = mdTokenNil;
882 if((pFD->m_ulOffset = ulOffset) != 0xFFFFFFFF) pClass->m_dwNumFieldsWithOffset++;
883 pFD->m_rvaLabel = rvaLabel;
885 pFD->m_pClass = pClass;
886 pFD->m_pbsValue = pVal;
887 pFD->m_pbsMarshal = m_pMarshal;
888 pFD->m_pPInvoke = m_pPInvoke;
889 pFD->m_dwAttr = flags;
891 m_tkCurrentCVOwner = 0;
892 m_pCustomDescrList = &(pFD->m_CustomDescrList);
894 pClass->m_FieldDList.PUSH(pFD);
895 pClass->m_fNewMembers = TRUE;
898 report->error("Failed to allocate Field Descriptor\n");
902 if(pVal) delete pVal;
903 if(m_pPInvoke) delete m_pPInvoke;
904 if(m_pMarshal) delete m_pMarshal;
911 BOOL Assembler::EmitField(FieldDescriptor* pFD)
913 WCHAR* wzFieldName=&wzUniBuf[0];
916 COR_SIGNATURE* mySig;
918 BYTE ValType = ELEMENT_TYPE_VOID;
919 void * pValue = NULL;
923 cSig = pFD->m_pbsSig->length();
924 mySig = (COR_SIGNATURE*)(pFD->m_pbsSig->ptr());
926 WszMultiByteToWideChar(g_uCodePage,0,pFD->m_szName,-1,wzFieldName,dwUniBuf); //int)cFieldNameLength);
927 if(IsFdPrivateScope(pFD->m_dwAttr))
929 WCHAR* p = wcsstr(wzFieldName,W("$PST04"));
933 if(pFD->m_pbsValue && pFD->m_pbsValue->length())
935 ValType = *(pFD->m_pbsValue->ptr());
936 lVal = pFD->m_pbsValue->length() - 1; // 1 is type byte
937 pValue = (void*)(pFD->m_pbsValue->ptr() + 1);
938 if(ValType == ELEMENT_TYPE_STRING)
940 //while(lVal % sizeof(WCHAR)) { pFD->m_pbsValue->appendInt8(0); lVal++; }
941 lVal /= sizeof(WCHAR);
943 #if defined(ALIGN_ACCESS) || BIGENDIAN
944 void* pValueTemp = _alloca(lVal * sizeof(WCHAR));
945 memcpy(pValueTemp, pValue, lVal * sizeof(WCHAR));
948 SwapStringLength((WCHAR*)pValue, lVal);
953 hr = m_pEmitter->DefineField(
966 report->error("Failed to define field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
971 //--------------------------------------------------------------------------------
972 if(IsFdPinvokeImpl(pFD->m_dwAttr)&&(pFD->m_pPInvoke))
974 if(pFD->m_pPInvoke->szAlias == NULL) pFD->m_pPInvoke->szAlias = pFD->m_szName;
975 if(FAILED(EmitPinvokeMap(mb,pFD->m_pPInvoke)))
977 report->error("Failed to define PInvoke map of .field '%s'\n",pFD->m_szName);
981 //--------------------------------------------------------------------------
982 if(pFD->m_pbsMarshal)
984 if(FAILED(hr = m_pEmitter->SetFieldMarshal (
985 mb, // [IN] given a fieldDef or paramDef token
986 (PCCOR_SIGNATURE)(pFD->m_pbsMarshal->ptr()), // [IN] native type specification
987 pFD->m_pbsMarshal->length()))) // [IN] count of bytes of pvNativeType
989 report->error("Failed to set field marshaling for '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
993 //--------------------------------------------------------------------------------
994 // Set the the RVA to a dummy value. later it will be fixed
995 // up to be something correct, but if we don't emit something
996 // the size of the meta-data will not be correct
999 m_fHaveFieldsWithRvas = TRUE;
1000 hr = m_pEmitter->SetFieldRVA(mb, 0xCCCCCCCC);
1003 report->error("Failed to set RVA for field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
1007 //--------------------------------------------------------------------------------
1008 EmitCustomAttributes(mb, &(pFD->m_CustomDescrList));
1011 pFD->m_fdFieldTok = mb;
1015 /**************************************************************************/
1016 void Assembler::EmitByte(int val)
1018 char ch = (char)val;
1019 //if((val < -128)||(val > 127))
1020 // report->warn("Emitting 0x%X as a byte: data truncated to 0x%X\n",(unsigned)val,(BYTE)ch);
1021 EmitBytes((BYTE *)&ch,1);
1024 /**************************************************************************/
1025 void Assembler::NewSEHDescriptor(void) //sets m_SEHD
1027 m_SEHDstack.PUSH(m_SEHD);
1028 m_SEHD = new SEH_Descriptor;
1029 if(m_SEHD == NULL) report->error("Failed to allocate SEH descriptor\n");
1031 /**************************************************************************/
1032 void Assembler::SetTryLabels(__in __nullterminated char * szFrom, __in __nullterminated char *szTo)
1035 Label *pLbl = m_pCurMethod->FindLabel(szFrom);
1038 m_SEHD->tryFrom = pLbl->m_PC;
1039 if((pLbl = m_pCurMethod->FindLabel(szTo))) m_SEHD->tryTo = pLbl->m_PC; //FindLabel: Method.CPP
1040 else report->error("Undefined 2nd label in 'try <label> to <label>'\n");
1042 else report->error("Undefined 1st label in 'try <label> to <label>'\n");
1044 /**************************************************************************/
1045 void Assembler::SetFilterLabel(__in __nullterminated char *szFilter)
1048 Label *pLbl = m_pCurMethod->FindLabel(szFilter);
1049 if(pLbl) m_SEHD->sehFilter = pLbl->m_PC;
1050 else report->error("Undefined label in 'filter <label>'\n");
1052 /**************************************************************************/
1053 void Assembler::SetCatchClass(mdToken catchClass)
1056 m_SEHD->cException = catchClass;
1059 /**************************************************************************/
1060 void Assembler::SetHandlerLabels(__in __nullterminated char *szHandlerFrom, __in __nullterminated char *szHandlerTo)
1063 Label *pLbl = m_pCurMethod->FindLabel(szHandlerFrom);
1066 m_SEHD->sehHandler = pLbl->m_PC;
1069 pLbl = m_pCurMethod->FindLabel(szHandlerTo);
1072 m_SEHD->sehHandlerTo = pLbl->m_PC;
1078 m_SEHD->sehHandlerTo = m_SEHD->sehHandler - 1;
1082 report->error("Undefined label in 'handler <label> to <label>'\n");
1084 /**************************************************************************/
1085 void Assembler::EmitTry(void) //enum CorExceptionFlag kind, char* beginLabel, char* endLabel, char* handleLabel, char* filterOrClass)
1089 bool isFilter=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FILTER),
1090 isFault=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FAULT),
1091 isFinally=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FINALLY);
1093 AddException(m_SEHD->tryFrom, m_SEHD->tryTo, m_SEHD->sehHandler, m_SEHD->sehHandlerTo,
1094 m_SEHD->cException, isFilter, isFault, isFinally);
1096 else report->error("Attempt to EmitTry with NULL SEH descriptor\n");
1098 /**************************************************************************/
1100 void Assembler::AddException(DWORD pcStart, DWORD pcEnd, DWORD pcHandler, DWORD pcHandlerTo, mdTypeRef crException, BOOL isFilter, BOOL isFault, BOOL isFinally)
1102 if (m_pCurMethod == NULL)
1104 report->error("Exceptions can be declared only when in a method scope\n");
1108 if (m_pCurMethod->m_dwNumExceptions >= m_pCurMethod->m_dwMaxNumExceptions)
1110 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *ptr =
1111 new COR_ILMETHOD_SECT_EH_CLAUSE_FAT[m_pCurMethod->m_dwMaxNumExceptions+MAX_EXCEPTIONS];
1114 report->error("Failed to reallocate SEH buffer\n");
1117 memcpy(ptr,m_pCurMethod->m_ExceptionList,m_pCurMethod->m_dwNumExceptions*sizeof(COR_ILMETHOD_SECT_EH_CLAUSE_FAT));
1118 delete [] m_pCurMethod->m_ExceptionList;
1119 m_pCurMethod->m_ExceptionList = ptr;
1120 m_pCurMethod->m_dwMaxNumExceptions += MAX_EXCEPTIONS;
1123 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *clause = &m_pCurMethod->m_ExceptionList[m_pCurMethod->m_dwNumExceptions];
1124 clause->SetTryOffset(pcStart);
1125 clause->SetTryLength(pcEnd - pcStart);
1126 clause->SetHandlerOffset(pcHandler);
1127 clause->SetHandlerLength(pcHandlerTo - pcHandler);
1128 clause->SetClassToken(crException);
1130 int flags = COR_ILEXCEPTION_CLAUSE_OFFSETLEN;
1132 flags |= COR_ILEXCEPTION_CLAUSE_FILTER;
1135 flags |= COR_ILEXCEPTION_CLAUSE_FAULT;
1138 flags |= COR_ILEXCEPTION_CLAUSE_FINALLY;
1140 clause->SetFlags((CorExceptionFlag)flags);
1142 m_pCurMethod->m_dwNumExceptions++;
1145 /**************************************************************************/
1146 void Assembler::EmitMaxStack(unsigned val)
1148 if(val > 0xFFFF) report->warn(".maxstack parameter exceeds 65535, truncated to %d\n",val&0xFFFF);
1149 if (m_pCurMethod) m_pCurMethod->m_MaxStack = val&0xFFFF;
1150 else report->error(".maxstack can be used only within a method scope\n");
1153 /**************************************************************************/
1154 void Assembler::EmitLocals(BinStr* sig)
1160 ARG_NAME_LIST *pAN, *pList= getArgNameList();
1164 for(pAN=pList; pAN; pAN = pAN->pNext)
1166 if(pAN->dwAttr == 0) pAN->dwAttr = m_pCurMethod->m_Locals.COUNT() +1;
1168 if((pVD = m_pCurMethod->m_Locals.PEEK(pAN->dwAttr)))
1172 report->warn("Local var slot %d is in use\n",pAN->dwAttr);
1174 if(pVD->pbsSig && ((pVD->pbsSig->length() != pAN->pSig->length()) ||
1175 (memcmp(pVD->pbsSig->ptr(),pAN->pSig->ptr(),pVD->pbsSig->length()))))
1177 report->error("Local var slot %d: type conflict\n",pAN->dwAttr);
1181 { // create new entry:
1182 for(unsigned n = m_pCurMethod->m_Locals.COUNT(); n <= pAN->dwAttr; n++)
1185 if(pVD != NULL) m_pCurMethod->m_Locals.PUSH(pVD);
1188 report->error("Out of memory allocating local var descriptor\n");
1194 pVD->dwSlot = pAN->dwAttr;
1195 pVD->pbsSig = pAN->pSig;
1196 pVD->bInScope = TRUE;
1198 if(pVD->pbsSig && (pVD->pbsSig->length() == 1))
1200 if(pVD->pbsSig->ptr()[0] == ELEMENT_TYPE_VOID)
1201 report->error("Illegal local var type: 'void'\n");
1203 m_pCurMethod->m_pCurrScope->pLocals =
1204 m_pCurMethod->catArgNameList(m_pCurMethod->m_pCurrScope->pLocals, pList);
1207 else report->error(".locals can be used only within a method scope\n");
1210 else report->error("Attempt to EmitLocals with NULL argument\n");
1213 /**************************************************************************/
1214 void Assembler::EmitEntryPoint()
1218 if(!m_fEntryPointPresent)
1220 if(IsMdStatic(m_pCurMethod->m_Attr))
1222 m_pCurMethod->m_fEntryPoint = TRUE;
1223 m_fEntryPointPresent = TRUE;
1225 else report->error("Non-static method as entry point\n");
1227 else report->error("Multiple .entrypoint declarations\n");
1229 else report->error(".entrypoint can be used only within a method scope\n");
1232 /**************************************************************************/
1233 void Assembler::EmitZeroInit()
1235 if (m_pCurMethod) m_pCurMethod->m_Flags |= CorILMethod_InitLocals;
1236 else report->error(".zeroinit can be used only within a method scope\n");
1239 /**************************************************************************/
1240 void Assembler::SetImplAttr(unsigned short attrval)
1244 if(IsMiNative(attrval)||IsMiOPTIL(attrval)||IsMiUnmanaged(attrval))
1245 report->error("Cannot compile native/unmanaged method\n");
1246 m_pCurMethod->m_wImplAttr = attrval;
1250 /**************************************************************************/
1251 void Assembler::EmitData(__in_opt void *buffer, unsigned len)
1256 HRESULT hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, len, 1, &ptr);
1259 report->error("Could not extend data section (out of memory?)");
1265 memcpy(ptr, buffer, len);
1269 memset(ptr, 0, len);
1274 /**************************************************************************/
1275 void Assembler::EmitDD(__in __nullterminated char *str)
1278 GlobalLabel *pLabel = FindGlobalLabel(str);
1281 HRESULT hr = m_pCeeFileGen->GetSectionDataLen(m_pCurSection, &loc);
1282 _ASSERTE(SUCCEEDED(hr));
1285 DWORD sizeofptr = (DWORD)((m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32) ? sizeof(DWORD) : sizeof(__int64));
1286 hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, sizeofptr, 1, (void**) &ptr);
1289 report->error("Could not extend data section (out of memory?)");
1294 dwAddr = pLabel->m_GlobalOffset;
1295 if (pLabel->m_Section != m_pGlobalDataSection) {
1296 report->error("For '&label', label must be in data section");
1297 m_State = STATE_FAIL;
1301 AddDeferredGlobalFixup(str, (BYTE*) ptr);
1303 hr = m_pCeeFileGen->AddSectionReloc(m_pCurSection, loc, m_pGlobalDataSection, srRelocHighLow);
1304 _ASSERTE(SUCCEEDED(hr));
1305 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
1307 report->error("Base relocations are emitted, while /STRIPRELOC option has been specified");
1309 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32)
1311 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1312 if (m_dwCeeFileFlags & ICEE_CREATE_MACHINE_I386)
1313 COR_SET_32BIT_REQUIRED(m_dwComImageFlags);
1318 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1319 *((__int64*)ptr) = (__int64)dwAddr;
1323 /**************************************************************************/
1324 GlobalLabel *Assembler::FindGlobalLabel(LPCUTF8 pszName)
1326 GlobalLabel lSearch(pszName,0,NULL), *pL;
1327 pL = m_lstGlobalLabel.FIND(&lSearch);
1328 lSearch.m_szName = NULL;
1330 //return m_lstGlobalLabel.FIND(pszName);
1333 /**************************************************************************/
1335 GlobalFixup *Assembler::AddDeferredGlobalFixup(__in __nullterminated char *pszLabel, BYTE* pReference)
1337 GlobalFixup *pNew = new GlobalFixup(pszLabel, (BYTE*) pReference);
1340 report->error("Failed to allocate global fixup\n");
1341 m_State = STATE_FAIL;
1344 m_lstGlobalFixup.PUSH(pNew);
1349 /**************************************************************************/
1350 void Assembler::AddDeferredILFixup(ILFixupType Kind)
1352 _ASSERTE(Kind != ilGlobal);
1353 AddDeferredILFixup(Kind, NULL);
1355 /**************************************************************************/
1357 void Assembler::AddDeferredILFixup(ILFixupType Kind,
1358 GlobalFixup *GFixup)
1360 ILFixup *pNew = new ILFixup(m_CurPC, Kind, GFixup);
1362 _ASSERTE(m_pCurMethod != NULL);
1365 report->error("Failed to allocate IL fixup\n");
1366 m_State = STATE_FAIL;
1369 m_pCurMethod->m_lstILFixup.PUSH(pNew);
1372 /**************************************************************************/
1373 void Assembler::EmitDataString(BinStr* str)
1378 DWORD DataLen = str->length();
1379 char *pb = (char*)(str->ptr());
1380 WCHAR *UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen] : &wzUniBuf[0];
1384 WszMultiByteToWideChar(g_uCodePage,0,pb,-1,UnicodeString,DataLen);
1385 EmitData(UnicodeString,DataLen*sizeof(WCHAR));
1386 if(DataLen >= dwUniBuf) delete [] UnicodeString;
1388 else report->error("\nOut of memory!\n");
1395 /**************************************************************************/
1396 unsigned Assembler::OpcodeLen(Instr* instr)
1398 return (m_fStdMapping ? OpcodeInfo[instr->opcode].Len : 3);
1400 /**************************************************************************/
1401 void Assembler::EmitOpcode(Instr* instr)
1403 if(m_fGeneratePDB &&
1404 ((instr->linenum != m_ulLastDebugLine)
1405 ||(instr->column != m_ulLastDebugColumn)
1406 ||(instr->linenum_end != m_ulLastDebugLineEnd)
1407 ||(instr->column_end != m_ulLastDebugColumnEnd)))
1411 LinePC *pLPC = new LinePC;
1414 pLPC->Line = instr->linenum;
1415 pLPC->Column = instr->column;
1416 pLPC->LineEnd = instr->linenum_end;
1417 pLPC->ColumnEnd = instr->column_end;
1419 pLPC->pWriter = instr->pWriter;
1420 m_pCurMethod->m_LinePCList.PUSH(pLPC);
1422 else report->error("\nOut of memory!\n");
1424 m_ulLastDebugLine = instr->linenum;
1425 m_ulLastDebugColumn = instr->column;
1426 m_ulLastDebugLineEnd = instr->linenum_end;
1427 m_ulLastDebugColumnEnd = instr->column_end;
1429 if(instr->opcode == CEE_ENDFILTER)
1433 if(m_pCurMethod->m_dwNumEndfilters >= m_pCurMethod->m_dwMaxNumEndfilters)
1435 DWORD *pdw = new DWORD[m_pCurMethod->m_dwMaxNumEndfilters+MAX_EXCEPTIONS];
1438 report->error("Failed to reallocate auxiliary SEH buffer\n");
1442 memcpy(pdw,m_pCurMethod->m_EndfilterOffsetList,m_pCurMethod->m_dwNumEndfilters*sizeof(DWORD));
1443 delete m_pCurMethod->m_EndfilterOffsetList;
1444 m_pCurMethod->m_EndfilterOffsetList = pdw;
1445 m_pCurMethod->m_dwMaxNumEndfilters += MAX_EXCEPTIONS;
1447 m_pCurMethod->m_EndfilterOffsetList[m_pCurMethod->m_dwNumEndfilters++] = m_CurPC+2;
1452 if (OpcodeInfo[instr->opcode].Len == 2)
1453 EmitByte(OpcodeInfo[instr->opcode].Std1);
1454 EmitByte(OpcodeInfo[instr->opcode].Std2);
1458 unsigned short us = (unsigned short)instr->opcode;
1460 EmitBytes((BYTE *)&us,2);
1465 /**************************************************************************/
1466 //void Assembler::OptimizeInstr(Instr* instr, int var)
1470 /**************************************************************************/
1471 unsigned Assembler::ShortOf(unsigned opcode)
1476 case CEE_LDARG: retcode=CEE_LDARG_S; break;
1477 case CEE_LDARGA: retcode=CEE_LDARGA_S; break;
1478 case CEE_STARG: retcode=CEE_STARG_S; break;
1480 case CEE_LDLOC: retcode=CEE_LDLOC_S; break;
1481 case CEE_LDLOCA: retcode=CEE_LDLOCA_S; break;
1482 case CEE_STLOC: retcode=CEE_STLOC_S; break;
1484 case CEE_BR: retcode=CEE_BR_S; break;
1485 case CEE_BRFALSE: retcode=CEE_BRFALSE_S; break;
1486 case CEE_BRTRUE: retcode=CEE_BRTRUE_S; break;
1487 case CEE_BEQ: retcode=CEE_BEQ_S; break;
1488 case CEE_BGE: retcode=CEE_BGE_S; break;
1489 case CEE_BGT: retcode=CEE_BGT_S; break;
1490 case CEE_BLE: retcode=CEE_BLE_S; break;
1491 case CEE_BLT: retcode=CEE_BLT_S; break;
1492 case CEE_BNE_UN: retcode=CEE_BNE_UN_S; break;
1493 case CEE_BGE_UN: retcode=CEE_BGE_UN_S; break;
1494 case CEE_BGT_UN: retcode=CEE_BGT_UN_S; break;
1495 case CEE_BLE_UN: retcode=CEE_BLE_UN_S; break;
1496 case CEE_BLT_UN: retcode=CEE_BLT_UN_S; break;
1497 case CEE_LEAVE: retcode=CEE_LEAVE_S; break;
1499 case CEE_LDC_I4: retcode=CEE_LDC_I4_S; break;
1500 case CEE_LDC_R8: retcode=CEE_LDC_R4; break;
1503 default: retcode = opcode; break;
1508 /**************************************************************************/
1509 void Assembler::EmitInstrVar(Instr* instr, int var)
1511 unsigned opc = instr->opcode;
1519 case CEE_LDARG_S: opc = CEE_LDARG_0 + var; break;
1522 case CEE_LDLOC_S: opc = CEE_LDLOC_0 + var; break;
1525 case CEE_STLOC_S: opc = CEE_STLOC_0 + var; break;
1529 if(opc != (unsigned) instr->opcode)
1531 instr->opcode = opc;
1538 opc = instr->opcode = ShortOf(opc);
1548 short sh = (short)var;
1549 EmitBytes((BYTE *)&sh,2);
1553 /**************************************************************************/
1554 void Assembler::EmitInstrVarByName(Instr* instr, __in __nullterminated char* label)
1556 int idx = -1, nArgVarFlag=0;
1557 switch(instr->opcode)
1575 DWORD L = (DWORD)strlen(label);
1576 if(nArgVarFlag == 1)
1578 idx = m_pCurMethod->findArgNum(m_pCurMethod->m_firstArgName,label,L);
1582 for(Scope* pSC = m_pCurMethod->m_pCurrScope; pSC; pSC=pSC->pSuperScope)
1584 idx = m_pCurMethod->findLocSlot(pSC->pLocals,label,L);
1588 if(idx >= 0) EmitInstrVar(instr,
1589 ((nArgVarFlag==0)||(m_pCurMethod->m_Attr & mdStatic))? idx : idx+1);
1590 else report->error("Undeclared identifier %s\n",label);
1593 report->error("Instructions can be used only when in a method scope\n");
1596 report->error("Named argument illegal for this instruction\n");
1598 instr->opcode = -1; // in case we got here with error
1601 /**************************************************************************/
1602 void Assembler::EmitInstrI(Instr* instr, int val)
1604 int opc = instr->opcode;
1607 if((val >= -1)&&(val <= 8))
1612 case CEE_LDC_I4_S: opc = CEE_LDC_I4_M1 + (val+1); break;
1616 if(opc != instr->opcode)
1618 instr->opcode = opc;
1623 if((-128 <= val)&&(val <= 127))
1625 opc = instr->opcode = ShortOf(opc);
1636 EmitBytes((BYTE *)&i,sizeof(int));
1640 /**************************************************************************/
1641 void Assembler::EmitInstrI8(Instr* instr, __int64* val)
1644 EmitBytes((BYTE *)val, sizeof(__int64));
1648 /**************************************************************************/
1649 void Assembler::EmitInstrR(Instr* instr, double* pval)
1651 unsigned opc = instr->opcode;
1655 float val = (float)*pval;
1656 EmitBytes((BYTE *)&val, sizeof(float));
1659 EmitBytes((BYTE *)pval, sizeof(double));
1662 /**************************************************************************/
1663 void Assembler::EmitInstrBrTarget(Instr* instr, __in __nullterminated char* label)
1665 Label * pLabel = m_pCurMethod->FindLabel(label);
1667 if (pLabel == NULL) // branching forward -- no optimization
1669 int pcrelsize = 1+(isShort(instr->opcode) ? 1 : 4); //size of the instruction plus argument
1670 AddDeferredFixup(label, m_pCurOutputPos+1,
1671 (m_CurPC + pcrelsize), pcrelsize-1);
1675 offset = pLabel->m_PC - m_CurPC;
1678 if((-128 <= offset-5)&&(offset-2 <= 127)) //need to take into account the argument size (worst cases)
1680 instr->opcode = ShortOf(instr->opcode);
1683 if(isShort(instr->opcode))
1686 if((-128 > offset)||(offset > 127))
1687 report->error("Offset too large for short branching instruction, truncated\n");
1693 int opc = instr->opcode;
1695 if(isShort(opc)) EmitByte(offset);
1696 else EmitBytes((BYTE *)&offset,4);
1698 /**************************************************************************/
1699 void Assembler::AddDeferredFixup(__in __nullterminated char *pszLabel, BYTE *pBytes, DWORD RelativeToPC, BYTE FixupSize)
1701 Fixup *pNew = new Fixup(pszLabel, pBytes, RelativeToPC, FixupSize);
1705 report->error("Failed to allocate deferred fixup\n");
1706 m_State = STATE_FAIL;
1709 m_pCurMethod->m_lstFixup.PUSH(pNew);
1711 /**************************************************************************/
1712 void Assembler::EmitInstrBrOffset(Instr* instr, int offset)
1714 unsigned opc=instr->opcode;
1717 if((-128 <= offset)&&(offset <= 127))
1719 opc = instr->opcode = ShortOf(opc);
1723 if(isShort(opc)) EmitByte(offset);
1727 EmitBytes((BYTE *)&i,4);
1731 /**************************************************************************/
1732 mdToken Assembler::MakeMemberRef(mdToken cr, __in __nullterminated char* pszMemberName, BinStr* sig)
1734 DWORD cSig = sig->length();
1735 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1736 mdToken mr = mdMemberRefNil;
1737 Class* pClass = NULL;
1738 if(cr == 0x00000001) cr = mdTokenNil; // Module -> nil for globals
1739 if(TypeFromToken(cr) == mdtTypeDef) pClass = m_lstClass.PEEK(RidFromToken(cr)-1);
1740 if((TypeFromToken(cr) == mdtTypeDef)||(cr == mdTokenNil))
1742 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1745 pMRD->m_tdClass = cr;
1746 pMRD->m_pClass = pClass;
1747 pMRD->m_szName = pszMemberName;
1748 pMRD->m_dwName = (DWORD)strlen(pszMemberName);
1749 pMRD->m_pSigBinStr = sig;
1750 pMRD->m_tkResolved = 0;
1751 if(*(sig->ptr())== IMAGE_CEE_CS_CALLCONV_FIELD)
1753 m_LocalFieldRefDList.PUSH(pMRD);
1754 mr = 0x98000000 | m_LocalFieldRefDList.COUNT();
1758 m_LocalMethodRefDList.PUSH(pMRD);
1759 mr = 0x99000000 | m_LocalMethodRefDList.COUNT();
1764 report->error("Failed to allocate MemberRef Descriptor\n");
1770 WszMultiByteToWideChar(g_uCodePage,0,pszMemberName,-1,wzUniBuf,dwUniBuf);
1772 if(cr == mdTokenNil) cr = mdTypeRefNil;
1773 if(TypeFromToken(cr) == mdtAssemblyRef)
1775 report->error("Cross-assembly global references are not supported ('%s')\n", pszMemberName);
1780 HRESULT hr = m_pEmitter->DefineMemberRef(cr, wzUniBuf, mySig, cSig, &mr);
1783 report->error("Unable to define member reference '%s'\n", pszMemberName);
1787 //if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,mr));
1788 delete pszMemberName;
1793 /**************************************************************************/
1794 void Assembler::SetMemberRefFixup(mdToken tk, unsigned opcode_len)
1798 switch(TypeFromToken(tk))
1803 if(m_pCurMethod != NULL)
1804 m_pCurMethod->m_LocalMemberRefFixupList.PUSH(
1805 new LocalMemberRefFixup(tk,(size_t)(m_CurPC + opcode_len)));
1811 /**************************************************************************/
1812 mdToken Assembler::MakeMethodSpec(mdToken tkParent, BinStr* sig)
1814 DWORD cSig = sig->length();
1815 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1816 mdMethodSpec mi = mdMethodSpecNil;
1817 if(TypeFromToken(tkParent) == 0x99000000) // Local MemberRef: postpone until resolved
1819 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1822 memset(pMRD,0,sizeof(MemberRefDescriptor));
1823 pMRD->m_tdClass = tkParent;
1824 pMRD->m_pSigBinStr = sig;
1825 m_MethodSpecList.PUSH(pMRD);
1826 mi = 0x9A000000 | m_MethodSpecList.COUNT();
1830 report->error("Failed to allocate MemberRef Descriptor\n");
1836 HRESULT hr = m_pEmitter->DefineMethodSpec(tkParent, mySig, cSig, &mi);
1839 report->error("Unable to define method instantiation");
1846 /**************************************************************************/
1847 void Assembler::EndEvent(void)
1849 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1850 if(m_pCurEvent->m_tkAddOn == 0)
1851 report->error("Event %s of class %s has no Add method. Event not emitted.",
1852 m_pCurEvent->m_szName,pClass->m_szFQN);
1853 else if(m_pCurEvent->m_tkRemoveOn == 0)
1854 report->error("Event %s of class %s has no Remove method. Event not emitted.",
1855 m_pCurEvent->m_szName,pClass->m_szFQN);
1858 pClass->m_EventDList.PUSH(m_pCurEvent);
1859 pClass->m_fNewMembers = TRUE;
1862 m_tkCurrentCVOwner = 0;
1863 m_pCustomDescrList = m_CustomDescrListStack.POP();
1866 void Assembler::ResetEvent(__inout_z __inout char* szName, mdToken typeSpec, DWORD dwAttr)
1868 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1870 char c = szName[MAX_CLASSNAME_LENGTH-1];
1871 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1872 report->error("Event '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1873 szName[MAX_CLASSNAME_LENGTH-1] = c;
1875 if((m_pCurEvent = new EventDescriptor))
1877 memset(m_pCurEvent,0,sizeof(EventDescriptor));
1878 m_pCurEvent->m_tdClass = m_pCurClass->m_cl;
1879 m_pCurEvent->m_szName = szName;
1880 m_pCurEvent->m_dwAttr = dwAttr;
1881 m_pCurEvent->m_tkEventType = typeSpec;
1882 m_pCurEvent->m_fNew = TRUE;
1883 m_tkCurrentCVOwner = 0;
1884 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1885 m_pCustomDescrList = &(m_pCurEvent->m_CustomDescrList);
1887 else report->error("Failed to allocate Event Descriptor\n");
1890 void Assembler::SetEventMethod(int MethodCode, mdToken tk)
1895 m_pCurEvent->m_tkAddOn = tk;
1898 m_pCurEvent->m_tkRemoveOn = tk;
1901 m_pCurEvent->m_tkFire = tk;
1904 m_pCurEvent->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
1908 /**************************************************************************/
1910 void Assembler::EndProp(void)
1912 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1913 pClass->m_PropDList.PUSH(m_pCurProp);
1914 pClass->m_fNewMembers = TRUE;
1916 m_tkCurrentCVOwner = 0;
1917 m_pCustomDescrList = m_CustomDescrListStack.POP();
1920 void Assembler::ResetProp(__inout_z __inout char * szName, BinStr* bsType, DWORD dwAttr, BinStr* pValue)
1922 DWORD cSig = bsType->length();
1923 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(bsType->ptr());
1925 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1927 char c = szName[MAX_CLASSNAME_LENGTH-1];
1928 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1929 report->error("Property '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1930 szName[MAX_CLASSNAME_LENGTH-1] = c;
1932 m_pCurProp = new PropDescriptor;
1933 if(m_pCurProp == NULL)
1935 report->error("Failed to allocate Property Descriptor\n");
1938 memset(m_pCurProp,0,sizeof(PropDescriptor));
1939 m_pCurProp->m_tdClass = m_pCurClass->m_cl;
1940 m_pCurProp->m_szName = szName;
1941 m_pCurProp->m_dwAttr = dwAttr;
1942 m_pCurProp->m_fNew = TRUE;
1944 m_pCurProp->m_pSig = new COR_SIGNATURE[cSig];
1945 if(m_pCurProp->m_pSig == NULL)
1947 report->error("\nOut of memory!\n");
1950 memcpy(m_pCurProp->m_pSig,mySig,cSig);
1951 m_pCurProp->m_dwCSig = cSig;
1953 if(pValue && pValue->length())
1955 BYTE* pch = pValue->ptr();
1956 m_pCurProp->m_dwCPlusTypeFlag = (DWORD)(*pch);
1957 m_pCurProp->m_cbValue = pValue->length() - 1;
1958 m_pCurProp->m_pValue = (PVOID)(pch+1);
1959 if(m_pCurProp->m_dwCPlusTypeFlag == ELEMENT_TYPE_STRING) m_pCurProp->m_cbValue /= sizeof(WCHAR);
1960 m_pCurProp->m_dwAttr |= prHasDefault;
1964 m_pCurProp->m_dwCPlusTypeFlag = ELEMENT_TYPE_VOID;
1965 m_pCurProp->m_pValue = NULL;
1966 m_pCurProp->m_cbValue = 0;
1968 m_tkCurrentCVOwner = 0;
1969 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1970 m_pCustomDescrList = &(m_pCurProp->m_CustomDescrList);
1973 void Assembler::SetPropMethod(int MethodCode, mdToken tk)
1978 m_pCurProp->m_tkSet = tk;
1981 m_pCurProp->m_tkGet = tk;
1984 m_pCurProp->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
1989 /**************************************************************************/
1990 void Assembler::EmitInstrStringLiteral(Instr* instr, BinStr* literal, BOOL ConvertToUnicode, BOOL Swap /*=FALSE*/)
1992 DWORD DataLen = literal->length(),L;
1993 unsigned __int8 *pb = literal->ptr();
1996 WCHAR *UnicodeString;
1999 //report->warn("Zero length string emitted\n");
2000 ConvertToUnicode = FALSE;
2002 if(ConvertToUnicode)
2004 UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen+1] : &wzUniBuf[0];
2005 literal->appendInt8(0);
2006 pb = literal->ptr();
2007 // convert string to Unicode
2008 L = UnicodeString ? WszMultiByteToWideChar(g_uCodePage,0,(char*)pb,-1,UnicodeString,DataLen+1) : 0;
2011 const char* sz=NULL;
2013 switch(dw=GetLastError())
2015 case ERROR_INSUFFICIENT_BUFFER: sz = "ERROR_INSUFFICIENT_BUFFER"; break;
2016 case ERROR_INVALID_FLAGS: sz = "ERROR_INVALID_FLAGS"; break;
2017 case ERROR_INVALID_PARAMETER: sz = "ERROR_INVALID_PARAMETER"; break;
2018 case ERROR_NO_UNICODE_TRANSLATION: sz = "ERROR_NO_UNICODE_TRANSLATION"; break;
2020 if(sz) report->error("Failed to convert string '%s' to Unicode: %s\n",(char*)pb,sz);
2021 else report->error("Failed to convert string '%s' to Unicode: error 0x%08X\n",(char*)pb,dw);
2031 literal->appendInt8(0);
2032 pb = literal->ptr();
2035 UnicodeString = (WCHAR*)pb;
2036 L = DataLen/sizeof(WCHAR);
2040 SwapStringLength(UnicodeString, L);
2043 // Add the string data to the metadata, which will fold dupes.
2044 hr = m_pEmitter->DefineUserString(
2051 report->error("Failed to add user string using DefineUserString, hr=0x%08x, data: '%S'\n",
2058 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,tk));
2060 EmitBytes((BYTE *)&tk,sizeof(mdToken));
2064 if(((void*)UnicodeString != (void*)pb)&&(DataLen >= dwUniBuf)) delete [] UnicodeString;
2065 instr->opcode = -1; // in case we got here with error
2068 /**************************************************************************/
2069 void Assembler::EmitInstrSig(Instr* instr, BinStr* sig)
2071 mdSignature MetadataToken;
2072 DWORD cSig = sig->length();
2073 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
2075 if (FAILED(m_pEmitter->GetTokenFromSig(mySig, cSig, &MetadataToken)))
2077 report->error("Unable to convert signature to metadata token.\n");
2083 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,MetadataToken));
2084 EmitBytes((BYTE *)&MetadataToken, sizeof(mdSignature));
2087 instr->opcode = -1; // in case we got here with error
2090 /**************************************************************************/
2091 void Assembler::EmitInstrSwitch(Instr* instr, Labels* targets)
2101 for(pLbls = targets, NumLabels = 0; pLbls; pLbls = pLbls->Next, NumLabels++);
2103 EmitBytes((BYTE *)&NumLabels,sizeof(int));
2104 DWORD PC_nextInstr = m_CurPC + 4*NumLabels;
2105 for(pLbls = targets; pLbls; pLbls = pLbls->Next)
2109 if((pLabel = m_pCurMethod->FindLabel(pLbls->Label)))
2111 offset = pLabel->m_PC - PC_nextInstr;
2112 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2116 // defer until we find the label
2117 AddDeferredFixup(pLbls->Label, m_pCurOutputPos, PC_nextInstr, 4 /* pcrelsize */ );
2119 pLbls->Label = NULL;
2120 if (m_fDisplayTraceOutput) report->msg("forward label %s\n", pLbls->Label);
2125 offset = (UINT)(UINT_PTR)pLbls->Label;
2126 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2128 EmitBytes((BYTE *)&offset, sizeof(UINT));
2133 /**************************************************************************/
2134 void Assembler::EmitLabel(__in __nullterminated char* label)
2136 _ASSERTE(m_pCurMethod);
2137 AddLabel(m_CurPC, label);
2139 /**************************************************************************/
2140 void Assembler::EmitDataLabel(__in __nullterminated char* label)
2142 AddGlobalLabel(label, m_pCurSection);
2145 /**************************************************************************/
2146 void Assembler::EmitBytes(BYTE *p, unsigned len)
2148 if(m_pCurOutputPos + len >= m_pEndOutputPos)
2150 size_t buflen = m_pEndOutputPos - m_pOutputBuffer;
2151 size_t newlen = buflen+(len/OUTPUT_BUFFER_INCREMENT + 1)*OUTPUT_BUFFER_INCREMENT;
2152 BYTE *pb = new BYTE[newlen];
2155 report->error("Failed to extend output buffer from %d to %d bytes. Aborting\n",
2159 size_t delta = pb - m_pOutputBuffer;
2162 GlobalFixup *pGSearch;
2163 for (i=0; (pSearch = m_pCurMethod->m_lstFixup.PEEK(i)); i++) pSearch->m_pBytes += delta;
2164 for (i=0; (pGSearch = m_lstGlobalFixup.PEEK(i)); i++) //need to move only those pointing to output buffer
2166 if((pGSearch->m_pReference >= m_pOutputBuffer)&&(pGSearch->m_pReference <= m_pEndOutputPos))
2167 pGSearch->m_pReference += delta;
2171 memcpy(pb,m_pOutputBuffer,m_CurPC);
2172 delete m_pOutputBuffer;
2173 m_pOutputBuffer = pb;
2174 m_pCurOutputPos = &m_pOutputBuffer[m_CurPC];
2175 m_pEndOutputPos = &m_pOutputBuffer[newlen];
2182 *m_pCurOutputPos = *p;
2185 SET_UNALIGNED_VAL16(m_pCurOutputPos, GET_UNALIGNED_16(p));
2188 SET_UNALIGNED_VAL32(m_pCurOutputPos, GET_UNALIGNED_32(p));
2191 SET_UNALIGNED_VAL64(m_pCurOutputPos, GET_UNALIGNED_64(p));
2198 m_pCurOutputPos += len;
2201 /**************************************************************************/
2202 BinStr* Assembler::EncodeSecAttr(__in __nullterminated char* szReflName, BinStr* pbsSecAttrBlob, unsigned nProps)
2206 // build the blob As BinStr
2207 unsigned L = (unsigned) strlen(szReflName);
2209 BinStr* pbsRet = new BinStr();
2210 // encode the Reflection name length
2211 cnt = CorSigCompressData(L, pbsRet->getBuff(5));
2212 pbsRet->remove(5 - cnt);
2214 if((pb = pbsRet->getBuff(L)) != NULL)
2215 memcpy(pb,szReflName,L);
2216 // find out the size of compressed nProps
2217 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2220 unsigned nSize = cnt + pbsSecAttrBlob->length();
2221 cnt = CorSigCompressData(nSize, pbsRet->getBuff(5));
2222 pbsRet->remove(5 - cnt);
2223 // actually encode nProps
2224 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2225 pbsRet->remove(5 - cnt);
2226 // append the props/values blob
2227 pbsRet->append(pbsSecAttrBlob);
2228 delete pbsSecAttrBlob;
2231 /**************************************************************************/
2232 void Assembler::EmitSecurityInfo(mdToken token,
2233 PermissionDecl* pPermissions,
2234 PermissionSetDecl* pPermissionSets)
2236 PermissionDecl *pPerm, *pPermNext;
2237 PermissionSetDecl *pPset, *pPsetNext;
2238 unsigned uCount = 0;
2239 COR_SECATTR *pAttrs;
2242 mdTypeRef tkTypeRef;
2245 DWORD dwErrorIndex = 0;
2249 for (pPerm = pPermissions; pPerm; pPerm = pPerm->m_Next)
2252 _ASSERTE(uCount > 0);
2253 // uCount is expected to be positive all the time. The if statement is here to please prefast.
2256 if((pAttrs = new COR_SECATTR[uCount])==NULL)
2258 report->error("\nOut of memory!\n");
2262 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetAsmRef("mscorlib");
2263 tkTypeRef = ResolveClassRef(tkMscorlib,"System.Security.Permissions.SecurityAction", NULL);
2264 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2265 pPermNext = pPerm->m_Next;
2267 pSig = new BinStr();
2268 pSig->appendInt8(IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS);
2269 pSig->appendInt8(1);
2270 pSig->appendInt8(ELEMENT_TYPE_VOID);
2271 pSig->appendInt8(ELEMENT_TYPE_VALUETYPE);
2272 uLength = CorSigCompressToken(tkTypeRef, pSig->getBuff(5));
2273 pSig->remove(5 - uLength);
2275 uLength = (unsigned)strlen(COR_CTOR_METHOD_NAME) + 1;
2276 if((szMemberName = new char[uLength]))
2278 memcpy(szMemberName, COR_CTOR_METHOD_NAME, uLength);
2279 pAttrs[i].tkCtor = MakeMemberRef(pPerm->m_TypeSpec, szMemberName, pSig);
2280 pAttrs[i].pCustomAttribute = (const void *)pPerm->m_Blob;
2281 pAttrs[i].cbCustomAttribute = pPerm->m_BlobLength;
2283 else report->error("\nOut of memory!\n");
2286 if (FAILED(m_pEmitter->DefineSecurityAttributeSet(token,
2291 _ASSERT(uCount >= dwErrorIndex);
2292 if (dwErrorIndex == uCount)
2294 report->error("Failed to define security attribute set for 0x%08X\n", token);
2298 report->error("Failed to define security attribute set for 0x%08X\n (error in permission %u)\n",
2299 token, uCount - dwErrorIndex);
2303 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2304 pPermNext = pPerm->m_Next;
2310 for (pPset = pPermissionSets; pPset; pPset = pPsetNext) {
2311 pPsetNext = pPset->m_Next;
2312 if(FAILED(m_pEmitter->DefinePermissionSet(token,
2314 pPset->m_Value->ptr(),
2315 pPset->m_Value->length(),
2317 report->error("Failed to define security permission set for 0x%08X\n", token);
2322 void Assembler::AddMethodImpl(mdToken tkImplementedTypeSpec, __in __nullterminated char* szImplementedName, BinStr* pImplementedSig,
2323 mdToken tkImplementingTypeSpec, __in_opt __nullterminated char* szImplementingName, BinStr* pImplementingSig)
2327 MethodImplDescriptor* pMID = new MethodImplDescriptor;
2328 pMID->m_fNew = TRUE;
2331 report->error("Failed to allocate MethodImpl Descriptor\n");
2334 pMID->m_tkDefiningClass = m_pCurClass->m_cl;
2335 if(szImplementingName) //called from class scope, overriding method specified
2337 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2338 pMID->m_tkImplementingMethod = MakeMemberRef(tkImplementingTypeSpec,szImplementingName,pImplementingSig);
2340 else //called from method scope, use current method as overriding
2344 if (pImplementedSig == NULL)
2346 pImplementedSig = new BinStr();
2347 memcpy(pImplementedSig->getBuff(m_pCurMethod->m_dwMethodCSig), m_pCurMethod->m_pMethodSig,m_pCurMethod->m_dwMethodCSig);
2349 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2350 pMID->m_tkImplementingMethod = 0;
2352 m_pCurMethod->m_MethodImplDList.PUSH(pMID); // copy goes to method's own list (ptr only)
2356 report->error("No overriding method specified");
2361 m_MethodImplDList.PUSH(pMID);
2364 report->error(".override directive outside class scope");
2366 // source file name paraphernalia
2367 void Assembler::SetSourceFileName(__in __nullterminated char* szName)
2373 if(strcmp(m_szSourceFileName,szName))
2375 strcpy_s(m_szSourceFileName,MAX_FILENAME_LENGTH*3+1,szName);
2376 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,m_wzSourceFileName,MAX_FILENAME_LENGTH);
2382 while((pDW = m_DocWriterList.PEEK(i++)) != NULL)
2384 if(!strcmp(szName,pDW->Name)) break;
2388 m_pSymDocument = pDW->pWriter;
2391 else if(m_pSymWriter)
2394 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,wzUniBuf,dwUniBuf);
2395 if(FAILED(hr=m_pSymWriter->DefineDocument(wzUniBuf,&m_guidLang,
2396 &m_guidLangVendor,&m_guidDoc,&m_pSymDocument)))
2398 m_pSymDocument = NULL;
2399 report->error("Failed to define a document writer");
2401 if((pDW = new DocWriter()) != NULL)
2404 pDW->pWriter = m_pSymDocument;
2405 m_DocWriterList.PUSH(pDW);
2409 report->error("Out of memory");
2413 else delete [] szName;
2415 else delete [] szName;
2417 else delete [] szName;
2420 void Assembler::SetSourceFileName(BinStr* pbsName)
2423 if(pbsName && (L = (ULONG)(pbsName->length())))
2425 pbsName->appendInt8(0);
2426 char* sz = new char[L+1];
2427 memcpy(sz,pbsName->ptr(),L+1);
2428 SetSourceFileName(sz);