Exemple #1
0
        private void ResolveStandAloneSigToken(StandAloneSignature entity)
        {
            var row = CreateStandAloneSigRow(entity, _metadata);
            var rid = _metadata.StandAloneSigTable.Add(row);

            _token = new MetadataToken(MetadataTokenType.Signature, rid);
        }
Exemple #2
0
        public void NewStandaloneSignature()
        {
            var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);

            // Import arbitrary method signature.
            var importer  = new ReferenceImporter(module);
            var signature = new StandAloneSignature(
                importer.ImportMethodSignature(MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)));

            // Ensure reference is added to the module by referencing it in main.
            var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;

            instructions.Insert(0, CilOpCodes.Ldnull);
            instructions.Insert(0, CilOpCodes.Calli, signature);

            // Rebuild.
            var builder = new ManagedPEImageBuilder();
            var result  = builder.CreateImage(module);

            // Assert valid token.
            var newToken = result.TokenMapping[signature];

            Assert.NotEqual(0u, newToken.Rid);

            // Assert token resolves to the same method reference.
            var newModule    = ModuleDefinition.FromImage(result.ConstructedImage);
            var newSignature = (StandAloneSignature)newModule.LookupMember(newToken);

            Assert.Equal(signature.Signature, newSignature.Signature, new SignatureComparer());
        }
Exemple #3
0
        public MetadataToken GetStandaloneSignatureToken(StandAloneSignature signature)
        {
            if (signature == null)
            {
                return(MetadataToken.Zero);
            }

            MetadataToken token;

            if (_members.TryGetValue(signature, out token))
            {
                return(token);
            }

            var table        = (StandAloneSignatureTable)_tableStream.GetTable(MetadataTokenType.StandAloneSig);
            var signatureRow = new MetadataRow <uint>
            {
                Column1 = _parentBuffer.BlobStreamBuffer.GetBlobOffset(signature.Signature)
            };

            table.Add(signatureRow);
            _members.Add(signature, token = signatureRow.MetadataToken);

            AddCustomAttributes(signature);

            return(token);
        }
Exemple #4
0
 public static MsilInstruction Create(MsilOpCode code, StandAloneSignature operand)
 {
     if (code.OperandType != MsilOperandType.InlineSig)
     {
         throw new ArgumentException("Opcode does not accept a signature operand.", "code");
     }
     return(new MsilInstruction(0, code, operand));
 }
Exemple #5
0
        public void VariablesTest()
        {
            // set up temp assembly.
            var assembly       = Utilities.CreateTempNetAssembly();
            var typeSystem     = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream    = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();
            var methodTable    = tableStream.GetTable <MethodDefinition>();
            var signatureTable = tableStream.GetTable <StandAloneSignature>();

            var variable  = new VariableSignature(typeSystem.String);
            var variable2 = new VariableSignature(typeSystem.Int32);

            // create localvarsig.
            var localVarSig = new LocalVariableSignature();

            localVarSig.Variables.Add(variable);
            localVarSig.Variables.Add(variable2);
            var signature = new StandAloneSignature(localVarSig);

            signatureTable.Add(signature);

            // write code.
            var body = methodTable[0].MethodBody;

            body.Signature = signature;

            body.Instructions.Clear();
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldloc, variable));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldloc, variable2));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ret));

            // build and validate.
            assembly    = Utilities.RebuildNetAssembly(assembly, true);
            methodTable = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>().GetTable <MethodDefinition>();
            var newBody = methodTable[0].MethodBody;

            Assert.IsNotNull(newBody.Signature);
            Assert.IsInstanceOfType(newBody.Signature.Signature, typeof(LocalVariableSignature));

            var newLocalVarSig = (LocalVariableSignature)newBody.Signature.Signature;

            Assert.AreEqual(localVarSig.Variables.Count, newLocalVarSig.Variables.Count);

            for (int i = 0; i < localVarSig.Variables.Count; i++)
            {
                Utilities.ValidateType(localVarSig.Variables[i].VariableType, newLocalVarSig.Variables[i].VariableType);
            }

            Assert.IsInstanceOfType(newBody.Instructions[0].Operand, typeof(VariableSignature));
            Utilities.ValidateType(variable.VariableType,
                                   ((VariableSignature)newBody.Instructions[0].Operand).VariableType);

            Assert.IsInstanceOfType(newBody.Instructions[2].Operand, typeof(VariableSignature));
            Utilities.ValidateType(variable2.VariableType,
                                   ((VariableSignature)newBody.Instructions[2].Operand).VariableType);
        }
        /// <summary>
        /// Verifies and inserts a instruction into the collection that references a standalone signature.
        /// </summary>
        /// <param name="index">The zero-based index at which the instruction should be inserted at.</param>
        /// <param name="code">The opcode.</param>
        /// <param name="signature">The referenced signature.</param>
        /// <returns>The created instruction.</returns>
        /// <exception cref="InvalidCilInstructionException">
        /// Occurs when the provided operation is not an opcode referencing a standalone signature.
        /// </exception>
        public CilInstruction Insert(int index, CilOpCode code, StandAloneSignature signature)
        {
            if (code.OperandType != CilOperandType.InlineSig)
            {
                throw new InvalidCilInstructionException(code);
            }

            return(InsertAndReturn(index, code, signature));
        }
