/// <summary>Sets the name and lexical scope of this local variable.</summary>
        /// <param name="name">The name of the local variable. </param>
        /// <param name="startOffset">The beginning offset of the lexical scope of the local variable. </param>
        /// <param name="endOffset">The ending offset of the lexical scope of the local variable. </param>
        /// <exception cref="T:System.InvalidOperationException">The containing type has been created with <see cref="M:System.Reflection.Emit.TypeBuilder.CreateType" />.-or- There is no symbolic writer defined for the containing module. </exception>
        /// <exception cref="T:System.NotSupportedException">This local is defined in a dynamic method, rather than in a method of a dynamic type.</exception>
        // Token: 0x060049F6 RID: 18934 RVA: 0x0010B4A8 File Offset: 0x001096A8
        public void SetLocalSymInfo(string name, int startOffset, int endOffset)
        {
            MethodBuilder methodBuilder = this.m_methodBuilder as MethodBuilder;

            if (methodBuilder == null)
            {
                throw new NotSupportedException();
            }
            ModuleBuilder moduleBuilder = (ModuleBuilder)methodBuilder.Module;

            if (methodBuilder.IsTypeCreated())
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
            }
            if (moduleBuilder.GetSymWriter() == null)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }
            SignatureHelper fieldSigHelper = SignatureHelper.GetFieldSigHelper(moduleBuilder);

            fieldSigHelper.AddArgument(this.m_localType);
            int num;

            byte[] sourceArray = fieldSigHelper.InternalGetSignature(out num);
            byte[] array       = new byte[num - 1];
            Array.Copy(sourceArray, 1, array, 0, num - 1);
            int currentActiveScopeIndex = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex();

            if (currentActiveScopeIndex == -1)
            {
                methodBuilder.m_localSymInfo.AddLocalSymInfo(name, array, this.m_localIndex, startOffset, endOffset);
                return;
            }
            methodBuilder.GetILGenerator().m_ScopeTree.AddLocalSymInfoToCurrentScope(name, array, this.m_localIndex, startOffset, endOffset);
        }
예제 #2
0
        /*******************
         *
         * This is different from CustomAttribute. This is stored into the SymWriter.
         *
         ********************/
        /// <include file='doc\MethodBuilder.uex' path='docs/doc[@for="MethodBuilder.SetSymCustomAttribute"]/*' />
        public void SetSymCustomAttribute(
            String name,                // SymCustomAttribute's name
            byte[]      data)           // the data blob
        {
            m_containingType.ThrowIfCreated();

            ModuleBuilder dynMod = (ModuleBuilder)m_module;

            if (dynMod.GetSymWriter() == null)
            {
                // Cannot SetSymCustomAttribute when it is not a debug module
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }

            SymbolToken tk = new SymbolToken(m_mdMethod.Token);

            dynMod.GetSymWriter().SetSymAttribute(tk, name, data);
        }
