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 if (RidFromToken(m_pManifest->GetAsmRefTokByName("netstandard")) != 0)
286 return GetAsmRef("netstandard");
289 return GetAsmRef("mscorlib");
292 mdToken Assembler::GetInterfaceImpl(mdToken tsClass, mdToken tsInterface)
294 mdToken result = mdTokenNil;
296 ULONG actualInterfaces;
297 mdInterfaceImpl impls;
299 while (SUCCEEDED(m_pImporter->EnumInterfaceImpls(&iiEnum, tsClass, &impls, 1, &actualInterfaces)))
301 if (actualInterfaces == 1)
303 mdToken classToken, interfaceToken;
304 if (FAILED(m_pImporter->GetInterfaceImplProps(impls, &classToken, &interfaceToken)))
306 if (classToken == tsClass && interfaceToken == tsInterface)
313 m_pImporter->CloseEnum(iiEnum);
317 /**************************************************************************/
318 mdToken Assembler::GetModRef(__in __nullterminated char* szName)
320 mdToken tkResScope = 0;
321 if(!strcmp(szName,m_szScopeName))
322 tkResScope = 1; // scope is "this module"
325 ImportDescriptor* pID;
327 tkResScope = mdModuleRefNil;
328 DWORD L = (DWORD)strlen(szName);
329 while((pID=m_ImportList.PEEK(i++)))
331 if(pID->dwDllName != L) continue;
332 if((L > 0) && (strcmp(pID->szDllName,szName)!=0)) continue;
333 tkResScope = pID->mrDll;
336 if(RidFromToken(tkResScope)==0)
337 report->error("Undefined module ref '%s'\n",szName);
341 /**************************************************************************/
342 mdToken Assembler::MakeTypeRef(mdToken tkResScope, LPCUTF8 pszFullClassName)
344 mdToken tkRet = mdTokenNil;
345 if(pszFullClassName && *pszFullClassName)
348 if((pc = strrchr(pszFullClassName,NESTING_SEP))) // scope: enclosing class
351 DWORD L = (DWORD)(pc-pszFullClassName);
352 if((szScopeName = new char[L+1]) != NULL)
354 memcpy(szScopeName,pszFullClassName,L);
356 tkResScope = MakeTypeRef(tkResScope,szScopeName);
357 delete [] szScopeName;
360 report->error("\nOut of memory!\n");
363 else pc = pszFullClassName;
366 // convert name to widechar
367 WszMultiByteToWideChar(g_uCodePage,0,pc,-1,wzUniBuf,dwUniBuf);
368 if(FAILED(m_pEmitter->DefineTypeRefByName(tkResScope, wzUniBuf, &tkRet))) tkRet = mdTokenNil;
373 /**************************************************************************/
375 DWORD Assembler::CheckClassFlagsIfNested(Class* pEncloser, DWORD attr)
377 DWORD wasAttr = attr;
378 if(pEncloser && (!IsTdNested(attr)))
381 report->error("Nested class has non-nested visibility (0x%08X)\n",attr);
384 attr &= ~tdVisibilityMask;
385 attr |= (IsTdPublic(wasAttr) ? tdNestedPublic : tdNestedPrivate);
386 report->warn("Nested class has non-nested visibility (0x%08X), changed to nested (0x%08X)\n",wasAttr,attr);
389 else if((pEncloser==NULL) && IsTdNested(attr))
392 report->error("Non-nested class has nested visibility (0x%08X)\n",attr);
395 attr &= ~tdVisibilityMask;
396 attr |= (IsTdNestedPublic(wasAttr) ? tdPublic : tdNotPublic);
397 report->warn("Non-nested class has nested visibility (0x%08X), changed to non-nested (0x%08X)\n",wasAttr,attr);
403 /**************************************************************************/
405 void Assembler::StartClass(__in __nullterminated char* name, DWORD attr, TyParList *typars)
407 Class *pEnclosingClass = m_pCurClass;
411 m_TyParList = typars;
413 if (m_pCurMethod != NULL)
415 report->error("Class cannot be declared within a method scope\n");
419 LL = pEnclosingClass->m_dwFQN+(ULONG)strlen(name)+2;
420 if((szFQN = new char[LL]))
421 sprintf_s(szFQN,LL,"%s%c%s",pEnclosingClass->m_szFQN,NESTING_SEP,name);
423 report->error("\nOut of memory!\n");
427 unsigned L = (unsigned)strlen(m_szFullNS);
428 unsigned LLL = (unsigned)strlen(name);
429 LL = L + LLL + (L ? 2 : 1);
430 if((szFQN = new char[LL]))
432 if(L) sprintf_s(szFQN,LL,"%s.%s",m_szFullNS,name);
433 else memcpy(szFQN,name,LL);
434 if(LL > MAX_CLASSNAME_LENGTH)
436 report->error("Full class name too long (%d characters, %d allowed).\n",LL-1,MAX_CLASSNAME_LENGTH-1);
440 report->error("\nOut of memory!\n");
442 if(szFQN == NULL) return;
446 tkThis = ResolveClassRef(1,szFQN,&m_pCurClass); // boils down to FindCreateClass(szFQN)
449 m_pCurClass = FindCreateClass(szFQN);
450 tkThis = m_pCurClass->m_cl;
452 if(m_pCurClass->m_bIsMaster)
454 m_pCurClass->m_Attr = CheckClassFlagsIfNested(pEnclosingClass, attr);
458 //m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&m_pCurClass->m_TyParBounds, &m_pCurClass->m_TyParNames, &m_pCurClass->m_TyParAttrs);
459 m_pCurClass->m_NumTyPars = m_TyParList->ToArray(&(m_pCurClass->m_TyPars));
463 else m_pCurClass->m_NumTyPars = 0;
464 m_pCurClass->m_pEncloser = pEnclosingClass;
465 } // end if(old class) else
466 m_tkCurrentCVOwner = 0;
467 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
468 m_pCustomDescrList = &(m_pCurClass->m_CustDList);
470 m_ClassStack.PUSH(pEnclosingClass);
474 /**************************************************************************/
476 void Assembler::AddClass()
478 mdTypeRef crExtends = mdTypeRefNil;
479 BOOL bIsEnum = FALSE;
480 BOOL bIsValueType = FALSE;
482 if(m_pCurClass->m_bIsMaster)
484 DWORD attr = m_pCurClass->m_Attr;
485 if(!IsNilToken(m_crExtends))
488 if(IsTdInterface(attr)) report->error("Base class in interface\n");
489 bIsValueType = (m_crExtends == m_tkSysValue)&&(m_pCurClass->m_cl != m_tkSysEnum);
490 bIsEnum = (m_crExtends == m_tkSysEnum);
491 crExtends = m_crExtends;
495 bIsEnum = ((attr & 0x40000000) != 0);
496 bIsValueType = ((attr & 0x80000000) != 0);
499 if (m_fAutoInheritFromObject && (crExtends == mdTypeRefNil) && (!IsTdInterface(attr)))
501 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetBaseAsmRef();
502 crExtends = bIsEnum ?
503 ResolveClassRef(tkMscorlib,"System.Enum",NULL)
505 ResolveClassRef(tkMscorlib,"System.ValueType",NULL)
506 : ResolveClassRef(tkMscorlib, "System.Object",NULL));
508 m_pCurClass->m_Attr = attr;
509 m_pCurClass->m_crExtends = (m_pCurClass->m_cl == m_tkSysObject)? mdTypeRefNil : crExtends;
511 if ((m_pCurClass->m_dwNumInterfaces = m_nImplList) != NULL)
513 if(bIsEnum) report->error("Enum implementing interface(s)\n");
514 if((m_pCurClass->m_crImplements = new mdTypeRef[m_nImplList+1]) != NULL)
515 memcpy(m_pCurClass->m_crImplements, m_crImplList, (m_nImplList+1)*sizeof(mdTypeRef));
518 report->error("Failed to allocate Impl List for class '%s'\n", m_pCurClass->m_szFQN);
519 m_pCurClass->m_dwNumInterfaces = 0;
522 else m_pCurClass->m_crImplements = NULL;
525 if(!IsTdSealed(attr))
527 if(OnErrGo) report->error("Non-sealed value class\n");
530 report->warn("Non-sealed value class, made sealed\n");
531 m_pCurClass->m_Attr |= tdSealed;
535 m_pCurClass->m_bIsMaster = FALSE;
536 } // end if(old class) else
538 m_crExtends = mdTypeRefNil;
541 /**************************************************************************/
542 void Assembler::EndClass()
544 m_pCurClass = m_ClassStack.POP();
545 m_tkCurrentCVOwner = 0;
546 m_pCustomDescrList = m_CustomDescrListStack.POP();
549 /**************************************************************************/
550 void Assembler::SetPinvoke(BinStr* DllName, int Ordinal, BinStr* Alias, int Attrs)
552 if(m_pPInvoke) delete m_pPInvoke;
553 if(DllName->length())
555 if((m_pPInvoke = new PInvokeDescriptor))
558 ImportDescriptor* pID;
559 if((pID = EmitImport(DllName)))
561 m_pPInvoke->mrDll = pID->mrDll;
562 m_pPInvoke->szAlias = NULL;
566 if((m_pPInvoke->szAlias = new char[l+1]))
568 memcpy(m_pPInvoke->szAlias,Alias->ptr(),l);
569 m_pPInvoke->szAlias[l] = 0;
571 else report->error("\nOut of memory!\n");
573 m_pPInvoke->dwAttrs = (DWORD)Attrs;
579 report->error("PInvoke refers to undefined imported DLL\n");
583 report->error("Failed to allocate PInvokeDescriptor\n");
587 m_pPInvoke = NULL; // No DLL name, it's "local" (IJW) PInvoke
588 report->error("Local (embedded native) PInvoke method, the resulting PE file is unusable\n");
590 if(DllName) delete DllName;
591 if(Alias) delete Alias;
594 /**************************************************************************/
595 void Assembler::StartMethod(__in __nullterminated char* name, BinStr* sig, CorMethodAttr flags, BinStr* retMarshal, DWORD retAttr, TyParList *typars)
597 if (m_pCurMethod != NULL)
599 report->error("Cannot declare a method '%s' within another method\n",name);
601 if (!m_fInitialisedMetaData)
603 if (FAILED(InitMetaData())) // impl. see WRITER.CPP
608 size_t namelen = strlen(name);
609 if(namelen >= MAX_CLASSNAME_LENGTH)
611 char c = name[MAX_CLASSNAME_LENGTH-1];
612 name[MAX_CLASSNAME_LENGTH-1] = 0;
613 report->error("Method '%s...' -- name too long (%d characters).\n",name,namelen);
614 name[MAX_CLASSNAME_LENGTH-1] = c;
616 if (!(flags & mdStatic))
617 *(sig->ptr()) |= IMAGE_CEE_CS_CALLCONV_HASTHIS;
618 else if(*(sig->ptr()) & (IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS))
620 if(OnErrGo) report->error("Method '%s' -- both static and instance\n", name);
623 report->warn("Method '%s' -- both static and instance, set to static\n", name);
624 *(sig->ptr()) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
628 if(!IsMdPrivateScope(flags))
631 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
632 DWORD L = (DWORD)strlen(name);
633 for(int j=0; (pMethod = pClass->m_MethodList.PEEK(j)); j++)
635 if( (pMethod->m_dwName == L) &&
636 (!strcmp(pMethod->m_szName,name)) &&
637 (pMethod->m_dwMethodCSig == sig->length()) &&
638 (!memcmp(pMethod->m_pMethodSig,sig->ptr(),sig->length()))
639 &&(!IsMdPrivateScope(pMethod->m_Attr)))
641 if(m_fTolerateDupMethods)
643 // reset for new body
644 pMethod->m_lstFixup.RESET(true);
645 //pMethod->m_lstLabel.RESET(true);
646 m_lstLabel.RESET(true);
647 pMethod->m_Locals.RESET(true);
648 delArgNameList(pMethod->m_firstArgName);
649 delArgNameList(pMethod->m_firstVarName);
650 pMethod->m_pCurrScope = &(pMethod->m_MainScope);
651 pMethod->m_pCurrScope->Reset();
652 pMethod->m_firstArgName = getArgNameList();
653 pMethod->m_dwNumExceptions = 0;
654 pMethod->m_dwNumEndfilters = 0;
655 if(pMethod->m_pRetMarshal) delete pMethod->m_pRetMarshal;
656 if(pMethod->m_pRetValue) delete pMethod->m_pRetValue;
658 pMethod->m_MethodImplDList.RESET(false); // ptrs in m_MethodImplDList are dups of those in Assembler
660 pMethod->m_CustomDescrList.RESET(true);
662 if(pMethod->m_fEntryPoint)
664 pMethod->m_fEntryPoint = FALSE;
665 m_fEntryPointPresent = FALSE;
668 if(pMethod->m_pbsBody)
670 // no need to remove relevant MemberRef Fixups from the Assembler list:
671 // their m_fNew flag is set to FALSE anyway.
672 // Just get rid of old method body
673 delete pMethod->m_pbsBody;
674 pMethod->m_pbsBody = NULL;
677 pMethod->m_fNewBody = TRUE;
678 m_pCurMethod = pMethod;
681 report->error("Duplicate method declaration\n");
686 if(m_pCurMethod == NULL)
690 if(IsMdAbstract(flags) && !IsTdAbstract(m_pCurClass->m_Attr))
692 report->error("Abstract method '%s' in non-abstract class '%s'\n",name,m_pCurClass->m_szFQN);
694 if(m_pCurClass->m_crExtends == m_tkSysEnum) report->error("Method in enum\n");
696 if(!strcmp(name,COR_CTOR_METHOD_NAME))
698 flags = (CorMethodAttr)(flags | mdSpecialName);
699 if(IsTdInterface(m_pCurClass->m_Attr)) report->error("Instance constructor in interface\n");
702 if(!IsMdStatic(flags))
704 if(IsTdInterface(m_pCurClass->m_Attr))
706 if(!IsMdPublic(flags)) report->error("Non-public instance method in interface\n");
707 if((!(IsMdVirtual(flags) && IsMdAbstract(flags))))
709 if(OnErrGo) report->error("Non-virtual, non-abstract instance method in interface\n");
712 report->warn("Non-virtual, non-abstract instance method in interface, set to such\n");
713 flags = (CorMethodAttr)(flags |mdVirtual | mdAbstract);
719 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
723 if(IsMdAbstract(flags))
725 if(OnErrGo) report->error("Global method '%s' can't be abstract\n",name);
728 report->warn("Global method '%s' can't be abstract, flag removed\n",name);
729 flags = (CorMethodAttr)(((int) flags) &~mdAbstract);
732 if(!IsMdStatic(flags))
734 if(OnErrGo) report->error("Non-static global method '%s'\n",name);
737 report->warn("Non-static global method '%s', made static\n",name);
738 flags = (CorMethodAttr)(flags | mdStatic);
739 *((BYTE*)(sig->ptr())) &= ~(IMAGE_CEE_CS_CALLCONV_HASTHIS | IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS);
742 m_pCurMethod = new Method(this, m_pCurClass, name, sig, flags);
745 m_pCurMethod->SetIsGlobalMethod();
746 if (m_fInitialisedMetaData == FALSE) InitMetaData();
753 if(m_pCurMethod->m_firstArgName)
755 for(ARG_NAME_LIST *pAN=m_pCurMethod->m_firstArgName; pAN; pAN = pAN->pNext)
759 int k = m_pCurMethod->findArgNum(pAN->pNext,pAN->szName,pAN->dwName);
761 report->warn("Duplicate param name '%s' in method '%s'\n",pAN->szName,name);
766 m_pCurMethod->m_pRetMarshal = retMarshal;
767 m_pCurMethod->m_dwRetAttr = retAttr;
768 m_tkCurrentCVOwner = 0;
769 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
770 m_pCustomDescrList = &(m_pCurMethod->m_CustomDescrList);
771 m_pCurMethod->m_MainScope.dwStart = m_CurPC;
774 //m_pCurMethod->m_NumTyPars = typars->ToArray(&m_pCurMethod->m_TyParBounds,
775 //&m_pCurMethod->m_TyParNames, NULL);
776 m_pCurMethod->m_NumTyPars = typars->ToArray(&(m_pCurMethod->m_TyPars));
780 else m_pCurMethod->m_NumTyPars = 0;
782 else report->error("Failed to allocate Method class\n");
783 } // end if new method
786 /**************************************************************************/
787 void Assembler::EndMethod()
790 if(m_pCurMethod->m_pCurrScope != &(m_pCurMethod->m_MainScope))
792 report->error("Invalid lexical scope structure in method %s\n",m_pCurMethod->m_szName);
794 m_pCurMethod->m_pCurrScope->dwEnd = m_CurPC;
795 if (DoFixups(m_pCurMethod)) AddMethod(m_pCurMethod); //AddMethod - see ASSEM.CPP
798 report->error("Method '%s' compilation failed.\n",m_pCurMethod->m_szName);
800 //m_pCurMethod->m_lstLabel.RESET(true);
801 m_lstLabel.RESET(true);
802 m_tkCurrentCVOwner = 0;
803 m_pCustomDescrList = m_CustomDescrListStack.POP();
804 ResetForNextMethod(); // see ASSEM.CPP
806 /**************************************************************************/
807 /* rvaLabel is the optional label that indicates this field points at a particular RVA */
808 void Assembler::AddField(__inout_z __inout char* name, BinStr* sig, CorFieldAttr flags, __in __nullterminated char* rvaLabel, BinStr* pVal, ULONG ulOffset)
810 FieldDescriptor* pFD;
812 mdToken tkParent = mdTokenNil;
816 report->error("Field cannot be declared within a method\n");
818 if(strlen(name) >= MAX_CLASSNAME_LENGTH)
820 char c = name[MAX_CLASSNAME_LENGTH-1];
821 name[MAX_CLASSNAME_LENGTH-1] = 0;
822 report->error("Field '%s...' -- name too long (%d characters).\n",name,strlen(name));
823 name[MAX_CLASSNAME_LENGTH-1] = c;
826 if(sig && (sig->length() >= 2))
828 if(sig->ptr()[1] == ELEMENT_TYPE_VOID)
829 report->error("Illegal use of type 'void'\n");
834 tkParent = m_pCurClass->m_cl;
836 if(IsTdInterface(m_pCurClass->m_Attr))
838 if(!IsFdStatic(flags))
840 report->warn("Instance field in interface (CLS violation)\n");
841 if(!IsFdPublic(flags)) report->error("Non-public instance field in interface\n");
847 if(ulOffset != 0xFFFFFFFF)
849 report->warn("Offset in global field '%s' is ignored\n",name);
850 ulOffset = 0xFFFFFFFF;
852 if(!IsFdStatic(flags))
854 if(OnErrGo) report->error("Non-static global field\n");
857 report->warn("Non-static global field, made static\n");
858 flags = (CorFieldAttr)(flags | fdStatic);
862 pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
863 n = pClass->m_FieldDList.COUNT();
864 DWORD L = (DWORD)strlen(name);
865 for(i = 0; i < n; i++)
867 pFD = pClass->m_FieldDList.PEEK(i);
868 if((pFD->m_tdClass == tkParent)&&(L==pFD->m_dwName)&&(!strcmp(pFD->m_szName,name))
869 &&(pFD->m_pbsSig->length() == sig->length())
870 &&(memcmp(pFD->m_pbsSig->ptr(),sig->ptr(),sig->length())==0))
872 report->error("Duplicate field declaration: '%s'\n",name);
876 if (rvaLabel && !IsFdStatic(flags))
877 report->error("Only static fields can have 'at' clauses\n");
881 if((pFD = new FieldDescriptor))
883 pFD->m_tdClass = tkParent;
884 pFD->m_szName = name;
886 pFD->m_fdFieldTok = mdTokenNil;
887 if((pFD->m_ulOffset = ulOffset) != 0xFFFFFFFF) pClass->m_dwNumFieldsWithOffset++;
888 pFD->m_rvaLabel = rvaLabel;
890 pFD->m_pClass = pClass;
891 pFD->m_pbsValue = pVal;
892 pFD->m_pbsMarshal = m_pMarshal;
893 pFD->m_pPInvoke = m_pPInvoke;
894 pFD->m_dwAttr = flags;
896 m_tkCurrentCVOwner = 0;
897 m_pCustomDescrList = &(pFD->m_CustomDescrList);
899 pClass->m_FieldDList.PUSH(pFD);
900 pClass->m_fNewMembers = TRUE;
903 report->error("Failed to allocate Field Descriptor\n");
907 if(pVal) delete pVal;
908 if(m_pPInvoke) delete m_pPInvoke;
909 if(m_pMarshal) delete m_pMarshal;
916 BOOL Assembler::EmitField(FieldDescriptor* pFD)
918 WCHAR* wzFieldName=&wzUniBuf[0];
921 COR_SIGNATURE* mySig;
923 BYTE ValType = ELEMENT_TYPE_VOID;
924 void * pValue = NULL;
928 cSig = pFD->m_pbsSig->length();
929 mySig = (COR_SIGNATURE*)(pFD->m_pbsSig->ptr());
931 WszMultiByteToWideChar(g_uCodePage,0,pFD->m_szName,-1,wzFieldName,dwUniBuf); //int)cFieldNameLength);
932 if(IsFdPrivateScope(pFD->m_dwAttr))
934 WCHAR* p = wcsstr(wzFieldName,W("$PST04"));
938 if(pFD->m_pbsValue && pFD->m_pbsValue->length())
940 ValType = *(pFD->m_pbsValue->ptr());
941 lVal = pFD->m_pbsValue->length() - 1; // 1 is type byte
942 pValue = (void*)(pFD->m_pbsValue->ptr() + 1);
943 if(ValType == ELEMENT_TYPE_STRING)
945 //while(lVal % sizeof(WCHAR)) { pFD->m_pbsValue->appendInt8(0); lVal++; }
946 lVal /= sizeof(WCHAR);
948 #if defined(ALIGN_ACCESS) || BIGENDIAN
949 void* pValueTemp = _alloca(lVal * sizeof(WCHAR));
950 memcpy(pValueTemp, pValue, lVal * sizeof(WCHAR));
953 SwapStringLength((WCHAR*)pValue, lVal);
958 hr = m_pEmitter->DefineField(
971 report->error("Failed to define field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
976 //--------------------------------------------------------------------------------
977 if(IsFdPinvokeImpl(pFD->m_dwAttr)&&(pFD->m_pPInvoke))
979 if(pFD->m_pPInvoke->szAlias == NULL) pFD->m_pPInvoke->szAlias = pFD->m_szName;
980 if(FAILED(EmitPinvokeMap(mb,pFD->m_pPInvoke)))
982 report->error("Failed to define PInvoke map of .field '%s'\n",pFD->m_szName);
986 //--------------------------------------------------------------------------
987 if(pFD->m_pbsMarshal)
989 if(FAILED(hr = m_pEmitter->SetFieldMarshal (
990 mb, // [IN] given a fieldDef or paramDef token
991 (PCCOR_SIGNATURE)(pFD->m_pbsMarshal->ptr()), // [IN] native type specification
992 pFD->m_pbsMarshal->length()))) // [IN] count of bytes of pvNativeType
994 report->error("Failed to set field marshaling for '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
998 //--------------------------------------------------------------------------------
999 // Set the the RVA to a dummy value. later it will be fixed
1000 // up to be something correct, but if we don't emit something
1001 // the size of the meta-data will not be correct
1002 if (pFD->m_rvaLabel)
1004 m_fHaveFieldsWithRvas = TRUE;
1005 hr = m_pEmitter->SetFieldRVA(mb, 0xCCCCCCCC);
1008 report->error("Failed to set RVA for field '%s' (HRESULT=0x%08X)\n",pFD->m_szName,hr);
1012 //--------------------------------------------------------------------------------
1013 EmitCustomAttributes(mb, &(pFD->m_CustomDescrList));
1016 pFD->m_fdFieldTok = mb;
1020 /**************************************************************************/
1021 void Assembler::EmitByte(int val)
1023 char ch = (char)val;
1024 //if((val < -128)||(val > 127))
1025 // report->warn("Emitting 0x%X as a byte: data truncated to 0x%X\n",(unsigned)val,(BYTE)ch);
1026 EmitBytes((BYTE *)&ch,1);
1029 /**************************************************************************/
1030 void Assembler::NewSEHDescriptor(void) //sets m_SEHD
1032 m_SEHDstack.PUSH(m_SEHD);
1033 m_SEHD = new SEH_Descriptor;
1034 if(m_SEHD == NULL) report->error("Failed to allocate SEH descriptor\n");
1036 /**************************************************************************/
1037 void Assembler::SetTryLabels(__in __nullterminated char * szFrom, __in __nullterminated char *szTo)
1040 Label *pLbl = m_pCurMethod->FindLabel(szFrom);
1043 m_SEHD->tryFrom = pLbl->m_PC;
1044 if((pLbl = m_pCurMethod->FindLabel(szTo))) m_SEHD->tryTo = pLbl->m_PC; //FindLabel: Method.CPP
1045 else report->error("Undefined 2nd label in 'try <label> to <label>'\n");
1047 else report->error("Undefined 1st label in 'try <label> to <label>'\n");
1049 /**************************************************************************/
1050 void Assembler::SetFilterLabel(__in __nullterminated char *szFilter)
1053 Label *pLbl = m_pCurMethod->FindLabel(szFilter);
1054 if(pLbl) m_SEHD->sehFilter = pLbl->m_PC;
1055 else report->error("Undefined label in 'filter <label>'\n");
1057 /**************************************************************************/
1058 void Assembler::SetCatchClass(mdToken catchClass)
1061 m_SEHD->cException = catchClass;
1064 /**************************************************************************/
1065 void Assembler::SetHandlerLabels(__in __nullterminated char *szHandlerFrom, __in __nullterminated char *szHandlerTo)
1068 Label *pLbl = m_pCurMethod->FindLabel(szHandlerFrom);
1071 m_SEHD->sehHandler = pLbl->m_PC;
1074 pLbl = m_pCurMethod->FindLabel(szHandlerTo);
1077 m_SEHD->sehHandlerTo = pLbl->m_PC;
1083 m_SEHD->sehHandlerTo = m_SEHD->sehHandler - 1;
1087 report->error("Undefined label in 'handler <label> to <label>'\n");
1089 /**************************************************************************/
1090 void Assembler::EmitTry(void) //enum CorExceptionFlag kind, char* beginLabel, char* endLabel, char* handleLabel, char* filterOrClass)
1094 bool isFilter=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FILTER),
1095 isFault=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FAULT),
1096 isFinally=(m_SEHD->sehClause == COR_ILEXCEPTION_CLAUSE_FINALLY);
1098 AddException(m_SEHD->tryFrom, m_SEHD->tryTo, m_SEHD->sehHandler, m_SEHD->sehHandlerTo,
1099 m_SEHD->cException, isFilter, isFault, isFinally);
1101 else report->error("Attempt to EmitTry with NULL SEH descriptor\n");
1103 /**************************************************************************/
1105 void Assembler::AddException(DWORD pcStart, DWORD pcEnd, DWORD pcHandler, DWORD pcHandlerTo, mdTypeRef crException, BOOL isFilter, BOOL isFault, BOOL isFinally)
1107 if (m_pCurMethod == NULL)
1109 report->error("Exceptions can be declared only when in a method scope\n");
1113 if (m_pCurMethod->m_dwNumExceptions >= m_pCurMethod->m_dwMaxNumExceptions)
1115 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *ptr =
1116 new COR_ILMETHOD_SECT_EH_CLAUSE_FAT[m_pCurMethod->m_dwMaxNumExceptions+MAX_EXCEPTIONS];
1119 report->error("Failed to reallocate SEH buffer\n");
1122 memcpy(ptr,m_pCurMethod->m_ExceptionList,m_pCurMethod->m_dwNumExceptions*sizeof(COR_ILMETHOD_SECT_EH_CLAUSE_FAT));
1123 delete [] m_pCurMethod->m_ExceptionList;
1124 m_pCurMethod->m_ExceptionList = ptr;
1125 m_pCurMethod->m_dwMaxNumExceptions += MAX_EXCEPTIONS;
1128 COR_ILMETHOD_SECT_EH_CLAUSE_FAT *clause = &m_pCurMethod->m_ExceptionList[m_pCurMethod->m_dwNumExceptions];
1129 clause->SetTryOffset(pcStart);
1130 clause->SetTryLength(pcEnd - pcStart);
1131 clause->SetHandlerOffset(pcHandler);
1132 clause->SetHandlerLength(pcHandlerTo - pcHandler);
1133 clause->SetClassToken(crException);
1135 int flags = COR_ILEXCEPTION_CLAUSE_OFFSETLEN;
1137 flags |= COR_ILEXCEPTION_CLAUSE_FILTER;
1140 flags |= COR_ILEXCEPTION_CLAUSE_FAULT;
1143 flags |= COR_ILEXCEPTION_CLAUSE_FINALLY;
1145 clause->SetFlags((CorExceptionFlag)flags);
1147 m_pCurMethod->m_dwNumExceptions++;
1150 /**************************************************************************/
1151 void Assembler::EmitMaxStack(unsigned val)
1153 if(val > 0xFFFF) report->warn(".maxstack parameter exceeds 65535, truncated to %d\n",val&0xFFFF);
1154 if (m_pCurMethod) m_pCurMethod->m_MaxStack = val&0xFFFF;
1155 else report->error(".maxstack can be used only within a method scope\n");
1158 /**************************************************************************/
1159 void Assembler::EmitLocals(BinStr* sig)
1165 ARG_NAME_LIST *pAN, *pList= getArgNameList();
1169 for(pAN=pList; pAN; pAN = pAN->pNext)
1171 if(pAN->dwAttr == 0) pAN->dwAttr = m_pCurMethod->m_Locals.COUNT() +1;
1173 if((pVD = m_pCurMethod->m_Locals.PEEK(pAN->dwAttr)))
1177 report->warn("Local var slot %d is in use\n",pAN->dwAttr);
1179 if(pVD->pbsSig && ((pVD->pbsSig->length() != pAN->pSig->length()) ||
1180 (memcmp(pVD->pbsSig->ptr(),pAN->pSig->ptr(),pVD->pbsSig->length()))))
1182 report->error("Local var slot %d: type conflict\n",pAN->dwAttr);
1186 { // create new entry:
1187 for(unsigned n = m_pCurMethod->m_Locals.COUNT(); n <= pAN->dwAttr; n++)
1190 if(pVD != NULL) m_pCurMethod->m_Locals.PUSH(pVD);
1193 report->error("Out of memory allocating local var descriptor\n");
1199 pVD->dwSlot = pAN->dwAttr;
1200 pVD->pbsSig = pAN->pSig;
1201 pVD->bInScope = TRUE;
1203 if(pVD->pbsSig && (pVD->pbsSig->length() == 1))
1205 if(pVD->pbsSig->ptr()[0] == ELEMENT_TYPE_VOID)
1206 report->error("Illegal local var type: 'void'\n");
1208 m_pCurMethod->m_pCurrScope->pLocals =
1209 m_pCurMethod->catArgNameList(m_pCurMethod->m_pCurrScope->pLocals, pList);
1212 else report->error(".locals can be used only within a method scope\n");
1215 else report->error("Attempt to EmitLocals with NULL argument\n");
1218 /**************************************************************************/
1219 void Assembler::EmitEntryPoint()
1223 if(!m_fEntryPointPresent)
1225 if(IsMdStatic(m_pCurMethod->m_Attr))
1227 m_pCurMethod->m_fEntryPoint = TRUE;
1228 m_fEntryPointPresent = TRUE;
1230 else report->error("Non-static method as entry point\n");
1232 else report->error("Multiple .entrypoint declarations\n");
1234 else report->error(".entrypoint can be used only within a method scope\n");
1237 /**************************************************************************/
1238 void Assembler::EmitZeroInit()
1240 if (m_pCurMethod) m_pCurMethod->m_Flags |= CorILMethod_InitLocals;
1241 else report->error(".zeroinit can be used only within a method scope\n");
1244 /**************************************************************************/
1245 void Assembler::SetImplAttr(unsigned short attrval)
1249 if(IsMiNative(attrval)||IsMiOPTIL(attrval)||IsMiUnmanaged(attrval))
1250 report->error("Cannot compile native/unmanaged method\n");
1251 m_pCurMethod->m_wImplAttr = attrval;
1255 /**************************************************************************/
1256 void Assembler::EmitData(__in_opt void *buffer, unsigned len)
1261 HRESULT hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, len, 1, &ptr);
1264 report->error("Could not extend data section (out of memory?)");
1270 memcpy(ptr, buffer, len);
1274 memset(ptr, 0, len);
1279 /**************************************************************************/
1280 void Assembler::EmitDD(__in __nullterminated char *str)
1283 GlobalLabel *pLabel = FindGlobalLabel(str);
1286 HRESULT hr = m_pCeeFileGen->GetSectionDataLen(m_pCurSection, &loc);
1287 _ASSERTE(SUCCEEDED(hr));
1290 DWORD sizeofptr = (DWORD)((m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32) ? sizeof(DWORD) : sizeof(__int64));
1291 hr = m_pCeeFileGen->GetSectionBlock(m_pCurSection, sizeofptr, 1, (void**) &ptr);
1294 report->error("Could not extend data section (out of memory?)");
1299 dwAddr = pLabel->m_GlobalOffset;
1300 if (pLabel->m_Section != m_pGlobalDataSection) {
1301 report->error("For '&label', label must be in data section");
1302 m_State = STATE_FAIL;
1306 AddDeferredGlobalFixup(str, (BYTE*) ptr);
1308 hr = m_pCeeFileGen->AddSectionReloc(m_pCurSection, loc, m_pGlobalDataSection, srRelocHighLow);
1309 _ASSERTE(SUCCEEDED(hr));
1310 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_STRIP_RELOCS)
1312 report->error("Base relocations are emitted, while /STRIPRELOC option has been specified");
1314 if(m_dwCeeFileFlags & ICEE_CREATE_FILE_PE32)
1316 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1317 if (m_dwCeeFileFlags & ICEE_CREATE_MACHINE_I386)
1318 COR_SET_32BIT_REQUIRED(m_dwComImageFlags);
1323 m_dwComImageFlags &= ~COMIMAGE_FLAGS_ILONLY;
1324 *((__int64*)ptr) = (__int64)dwAddr;
1328 /**************************************************************************/
1329 GlobalLabel *Assembler::FindGlobalLabel(LPCUTF8 pszName)
1331 GlobalLabel lSearch(pszName,0,NULL), *pL;
1332 pL = m_lstGlobalLabel.FIND(&lSearch);
1333 lSearch.m_szName = NULL;
1335 //return m_lstGlobalLabel.FIND(pszName);
1338 /**************************************************************************/
1340 GlobalFixup *Assembler::AddDeferredGlobalFixup(__in __nullterminated char *pszLabel, BYTE* pReference)
1342 GlobalFixup *pNew = new GlobalFixup(pszLabel, (BYTE*) pReference);
1345 report->error("Failed to allocate global fixup\n");
1346 m_State = STATE_FAIL;
1349 m_lstGlobalFixup.PUSH(pNew);
1354 /**************************************************************************/
1355 void Assembler::AddDeferredILFixup(ILFixupType Kind)
1357 _ASSERTE(Kind != ilGlobal);
1358 AddDeferredILFixup(Kind, NULL);
1360 /**************************************************************************/
1362 void Assembler::AddDeferredILFixup(ILFixupType Kind,
1363 GlobalFixup *GFixup)
1365 ILFixup *pNew = new ILFixup(m_CurPC, Kind, GFixup);
1367 _ASSERTE(m_pCurMethod != NULL);
1370 report->error("Failed to allocate IL fixup\n");
1371 m_State = STATE_FAIL;
1374 m_pCurMethod->m_lstILFixup.PUSH(pNew);
1377 /**************************************************************************/
1378 void Assembler::EmitDataString(BinStr* str)
1383 DWORD DataLen = str->length();
1384 char *pb = (char*)(str->ptr());
1385 WCHAR *UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen] : &wzUniBuf[0];
1389 WszMultiByteToWideChar(g_uCodePage,0,pb,-1,UnicodeString,DataLen);
1390 EmitData(UnicodeString,DataLen*sizeof(WCHAR));
1391 if(DataLen >= dwUniBuf) delete [] UnicodeString;
1393 else report->error("\nOut of memory!\n");
1400 /**************************************************************************/
1401 unsigned Assembler::OpcodeLen(Instr* instr)
1403 return (m_fStdMapping ? OpcodeInfo[instr->opcode].Len : 3);
1405 /**************************************************************************/
1406 void Assembler::EmitOpcode(Instr* instr)
1408 if(m_fGeneratePDB &&
1409 ((instr->linenum != m_ulLastDebugLine)
1410 ||(instr->column != m_ulLastDebugColumn)
1411 ||(instr->linenum_end != m_ulLastDebugLineEnd)
1412 ||(instr->column_end != m_ulLastDebugColumnEnd)))
1416 LinePC *pLPC = new LinePC;
1419 pLPC->Line = instr->linenum;
1420 pLPC->Column = instr->column;
1421 pLPC->LineEnd = instr->linenum_end;
1422 pLPC->ColumnEnd = instr->column_end;
1424 pLPC->pWriter = instr->pWriter;
1425 m_pCurMethod->m_LinePCList.PUSH(pLPC);
1427 else report->error("\nOut of memory!\n");
1429 m_ulLastDebugLine = instr->linenum;
1430 m_ulLastDebugColumn = instr->column;
1431 m_ulLastDebugLineEnd = instr->linenum_end;
1432 m_ulLastDebugColumnEnd = instr->column_end;
1434 if(instr->opcode == CEE_ENDFILTER)
1438 if(m_pCurMethod->m_dwNumEndfilters >= m_pCurMethod->m_dwMaxNumEndfilters)
1440 DWORD *pdw = new DWORD[m_pCurMethod->m_dwMaxNumEndfilters+MAX_EXCEPTIONS];
1443 report->error("Failed to reallocate auxiliary SEH buffer\n");
1447 memcpy(pdw,m_pCurMethod->m_EndfilterOffsetList,m_pCurMethod->m_dwNumEndfilters*sizeof(DWORD));
1448 delete m_pCurMethod->m_EndfilterOffsetList;
1449 m_pCurMethod->m_EndfilterOffsetList = pdw;
1450 m_pCurMethod->m_dwMaxNumEndfilters += MAX_EXCEPTIONS;
1452 m_pCurMethod->m_EndfilterOffsetList[m_pCurMethod->m_dwNumEndfilters++] = m_CurPC+2;
1457 if (OpcodeInfo[instr->opcode].Len == 2)
1458 EmitByte(OpcodeInfo[instr->opcode].Std1);
1459 EmitByte(OpcodeInfo[instr->opcode].Std2);
1463 unsigned short us = (unsigned short)instr->opcode;
1465 EmitBytes((BYTE *)&us,2);
1470 /**************************************************************************/
1471 //void Assembler::OptimizeInstr(Instr* instr, int var)
1475 /**************************************************************************/
1476 unsigned Assembler::ShortOf(unsigned opcode)
1481 case CEE_LDARG: retcode=CEE_LDARG_S; break;
1482 case CEE_LDARGA: retcode=CEE_LDARGA_S; break;
1483 case CEE_STARG: retcode=CEE_STARG_S; break;
1485 case CEE_LDLOC: retcode=CEE_LDLOC_S; break;
1486 case CEE_LDLOCA: retcode=CEE_LDLOCA_S; break;
1487 case CEE_STLOC: retcode=CEE_STLOC_S; break;
1489 case CEE_BR: retcode=CEE_BR_S; break;
1490 case CEE_BRFALSE: retcode=CEE_BRFALSE_S; break;
1491 case CEE_BRTRUE: retcode=CEE_BRTRUE_S; break;
1492 case CEE_BEQ: retcode=CEE_BEQ_S; break;
1493 case CEE_BGE: retcode=CEE_BGE_S; break;
1494 case CEE_BGT: retcode=CEE_BGT_S; break;
1495 case CEE_BLE: retcode=CEE_BLE_S; break;
1496 case CEE_BLT: retcode=CEE_BLT_S; break;
1497 case CEE_BNE_UN: retcode=CEE_BNE_UN_S; break;
1498 case CEE_BGE_UN: retcode=CEE_BGE_UN_S; break;
1499 case CEE_BGT_UN: retcode=CEE_BGT_UN_S; break;
1500 case CEE_BLE_UN: retcode=CEE_BLE_UN_S; break;
1501 case CEE_BLT_UN: retcode=CEE_BLT_UN_S; break;
1502 case CEE_LEAVE: retcode=CEE_LEAVE_S; break;
1504 case CEE_LDC_I4: retcode=CEE_LDC_I4_S; break;
1505 case CEE_LDC_R8: retcode=CEE_LDC_R4; break;
1508 default: retcode = opcode; break;
1513 /**************************************************************************/
1514 void Assembler::EmitInstrVar(Instr* instr, int var)
1516 unsigned opc = instr->opcode;
1524 case CEE_LDARG_S: opc = CEE_LDARG_0 + var; break;
1527 case CEE_LDLOC_S: opc = CEE_LDLOC_0 + var; break;
1530 case CEE_STLOC_S: opc = CEE_STLOC_0 + var; break;
1534 if(opc != (unsigned) instr->opcode)
1536 instr->opcode = opc;
1543 opc = instr->opcode = ShortOf(opc);
1553 short sh = (short)var;
1554 EmitBytes((BYTE *)&sh,2);
1558 /**************************************************************************/
1559 void Assembler::EmitInstrVarByName(Instr* instr, __in __nullterminated char* label)
1561 int idx = -1, nArgVarFlag=0;
1562 switch(instr->opcode)
1580 DWORD L = (DWORD)strlen(label);
1581 if(nArgVarFlag == 1)
1583 idx = m_pCurMethod->findArgNum(m_pCurMethod->m_firstArgName,label,L);
1587 for(Scope* pSC = m_pCurMethod->m_pCurrScope; pSC; pSC=pSC->pSuperScope)
1589 idx = m_pCurMethod->findLocSlot(pSC->pLocals,label,L);
1593 if(idx >= 0) EmitInstrVar(instr,
1594 ((nArgVarFlag==0)||(m_pCurMethod->m_Attr & mdStatic))? idx : idx+1);
1595 else report->error("Undeclared identifier %s\n",label);
1598 report->error("Instructions can be used only when in a method scope\n");
1601 report->error("Named argument illegal for this instruction\n");
1603 instr->opcode = -1; // in case we got here with error
1606 /**************************************************************************/
1607 void Assembler::EmitInstrI(Instr* instr, int val)
1609 int opc = instr->opcode;
1612 if((val >= -1)&&(val <= 8))
1617 case CEE_LDC_I4_S: opc = CEE_LDC_I4_M1 + (val+1); break;
1621 if(opc != instr->opcode)
1623 instr->opcode = opc;
1628 if((-128 <= val)&&(val <= 127))
1630 opc = instr->opcode = ShortOf(opc);
1641 EmitBytes((BYTE *)&i,sizeof(int));
1645 /**************************************************************************/
1646 void Assembler::EmitInstrI8(Instr* instr, __int64* val)
1649 EmitBytes((BYTE *)val, sizeof(__int64));
1653 /**************************************************************************/
1654 void Assembler::EmitInstrR(Instr* instr, double* pval)
1656 unsigned opc = instr->opcode;
1660 float val = (float)*pval;
1661 EmitBytes((BYTE *)&val, sizeof(float));
1664 EmitBytes((BYTE *)pval, sizeof(double));
1667 /**************************************************************************/
1668 void Assembler::EmitInstrBrTarget(Instr* instr, __in __nullterminated char* label)
1670 Label * pLabel = m_pCurMethod->FindLabel(label);
1672 if (pLabel == NULL) // branching forward -- no optimization
1674 int pcrelsize = 1+(isShort(instr->opcode) ? 1 : 4); //size of the instruction plus argument
1675 AddDeferredFixup(label, m_pCurOutputPos+1,
1676 (m_CurPC + pcrelsize), pcrelsize-1);
1680 offset = pLabel->m_PC - m_CurPC;
1683 if((-128 <= offset-5)&&(offset-2 <= 127)) //need to take into account the argument size (worst cases)
1685 instr->opcode = ShortOf(instr->opcode);
1688 if(isShort(instr->opcode))
1691 if((-128 > offset)||(offset > 127))
1692 report->error("Offset too large for short branching instruction, truncated\n");
1698 int opc = instr->opcode;
1700 if(isShort(opc)) EmitByte(offset);
1701 else EmitBytes((BYTE *)&offset,4);
1703 /**************************************************************************/
1704 void Assembler::AddDeferredFixup(__in __nullterminated char *pszLabel, BYTE *pBytes, DWORD RelativeToPC, BYTE FixupSize)
1706 Fixup *pNew = new Fixup(pszLabel, pBytes, RelativeToPC, FixupSize);
1710 report->error("Failed to allocate deferred fixup\n");
1711 m_State = STATE_FAIL;
1714 m_pCurMethod->m_lstFixup.PUSH(pNew);
1716 /**************************************************************************/
1717 void Assembler::EmitInstrBrOffset(Instr* instr, int offset)
1719 unsigned opc=instr->opcode;
1722 if((-128 <= offset)&&(offset <= 127))
1724 opc = instr->opcode = ShortOf(opc);
1728 if(isShort(opc)) EmitByte(offset);
1732 EmitBytes((BYTE *)&i,4);
1736 /**************************************************************************/
1737 mdToken Assembler::MakeMemberRef(mdToken cr, __in __nullterminated char* pszMemberName, BinStr* sig)
1739 DWORD cSig = sig->length();
1740 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1741 mdToken mr = mdMemberRefNil;
1742 Class* pClass = NULL;
1743 if(cr == 0x00000001) cr = mdTokenNil; // Module -> nil for globals
1744 if(TypeFromToken(cr) == mdtTypeDef) pClass = m_lstClass.PEEK(RidFromToken(cr)-1);
1745 if((TypeFromToken(cr) == mdtTypeDef)||(cr == mdTokenNil))
1747 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1750 pMRD->m_tdClass = cr;
1751 pMRD->m_pClass = pClass;
1752 pMRD->m_szName = pszMemberName;
1753 pMRD->m_dwName = (DWORD)strlen(pszMemberName);
1754 pMRD->m_pSigBinStr = sig;
1755 pMRD->m_tkResolved = 0;
1756 if(*(sig->ptr())== IMAGE_CEE_CS_CALLCONV_FIELD)
1758 m_LocalFieldRefDList.PUSH(pMRD);
1759 mr = 0x98000000 | m_LocalFieldRefDList.COUNT();
1763 m_LocalMethodRefDList.PUSH(pMRD);
1764 mr = 0x99000000 | m_LocalMethodRefDList.COUNT();
1769 report->error("Failed to allocate MemberRef Descriptor\n");
1775 WszMultiByteToWideChar(g_uCodePage,0,pszMemberName,-1,wzUniBuf,dwUniBuf);
1777 if(cr == mdTokenNil) cr = mdTypeRefNil;
1778 if(TypeFromToken(cr) == mdtAssemblyRef)
1780 report->error("Cross-assembly global references are not supported ('%s')\n", pszMemberName);
1785 HRESULT hr = m_pEmitter->DefineMemberRef(cr, wzUniBuf, mySig, cSig, &mr);
1788 report->error("Unable to define member reference '%s'\n", pszMemberName);
1792 //if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,mr));
1793 delete pszMemberName;
1798 /**************************************************************************/
1799 void Assembler::SetMemberRefFixup(mdToken tk, unsigned opcode_len)
1803 switch(TypeFromToken(tk))
1808 if(m_pCurMethod != NULL)
1809 m_pCurMethod->m_LocalMemberRefFixupList.PUSH(
1810 new LocalMemberRefFixup(tk,(size_t)(m_CurPC + opcode_len)));
1816 /**************************************************************************/
1817 mdToken Assembler::MakeMethodSpec(mdToken tkParent, BinStr* sig)
1819 DWORD cSig = sig->length();
1820 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
1821 mdMethodSpec mi = mdMethodSpecNil;
1822 if(TypeFromToken(tkParent) == 0x99000000) // Local MemberRef: postpone until resolved
1824 MemberRefDescriptor* pMRD = new MemberRefDescriptor;
1827 memset(pMRD,0,sizeof(MemberRefDescriptor));
1828 pMRD->m_tdClass = tkParent;
1829 pMRD->m_pSigBinStr = sig;
1830 m_MethodSpecList.PUSH(pMRD);
1831 mi = 0x9A000000 | m_MethodSpecList.COUNT();
1835 report->error("Failed to allocate MemberRef Descriptor\n");
1841 HRESULT hr = m_pEmitter->DefineMethodSpec(tkParent, mySig, cSig, &mi);
1844 report->error("Unable to define method instantiation");
1851 /**************************************************************************/
1852 void Assembler::EndEvent(void)
1854 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1855 if(m_pCurEvent->m_tkAddOn == 0)
1856 report->error("Event %s of class %s has no Add method. Event not emitted.",
1857 m_pCurEvent->m_szName,pClass->m_szFQN);
1858 else if(m_pCurEvent->m_tkRemoveOn == 0)
1859 report->error("Event %s of class %s has no Remove method. Event not emitted.",
1860 m_pCurEvent->m_szName,pClass->m_szFQN);
1863 pClass->m_EventDList.PUSH(m_pCurEvent);
1864 pClass->m_fNewMembers = TRUE;
1867 m_tkCurrentCVOwner = 0;
1868 m_pCustomDescrList = m_CustomDescrListStack.POP();
1871 void Assembler::ResetEvent(__inout_z __inout char* szName, mdToken typeSpec, DWORD dwAttr)
1873 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1875 char c = szName[MAX_CLASSNAME_LENGTH-1];
1876 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1877 report->error("Event '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1878 szName[MAX_CLASSNAME_LENGTH-1] = c;
1880 if((m_pCurEvent = new EventDescriptor))
1882 memset(m_pCurEvent,0,sizeof(EventDescriptor));
1883 m_pCurEvent->m_tdClass = m_pCurClass->m_cl;
1884 m_pCurEvent->m_szName = szName;
1885 m_pCurEvent->m_dwAttr = dwAttr;
1886 m_pCurEvent->m_tkEventType = typeSpec;
1887 m_pCurEvent->m_fNew = TRUE;
1888 m_tkCurrentCVOwner = 0;
1889 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1890 m_pCustomDescrList = &(m_pCurEvent->m_CustomDescrList);
1892 else report->error("Failed to allocate Event Descriptor\n");
1895 void Assembler::SetEventMethod(int MethodCode, mdToken tk)
1900 m_pCurEvent->m_tkAddOn = tk;
1903 m_pCurEvent->m_tkRemoveOn = tk;
1906 m_pCurEvent->m_tkFire = tk;
1909 m_pCurEvent->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
1913 /**************************************************************************/
1915 void Assembler::EndProp(void)
1917 Class* pClass = (m_pCurClass ? m_pCurClass : m_pModuleClass);
1918 pClass->m_PropDList.PUSH(m_pCurProp);
1919 pClass->m_fNewMembers = TRUE;
1921 m_tkCurrentCVOwner = 0;
1922 m_pCustomDescrList = m_CustomDescrListStack.POP();
1925 void Assembler::ResetProp(__inout_z __inout char * szName, BinStr* bsType, DWORD dwAttr, BinStr* pValue)
1927 DWORD cSig = bsType->length();
1928 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(bsType->ptr());
1930 if(strlen(szName) >= MAX_CLASSNAME_LENGTH)
1932 char c = szName[MAX_CLASSNAME_LENGTH-1];
1933 szName[MAX_CLASSNAME_LENGTH-1] = 0;
1934 report->error("Property '%s...' -- name too long (%d characters).\n",szName,strlen(szName));
1935 szName[MAX_CLASSNAME_LENGTH-1] = c;
1937 m_pCurProp = new PropDescriptor;
1938 if(m_pCurProp == NULL)
1940 report->error("Failed to allocate Property Descriptor\n");
1943 memset(m_pCurProp,0,sizeof(PropDescriptor));
1944 m_pCurProp->m_tdClass = m_pCurClass->m_cl;
1945 m_pCurProp->m_szName = szName;
1946 m_pCurProp->m_dwAttr = dwAttr;
1947 m_pCurProp->m_fNew = TRUE;
1949 m_pCurProp->m_pSig = new COR_SIGNATURE[cSig];
1950 if(m_pCurProp->m_pSig == NULL)
1952 report->error("\nOut of memory!\n");
1955 memcpy(m_pCurProp->m_pSig,mySig,cSig);
1956 m_pCurProp->m_dwCSig = cSig;
1958 if(pValue && pValue->length())
1960 BYTE* pch = pValue->ptr();
1961 m_pCurProp->m_dwCPlusTypeFlag = (DWORD)(*pch);
1962 m_pCurProp->m_cbValue = pValue->length() - 1;
1963 m_pCurProp->m_pValue = (PVOID)(pch+1);
1964 if(m_pCurProp->m_dwCPlusTypeFlag == ELEMENT_TYPE_STRING) m_pCurProp->m_cbValue /= sizeof(WCHAR);
1965 m_pCurProp->m_dwAttr |= prHasDefault;
1969 m_pCurProp->m_dwCPlusTypeFlag = ELEMENT_TYPE_VOID;
1970 m_pCurProp->m_pValue = NULL;
1971 m_pCurProp->m_cbValue = 0;
1973 m_tkCurrentCVOwner = 0;
1974 m_CustomDescrListStack.PUSH(m_pCustomDescrList);
1975 m_pCustomDescrList = &(m_pCurProp->m_CustomDescrList);
1978 void Assembler::SetPropMethod(int MethodCode, mdToken tk)
1983 m_pCurProp->m_tkSet = tk;
1986 m_pCurProp->m_tkGet = tk;
1989 m_pCurProp->m_tklOthers.PUSH((mdToken*)(UINT_PTR)tk);
1994 /**************************************************************************/
1995 void Assembler::EmitInstrStringLiteral(Instr* instr, BinStr* literal, BOOL ConvertToUnicode, BOOL Swap /*=FALSE*/)
1997 DWORD DataLen = literal->length(),L;
1998 unsigned __int8 *pb = literal->ptr();
2001 WCHAR *UnicodeString;
2004 //report->warn("Zero length string emitted\n");
2005 ConvertToUnicode = FALSE;
2007 if(ConvertToUnicode)
2009 UnicodeString = (DataLen >= dwUniBuf) ? new WCHAR[DataLen+1] : &wzUniBuf[0];
2010 literal->appendInt8(0);
2011 pb = literal->ptr();
2012 // convert string to Unicode
2013 L = UnicodeString ? WszMultiByteToWideChar(g_uCodePage,0,(char*)pb,-1,UnicodeString,DataLen+1) : 0;
2016 const char* sz=NULL;
2018 switch(dw=GetLastError())
2020 case ERROR_INSUFFICIENT_BUFFER: sz = "ERROR_INSUFFICIENT_BUFFER"; break;
2021 case ERROR_INVALID_FLAGS: sz = "ERROR_INVALID_FLAGS"; break;
2022 case ERROR_INVALID_PARAMETER: sz = "ERROR_INVALID_PARAMETER"; break;
2023 case ERROR_NO_UNICODE_TRANSLATION: sz = "ERROR_NO_UNICODE_TRANSLATION"; break;
2025 if(sz) report->error("Failed to convert string '%s' to Unicode: %s\n",(char*)pb,sz);
2026 else report->error("Failed to convert string '%s' to Unicode: error 0x%08X\n",(char*)pb,dw);
2036 literal->appendInt8(0);
2037 pb = literal->ptr();
2040 UnicodeString = (WCHAR*)pb;
2041 L = DataLen/sizeof(WCHAR);
2045 SwapStringLength(UnicodeString, L);
2048 // Add the string data to the metadata, which will fold dupes.
2049 hr = m_pEmitter->DefineUserString(
2056 report->error("Failed to add user string using DefineUserString, hr=0x%08x, data: '%S'\n",
2063 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,tk));
2065 EmitBytes((BYTE *)&tk,sizeof(mdToken));
2069 if(((void*)UnicodeString != (void*)pb)&&(DataLen >= dwUniBuf)) delete [] UnicodeString;
2070 instr->opcode = -1; // in case we got here with error
2073 /**************************************************************************/
2074 void Assembler::EmitInstrSig(Instr* instr, BinStr* sig)
2076 mdSignature MetadataToken;
2077 DWORD cSig = sig->length();
2078 COR_SIGNATURE* mySig = (COR_SIGNATURE *)(sig->ptr());
2080 if (FAILED(m_pEmitter->GetTokenFromSig(mySig, cSig, &MetadataToken)))
2082 report->error("Unable to convert signature to metadata token.\n");
2088 if(m_fOBJ) m_pCurMethod->m_TRDList.PUSH(new TokenRelocDescr(m_CurPC,MetadataToken));
2089 EmitBytes((BYTE *)&MetadataToken, sizeof(mdSignature));
2092 instr->opcode = -1; // in case we got here with error
2095 /**************************************************************************/
2096 void Assembler::EmitInstrSwitch(Instr* instr, Labels* targets)
2106 for(pLbls = targets, NumLabels = 0; pLbls; pLbls = pLbls->Next, NumLabels++);
2108 EmitBytes((BYTE *)&NumLabels,sizeof(int));
2109 DWORD PC_nextInstr = m_CurPC + 4*NumLabels;
2110 for(pLbls = targets; pLbls; pLbls = pLbls->Next)
2114 if((pLabel = m_pCurMethod->FindLabel(pLbls->Label)))
2116 offset = pLabel->m_PC - PC_nextInstr;
2117 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2121 // defer until we find the label
2122 AddDeferredFixup(pLbls->Label, m_pCurOutputPos, PC_nextInstr, 4 /* pcrelsize */ );
2124 pLbls->Label = NULL;
2125 if (m_fDisplayTraceOutput) report->msg("forward label %s\n", pLbls->Label);
2130 offset = (UINT)(UINT_PTR)pLbls->Label;
2131 if (m_fDisplayTraceOutput) report->msg("%d\n", offset);
2133 EmitBytes((BYTE *)&offset, sizeof(UINT));
2138 /**************************************************************************/
2139 void Assembler::EmitLabel(__in __nullterminated char* label)
2141 _ASSERTE(m_pCurMethod);
2142 AddLabel(m_CurPC, label);
2144 /**************************************************************************/
2145 void Assembler::EmitDataLabel(__in __nullterminated char* label)
2147 AddGlobalLabel(label, m_pCurSection);
2150 /**************************************************************************/
2151 void Assembler::EmitBytes(BYTE *p, unsigned len)
2153 if(m_pCurOutputPos + len >= m_pEndOutputPos)
2155 size_t buflen = m_pEndOutputPos - m_pOutputBuffer;
2156 size_t newlen = buflen+(len/OUTPUT_BUFFER_INCREMENT + 1)*OUTPUT_BUFFER_INCREMENT;
2157 BYTE *pb = new BYTE[newlen];
2160 report->error("Failed to extend output buffer from %d to %d bytes. Aborting\n",
2164 size_t delta = pb - m_pOutputBuffer;
2167 GlobalFixup *pGSearch;
2168 for (i=0; (pSearch = m_pCurMethod->m_lstFixup.PEEK(i)); i++) pSearch->m_pBytes += delta;
2169 for (i=0; (pGSearch = m_lstGlobalFixup.PEEK(i)); i++) //need to move only those pointing to output buffer
2171 if((pGSearch->m_pReference >= m_pOutputBuffer)&&(pGSearch->m_pReference <= m_pEndOutputPos))
2172 pGSearch->m_pReference += delta;
2176 memcpy(pb,m_pOutputBuffer,m_CurPC);
2177 delete m_pOutputBuffer;
2178 m_pOutputBuffer = pb;
2179 m_pCurOutputPos = &m_pOutputBuffer[m_CurPC];
2180 m_pEndOutputPos = &m_pOutputBuffer[newlen];
2187 *m_pCurOutputPos = *p;
2190 SET_UNALIGNED_VAL16(m_pCurOutputPos, GET_UNALIGNED_16(p));
2193 SET_UNALIGNED_VAL32(m_pCurOutputPos, GET_UNALIGNED_32(p));
2196 SET_UNALIGNED_VAL64(m_pCurOutputPos, GET_UNALIGNED_64(p));
2203 m_pCurOutputPos += len;
2206 /**************************************************************************/
2207 BinStr* Assembler::EncodeSecAttr(__in __nullterminated char* szReflName, BinStr* pbsSecAttrBlob, unsigned nProps)
2211 // build the blob As BinStr
2212 unsigned L = (unsigned) strlen(szReflName);
2214 BinStr* pbsRet = new BinStr();
2215 // encode the Reflection name length
2216 cnt = CorSigCompressData(L, pbsRet->getBuff(5));
2217 pbsRet->remove(5 - cnt);
2219 if((pb = pbsRet->getBuff(L)) != NULL)
2220 memcpy(pb,szReflName,L);
2221 // find out the size of compressed nProps
2222 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2225 unsigned nSize = cnt + pbsSecAttrBlob->length();
2226 cnt = CorSigCompressData(nSize, pbsRet->getBuff(5));
2227 pbsRet->remove(5 - cnt);
2228 // actually encode nProps
2229 cnt = CorSigCompressData(nProps, pbsRet->getBuff(5));
2230 pbsRet->remove(5 - cnt);
2231 // append the props/values blob
2232 pbsRet->append(pbsSecAttrBlob);
2233 delete pbsSecAttrBlob;
2236 /**************************************************************************/
2237 void Assembler::EmitSecurityInfo(mdToken token,
2238 PermissionDecl* pPermissions,
2239 PermissionSetDecl* pPermissionSets)
2241 PermissionDecl *pPerm, *pPermNext;
2242 PermissionSetDecl *pPset, *pPsetNext;
2243 unsigned uCount = 0;
2244 COR_SECATTR *pAttrs;
2247 mdTypeRef tkTypeRef;
2250 DWORD dwErrorIndex = 0;
2254 for (pPerm = pPermissions; pPerm; pPerm = pPerm->m_Next)
2257 _ASSERTE(uCount > 0);
2258 // uCount is expected to be positive all the time. The if statement is here to please prefast.
2261 if((pAttrs = new COR_SECATTR[uCount])==NULL)
2263 report->error("\nOut of memory!\n");
2267 mdToken tkMscorlib = m_fIsMscorlib ? 1 : GetAsmRef("mscorlib");
2268 tkTypeRef = ResolveClassRef(tkMscorlib,"System.Security.Permissions.SecurityAction", NULL);
2269 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2270 pPermNext = pPerm->m_Next;
2272 pSig = new BinStr();
2273 pSig->appendInt8(IMAGE_CEE_CS_CALLCONV_DEFAULT_HASTHIS);
2274 pSig->appendInt8(1);
2275 pSig->appendInt8(ELEMENT_TYPE_VOID);
2276 pSig->appendInt8(ELEMENT_TYPE_VALUETYPE);
2277 uLength = CorSigCompressToken(tkTypeRef, pSig->getBuff(5));
2278 pSig->remove(5 - uLength);
2280 uLength = (unsigned)strlen(COR_CTOR_METHOD_NAME) + 1;
2281 if((szMemberName = new char[uLength]))
2283 memcpy(szMemberName, COR_CTOR_METHOD_NAME, uLength);
2284 pAttrs[i].tkCtor = MakeMemberRef(pPerm->m_TypeSpec, szMemberName, pSig);
2285 pAttrs[i].pCustomAttribute = (const void *)pPerm->m_Blob;
2286 pAttrs[i].cbCustomAttribute = pPerm->m_BlobLength;
2288 else report->error("\nOut of memory!\n");
2291 if (FAILED(m_pEmitter->DefineSecurityAttributeSet(token,
2296 _ASSERT(uCount >= dwErrorIndex);
2297 if (dwErrorIndex == uCount)
2299 report->error("Failed to define security attribute set for 0x%08X\n", token);
2303 report->error("Failed to define security attribute set for 0x%08X\n (error in permission %u)\n",
2304 token, uCount - dwErrorIndex);
2308 for (pPerm = pPermissions, i = 0; pPerm; pPerm = pPermNext, i++) {
2309 pPermNext = pPerm->m_Next;
2315 for (pPset = pPermissionSets; pPset; pPset = pPsetNext) {
2316 pPsetNext = pPset->m_Next;
2317 if(FAILED(m_pEmitter->DefinePermissionSet(token,
2319 pPset->m_Value->ptr(),
2320 pPset->m_Value->length(),
2322 report->error("Failed to define security permission set for 0x%08X\n", token);
2327 void Assembler::AddMethodImpl(mdToken tkImplementedTypeSpec, __in __nullterminated char* szImplementedName, BinStr* pImplementedSig,
2328 mdToken tkImplementingTypeSpec, __in_opt __nullterminated char* szImplementingName, BinStr* pImplementingSig)
2332 MethodImplDescriptor* pMID = new MethodImplDescriptor;
2333 pMID->m_fNew = TRUE;
2336 report->error("Failed to allocate MethodImpl Descriptor\n");
2339 pMID->m_tkDefiningClass = m_pCurClass->m_cl;
2340 if(szImplementingName) //called from class scope, overriding method specified
2342 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2343 pMID->m_tkImplementingMethod = MakeMemberRef(tkImplementingTypeSpec,szImplementingName,pImplementingSig);
2345 else //called from method scope, use current method as overriding
2349 if (pImplementedSig == NULL)
2351 pImplementedSig = new BinStr();
2352 memcpy(pImplementedSig->getBuff(m_pCurMethod->m_dwMethodCSig), m_pCurMethod->m_pMethodSig,m_pCurMethod->m_dwMethodCSig);
2354 pMID->m_tkImplementedMethod = MakeMemberRef(tkImplementedTypeSpec,szImplementedName,pImplementedSig);
2355 pMID->m_tkImplementingMethod = 0;
2357 m_pCurMethod->m_MethodImplDList.PUSH(pMID); // copy goes to method's own list (ptr only)
2361 report->error("No overriding method specified");
2366 m_MethodImplDList.PUSH(pMID);
2369 report->error(".override directive outside class scope");
2371 // source file name paraphernalia
2372 void Assembler::SetSourceFileName(__in __nullterminated char* szName)
2378 if(strcmp(m_szSourceFileName,szName))
2380 strcpy_s(m_szSourceFileName,MAX_FILENAME_LENGTH*3+1,szName);
2381 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,m_wzSourceFileName,MAX_FILENAME_LENGTH);
2387 while((pDW = m_DocWriterList.PEEK(i++)) != NULL)
2389 if(!strcmp(szName,pDW->Name)) break;
2393 m_pSymDocument = pDW->pWriter;
2396 else if(m_pSymWriter)
2399 WszMultiByteToWideChar(g_uCodePage,0,szName,-1,wzUniBuf,dwUniBuf);
2400 if(FAILED(hr=m_pSymWriter->DefineDocument(wzUniBuf,&m_guidLang,
2401 &m_guidLangVendor,&m_guidDoc,&m_pSymDocument)))
2403 m_pSymDocument = NULL;
2404 report->error("Failed to define a document writer");
2406 if((pDW = new DocWriter()) != NULL)
2409 pDW->pWriter = m_pSymDocument;
2410 m_DocWriterList.PUSH(pDW);
2414 report->error("Out of memory");
2418 else delete [] szName;
2420 else delete [] szName;
2422 else delete [] szName;
2425 void Assembler::SetSourceFileName(BinStr* pbsName)
2428 if(pbsName && (L = (ULONG)(pbsName->length())))
2430 pbsName->appendInt8(0);
2431 char* sz = new char[L+1];
2432 memcpy(sz,pbsName->ptr(),L+1);
2433 SetSourceFileName(sz);