public void VisitMethodBodyReference(IReference reference) { ITypeReference typeReference = reference as ITypeReference; if (typeReference != null) { this.typeReferenceNeedsToken = true; this.Visit(typeReference); Debug.Assert(!this.typeReferenceNeedsToken); } else { IFieldReference fieldReference = reference as IFieldReference; if (fieldReference != null) { if (fieldReference.IsContextualNamedEntity) { ((IContextualNamedEntity)fieldReference).AssociateWithMetadataWriter(this.metadataWriter); } this.Visit(fieldReference); } else { IMethodReference methodReference = reference as IMethodReference; if (methodReference != null) { this.Visit(methodReference); } } } }
public void WriteMethodReference(IMethodReference methodReference) { WriteIndent(); Append("<font color=\"darkgreen\">"); Append("<a href=\"resource://["); Append(methodReference.Resolve().DeclaringType.Assembly.Name); Append(']'); Append(methodReference.Resolve().DeclaringType.Namespace); Append('.'); Append(methodReference.Resolve().DeclaringType.Name); Append("::"); Append(methodReference.Name); Append("\">"); if ((methodReference.Name == ".ctor") || (methodReference.Name == ".cctor")) { Write(methodReference.Resolve().DeclaringType.Name); } else { Write(methodReference.Name); } Append("</a>"); Append("</font>"); }
public override void TraverseChildren(ITokenOf tokenOf) { base.TraverseChildren(tokenOf); ITypeReference type; IFieldReference /*?*/ field = tokenOf.Definition as IFieldReference; if (field != null) { type = this.platformType.SystemRuntimeFieldHandle; } else { IMethodReference /*?*/ method = tokenOf.Definition as IMethodReference; if (method != null) { type = this.platformType.SystemRuntimeMethodHandle; } else { Contract.Assume(tokenOf.Definition is ITypeReference); type = this.platformType.SystemRuntimeTypeHandle; } } ((TokenOf)tokenOf).Type = type; }
/// <summary> /// Returns the unspecialized version of the given method reference. /// </summary> public static IMethodReference Unspecialize(IMethodReference method) { var smr = method as ISpecializedMethodReference; if (smr != null) return smr.UnspecializedVersion; var gmir = method as IGenericMethodInstanceReference; if (gmir != null) return gmir.GenericMethod; return method; }
private void AddDependencyFromMethodBody(IMethodBody methodBody) { foreach (ILocalDefinition local in methodBody.LocalVariables) { AddDependency(local.Type); } foreach (IOperation op in methodBody.Operations) { switch (op.OperationCode) { case OperationCode.Castclass: case OperationCode.Box: case OperationCode.Unbox: case OperationCode.Unbox_Any: AddDependency((ITypeReference)op.Value); break; case OperationCode.Call: //case OperationCode.Calli: Native calls case OperationCode.Callvirt: case OperationCode.Newobj: case OperationCode.Ldftn: case OperationCode.Ldvirtftn: IMethodReference methodRef = (IMethodReference)op.Value; AddDependencyForCalledMethod(methodRef); break; } } }
unsafe uint IMetaDataImport.GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { IMethodReference m = null; if ((mb & 0xFF000000) == 0x0A000000) { m = this.writer.memberRefList[(int)(mb & 0xFFFFFF) - 1] as IMethodReference; } else { m = this.writer.methodDefList[(int)(mb & 0xFFFFFF) - 1]; } pchMethod = 0; pClass = 0; pClass = this.writer.GetTypeToken(m.ContainingType); string methName = m.Name.Value; pchMethod = (uint)methName.Length; if (pchMethod > cchMethod) { pchMethod = cchMethod - 1; } char *pMethName = (char *)szMethod.ToPointer(); for (int i = 0; i < pchMethod; i++) { *(pMethName + i) = methName[i]; } *(pMethName + pchMethod) = (char)0; return(0); }
public DotNetDesktopStubMethodBodyEmitter(IMetadataHost host) : base(host) { this.consoleWriteLine = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Console"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("WriteLine"), 0, host.PlatformType.SystemString); this.environmentGetStackTrace = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemString, host.NameTable.GetNameFor("get_StackTrace"), 0); this.environmentExit = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("Exit"), 0, host.PlatformType.SystemInt32); }
public IMethodDeclaration Resolve() { // If we have already resolved this, and the reference is still // alive, then return it. if (this.methodDeclaration != null && this.methodDeclaration.IsAlive) { return((IMethodDeclaration)this.methodDeclaration.Target); } // Try resolving the generic method for which this is a specialization IMethodReference genericDecl = this.GenericMethod.Resolve(); if (genericDecl == null) { return(null); } // Build the instance declaration IMethodDeclaration instDecl = new XMethodInstanceDeclaration(); instDecl.GenericMethod = genericDecl; instDecl.GenericArguments.AddRange(this.GenericArguments); ITypeReference declaringType = this.DeclaringType as ITypeReference; if (declaringType != null) { instDecl.DeclaringType = declaringType.Resolve(); } // Are there other properties of instDecl that we should set? this.methodDeclaration = new WeakReference(instDecl); return((IMethodDeclaration)this.methodDeclaration.Target); }
/// <summary> /// Appends the method name, optionally including the containing type name and using special names for methods with IsSpecialName set to true. /// </summary> protected virtual void AppendMethodName(IMethodReference method, NameFormattingOptions formattingOptions, StringBuilder sb) { if ((formattingOptions & NameFormattingOptions.OmitContainingType) == 0) { sb.Append(_typeNameFormatter.GetTypeName(method.ContainingType, formattingOptions)); sb.Append('.'); } // Special name translation string methodName = method.Name.Value; if (method.ResolvedMethod.IsSpecialName && (formattingOptions & NameFormattingOptions.PreserveSpecialNames) == 0) { if (methodName.StartsWith("get_")) { //^ assume methodName.Length >= 4; sb.Append(methodName.Substring(4)); sb.Append(".get"); } else if (methodName.StartsWith("set_")) { //^ assume methodName.Length >= 4; sb.Append(methodName.Substring(4)); sb.Append(".set"); } else { sb.Append(methodName); } } else { sb.Append(methodName); } }
private static bool IsFactoryForPlatformNotSupported(IMethodReference reference) { if (reference.ResolvedMethod is Dummy || reference.ResolvedMethod.IsAbstract) { return(false); } IMethodReference constructorReference = null; foreach (var op in reference.ResolvedMethod.Body.Operations) { switch (op.OperationCode) { case OperationCode.Newobj: constructorReference = op.Value as IMethodReference; break; case OperationCode.Ret: if (constructorReference != null && IsPlatformNotSupported(constructorReference)) { return(true); } break; } } return(false); }
/// <summary> /// Returns a C#-like string that corresponds to the given type member definition and that conforms to the specified formatting options. /// </summary> //^ [Pure] public virtual string GetMemberSignature(ITypeMemberReference member, NameFormattingOptions formattingOptions) { IMethodReference /*?*/ method = member as IMethodReference; if (method != null) { return(this.GetMethodSignature(method, formattingOptions)); } ITypeReference /*?*/ type = member as ITypeReference; if (type != null) { return(_typeNameFormatter.GetTypeName(type, formattingOptions)); } IEventDefinition /*?*/ eventDef = member as IEventDefinition; if (eventDef != null) { return(this.GetEventSignature(eventDef, formattingOptions)); } IFieldReference /*?*/ field = member as IFieldReference; if (field != null) { return(this.GetFieldSignature(field, formattingOptions)); } IPropertyDefinition /*?*/ property = member as IPropertyDefinition; if (property != null) { return(this.GetPropertySignature(property, formattingOptions)); } return(member.Name.Value); }
public DotNetDesktopStubMethodBodyEmitter(IMetadataHost host) : base(host) { this.consoleWriteLine = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Console"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("WriteLine"), 0, host.PlatformType.SystemString); this.environmentGetStackTrace = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemString, host.NameTable.GetNameFor("get_StackTrace"), 0); this.environmentExit = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Environment"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("Exit"), 0, host.PlatformType.SystemInt32); }
public WindowsPhoneStubMethodBodyEmitter(IMetadataHost host) : base(host) { this.consoleWriteLine = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Console"), CallingConvention.Default, host.PlatformType.SystemVoid, host.NameTable.GetNameFor("WriteLine"), 0, host.PlatformType.SystemString); this.stackTraceConstructor = new Microsoft.Cci.MethodReference(host, GarbageCollectHelper.CreateTypeReference(host, coreAssemblyReference, "System.Diagnostics.StackTrace"), CallingConvention.HasThis, host.PlatformType.SystemVoid, host.NameTable.GetNameFor(".ctor"), 0); this.toString = new Microsoft.Cci.MethodReference(host, host.PlatformType.SystemObject, CallingConvention.HasThis, host.PlatformType.SystemString, host.NameTable.GetNameFor("ToString"), 0); }
public static IMethodReference CanonicalizeMethodReference(IMethodReference method) { // function pointers don't have declaring types and they don't // really fit our model, so we ignore them. if (null == method.ContainingType) { return(null); } // // first canonicalize the method... // IGenericMethodInstanceReference genMeth = method as IGenericMethodInstanceReference; if ((genMeth != null)) { method = genMeth.GenericMethod; } //ITypeDefinitionMember memberDef; ISpecializedMethodReference specializedMethodRef = method as ISpecializedMethodReference; if (specializedMethodRef != null) { method = specializedMethodRef.UnspecializedVersion; } //else //member = member as ITypeDefinitionMember; return(method); }
public string GetNameWithParameterList(IMethodReference value) { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { writer.Write(this.GetName(value)); writer.Write("("); IParameterDeclarationCollection parameters = value.Parameters; for (int i = 0; i < parameters.Count; i++) { if (i != 0) { writer.Write(", "); } writer.Write(parameters[i].ParameterType.ToString()); } if (value.CallingConvention == MethodCallingConvention.VariableArguments) { if (value.Parameters.Count > 0) { writer.Write(", "); } writer.Write("..."); } writer.Write(")"); if ((value.Name != ".ctor") && (value.Name != ".cctor")) { writer.Write(" : "); writer.Write(value.ReturnType.Type.ToString()); } return(writer.ToString()); } }
public bool Matches(IMethodReference method) { var sig = CreateIdentifier(method); _log.Debug("matching: "+sig); //AKB to rethink return sig.MethodNameWithoutParams == _identifier.MethodNameWithoutParams; }
public V ReceiverValueForVirtualCallInstruction(IOperation operation) { Contract.Requires(operation.Value is IMethodReference); IMethodReference methodCalled = operation.Value as IMethodReference; return(FindReceiverInPreStateOperandStack(preStatesByOperation[operation], methodCalled)); }
private bool IsCallToContractMethod(IOperation op) { if (op.OperationCode != OperationCode.Call) { return(false); } IMethodReference method = op.Value as IMethodReference; if (method == null) { return(false); } ITypeReference contractClass = method.ContainingType; if (!TypeHelper.TypesAreEquivalent(contractClass, this.contractClassType)) { return(false); } switch (method.Name.Value) { case "Requires": case "RequiresAlways": // TODO: Remove once RequiresAlways is gone from the library case "Ensures": case "EnsuresOnThrow": case "Invariant": case "Assert": case "Assume": return(true); default: return(false); } }
public static Boolean IsCurrentlyMissing(IMethodReference methodReference) { // The value of this condition can change throughout the execution of the translation. // For that reason, it should be called at the end of the translation again to confirm // the method is actually missing from the binary. return(!methodsTranslated.Contains(BoogieMethod.From(methodReference).Name)); }
/// <summary> /// Methods that are iterators or async methods must have their bodies preserved /// in the reference assembly because (for now) their contracts are left in the /// MoveNext method found in the nested type defined in the containing type of this /// method. The contract extraction that is done by downstream tools depends on /// *this* method containing the preamble that creates an instance of that nested /// type, otherwise they assume the method does *not* have any contracts (which /// is incorrect). /// </summary> private bool IsIteratorOrAsyncMethod(IMethodDefinition currentMethod) { // walk the Operations looking for the first newobj instruction IMethodReference ctor = null; foreach (var op in currentMethod.Body.Operations) { if (op.OperationCode == OperationCode.Newobj) { ctor = op.Value as IMethodReference; break; } } if (ctor == null) { return(false); } var nestedType = ctor.ContainingType as INestedTypeReference; if (nestedType == null) { return(false); } if (nestedType.ContainingType.InternedKey != currentMethod.ContainingType.InternedKey) { return(false); } if (!TypeHelper.IsCompilerGenerated(ctor.ResolvedMethod.ContainingTypeDefinition)) { return(false); } var m = TypeHelper.GetMethod(nestedType.ResolvedType, this.host.NameTable.GetNameFor("MoveNext")); return(!(m is Dummy)); }
private static IMethodDefinition ResolveUnspecializedMethodOrThrow(IMethodReference methodReference) { var resolvedMethod = Sink.Unspecialize(methodReference).ResolvedMethod; if (resolvedMethod == Dummy.Method) { // avoid downstream errors, fail early throw new TranslationException(ExceptionType.UnresolvedMethod, MemberHelper.GetMethodSignature(methodReference, NameFormattingOptions.None)); } return resolvedMethod; }
public CustomAttribute( IMethodReference constructor, ITypeReference type, ReadOnlyArray<MetadataConstant> positionalArguments) : this(constructor, type, positionalArguments, ReadOnlyArray<IMetadataNamedArgument>.Empty) { }
public IEnumerable <MethodInfo> GetUsedMethods(object method) { var analyzedMethod = method as IMethodDeclaration; if (analyzedMethod.Body == null) { yield break; } var body = analyzedMethod.Body as IMethodBody; var instructions = body.Instructions.OfType <IInstruction>(); foreach (IInstruction instr in instructions) { IMethodReference mr = instr.Value as IMethodReference; if (mr != null) { IMethodDeclaration def = mr.Resolve(); if (def != null) { yield return(HAL.Converter.Method(def)); } } } yield break; }
private void AddDependency(IMethodReference method) { method = method.UnWrapMember <IMethodReference>(); // We are not directly interested in generic instances, they will get broken down into // their various pieces from the traversal and that is what we are interested in. if (method.IsGenericInstance()) { return; } // We don't care about WindowsRuntime methods if (method.IsWindowsRuntimeMember()) { return; } AddGeneralDependency(method); if (this.ComputeFullClosure) { IMethodDefinition methodDef = method.ResolvedMethod; if (methodDef is Dummy) { _unresolvedDependencies.Add(method); } else { base.Traverse(methodDef); } } }
/// <summary> /// Get the reference of a method in the closure class as used by other methods in the same class. /// </summary> private IMethodReference GetReferenceOfMethodUsedByPeers(IMethodDefinition method) { IMethodReference methodReference = null; ITypeReference typeReference = this.ClosureDefinitionReference; ISpecializedNestedTypeReference specializedNestedTypeRef = typeReference as ISpecializedNestedTypeReference; IGenericTypeInstanceReference genericInstanceRef = typeReference as IGenericTypeInstanceReference; if (specializedNestedTypeRef != null || genericInstanceRef != null) { methodReference = new SpecializedMethodReference() { ContainingType = typeReference, GenericParameterCount = method.GenericParameterCount, InternFactory = this.host.InternFactory, UnspecializedVersion = method, Type = method.Type, Name = method.Name, CallingConvention = method.CallingConvention, Parameters = method.ParameterCount == 0 ? null : new List <IParameterTypeInformation>(((IMethodReference)method).Parameters), ExtraParameters = null, ReturnValueIsByRef = method.ReturnValueIsByRef, ReturnValueIsModified = method.ReturnValueIsModified, Attributes = null, }; } else { methodReference = method; } return(methodReference); }
public static MethodVisibility GetVisibility(IPropertyReference value) { MethodVisibility visibility = MethodVisibility.Public; IPropertyDeclaration propertyDeclaration = value.Resolve(); if (propertyDeclaration != null) { IMethodReference setMethodReference = propertyDeclaration.SetMethod; IMethodDeclaration setMethod = (setMethodReference == null) ? null : setMethodReference.Resolve(); IMethodReference getMethodReference = propertyDeclaration.GetMethod; IMethodDeclaration getMethod = (getMethodReference == null) ? null : getMethodReference.Resolve(); if ((setMethod != null) && (getMethod != null)) { if (getMethod.Visibility == setMethod.Visibility) { visibility = getMethod.Visibility; } } else if (setMethod != null) { visibility = setMethod.Visibility; } else if (getMethod != null) { visibility = getMethod.Visibility; } } return(visibility); }
public void SetPEEntryPoint(IMethodSymbol method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); Debug.Assert(OutputKind.IsApplication()); PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); }
/// <summary> /// A rewriter for CodeModel method bodies, which changes any foreach loops found in the body into lower level structures. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in a block of statements to IPrimarySourceLocation objects. May be null.</param> public ForEachRemover(IMetadataHost host, ISourceLocationProvider /*?*/ sourceLocationProvider) : base(host) { this.sourceLocationProvider = sourceLocationProvider; this.moveNext = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = host.PlatformType.SystemCollectionsIEnumerator, InternFactory = host.InternFactory, Name = host.NameTable.GetNameFor("MoveNext"), Parameters = new List <IParameterTypeInformation>(), Type = host.PlatformType.SystemBoolean, }; var assemblyReference = new Immutable.AssemblyReference(this.host, this.host.CoreAssemblySymbolicIdentity); IUnitNamespaceReference ns = new Immutable.RootUnitNamespaceReference(assemblyReference); ns = new Immutable.NestedUnitNamespaceReference(ns, this.host.NameTable.GetNameFor("System")); var iDisposable = new Immutable.NamespaceTypeReference(this.host, ns, this.host.NameTable.GetNameFor("IDisposable"), 0, false, false, true, PrimitiveTypeCode.Reference); this.disposeMethod = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = iDisposable, InternFactory = host.InternFactory, Name = this.host.NameTable.GetNameFor("Dispose"), Parameters = new List <IParameterTypeInformation>(), Type = this.host.PlatformType.SystemVoid, }; }
private bool TryGetOffsetOfLastContractCall(List <IOperation> /*?*/ instrs, out uint offset) { offset = uint.MaxValue; if (instrs == null) { return(false); // not found } for (int i = instrs.Count - 1; 0 <= i; i--) { IOperation op = instrs[i]; if (op.OperationCode != OperationCode.Call) { continue; } IMethodReference method = op.Value as IMethodReference; if (method == null) { continue; } if (Microsoft.Cci.MutableContracts.ContractHelper.IsValidatorOrAbbreviator(method)) { offset = op.Offset; return(true); } var methodName = method.Name.Value; if (TypeHelper.TypesAreEquivalent(method.ContainingType, this.contractClassType) && IsNameOfPublicContractMethod(methodName) ) { offset = op.Offset; return(true); } } return(false); // not found }
public void Test() { // Get method body information. MethodInfo mi = typeof(Sample).GetMethod("MethodBodyExample", BindingFlags.Instance | BindingFlags.NonPublic); IMethodReference methodReference = AssemblyManager.FindMethod(mi); IList <IStatement> statements = methodReference.Resolve().Body.Statements; }
// Put return type after the signature public override string GetMethodSignature(IMethodReference method, NameFormattingOptions formattingOptions) { string baseSig = base.GetMethodSignature(method, (formattingOptions & ~NameFormattingOptions.ReturnType)); StringBuilder sb = new StringBuilder(baseSig); AppendReturnTypeSignature(method, (formattingOptions | NameFormattingOptions.ReturnType), sb); return sb.ToString(); }
/// <summary> /// Tests is the given Assembly is a BizTalk assembly or not. /// </summary> /// <param name="assembly">Assembly to test.</param> /// <returns>true if this is a BizTalk assembly, false otherwise.</returns> private static bool TestForBizTalkAssembly(IAssembly assembly) { bool isBTSAssembly = false; if (assembly != null) { // A BizTalk assembly is a Library if (assembly.Type == AssemblyType.Library) { // A BizTalk assembly has the "BizTalkAssemblyAttribute" set foreach (ICustomAttribute attribute in assembly.Attributes) { // Get the constructor MethodReference for this attribute IMethodReference ctorReference = attribute.Constructor as IMethodReference; if (ctorReference != null) { // Get the declaring type for the constructor ITypeReference ctorDeclaringType = ctorReference.DeclaringType as ITypeReference; if (ctorDeclaringType != null) { isBTSAssembly = (String.CompareOrdinal(ctorDeclaringType.Owner.ToString(), Constants.XLANGBaseTypesFullyQualifiedAssemblyName) == 0) && (String.CompareOrdinal(Constants.BizTalkAssemblyAttribute, ctorDeclaringType.ToString()) == 0); // If we found the attribute we expect, we can declare it is a BizTalk assembly if (isBTSAssembly) { break; } } } } } } return(isBTSAssembly); }
internal IMethodReference Map(IMethodReference methodReference) { var result = new MetadataDeepCopier(host).Copy(methodReference); var rewriter = new ActualMutator(host, targetUnit, sourceUnitIdentity); return(rewriter.Rewrite(result)); }
public static bool IsVisible(IMethodReference value, IVisibilityConfiguration visibility) { if (IsVisible(value.DeclaringType, visibility)) { switch (value.Resolve().Visibility) { case MethodVisibility.PrivateScope: case MethodVisibility.Private: return(visibility.Private); case MethodVisibility.FamilyAndAssembly: return(visibility.FamilyAndAssembly); case MethodVisibility.Assembly: return(visibility.Assembly); case MethodVisibility.Family: return(visibility.Family); case MethodVisibility.FamilyOrAssembly: return(visibility.FamilyOrAssembly); case MethodVisibility.Public: return(visibility.Public); } throw new NotSupportedException(); } return(false); }
/// <summary> /// A rewriter for CodeModel method bodies, which changes any foreach loops found in the body into lower level structures. /// </summary> /// <param name="host">An object representing the application that is hosting the converter. It is used to obtain access to some global /// objects and services such as the shared name table and the table for interning references.</param> /// <param name="sourceLocationProvider">An object that can map the ILocation objects found in a block of statements to IPrimarySourceLocation objects. May be null.</param> public ForEachRemover(IMetadataHost host, ISourceLocationProvider/*?*/ sourceLocationProvider) : base(host) { this.sourceLocationProvider = sourceLocationProvider; this.moveNext = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = host.PlatformType.SystemCollectionsIEnumerator, InternFactory = host.InternFactory, Name = host.NameTable.GetNameFor("MoveNext"), Parameters = new List<IParameterTypeInformation>(), Type = host.PlatformType.SystemBoolean, }; var assemblyReference = new Immutable.AssemblyReference(this.host, this.host.CoreAssemblySymbolicIdentity); IUnitNamespaceReference ns = new Immutable.RootUnitNamespaceReference(assemblyReference); ns = new Immutable.NestedUnitNamespaceReference(ns, this.host.NameTable.GetNameFor("System")); var iDisposable = new Immutable.NamespaceTypeReference(this.host, ns, this.host.NameTable.GetNameFor("IDisposable"), 0, false, false, true, PrimitiveTypeCode.Reference); this.disposeMethod = new MethodReference() { CallingConvention = CallingConvention.HasThis, ContainingType = iDisposable, InternFactory = host.InternFactory, Name = this.host.NameTable.GetNameFor("Dispose"), Parameters = new List<IParameterTypeInformation>(), Type = this.host.PlatformType.SystemVoid, }; }
public string GetName(IMethodReference value) { ITypeCollection genericArguments = value.GenericArguments; if (genericArguments.Count > 0) { using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture)) { for (int i = 0; i < genericArguments.Count; i++) { if (i != 0) { writer.Write(", "); } IType type = genericArguments[i]; if (type != null) { writer.Write(type.ToString()); } else { writer.Write("???"); } } return(value.Name + "<" + writer.ToString() + ">"); } } return(value.Name); }
public CustomAttribute( IMethodReference constructor, ITypeReference type, ReadOnlyArray <MetadataConstant> positionalArguments) : this(constructor, type, positionalArguments, ReadOnlyArray <IMetadataNamedArgument> .Empty) { }
private void AddAlternativeInvocation(BlockStatement block, IMethodDefinition fakeMethod, IMethodReference originalCall) { var context = new ReplacementMethodConstructionContext(host, originalCall, fakeMethod, block, log, null); var methodBuilder = context.GetMethodBuilder(); methodBuilder.BuildMethod(); }
public static MethodIdentifier CreateIdentifier(IMethodReference method) { method = MemberHelper.UninstantiateAndUnspecialize(method); return new MethodIdentifier(MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature | NameFormattingOptions.TypeParameters | NameFormattingOptions.ParameterModifiers)); }
public ReplacementMethodConstructionContext(IMetadataHost host, IMethodReference originalCall, IMethodDefinition fakeMethod, BlockStatement block, ILogger log, IReplaceableReference originalReference) { this.host = host; this.block = block; this.log = log; this.originalReference = originalReference; this.originalCall = originalCall; fakeMethodParameters = fakeMethod.Parameters; returnType = fakeMethod.Type; }
public CustomAttribute( IMethodReference constructor, ITypeReference type, ReadOnlyArray<MetadataConstant> positionalArguments, ReadOnlyArray<IMetadataNamedArgument> namedArguments) { this.constructor = constructor; this.type = type; this.positionalArguments = positionalArguments; this.namedArguments = namedArguments; }
public static IMethodDefinition ResolveMethodThrowing(IMethodReference method) { IMethodDefinition result = method.ResolvedMethod; if (result == Dummy.Method || result == null) { throw new Exception(String.Format("Cannot resolve member '{0}'. Are all dependent assemblies loaded?", method.ToString())); } Debug.Assert(!result.GetType().Name.Contains("Dummy")); return result; }
private static bool TryGetCompatibileModifier(IMethodDefinition resolvedMethod, out IMethodReference accessor) { var result = resolvedMethod.ContainingTypeDefinition.Properties .FirstOrDefault(p => p.Setter != null && p.Setter.Name.UniqueKey != resolvedMethod.Name.UniqueKey && TypeHelper.ParameterListsAreEquivalent(p.Setter.Parameters, resolvedMethod.Parameters)); if (result == null) { accessor = null; return false; } else { accessor = result.Setter; return true; } }
internal string Mangle(IMethodReference method) { Contract.Requires(method != null); method.ResolvedMethod.Dispatch(this); //compute the hash var sb = new StringBuilder(); sb.Append('_'); sb.Append((uint)this.hash); sb.Append('_'); this.AppendSanitizedName(sb, TypeHelper.GetTypeName(method.ContainingType)); sb.Append('_'); this.AppendSanitizedName(sb, method.Name.Value); foreach (var par in method.Parameters) { sb.Append('_'); this.AppendSanitizedName(sb, TypeHelper.GetTypeName(par.Type, NameFormattingOptions.OmitContainingType)); } return sb.ToString(); }
/// <summary> /// Creates the normalize method definition. /// </summary> /// <param name="methodReference">The method reference.</param> /// <returns>A new NormalizeMethodDefinition instance, based on the input.</returns> internal static NormalizeMethodDefinition CreateNormalizeMethodDefinition(IMethodReference methodReference) { if (methodReference == null) { throw new ArgumentNullException("methodReference"); } ITypeReference typeReference = methodReference.DeclaringType as ITypeReference; return new NormalizeMethodDefinition( typeReference.Name, typeReference.Namespace, methodReference.Name, BuildParameterList(methodReference.Parameters), methodReference.ReturnType.Type.ToString(), string.Empty); }
/// <summary> /// Returns the interned key for the generic method parameter constructed with the given index /// </summary> /// <param name="definingMethodReference">A reference to the method defining the referenced generic parameter.</param> /// <param name="index">The index of the referenced generic parameter. This is an index rather than a name because metadata in CLR /// PE files contain only the index, not the name.</param> uint GetGenericMethodParameterReferenceInternId(IMethodReference definingMethodReference, uint index) { Contract.Requires(definingMethodReference != null); if (!(this.CurrentMethodReference is Dummy)) { //this happens when the defining method reference contains a type in its signature which either is, or contains, //a reference to this generic method type parameter. In that case we break the cycle by just using the index of //the generic parameter. Only method references that refer to their own type parameters will ever //get this version of the interned id. return index+1000000; //provide a big offset to minimize the chances of a structural type in the //signature of the method interning onto some other type that is parameterized by a type whose intern key is index. } this.CurrentMethodReference = definingMethodReference; //short circuit recursive calls back to this method uint definingMethodReferenceInternId = this.GetMethodReferenceInternedId(definingMethodReference); this.CurrentMethodReference = Dummy.MethodReference; uint value = this.GenericMethodTypeParameterHashTable.Find(definingMethodReferenceInternId, index); if (value == 0) { value = this.CurrentTypeInternValue++; this.GenericMethodTypeParameterHashTable.Add(definingMethodReferenceInternId, index, value); } return value; }
/// <summary> /// /// </summary> public InternFactory() { this.CurrentAssemblyInternValue = 0x00001000; this.CurrentMethodReference = Dummy.MethodReference; this.CurrentModuleInternValue = 0x00000001; this.CurrentNamespaceInternValue = 0x00000001; this.CurrentTypeInternValue = 0x00000100; this.CurrentTypeListInternValue = 0x00000001; this.CurrentCustomModifierInternValue = 0x00000001; this.CurrentCustomModifierListInternValue = 0x00000001; this.CurrentMethodReferenceInternValue = 0x00000001; this.CurrentFieldReferenceInternValue = 0x00000001; this.CurrentParameterTypeInternValue = 0x00000001; this.CurrentParameterTypeListInternValue = 0x00000001; this.CurrentSignatureInternValue = 0x00000001; this.AssemblyHashtable = new MultiHashtable<AssemblyStore>(); this.ModuleHashtable = new MultiHashtable<ModuleStore>(); this.NestedNamespaceHashtable = new DoubleHashtable(); this.NamespaceTypeHashtable = new MultiHashtable<NamespaceTypeStore>(); this.NestedTypeHashtable = new MultiHashtable<NestedTypeStore>(); this.VectorTypeHashTable = new Hashtable(); this.PointerTypeHashTable = new Hashtable(); this.ManagedPointerTypeHashTable = new Hashtable(); this.MatrixTypeHashtable = new MultiHashtable<MatrixTypeStore>(); this.TypeListHashtable = new DoubleHashtable(); this.GenericTypeInstanceHashtable = new DoubleHashtable(); this.GenericMethodInstanceHashtable = new DoubleHashtable(); this.GenericTypeParameterHashtable = new DoubleHashtable(); this.GenericMethodTypeParameterHashTable = new DoubleHashtable(); this.CustomModifierHashTable = new DoubleHashtable(); this.CustomModifierListHashTable = new DoubleHashtable(); this.ParameterTypeHashtable = new MultiHashtable<ParameterTypeStore>(); this.ParameterTypeListHashtable = new DoubleHashtable(); this.SignatureHashtable = new MultiHashtable<SignatureStore>(); this.FunctionTypeHashTable = new Hashtable(); this.ModifiedTypeHashtable = new DoubleHashtable(); this.MethodReferenceHashtable = new Hashtable<MultiHashtable<SignatureStore>>(); this.FieldReferenceHashtable = new Hashtable<DoubleHashtable>(); }
public virtual void onMetadataElement(IMethodReference methodReference) { }
private void AddDependencyForCalledMethod(IMethodReference method) { AddDependency(method.ContainingType, false); this._methodDependents.Add(method); }
uint IInternFactory.GetGenericMethodParameterReferenceInternedKey(IMethodReference methodReference, int index) { lock (GlobalLock.LockingObject) { return this.GetGenericMethodParameterReferenceInternId(methodReference, (uint)index); } }
internal CustomAttributeDecoder(PEFileToObjectModel peFileToObjectModel, MemoryReader signatureMemoryReader, uint customAttributeRowId, IMethodReference attributeConstructor) : base(peFileToObjectModel, signatureMemoryReader) { this.CustomAttribute = Dummy.CustomAttribute; ushort prolog = this.SignatureMemoryReader.ReadUInt16(); if (prolog != SerializationType.CustomAttributeStart) return; int len = attributeConstructor.ParameterCount; IMetadataExpression[]/*?*/ exprList = len == 0 ? null : new IMetadataExpression[len]; int i = 0; foreach (var parameter in attributeConstructor.Parameters) { var parameterType = parameter.Type; if (parameterType is Dummy) { // Error... return; } ExpressionBase/*?*/ argument = this.ReadSerializedValue(parameterType); if (argument == null) { // Error... this.decodeFailed = true; return; } exprList[i++] = argument; } IMetadataNamedArgument[]/*?*/ namedArgumentArray = null; if (2 <= (int)this.SignatureMemoryReader.RemainingBytes) { ushort numOfNamedArgs = this.SignatureMemoryReader.ReadUInt16(); if (numOfNamedArgs > 0) { namedArgumentArray = new IMetadataNamedArgument[numOfNamedArgs]; for (i = 0; i < numOfNamedArgs; ++i) { if (0 >= (int)this.SignatureMemoryReader.RemainingBytes) break; bool isField = this.SignatureMemoryReader.ReadByte() == SerializationType.Field; ITypeReference/*?*/ memberType = this.GetFieldOrPropType(); if (memberType == null) { // Error... return; } string/*?*/ memberStr = this.GetSerializedString(); if (memberStr == null) return; IName memberName = this.PEFileToObjectModel.NameTable.GetNameFor(memberStr); ExpressionBase/*?*/ value = this.ReadSerializedValue(memberType); if (value == null) { // Error... return; } ITypeReference/*?*/ moduleTypeRef = attributeConstructor.ContainingType; if (moduleTypeRef == null) { // Error... return; } FieldOrPropertyNamedArgumentExpression namedArg = new FieldOrPropertyNamedArgumentExpression(memberName, moduleTypeRef, isField, memberType, value); namedArgumentArray[i] = namedArg; } } } this.CustomAttribute = peFileToObjectModel.ModuleReader.metadataReaderHost.Rewrite(peFileToObjectModel.Module, new CustomAttribute(peFileToObjectModel, customAttributeRowId, attributeConstructor, exprList, namedArgumentArray)); }
public override void TraverseChildren(IMethodReference methodReference) { base.TraverseChildren(methodReference); }
/// <summary> /// Performs some computation with the given method reference. /// </summary> public void Visit(IMethodReference methodReference) { }
/// <summary> /// Wraps a call to GetMethodContractFor inside of a try-catch statement. /// </summary> public static bool TryGetMethodContract(CodeContractAwareHostEnvironment host, IMethodReference method, out IMethodContract methodContract, DocTracker docTracker) { Contract.Requires(host != null); Contract.Requires(method != null); Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out methodContract) != null); try { methodContract = ContractHelper.GetMethodContractFor(host, method.ResolvedMethod); } catch (NullReferenceException) { docTracker.WriteLine("ERROR: NullReferenceException was thrown in CCI!"); methodContract = null; } //} catch (Exception e) { // docTracker.WriteLine("ERROR: Exception of type '{0}' was thrown in CCI!", e.GetType().Name); // docTracker.WriteLine("\t'{0}'", e.Message); // methodContract = null; //} return methodContract != null; }
protected override void ReserveMethodToken(IMethodReference methodReference) { this.metadataWriter.GetMethodToken(methodReference); }
uint GetMethodReferenceInternedId(IMethodReference methodReference) { Contract.Requires(methodReference != null); var genInstanceRef = methodReference as IGenericMethodInstanceReference; if (genInstanceRef != null) return this.GetGenericMethodInstanceReferenceInternedKey(genInstanceRef); uint containingTypeReferenceInternedId = this.GetTypeReferenceInternId(methodReference.ContainingType); uint requiredParameterTypesInternedId = this.GetParameterTypeListInternId(methodReference.Parameters.GetEnumerator()); uint returnValueCustomModifiersInternedId = 0; uint genericParameterCount = methodReference.GenericParameterCount; if (methodReference.ReturnValueIsModified) returnValueCustomModifiersInternedId = this.GetCustomModifierListInternId(methodReference.ReturnValueCustomModifiers.GetEnumerator()); uint returnTypeReferenceInternedId = this.GetTypeReferenceInternId(methodReference.Type); MultiHashtable<SignatureStore>/*?*/ methods = this.MethodReferenceHashtable.Find(containingTypeReferenceInternedId); if (methods == null) { methods = new MultiHashtable<SignatureStore>(); this.MethodReferenceHashtable.Add(containingTypeReferenceInternedId, methods); } foreach (SignatureStore signatureStore in methods.GetValuesFor((uint)methodReference.Name.UniqueKey)) { if ( signatureStore.CallingConvention == methodReference.CallingConvention && signatureStore.RequiredParameterListInternedId == requiredParameterTypesInternedId && signatureStore.ReturnValueCustomModifiersListInteredId == returnValueCustomModifiersInternedId && signatureStore.ReturnValueIsByRef == methodReference.ReturnValueIsByRef && signatureStore.ReturnTypeReferenceInternedId == returnTypeReferenceInternedId && signatureStore.GenericParameterCount == genericParameterCount ) { return signatureStore.InternedId; } } SignatureStore signatureStore1 = new SignatureStore(methodReference.CallingConvention, requiredParameterTypesInternedId, 0, methodReference.ReturnValueIsByRef, returnValueCustomModifiersInternedId, returnTypeReferenceInternedId, genericParameterCount, this.CurrentMethodReferenceInternValue++); methods.Add((uint)methodReference.Name.UniqueKey, signatureStore1); return signatureStore1.InternedId; }
uint IInternFactory.GetMethodInternedKey(IMethodReference methodReference) { lock (GlobalLock.LockingObject) { return this.GetMethodReferenceInternedId(methodReference); } }
internal CustomAttribute(PEFileToObjectModel peFileToObjectModel, uint attributeRowId, IMethodReference constructor, IMetadataExpression[]/*?*/ arguments, IMetadataNamedArgument[]/*?*/ namedArguments) : base(peFileToObjectModel) { this.AttributeRowId = attributeRowId; this.Constructor = constructor; this.Arguments = arguments; this.NamedArguments = namedArguments; }
internal SecurityCustomAttribute(SecurityAttribute containingSecurityAttribute, IMethodReference constructorReference, IMetadataNamedArgument[]/*?*/ namedArguments) { this.ContainingSecurityAttribute = containingSecurityAttribute; this.ConstructorReference = constructorReference; this.NamedArguments = namedArguments; }
public abstract bool Matches(IMethodReference method);