예제 #3
0
        /// <summary>设置该局部变量的名称和词法范围。</summary>
        /// <param name="name">局部变量的名称。</param>
        /// <param name="startOffset">局部变量词法范围的开始偏移量。</param>
        /// <param name="endOffset">局部变量词法范围的结束偏移量。</param>
        /// <exception cref="T:System.InvalidOperationException">已经用 <see cref="M:System.Reflection.Emit.TypeBuilder.CreateType" /> 创建了该包含类型。- 或 -没有为包含模块定义的符号编写器。</exception>
        /// <exception cref="T:System.NotSupportedException">此局部变量是使用动态方法(而不是动态类型的方法)来定义的。</exception>
        public void SetLocalSymInfo(string name, int startOffset, int endOffset)
        {
            MethodBuilder methodBuilder = this.m_methodBuilder as MethodBuilder;

            if ((MethodInfo)methodBuilder == (MethodInfo)null)
            {
                throw new NotSupportedException();
            }
            ModuleBuilder moduleBuilder = (ModuleBuilder)methodBuilder.Module;

            if (methodBuilder.IsTypeCreated())
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
            }
            if (moduleBuilder.GetSymWriter() == null)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }
            SignatureHelper fieldSigHelper = SignatureHelper.GetFieldSigHelper((Module)moduleBuilder);
            Type            clsArgument    = this.m_localType;

            fieldSigHelper.AddArgument(clsArgument);
            int num;
            // ISSUE: explicit reference operation
            // ISSUE: variable of a reference type
            int& length1 = @num;

            byte[] signature1  = fieldSigHelper.InternalGetSignature(length1);
            byte[] signature2  = new byte[num - 1];
            int    sourceIndex = 1;

            byte[] numArray         = signature2;
            int    destinationIndex = 0;
            int    length2          = num - 1;

            Array.Copy((Array)signature1, sourceIndex, (Array)numArray, destinationIndex, length2);
            if (methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex() == -1)
            {
                methodBuilder.m_localSymInfo.AddLocalSymInfo(name, signature2, this.m_localIndex, startOffset, endOffset);
            }
            else
            {
                methodBuilder.GetILGenerator().m_ScopeTree.AddLocalSymInfoToCurrentScope(name, signature2, this.m_localIndex, startOffset, endOffset);
            }
        }
예제 #4
0
        public void SetSymCustomAttribute(String name, byte[] data)
        {
            ThrowIfGeneric();

            // This is different from CustomAttribute. This is stored into the SymWriter.
            m_containingType.ThrowIfCreated();

            ModuleBuilder dynMod = (ModuleBuilder)m_module;

            if (dynMod.GetSymWriter() == null)
            {
                // Cannot SetSymCustomAttribute when it is not a debug module
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }

            if (m_symCustomAttrs == null)
            {
                m_symCustomAttrs = new ArrayList();
            }

            m_symCustomAttrs.Add(new SymCustomAttr(name, data));
        }