Exemple #7
0
        /// <inheritdoc />
        public MetadataToken GetStandAloneSignatureToken(StandAloneSignature signature)
        {
            var table = Metadata.TablesStream.GetTable <StandAloneSignatureRow>(TableIndex.StandAloneSig);
            var row   = new StandAloneSignatureRow(
                Metadata.BlobStream.GetBlobIndex(this, signature.Signature));

            var token = table.Add(row);

            AddCustomAttributes(token, signature);
            return(token);
        }
Exemple #8
0
 internal void WriteStandAloneSig(StandAloneSignature signature)
 {
     if (signature.UpdateRowOnRebuild)
     {
         object[] parts = new object[]
         {
             GetHeapOffset(netHeader.BlobHeap, Convert.ToUInt32(signature.MetaDataRow.Parts[0])), // TODO: Serialize signatures.
         };
         signature.MetaDataRow = new MetaDataRow(parts);
     }
     writer.Write(signature.MetaDataRow.GenerateBytes());
 }
Exemple #9
0
 private FatMethodHeader ComputeFatHeader(MethodDefinition methodDef)
 {
     return(new FatMethodHeader()
     {
         Size = 0x30,
         MaxStack = (ushort)methodDef.Body.MaxStack,
         CodeSize = (uint)methodDef.Body.CodeSize,
         Attributes = GetFatHeaderAttributes(methodDef),
         LocalVarSigTok = _metadata.ResolveToken(
             StandAloneSignature
             .GetVariablesSignature(methodDef.Body.Variables, _metadata))
     });
 }
Exemple #10
0
        private void ReadSignature(MethodRow row, MetadataSystem metadata)
        {
            var blob = metadata.ResolveBlob(row.Signature);
            var sig  = new StandAloneSignature(blob);

            CallingConventions = (CallingConventions)sig.ReadByte();
            ParamCount         = sig.ReadCompressedUInt32();
            ReturnType         = sig.ReadType(metadata);

            ParamTypes = new ITypeInfo[ParamCount];
            for (int index = 0; index < ParamCount; index++)
            {
                ParamTypes[index] = sig.ReadType(metadata);
            }
        }
        private static int DetermineVarPushCount(CilInstruction instruction)
        {
            var signature = instruction.Operand switch
            {
                IMethodDescriptor method => method.Signature,
                StandAloneSignature standAloneSig => standAloneSig.Signature as MethodSignature,
                _ => null
            };

            if (signature == null)
            {
                return(0);
            }

            if (!signature.ReturnType.IsTypeOf("System", "Void") || instruction.OpCode.Code == CilCode.Newobj)
            {
                return(1);
            }

            return(0);
        }
Exemple #12
0
        private CilRawMethodBody BuildFatMethodBody(MethodBodySerializationContext context, CilMethodBody body, byte[] code)
        {
            // Serialize local variables.
            MetadataToken token;

            if (body.LocalVariables.Count == 0)
            {
                token = MetadataToken.Zero;
            }
            else
            {
                var localVarSig   = new LocalVariablesSignature(body.LocalVariables.Select(v => v.VariableType));
                var standAloneSig = new StandAloneSignature(localVarSig);
                token = context.TokenProvider.GetStandAloneSignatureToken(standAloneSig);
            }

            var fatBody = new CilRawFatMethodBody(CilMethodBodyAttributes.Fat, (ushort)body.MaxStack, token, code);

            fatBody.InitLocals = body.InitializeLocals;

            // Build up EH table section.
            if (body.ExceptionHandlers.Count > 0)
            {
                fatBody.HasSections = true;
                bool needsFatFormat = body.ExceptionHandlers.Any(e => e.IsFat);

                var attributes = CilExtraSectionAttributes.EHTable;
                if (needsFatFormat)
                {
                    attributes |= CilExtraSectionAttributes.FatFormat;
                }

                var rawSectionData = SerializeExceptionHandlers(context, body.ExceptionHandlers, needsFatFormat);
                var section        = new CilExtraSection(attributes, rawSectionData);
                fatBody.ExtraSections.Add(section);
            }

            return(fatBody);
        }
        private static int DetermineVarPopCount(CilInstruction instruction, bool isVoid)
        {
            var opCode    = instruction.OpCode;
            var signature = instruction.Operand switch
            {
                IMethodDescriptor method => method.Signature,
                StandAloneSignature standAloneSig => standAloneSig.Signature as MethodSignature,
                _ => null
            };

            if (signature == null)
            {
                if (opCode.Code == CilCode.Ret)
                {
                    return(isVoid ? 0 : 1);
                }
            }
            else
            {
                int count = signature.GetTotalParameterCount();
                switch (opCode.Code)
                {
                case CilCode.Newobj:
                    // NewObj produces instead of consumes the this parameter.
                    count--;
                    break;

                case CilCode.Calli:
                    // Calli consumes an extra parameter (the address to call).
                    count++;
                    break;
                }
                return(count);
            }

            return(0);
        }
