public static MethodSpecification Combine(this MethodSpecification left, MethodSpecification right) { if (left == Any) { return(right); } if (right == Any) { return(left); } if (left == null || right == null) { return(left ?? right); } return(x => { var leftOutcome = left(x); return leftOutcome.WasSuccessful ? leftOutcome & right(x) : leftOutcome; }); }
public MethodSpecificationMethod(GenericContext gc, MethodSpecificationHandle handle) : base(gc) { this.handle = handle; ms = Cx.MdReader.GetMethodSpecification(handle); typeParams = ms.DecodeSignature(Cx.TypeSignatureDecoder, gc); unboundMethod = (Method)Cx.CreateGeneric(gc, ms.Method); }
public MetadataToken GetMethodSpecificationToken(MethodSpecification specification) { MetadataToken token; if (_members.TryGetValue(specification, out token)) { return(token); } AssertIsImported(specification); var specificationRow = new MetadataRow <uint, uint> { Column1 = _tableStream.GetIndexEncoder(CodedIndex.MethodDefOrRef) .EncodeToken(GetMethodToken(specification.Method)), Column2 = _parentBuffer.BlobStreamBuffer.GetBlobOffset(specification.Signature) }; if (!_methodSpecs.TryGetValue(specificationRow, out token)) { var table = (MethodSpecificationTable)_tableStream.GetTable(MetadataTokenType.MethodSpec); table.Add(specificationRow); token = specificationRow.MetadataToken; _methodSpecs.Add(specificationRow, token); _members.Add(specification, token); } return(token); }
private Object ResolveMethodSpecification(MethodSpecificationHandle handle) { MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle); object resolvedMethod = GetObject(methodSpecification.Method, NotFoundBehavior.ReturnResolutionFailure); if (resolvedMethod is ResolutionFailure) { return(resolvedMethod); } MethodDesc methodDef = resolvedMethod as MethodDesc; if (methodDef == null) { ThrowHelper.ThrowBadImageFormatException($"method expected for handle {handle.ToString()}"); } BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader, NotFoundBehavior.ReturnResolutionFailure); TypeDesc[] instantiation = parser.ParseMethodSpecSignature(); if (instantiation == null) { return(parser.ResolutionFailure); } return(Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation))); }
/// <summary> /// Emit a method specification. /// </summary> /// <param name="methodSpecHandle">Method specification handle</param> private string EmitMethodSpecificationName(MethodSpecificationHandle methodSpecHandle) { MethodSpecification methodSpec = _metadataReader.GetMethodSpecification(methodSpecHandle); DisassemblingGenericContext genericContext = new DisassemblingGenericContext(Array.Empty <string>(), Array.Empty <string>()); return(EmitHandleName(methodSpec.Method, namespaceQualified: true) + methodSpec.DecodeSignature <string, DisassemblingGenericContext>(this, genericContext)); }
public MethodSpecEntry(PEFile module, MethodSpecificationHandle handle) { this.metadataOffset = module.Reader.PEHeaders.MetadataStartOffset; this.module = module; this.metadata = module.Metadata; this.handle = handle; this.methodSpec = metadata.GetMethodSpecification(handle); }
/// <inheritdoc /> public int GetHashCode(MethodSpecification obj) { unchecked { int hashCode = obj.Method == null ? 0 : obj.Method.GetHashCode(); hashCode = (hashCode * 397) ^ GetHashCode(obj.Signature); return(hashCode); } }
void addMethodSpecification(MethodSpecification methodSpecification) { if (methodSpecification == null) { return; } addMethodReference(methodSpecification); pushMember(methodSpecification.ElementMethod); }
/// <summary> /// Updates the member type references. /// </summary> /// <param name="context">The context.</param> /// <param name="memberReference">The member reference.</param> private static void UpdateMemberTypeReferences(ICloakContext context, MemberReference memberReference) { //Get the type reference for this TypeReference methodType = memberReference.DeclaringType; //Get the assembly for this if (methodType.Scope is AssemblyNameReference) { string assemblyName = ((AssemblyNameReference)methodType.Scope).FullName; //Check if this needs to be updated if (context.MappingGraph.IsAssemblyMappingDefined(assemblyName)) { AssemblyMapping assemblyMapping = context.MappingGraph.GetAssemblyMapping(assemblyName); TypeMapping t = assemblyMapping.GetTypeMapping(methodType); if (t == null) { return; //No type defined } //Update the type name if (!String.IsNullOrEmpty(t.ObfuscatedTypeName)) { methodType.Name = t.ObfuscatedTypeName; } //We can't change method specifications.... if (memberReference is MethodSpecification) { MethodSpecification specification = (MethodSpecification)memberReference; MethodReference meth = specification.GetElementMethod(); //Update the method name also if available if (t.HasMethodMapping(meth)) { meth.Name = t.GetObfuscatedMethodName(meth); } } else if (memberReference is FieldReference) { FieldReference fr = (FieldReference)memberReference; if (t.HasFieldMapping(fr)) { memberReference.Name = t.GetObfuscatedFieldName(fr); } } else if (memberReference is MethodReference) //Is this ever used?? Used to be just an else without if { MethodReference mr = (MethodReference)memberReference; //Update the method name also if available if (t.HasMethodMapping(mr)) { memberReference.Name = t.GetObfuscatedMethodName(mr); } } } } }
public MethodSpecificationMethod(GenericContext gc, MethodSpecificationHandle handle) : base(gc) { ms = cx.mdReader.GetMethodSpecification(handle); typeParams = ms.DecodeSignature(cx.TypeSignatureDecoder, gc); unboundMethod = (Method)cx.CreateGeneric(gc, ms.Method); declaringType = unboundMethod.DeclaringType; ShortId = unboundMethod.ShortId + openAngle + CIL.Id.CommaSeparatedList(typeParams.Select(p => p.ShortId)) + closeAngle; }
public static MethodSpecification Returns(this MethodSpecification @this, Func <MethodInfo, TypeSpecification, TypeSpecification> returnSpecification) { Guard.NotNull(@this, "this"); Guard.NotNull(returnSpecification, "returnSpecification"); return(@this.Combine(m => { var returnSpec = returnSpecification(m, TypeSpecificationBuilder.Any); return returnSpec(m.ReturnType); })); }
private Object ResolveMethodSpecification(MethodSpecificationHandle handle) { MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle); MethodDesc methodDef = GetMethod(methodSpecification.Method); BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); TypeDesc[] instantiation = parser.ParseMethodSpecSignature(); return(Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation))); }
/// <inheritdoc /> public MetadataToken GetMethodSpecificationToken(MethodSpecification method) { var table = Metadata.TablesStream.GetTable <MethodSpecificationRow>(TableIndex.MethodSpec); var row = new MethodSpecificationRow( AddMethodDefOrRef(method.Method), Metadata.BlobStream.GetBlobIndex(this, method.Signature)); var token = table.Add(row); AddCustomAttributes(token, method); return(token); }
internal void WriteMethodSpec(MethodSpecification methodSpec) { if (methodSpec.UpdateRowOnRebuild) { object[] parts = new object[] { GetCodedIndex(tablesHeap.MethodDefOrRef, methodSpec.OriginalMethod), GetHeapOffset(netHeader.BlobHeap, Convert.ToUInt32(methodSpec.MetaDataRow.parts[1])), // TODO: Serialize signatures. }; methodSpec.MetaDataRow = new MetaDataRow(parts); } writer.Write(methodSpec.MetaDataRow.GenerateBytes()); }
private void EmitMethodSpecificationSignature(MethodWithToken method, uint flags, bool enforceDefEncoding, SignatureContext context) { ModuleToken methodToken = method.Token; if (method.Method.HasInstantiation && !method.Method.IsGenericMethodDefinition) { flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MethodInstantiation; if (!method.Token.IsNull) { if (method.Token.TokenType == CorTokenType.mdtMethodSpec) { MethodSpecification methodSpecification = methodToken.MetadataReader.GetMethodSpecification((MethodSpecificationHandle)methodToken.Handle); methodToken = new ModuleToken(methodToken.Module, methodSpecification.Method); } } } Debug.Assert(!methodToken.IsNull); switch (methodToken.TokenType) { case CorTokenType.mdtMethodDef: break; case CorTokenType.mdtMemberRef: flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MemberRefToken; break; default: throw new NotImplementedException(); } EmitUInt(flags); if ((flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_OwnerType) != 0) { // The type here should be the type referred to by the memberref (if this is one, not the type where the method was eventually found! EmitTypeSignature(method.OwningType, context); } EmitTokenRid(methodToken.Token); if ((flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MethodInstantiation) != 0) { Instantiation instantiation = method.Method.Instantiation; EmitUInt((uint)instantiation.Length); SignatureContext outerContext = context.OuterContext; for (int typeParamIndex = 0; typeParamIndex < instantiation.Length; typeParamIndex++) { EmitTypeSignature(instantiation[typeParamIndex], outerContext); } } }
public static MethodSpecification Parameter(this MethodSpecification @this, Func <MethodInfo, ParameterSpecification, ParameterSpecification> parameterSpecification) { Guard.NotNull(@this, "this"); Guard.NotNull(parameterSpecification, "parameterSpecification"); return(@this.Combine(m => { var parameterSpec = parameterSpecification(m, ParameterSpecificationBuilder.Any); var outcomes = m.GetParameters().Select(x => parameterSpec(x)); return outcomes .TryFirst(x => x.WasSuccessful) .ValueOrDefault(() => outcomes.Combine()); })); }
public void UpdateReference(Identifier old, Identifier @new) { MethodSpecification mSpec = refer as MethodSpecification; if (mSpec == null || !(mSpec.DeclaringType.GetElementType() is TypeDefinition)) { TypeSpecification tSpec = refer.DeclaringType as TypeSpecification; TypeDefinition par = tSpec.GetElementType() as TypeDefinition; if (tSpec != null && par != null) { refer.Name = @new.name; } } }
public bool Equals(MethodSpecification specification1, MethodSpecification specification2) { if (specification1 == null && specification2 == null) { return(true); } if (specification1 == null || specification2 == null) { return(false); } return(Equals(specification1.Signature, specification2.Signature) && Equals(specification1.Method, specification2.Method)); }
/// <inheritdoc /> public bool Equals(MethodSpecification x, MethodSpecification y) { if (ReferenceEquals(x, y)) { return(true); } if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) { return(false); } return(Equals(x.Method, y.Method) && Equals(x.Signature, y.Signature)); }
public static MethodSpecification GenericArgument(this MethodSpecification @this, Func <MethodInfo, TypeArgumentSpecification, TypeArgumentSpecification> argumentSpecification) { Guard.NotNull(@this, "this"); Guard.NotNull(argumentSpecification, "argumentSpecification"); return(@this.Combine(m => { var argSpec = argumentSpecification(m, TypeArgumentSpecificationBuilder.Any); var outcomes = m.GetGenericArguments().Select(x => argSpec(x)); return outcomes .TryFirst(x => x.WasSuccessful) .ValueOrDefault(() => outcomes.Combine()); })); }
public void AddModuleTokenForMethod(MethodDesc method, ModuleToken token) { if (token.TokenType == CorTokenType.mdtMethodSpec) { MethodSpecification methodSpec = token.MetadataReader.GetMethodSpecification((MethodSpecificationHandle)token.Handle); methodSpec.DecodeSignature <DummyTypeInfo, ModuleTokenResolver>(new TokenResolverProvider(this, token.Module), this); token = new ModuleToken(token.Module, methodSpec.Method); } if (token.TokenType == CorTokenType.mdtMemberRef) { MemberReference memberRef = token.MetadataReader.GetMemberReference((MemberReferenceHandle)token.Handle); EntityHandle owningTypeHandle = memberRef.Parent; AddModuleTokenForType(method.OwningType, new ModuleToken(token.Module, owningTypeHandle)); memberRef.DecodeMethodSignature <DummyTypeInfo, ModuleTokenResolver>(new TokenResolverProvider(this, token.Module), this); } }
public void OperandTypeMethod() { var methodBody = CreateDummyMethodBody(); var image = methodBody.Method.Image; var importer = new ReferenceImporter(image); var instructions = methodBody.Instructions; var simpleMethod = importer.ImportMethod(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) })); var genericInstanceMethod = new MethodSpecification( new MemberReference( importer.ImportType(typeof(Activator)), "CreateInstance", new MethodSignature(new GenericParameterSignature(GenericParameterType.Method, 0)) { GenericParameterCount = 1, IsGeneric = true }), new GenericInstanceMethodSignature(importer.ImportTypeSignature(typeof(Stream)))); instructions.AddRange(new[] { CilInstruction.Create(CilOpCodes.Ldstr, "Some String"), CilInstruction.Create(CilOpCodes.Call, simpleMethod), CilInstruction.Create(CilOpCodes.Call, importer.ImportMethod(genericInstanceMethod)), CilInstruction.Create(CilOpCodes.Pop), CilInstruction.Create(CilOpCodes.Ret) }); var mapping = image.Header.UnlockMetadata(); image = image.Header.LockMetadata(); var newMethod = (MethodDefinition)image.ResolveMember(mapping[methodBody.Method]); instructions = newMethod.CilMethodBody.Instructions; Assert.Equal(simpleMethod, instructions[1].Operand as IMemberReference, _comparer); Assert.Equal(genericInstanceMethod, instructions[2].Operand as IMemberReference, _comparer); }
private static string GetGenericParametersSignature(MethodSpecification methodSpec, CilTypeProvider provider) { var genericParameters = SignatureDecoder.DecodeMethodSpecificationSignature(methodSpec.Signature, provider); StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < genericParameters.Length; i++) { if (i == 0) { sb.Append("<"); } sb.Append(genericParameters[i]); sb.Append(","); } if (i > 0) { sb.Length--; sb.Append(">"); } return(sb.ToString()); }
public void ImportGenericInstanceMethod() { var assembly = NetAssemblyFactory.CreateAssembly(DummyAssemblyName, true); var image = assembly.NetDirectory.MetadataHeader.LockMetadata(); var importer = new ReferenceImporter(image); var specification = new MethodSpecification( new MemberReference( CreateTypeReference(typeof(Activator)), "CreateInstance", new MethodSignature(new GenericParameterSignature(GenericParameterType.Method, 0)) { GenericParameterCount = 1 }), new GenericInstanceMethodSignature(CreateTypeDefOrRef(typeof(Stream)))); var newSpecification = importer.ImportMethod(specification); Assert.NotSame(specification, newSpecification); Assert.Equal(specification, newSpecification, _comparer); Assert.Equal(image, newSpecification.Image); }
private static MemberReference ElementTypeFor(MethodSpecification genericInstanceMethod) { return(genericInstanceMethod.ElementMethod); }
private void EmitMethodSpecificationSignature(MethodWithToken method, uint flags, bool enforceDefEncoding, SignatureContext context) { ModuleToken methodToken = method.Token; if (method.Method.HasInstantiation) { flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MethodInstantiation; if (!method.Token.IsNull) { if (method.Token.TokenType == CorTokenType.mdtMethodSpec) { MethodSpecification methodSpecification = methodToken.MetadataReader.GetMethodSpecification((MethodSpecificationHandle)methodToken.Handle); methodToken = new ModuleToken(methodToken.Module, methodSpecification.Method); } } } if (methodToken.IsNull && !enforceDefEncoding) { methodToken = context.GetModuleTokenForMethod(method.Method, throwIfNotFound: false); } if (methodToken.IsNull) { flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_OwnerType; methodToken = context.GetModuleTokenForMethod(method.Method); } if (method.Method.OwningType.HasInstantiation) { // resolveToken currently resolves the token in the context of a given scope; // in such case, we receive a method on instantiated type along with the // generic definition token. flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_OwnerType; } switch (methodToken.TokenType) { case CorTokenType.mdtMethodDef: break; case CorTokenType.mdtMemberRef: flags |= (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MemberRefToken; break; default: throw new NotImplementedException(); } EmitUInt(flags); if ((flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_OwnerType) != 0) { EmitTypeSignature(method.Method.OwningType, context); } EmitTokenRid(methodToken.Token); if ((flags & (uint)ReadyToRunMethodSigFlags.READYTORUN_METHOD_SIG_MethodInstantiation) != 0) { Instantiation instantiation = method.Method.Instantiation; EmitUInt((uint)instantiation.Length); SignatureContext outerContext = context.OuterContext; for (int typeParamIndex = 0; typeParamIndex < instantiation.Length; typeParamIndex++) { EmitTypeSignature(instantiation[typeParamIndex], outerContext); } } }
private static string GetGenericParametersSignature(MethodSpecification methodSpec, CilTypeProvider provider) { var genericParameters = SignatureDecoder.DecodeMethodSpecificationSignature(methodSpec.Signature, provider); StringBuilder sb = new StringBuilder(); int i; for(i = 0; i < genericParameters.Length; i++) { if(i == 0) { sb.Append("<"); } sb.Append(genericParameters[i]); sb.Append(","); } if(i > 0) { sb.Length--; sb.Append(">"); } return sb.ToString(); }
public static MethodSpecification Combine(this MethodSpecification left, MethodSpecification right) { if (left == Any) return right; if (right == Any) return left; if (left == null || right == null) return left ?? right; return x => { var leftOutcome = left(x); return leftOutcome.WasSuccessful ? leftOutcome & right(x) : leftOutcome; }; }
public static MethodSpecification Named(this MethodSpecification @this, string name) { Guard.NotNull(@this, "this"); return(@this.Combine(m => Outcome.FailIf(m.Name != name, String.Format("Was not named '{0}'.", name)))); }
public static MethodSpecification IsPublic(this MethodSpecification @this) { Guard.NotNull(@this, "this"); return(@this.Combine(m => Outcome.FailIf(!m.IsPublic, "Was not public."))); }
public static MethodSpecification IsClosedGeneric(this MethodSpecification @this) { Guard.NotNull(@this, "this"); return(@this.Combine(m => Outcome.FailIf(m.IsGenericMethodDefinition, "Was not closed generic."))); }
public static MethodSpecification HasGenericArguments(this MethodSpecification @this, int count) { Guard.NotNull(@this, "this"); return(@this.Combine(m => Outcome.FailIf(m.GetGenericArguments().Length != count, String.Format("Did not have {0} generic argument(s).", count)))); }