예제 #5
0
        /**********************************************
        * Sets the IL of the method.  An ILGenerator is passed as an argument and the method
        * queries this instance to get all of the information which it needs.
        * @param il An ILGenerator with some il defined.
        * @exception ArgumentException if <EM>il</EM> is null.
        **********************************************/
        internal void CreateMethodBodyHelper(ILGenerator il)
        {
            __ExceptionInfo[] excp;
            int counter = 0;

            int[]         filterAddrs;
            int[]         catchAddrs;
            int[]         catchEndAddrs;
            Type[]        catchClass;
            int[]         type;
            int           numCatch;
            int           start, end;
            ModuleBuilder dynMod = (ModuleBuilder)m_module;

            m_containingType.ThrowIfCreated();

            if (m_bIsBaked)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
            }

            if (il == null)
            {
                throw new ArgumentNullException("il");
            }

            if (il.m_methodBuilder != this && il.m_methodBuilder != null)
            {
                // you don't need to call CreateMethodBody when you get your ILGenerator
                // through MethodBuilder::GetILGenerator.
                //

                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
            }
            if ((m_dwMethodImplFlags & MethodImplAttributes.PreserveSig) != 0 ||
                (m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
                (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
                (m_iAttributes & MethodAttributes.PinvokeImpl) != 0)
            {
                // cannot attach method body if methodimpl is marked not marked as managed IL
                // @todo: what error should we throw here?
                //
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"));
            }

            if (il.m_ScopeTree.m_iOpenScopeCount != 0)
            {
                // There are still unclosed local scope
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
            }


            m_ubBody = il.BakeByteArray();

            m_RVAFixups       = il.GetRVAFixups();
            mm_mdMethodFixups = il.GetTokenFixups();

            //Okay, now the fun part.  Calculate all of the exceptions.
            excp            = il.GetExceptions();
            m_numExceptions = CalculateNumberOfExceptions(excp);
            if (m_numExceptions > 0)
            {
                m_exceptions = new __ExceptionInstance[m_numExceptions];

                for (int i = 0; i < excp.Length; i++)
                {
                    filterAddrs   = excp[i].GetFilterAddresses();
                    catchAddrs    = excp[i].GetCatchAddresses();
                    catchEndAddrs = excp[i].GetCatchEndAddresses();
                    catchClass    = excp[i].GetCatchClass();


                    // track the reference of the catch class
                    for (int j = 0; j < catchClass.Length; j++)
                    {
                        if (catchClass[j] != null)
                        {
                            dynMod.GetTypeToken(catchClass[j]);
                        }
                    }

                    numCatch = excp[i].GetNumberOfCatches();
                    start    = excp[i].GetStartAddress();
                    end      = excp[i].GetEndAddress();
                    type     = excp[i].GetExceptionTypes();
                    for (int j = 0; j < numCatch; j++)
                    {
                        int tkExceptionClass = 0;
                        if (catchClass[j] != null)
                        {
                            tkExceptionClass = dynMod.GetTypeToken(catchClass[j]).Token;
                        }
                        switch (type[j])
                        {
                        case __ExceptionInfo.None:
                        case __ExceptionInfo.Fault:
                        case __ExceptionInfo.Filter:
                            m_exceptions[counter++] = new __ExceptionInstance(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;

                        case __ExceptionInfo.Finally:
                            m_exceptions[counter++] = new __ExceptionInstance(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;
                        }
                    }
                }
            }


            m_bIsBaked = true;

            if (dynMod.GetSymWriter() != null)
            {
                // set the debugging information such as scope and line number
                // if it is in a debug module
                //
                SymbolToken   tk        = new SymbolToken(m_mdMethod.Token);
                ISymbolWriter symWriter = dynMod.GetSymWriter();

                // call OpenMethod to make this method the current method
                symWriter.OpenMethod(tk);

                // call OpenScope because OpenMethod no longer implicitly creating
                // the top-levelsmethod scope
                //
                symWriter.OpenScope(0);
                if (m_localSymInfo != null)
                {
                    m_localSymInfo.EmitLocalSymInfo(symWriter);
                }
                il.m_ScopeTree.EmitScopeTree(symWriter);
                il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
                symWriter.CloseScope(il.m_length);
                symWriter.CloseMethod();
            }
        }
예제 #6
0
        internal void CreateMethodBodyHelper(ILGenerator il)
        {
            // Sets the IL of the method.  An ILGenerator is passed as an argument and the method
            // queries this instance to get all of the information which it needs.
            if (il == null)
            {
                throw new ArgumentNullException(nameof(il));
            }

            __ExceptionInfo[] excp;
            int counter = 0;

            int[]         filterAddrs;
            int[]         catchAddrs;
            int[]         catchEndAddrs;
            Type[]        catchClass;
            int[]         type;
            int           numCatch;
            int           start, end;
            ModuleBuilder dynMod = (ModuleBuilder)m_module;

            m_containingType.ThrowIfCreated();

            if (m_bIsBaked)
            {
                throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
            }

            if (il.m_methodBuilder != this && il.m_methodBuilder != null)
            {
                // you don't need to call DefineBody when you get your ILGenerator
                // through MethodBuilder::GetILGenerator.
                //

                throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
            }

            ThrowIfShouldNotHaveBody();

            if (il.m_ScopeTree.m_iOpenScopeCount != 0)
            {
                // There are still unclosed local scope
                throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
            }


            m_ubBody = il.BakeByteArray();

            m_mdMethodFixups = il.GetTokenFixups();

            //Okay, now the fun part.  Calculate all of the exceptions.
            excp = il.GetExceptions() !;
            int numExceptions = CalculateNumberOfExceptions(excp);

            if (numExceptions > 0)
            {
                m_exceptions = new ExceptionHandler[numExceptions];

                for (int i = 0; i < excp.Length; i++)
                {
                    filterAddrs   = excp[i].GetFilterAddresses();
                    catchAddrs    = excp[i].GetCatchAddresses();
                    catchEndAddrs = excp[i].GetCatchEndAddresses();
                    catchClass    = excp[i].GetCatchClass();

                    numCatch = excp[i].GetNumberOfCatches();
                    start    = excp[i].GetStartAddress();
                    end      = excp[i].GetEndAddress();
                    type     = excp[i].GetExceptionTypes();
                    for (int j = 0; j < numCatch; j++)
                    {
                        int tkExceptionClass = 0;
                        if (catchClass[j] != null)
                        {
                            tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
                        }

                        switch (type[j])
                        {
                        case __ExceptionInfo.None:
                        case __ExceptionInfo.Fault:
                        case __ExceptionInfo.Filter:
                            m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;

                        case __ExceptionInfo.Finally:
                            m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
                            break;
                        }
                    }
                }
            }


            m_bIsBaked = true;

            if (dynMod.GetSymWriter() != null)
            {
                // set the debugging information such as scope and line number
                // if it is in a debug module
                //
                SymbolToken   tk        = new SymbolToken(MetadataTokenInternal);
                ISymbolWriter symWriter = dynMod.GetSymWriter() !; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388

                // call OpenMethod to make this method the current method
                symWriter.OpenMethod(tk);

                // call OpenScope because OpenMethod no longer implicitly creating
                // the top-levelsmethod scope
                //
                symWriter.OpenScope(0);

                if (m_symCustomAttrs != null)
                {
                    foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
                    {
                        dynMod.GetSymWriter() !.SetSymAttribute(
                            new SymbolToken(MetadataTokenInternal),
                            symCustomAttr.m_name,
                            symCustomAttr.m_data);
                    }
                }

                if (m_localSymInfo != null)
                {
                    m_localSymInfo.EmitLocalSymInfo(symWriter);
                }
                il.m_ScopeTree.EmitScopeTree(symWriter);
                il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
                symWriter.CloseScope(il.ILOffset);
                symWriter.CloseMethod();
            }
        }
예제 #7
0
        internal void CreateMethodBodyHelper(ILGenerator il)
        {
            if (il == null)
            {
                throw new ArgumentNullException("il");
            }
            int           num    = 0;
            ModuleBuilder module = this.m_module;

            this.m_containingType.ThrowIfCreated();
            if (this.m_bIsBaked)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
            }
            if ((il.m_methodBuilder != this) && (il.m_methodBuilder != null))
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
            }
            this.ThrowIfShouldNotHaveBody();
            if (il.m_ScopeTree.m_iOpenScopeCount != 0)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
            }
            this.m_ubBody         = il.BakeByteArray();
            this.m_RVAFixups      = il.GetRVAFixups();
            this.m_mdMethodFixups = il.GetTokenFixups();
            __ExceptionInfo[] exceptions = il.GetExceptions();
            this.m_numExceptions = this.CalculateNumberOfExceptions(exceptions);
            if (this.m_numExceptions > 0)
            {
                this.m_exceptions = new __ExceptionInstance[this.m_numExceptions];
                for (int i = 0; i < exceptions.Length; i++)
                {
                    int[]  filterAddresses   = exceptions[i].GetFilterAddresses();
                    int[]  catchAddresses    = exceptions[i].GetCatchAddresses();
                    int[]  catchEndAddresses = exceptions[i].GetCatchEndAddresses();
                    Type[] catchClass        = exceptions[i].GetCatchClass();
                    for (int j = 0; j < catchClass.Length; j++)
                    {
                        if (catchClass[j] != null)
                        {
                            module.GetTypeTokenInternal(catchClass[j]);
                        }
                    }
                    int   numberOfCatches = exceptions[i].GetNumberOfCatches();
                    int   startAddress    = exceptions[i].GetStartAddress();
                    int   endAddress      = exceptions[i].GetEndAddress();
                    int[] exceptionTypes  = exceptions[i].GetExceptionTypes();
                    for (int k = 0; k < numberOfCatches; k++)
                    {
                        int exceptionClass = 0;
                        if (catchClass[k] != null)
                        {
                            exceptionClass = module.GetTypeTokenInternal(catchClass[k]).Token;
                        }
                        switch (exceptionTypes[k])
                        {
                        case 0:
                        case 1:
                        case 4:
                            this.m_exceptions[num++] = new __ExceptionInstance(startAddress, endAddress, filterAddresses[k], catchAddresses[k], catchEndAddresses[k], exceptionTypes[k], exceptionClass);
                            break;

                        case 2:
                            this.m_exceptions[num++] = new __ExceptionInstance(startAddress, exceptions[i].GetFinallyEndAddress(), filterAddresses[k], catchAddresses[k], catchEndAddresses[k], exceptionTypes[k], exceptionClass);
                            break;
                        }
                    }
                }
            }
            this.m_bIsBaked = true;
            if (module.GetSymWriter() != null)
            {
                SymbolToken   method    = new SymbolToken(this.MetadataTokenInternal);
                ISymbolWriter symWriter = module.GetSymWriter();
                symWriter.OpenMethod(method);
                symWriter.OpenScope(0);
                if (this.m_symCustomAttrs != null)
                {
                    foreach (SymCustomAttr attr in this.m_symCustomAttrs)
                    {
                        module.GetSymWriter().SetSymAttribute(new SymbolToken(this.MetadataTokenInternal), attr.m_name, attr.m_data);
                    }
                }
                if (this.m_localSymInfo != null)
                {
                    this.m_localSymInfo.EmitLocalSymInfo(symWriter);
                }
                il.m_ScopeTree.EmitScopeTree(symWriter);
                il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
                symWriter.CloseScope(il.ILOffset);
                symWriter.CloseMethod();
            }
        }