Exemple #14
0
 public static MsilInstruction Create(MsilOpCode code, StandAloneSignature operand)
 {
     if (code.OperandType != MsilOperandType.InlineSig)
         throw new ArgumentException("Opcode does not accept a signature operand.", "code");
     return new MsilInstruction(0, code, operand);
 }
        public uint WriteSignature(IMethodInfo methodInfo)
        {
            var signature = StandAloneSignature.GetMethodSignature(methodInfo, this);

            return(WriteBlob(signature));
        }
Exemple #16
0
 private StandAloneSigRow CreateStandAloneSigRow(StandAloneSignature entity, MetadataBuilder metadata)
 {
     return(new StandAloneSigRow(metadata.WriteBlob(entity)));
 }
Exemple #17
0
 public void VisitStandAloneSignature(StandAloneSignature entity) => ResolveStandAloneSigToken(entity);
 public CilInstruction Add(CilOpCode code, StandAloneSignature signature) => Insert(Count, code, signature);
        public uint WriteSignature(IMemberReference memberRef)
        {
            var signature = StandAloneSignature.GetMemberReferenceSignature(memberRef, this);

            return(WriteBlob(signature));
        }
        public void VariablesTest()
        {
            // set up temp assembly.
            var assembly = Utilities.CreateTempNetAssembly();
            var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem;
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var methodTable = tableStream.GetTable<MethodDefinition>();
            var signatureTable = tableStream.GetTable<StandAloneSignature>();

            var variable = new VariableSignature(typeSystem.String);
            var variable2 = new VariableSignature(typeSystem.Int32);

            // create localvarsig.
            var localVarSig = new LocalVariableSignature();
            localVarSig.Variables.Add(variable);
            localVarSig.Variables.Add(variable2);
            var signature = new StandAloneSignature(localVarSig);
            signatureTable.Add(signature);

            // write code.
            var body = methodTable[0].MethodBody;
            body.Signature = signature;

            body.Instructions.Clear();
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldloc, variable));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ldloc, variable2));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Pop));
            body.Instructions.Add(MsilInstruction.Create(MsilOpCodes.Ret));

            // build and validate.
            assembly = Utilities.RebuildNetAssembly(assembly, true);
            methodTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<MethodDefinition>();
            var newBody = methodTable[0].MethodBody;

            Assert.IsNotNull(newBody.Signature);
            Assert.IsInstanceOfType(newBody.Signature.Signature, typeof(LocalVariableSignature));

            var newLocalVarSig = (LocalVariableSignature)newBody.Signature.Signature;
            Assert.AreEqual(localVarSig.Variables.Count, newLocalVarSig.Variables.Count);

            for (int i = 0; i < localVarSig.Variables.Count; i++)
                Utilities.ValidateType(localVarSig.Variables[i].VariableType, newLocalVarSig.Variables[i].VariableType);

            Assert.IsInstanceOfType(newBody.Instructions[0].Operand, typeof(VariableSignature));
            Utilities.ValidateType(variable.VariableType,
                ((VariableSignature)newBody.Instructions[0].Operand).VariableType);

            Assert.IsInstanceOfType(newBody.Instructions[2].Operand, typeof(VariableSignature));
            Utilities.ValidateType(variable2.VariableType,
                ((VariableSignature)newBody.Instructions[2].Operand).VariableType);
        }
Exemple #21
0
 private void UpdateStandAloneSig(Workspace workspace, StandAloneSignature signature)
 {
     // TODO: serialize blob.
 }
        public uint WriteSignature(CustomAttribute attribute)
        {
            var signature = StandAloneSignature.GetAttributeSignature(attribute, this);

            return(WriteBlob(signature));
        }
        public uint WriteSignature(FieldDefinition fieldDef)
        {
            var signature = StandAloneSignature.GetFieldSignature(fieldDef, this);

            return(WriteBlob(signature));
        }
        public uint WriteSignature(ITypeInfo type)
        {
            var signature = StandAloneSignature.GetTypeSignature(type, this);

            return(WriteBlob(signature));
        }