예제 #8
0
        public void CreateAssembly()
        {
            // we need to process global assembly attributes before creating assembly name
            _assembly_name = CreateAssemblyName();

            _assembly_name.Name = Path.GetFileNameWithoutExtension(_OutputFileName);

            var assembly_requirements =
                (Manager.Options.CompileToMemory)
                    ? Emit.AssemblyBuilderAccess.Run
                    : Emit.AssemblyBuilderAccess.Save;

            var dir = Path.GetDirectoryName(Path.GetFullPath(_OutputFileName));
            if (!Directory.Exists(dir))
                Message.FatalError($"specified output directory `$dir' does not exist");

            PermissionSet required;
            PermissionSet optional;
            PermissionSet refused;

            foreach ((action, perm_set) in Manager.AttributeCompiler.GetPermissionSets(assembly_attributes))
            {
                switch (action)
                {
                    case Permissions.SecurityAction.RequestMinimum:
                        required = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestOptional:
                        optional = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestRefuse:
                        refused = perm_set;
                        break;
                    default:
                        Message.FatalError($"$action is not valid here");
                        break;
                }
            }

            /* define a dynamic assembly */
            this._assembly_builder =
                System.AppDomain.CurrentDomain.DefineDynamicAssembly
                (this._assembly_name,
                    assembly_requirements,
                    dir, required, optional, refused);

            GetInformationalAssemblyAttributes().Iter(this._assembly_builder.SetCustomAttribute);

            if (_assembly_name.Name == "")
                Message.FatalError("name of output assembly cannot be empty");

            /* create a dynamic module */
            this._module_builder =
                (Manager.Options.CompileToMemory)
                    // we cannot give output filename if we are compiling only to Run
                    ? this._assembly_builder.DefineDynamicModule(_assembly_name.Name, Manager.Options.EmitDebug)
                    : this._assembly_builder.DefineDynamicModule(_assembly_name.Name,
                        Path.GetFileName(_OutputFileName),
                        Manager.Options.EmitDebug);

            if (Manager.Options.EmitDebug)
                _debug_emit = _module_builder.GetSymWriter();
        }