/// <summary> /// Make a call site object equipped with an initial target method handle. </summary> /// <param name="targetType"> the desired type of the call site </param> /// <param name="createTargetHook"> a hook which will bind the call site to the target method handle </param> /// <exception cref="WrongMethodTypeException"> if the hook cannot be invoked on the required arguments, /// or if the target returned by the hook is not of the given {@code targetType} </exception> /// <exception cref="NullPointerException"> if the hook returns a null value </exception> /// <exception cref="ClassCastException"> if the hook returns something other than a {@code MethodHandle} </exception> /// <exception cref="Throwable"> anything else thrown by the hook function </exception> /*package-private*/ //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable internal CallSite(MethodType targetType, MethodHandle createTargetHook) : this(targetType) { ConstantCallSite selfCCS = (ConstantCallSite)this; MethodHandle boundTarget = (MethodHandle)createTargetHook.InvokeWithArguments(selfCCS); CheckTargetChange(this.Target_Renamed, boundTarget); this.Target_Renamed = boundTarget; }
/*non-public*/ internal virtual MethodHandle MakeDynamicInvoker() { MethodHandle getTarget = GET_TARGET.BindArgumentL(0, this); MethodHandle invoker = MethodHandles.ExactInvoker(this.Type()); return(MethodHandles.FoldArguments(invoker, getTarget)); }
public static void Hook(this IntPtr targetPtr, MethodInfo patch) { unsafe { MelonUtils.NativeHookAttach(targetPtr, patch !.MethodHandle.GetFunctionPointer()); } }
private StatusCode DispatchControllerMethod( RequestContext context, MethodHandle methodHandle, IList <Variant> inputArguments, List <StatusCode> inputArgumentResults, List <Variant> outputArguments) { SystemFunction data = methodHandle.MethodData as SystemFunction; if (data != null) { this.currentData = "CALL " + data.Function + inputArguments[0].ToString(); GenericEvent e = new GenericEvent(Server.FilterManager); e.Initialize( null, ObjectTypeIds.SystemEventType, ParsedNodeId.Construct(0, "Jemima", DefaultNamespaceIndex), "Jemima", EventSeverity.Medium, "A Jemima is CALL." ); //e.Set(e.ToPath(new QualifiedName("Jackey", DefaultNamespaceIndex)), currentData); ReportEvent(e.SourceNode, e); return(StatusCodes.Good); } return(StatusCodes.BadNotImplemented); }
public RuntimeMethodHandle GetRuntimeMethodHandle(Type[] genericArgs) { Debug.Assert(genericArgs == null || genericArgs.Length > 0); RuntimeTypeHandle[] genericArgHandles; if (genericArgs != null) { genericArgHandles = new RuntimeTypeHandle[genericArgs.Length]; for (int i = 0; i < genericArgHandles.Length; i++) { genericArgHandles[i] = genericArgs[i].TypeHandle; } } else { genericArgHandles = null; } TypeManagerHandle typeManager = TypeLoaderEnvironment.Instance.ModuleList.GetModuleForMetadataReader(Reader); return(TypeLoaderEnvironment.Instance.GetRuntimeMethodHandleForComponents( DeclaringType.TypeHandle, Name, RuntimeSignature.CreateFromMethodHandle(typeManager, MethodHandle.AsInt()), genericArgHandles)); }
public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, MethodType oldType, int[] permutationOrNull) { #if FIRST_PASS return(null); #else // LAME why does OpenJDK name the parameter permutationOrNull while it is not allowed to be null? if (permutationOrNull.Length != oldType.parameterCount()) { throw new java.lang.IllegalArgumentException("wrong number of arguments in permutation"); } MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("MethodHandleImpl.permuteArguments", newType, target); for (int i = 0, argCount = newType.parameterCount(); i < permutationOrNull.Length; i++) { // make sure to only read each array element once, to avoid having to make a defensive copy of the array int perm = permutationOrNull[i]; if (perm < 0 || perm >= argCount) { throw new java.lang.IllegalArgumentException("permutation argument out of range"); } dm.Ldarg(perm); dm.Convert(oldType.parameterType(i), newType.parameterType(perm), 0); } dm.CallTarget(); dm.Convert(oldType.returnType(), newType.returnType(), 0); dm.Ret(); return(dm.CreateAdapter()); #endif }
private RuntimeFatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, ReflectionDomain reflectionDomain, MetadataReader reader, Handle typeHandle, TypeContext typeContext) : base(member, position, reflectionDomain, reader, typeHandle, typeContext) { _methodHandle = methodHandle; _parameterHandle = parameterHandle; _parameter = parameterHandle.GetParameter(reader); }
// called from Lookup.revealDirect() (instead of MethodHandle.internalMemberName()) via map.xml replace-method-call public static MemberName internalMemberName(MethodHandle mh) { #if FIRST_PASS return(null); #else MemberName mn = mh.internalMemberName(); if (mn.isStatic() && mn.getName() == "<init>") { // HACK since we convert String constructors into static methods, we have to undo that here // Note that the MemberName we return is only used for a security check and by InfoFromMemberName (a MethodHandleInfo implementation), // so we don't need to make it actually invokable. MemberName alt = new MemberName(); typeof(MemberName).GetField("clazz", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(alt, mn.getDeclaringClass()); typeof(MemberName).GetField("name", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(alt, mn.getName()); typeof(MemberName).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(alt, mn.getMethodType().changeReturnType(typeof(void))); int flags = mn._flags(); flags -= MethodHandleNatives.Constants.MN_IS_METHOD; flags += MethodHandleNatives.Constants.MN_IS_CONSTRUCTOR; flags &= ~(MethodHandleNatives.Constants.MN_REFERENCE_KIND_MASK << MethodHandleNatives.Constants.MN_REFERENCE_KIND_SHIFT); flags |= MethodHandleNatives.Constants.REF_newInvokeSpecial << MethodHandleNatives.Constants.MN_REFERENCE_KIND_SHIFT; flags &= ~MethodHandleNatives.Constants.ACC_STATIC; alt._flags(flags); return(alt); } return(mn); #endif }
#pragma warning disable 618 // obsolete warning reported when RowIds are used private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodHandle methodDef) { MethodDefTreatment treatment = 0; foreach (var caHandle in peFileReader.GetCustomAttributes(methodDef)) { CustomAttribute ca = peFileReader.GetCustomAttribute(caHandle); StringHandle namespaceHandle, nameHandle; if (!ca.GetFullTypeName(out namespaceHandle, out nameHandle)) { continue; } if (peFileReader.StringStream.CheckForText(namespaceHandle, "Windows.UI.Xaml")) { if (peFileReader.StringStream.CheckForText(nameHandle, "TreatAsPublicMethodAttribute")) { treatment |= MethodDefTreatment.MarkPublicFlag; } if (peFileReader.StringStream.CheckForText(nameHandle, "TreatAsAbstractMethodAttribute")) { treatment |= MethodDefTreatment.MarkAbstractFlag; } } } return(treatment); }
public static MethodHandle makeSpreadArguments(MethodType newType, MethodHandle target, java.lang.Class spreadArgType, int spreadArgPos, int spreadArgCount) { #if FIRST_PASS return(null); #else TypeWrapper twComponent = TypeWrapper.FromClass(spreadArgType).ElementTypeWrapper; MethodHandleUtil.DynamicMethodBuilder dm = new MethodHandleUtil.DynamicMethodBuilder("AdapterMethodHandle.spreadArguments", newType, target); for (int i = 0, count = newType.parameterCount(); i < count; i++) { if (i == spreadArgPos) { for (int j = 0; j < spreadArgCount; j++) { dm.Ldarg(i); dm.LoadArrayElement(j, twComponent); dm.Convert(twComponent.ClassObject, target.type().parameterType(i + j), 0); } } else { dm.Ldarg(i); } } dm.CallTarget(); dm.Ret(); return(dm.CreateAdapter()); #endif }
private NativeFormatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, QSignatureTypeHandle qualifiedParameterTypeHandle, TypeContext typeContext) : base(member, position, qualifiedParameterTypeHandle, typeContext) { _methodHandle = methodHandle; _parameterHandle = parameterHandle; _parameter = parameterHandle.GetParameter(Reader); }
private bool GetAccessor(MethodSemanticsAttributes methodSemanticsAttribute, out MethodHandle methodHandle) { bool inherited = !_reflectedType.Equals(_contextTypeInfo); foreach (MethodSemanticsHandle methodSemanticsHandle in _property.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == methodSemanticsAttribute) { methodHandle = methodSemantics.Method; if (inherited) { MethodAttributes flags = methodHandle.GetMethod(_reader).Flags; if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) { continue; } } return(true); } } methodHandle = default(MethodHandle); return(false); }
/// <summary> /// Constructs a new method declaration. /// </summary> /// <param name="handle">The method handle (may be an empty handle).</param> /// <param name="returnType">The return type.</param> /// <param name="flags">Custom method flags.</param> public MethodDeclaration( MethodHandle handle, TypeNode returnType, MethodFlags flags) : this(handle, returnType, null, flags) { }
/// <summary> /// Constructs a new method declaration with an implicit handle. /// </summary> /// <param name="name">The method name.</param> /// <param name="returnType">The return type.</param> /// <param name="flags">Custom method flags.</param> public MethodDeclaration( string name, TypeNode returnType, MethodFlags flags) : this(MethodHandle.Create(name), returnType, flags) { }
/// <summary> /// Constructs a new method declaration. /// </summary> /// <param name="handle">The method handle (may be an empty handle).</param> /// <param name="returnType">The return type.</param> /// <param name="source">The source method.</param> public MethodDeclaration( MethodHandle handle, TypeNode returnType, MethodBase source) : this(handle, returnType, source, MethodFlags.None) { }
public CallRloStaticMethodInstruction(CodeLocationTag codeLocation, MethodHandle methodHandle, HighSsaRegister returnDest, HighSsaRegister[] parameters) { CodeLocation = codeLocation; m_methodHandle = methodHandle; m_returnDest = returnDest; m_parameters = parameters; }
private MemberInfo GetOrAddPropertyInfo(PropertyHandle handle) { if (this.properties == null) { properties = new Dictionary <PropertyHandle, MemberInfo>(); } MemberInfo result = null; if (!properties.TryGetValue(handle, out result)) { var property = metadataReader.GetProperty(handle); var propertyMethodHandles = property.GetAssociatedMethods(); TypeHandle declaringTypeHandle; MethodHandle accessorMethod = propertyMethodHandles.Getter; if (accessorMethod.IsNil) { accessorMethod = propertyMethodHandles.Setter; } declaringTypeHandle = metadataReader.GetDeclaringType(accessorMethod); result = new MemberInfo(MemberKind.Property); result.Token = this.metadataReader.GetToken(handle); result.DeclaringTypeHandle = declaringTypeHandle; result.Handle = handle; properties.Add(handle, result); } return(result); }
internal static RuntimeNamedMethodInfo GetRuntimeNamedMethodInfo(MethodHandle methodHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { RuntimeNamedMethodInfo method = new RuntimeNamedMethodInfo(methodHandle, definingTypeInfo, contextTypeInfo); method.WithDebugName(); return(method); }
public MethodSignatureComparer( QMethodDefinition methodHandle) { if (methodHandle.IsNativeFormatMetadataBased) { _metadataReader = methodHandle.NativeFormatReader; _methodHandle = methodHandle.NativeFormatHandle; _method = _methodHandle.GetMethod(_metadataReader); _methodSignature = _method.Signature.GetMethodSignature(_metadataReader); _isGeneric = (_methodSignature.GenericParameterCount != 0); // Precalculate initial method attributes used in signature queries _isStatic = (_method.Flags & MethodAttributes.Static) != 0; } else { _metadataReader = null; _methodHandle = default(MethodHandle); _method = default(Method); _methodSignature = default(MethodSignature); _isGeneric = false; _isStatic = false; } }
private RuntimeFatMethodParameterInfo(MethodBase member, MethodHandle methodHandle, int position, ParameterHandle parameterHandle, MetadataReader reader, Handle typeHandle, TypeContext typeContext) : base(member, position, reader, typeHandle, typeContext) { _methodHandle = methodHandle; _parameterHandle = parameterHandle; _parameter = parameterHandle.GetParameter(reader); }
public void VisualizeMethodBody(MethodBodyBlock body, MethodHandle methodHandle, bool emitHeader = true) { StringBuilder builder = new StringBuilder(); // TODO: Inspect EncLog to find a containing type and display qualified name. var method = GetMethod(methodHandle); if (emitHeader) { builder.AppendFormat("Method {0} (0x{1:X8})", Literal(method.Name), MetadataTokens.GetToken(methodHandle)); builder.AppendLine(); } // TODO: decode signature if (!body.LocalSignature.IsNil) { var localSignature = GetLocalSignature(body.LocalSignature); builder.AppendFormat(" Locals: {0}", Literal(localSignature)); builder.AppendLine(); } ILVisualizerAsTokens.Instance.DumpMethod( builder, body.MaxStack, body.GetILBytes(), ImmutableArray.Create <ILVisualizer.LocalInfo>(), // TODO ImmutableArray.Create <ILVisualizer.HandlerSpan>()); // TOOD: ILVisualizer.GetHandlerSpans(body.ExceptionRegions) builder.AppendLine(); writer.Write(builder.ToString()); }
/** * Emit an invoke for the given name. */ void emitInvoke(Name name) { //assert(!isLinkerMethodInvoke(name)); // should use the static path for these if (true) { // push receiver MethodHandle target = name.function._resolvedHandle(); //assert(target != null) : name.exprString(); //mv.visitLdcInsn(constantPlaceholder(target)); EmitConstant(target); emitReferenceCast(CoreClasses.java.lang.invoke.MethodHandle.Wrapper.ClassObject, target); } else { // load receiver //emitAloadInsn(0); //emitReferenceCast(MethodHandle.class, null); //mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG); //mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG); // TODO more to come } // push arguments emitPushArguments(name); // invocation MethodType type = name.function.methodType(); //mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false); EmitInvokeBasic(type.basicType()); }
public static int AsInt(this MethodHandle methodHandle) { unsafe { return(*(int *)&methodHandle); } }
internal PEMethodSymbol( PEModuleSymbol moduleSymbol, PENamedTypeSymbol containingType, MethodHandle methodDef) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(!methodDef.IsNil); this.handle = methodDef; this.containingType = containingType; MethodAttributes localflags = 0; try { int rva; moduleSymbol.Module.GetMethodDefPropsOrThrow(methodDef, out this.name, out this.implFlags, out localflags, out rva); } catch (BadImageFormatException) { if ((object)this.name == null) { this.name = String.Empty; } lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this); } this.flags = localflags; }
// // Retrieves the MethodBase for a given method handle. Helper to implement Delegate.GetMethodInfo() // public MethodBase GetMethod(RuntimeTypeHandle declaringTypeHandle, MethodHandle methodHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle(); RuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers; MetadataReader reader = definingTypeInfo.Reader; if (methodHandle.IsConstructor(reader)) { return(RuntimePlainConstructorInfo.GetRuntimePlainConstructorInfo(methodHandle, definingTypeInfo, contextTypeInfo)); } else { // RuntimeMethodHandles always yield methods whose ReflectedType is the DeclaringType. RuntimeTypeInfo reflectedType = contextTypeInfo; RuntimeNamedMethodInfo runtimeNamedMethodInfo = RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodHandle, definingTypeInfo, contextTypeInfo, reflectedType); if (!runtimeNamedMethodInfo.IsGenericMethod) { return(runtimeNamedMethodInfo); } else { RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[genericMethodTypeArgumentHandles.Length]; for (int i = 0; i < genericMethodTypeArgumentHandles.Length; i++) { genericTypeArguments[i] = genericMethodTypeArgumentHandles[i].GetTypeForRuntimeTypeHandle(); } return(RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(runtimeNamedMethodInfo, genericTypeArguments)); } } }
/// <summary> /// Returns a method handle which always delegates either to the target or the fallback. /// The method handle will delegate to the target exactly as long as the switch point is valid. /// After that, it will permanently delegate to the fallback. /// <para> /// The target and fallback must be of exactly the same method type, /// and the resulting combined method handle will also be of this type. /// /// </para> /// </summary> /// <param name="target"> the method handle selected by the switch point as long as it is valid </param> /// <param name="fallback"> the method handle selected by the switch point after it is invalidated </param> /// <returns> a combined method handle which always calls either the target or fallback </returns> /// <exception cref="NullPointerException"> if either argument is null </exception> /// <exception cref="IllegalArgumentException"> if the two method types do not match </exception> /// <seealso cref= MethodHandles#guardWithTest </seealso> public virtual MethodHandle GuardWithTest(MethodHandle target, MethodHandle fallback) { if (Mcs.Target == K_false) { return(fallback); // already invalid } return(MethodHandles.GuardWithTest(McsInvoker, target, fallback)); }
public EventMember(EventInfo eventInfo) : base(eventInfo) { this.EventHandlerType = eventInfo.EventHandlerType !.TypeHandle.GetTypeMember(); this.AddEventHandler = eventInfo.AddMethod !.MethodHandle.GetMethodMember(this.Type.Handle); this.RaiseEvent = eventInfo.RaiseMethod?.MethodHandle.GetMethodMember(this.Type.Handle); this.RemoveEventHandler = eventInfo.RemoveMethod !.MethodHandle.GetMethodMember(this.Type.Handle); }
// // methodHandle - the "tkMethodDef" that identifies the method. // definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // public RuntimeMethodCommon(MethodHandle methodHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _definingTypeInfo = definingTypeInfo; _methodHandle = methodHandle; _contextTypeInfo = contextTypeInfo; _reader = definingTypeInfo.Reader; _method = methodHandle.GetMethod(_reader); }
private static LambdaForm ChooseDelegatingForm(MethodHandle target) { if (target is SimpleMethodHandle) { return(target.InternalForm()); // no need for an indirection } return(MakeReinvokerForm(target, MethodTypeForm.LF_DELEGATE, typeof(DelegatingMethodHandle), NF_getTarget)); }
public static object invokeExact(MethodHandle thisObject, object[] args) { #if FIRST_PASS return(null); #else return(IKVM.Runtime.ByteCodeHelper.GetDelegateForInvokeExact <IKVM.Runtime.MH <object[], object> >(thisObject)(args)); #endif }
public static object invoke(MethodHandle thisObject, object[] args) { #if FIRST_PASS return(null); #else return(thisObject.invokeWithArguments(args)); #endif }
// TODO: Index by signature. public bool TryGetMethod(string name, out MethodHandle handle) { if (this.methodDefs == null) { this.methodDefs = GetMethodDefs(this.reader, this.typeHandle); } return(this.methodDefs.TryGetValue(name, out handle)); }
// // methodHandle - the "tkMethodDef" that identifies the method. // definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // public NativeFormatMethodCommon(MethodHandle methodHandle, NativeFormatRuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _definingTypeInfo = definingTypeInfo; _methodHandle = methodHandle; _contextTypeInfo = contextTypeInfo; _reader = definingTypeInfo.Reader; _method = methodHandle.GetMethod(_reader); }
public CallRloInstanceMethodInstruction(CodeLocationTag codeLocation, MethodHandle methodHandle, HighSsaRegister returnDest, HighSsaRegister instanceSrc, HighSsaRegister[] parameters) { this.CodeLocation = codeLocation; m_methodHandle = methodHandle; m_instanceSrc = instanceSrc; m_parameters = parameters; m_returnDest = returnDest; }
// // Creates the appropriate flavor of Invoker depending on the calling convention "shape" (static, instance or virtual.) // internal static MethodInvoker CreateMethodInvoker(MetadataReader reader, RuntimeTypeHandle declaringTypeHandle, MethodHandle methodHandle, MethodInvokeInfo methodInvokeInfo) { Method method = methodHandle.GetMethod(reader); MethodAttributes methodAttributes = method.Flags; if (0 != (methodAttributes & MethodAttributes.Static)) return new StaticMethodInvoker(methodInvokeInfo); else if (methodInvokeInfo.VirtualResolveData != IntPtr.Zero) return new VirtualMethodInvoker(methodInvokeInfo, declaringTypeHandle); else return new InstanceMethodInvoker(methodInvokeInfo, declaringTypeHandle); }
public NullableInstanceMethodInvoker(MetadataReader reader, MethodHandle methodHandle, RuntimeTypeHandle nullableTypeHandle, MethodInvokeInfo methodInvokeInfo) { _id = NullableMethodId.None; _nullableTypeHandle = nullableTypeHandle; Method method = methodHandle.GetMethod(reader); if (MethodAttributes.Public == (method.Flags & MethodAttributes.MemberAccessMask)) { // Note: Since we control the definition of Nullable<>, we're not checking signatures here. String name = method.Name.GetConstantStringValue(reader).Value; switch (name) { case "GetType": _id = NullableMethodId.GetType; break; case "ToString": _id = NullableMethodId.ToString; break; case "Equals": _id = NullableMethodId.Equals; break; case "GetHashCode": _id = NullableMethodId.GetHashCode; break; case ".ctor": _id = NullableMethodId.Ctor; break; case "get_HasValue": _id = NullableMethodId.get_HasValue; break; case "get_Value": _id = NullableMethodId.get_Value; break; case "GetValueOrDefault": IEnumerator<ParameterTypeSignatureHandle> parameters = method.Signature.GetMethodSignature(reader).Parameters.GetEnumerator(); if (parameters.MoveNext()) _id = NullableMethodId.GetValueOrDefault_1; else _id = NullableMethodId.GetValueOrDefault_0; break; default: break; } } }
/// <summary> /// Returns true if the method should be imported. Returns false for private methods that are not /// explicit interface implementations. For other methods, visibility and the value of /// <paramref name="importOptions"/> are considered. /// </summary> public static bool ShouldImportMethod(this PEModule module, MethodHandle methodDef, MetadataImportOptions importOptions) { try { var flags = module.GetMethodDefFlagsOrThrow(methodDef); // If the method is virtual, it must be accessible, although // it may be an explicit (private) interface implementation. // Otherwise, we need to check the accessibility. if ((flags & MethodAttributes.Virtual) == 0) { switch (flags & MethodAttributes.MemberAccessMask) { case MethodAttributes.Private: case MethodAttributes.PrivateScope: if (importOptions != MetadataImportOptions.All) { return false; } break; case MethodAttributes.Assembly: if (importOptions == MetadataImportOptions.Public) { return false; } break; } } } catch (BadImageFormatException) { } try { // As in the native C# compiler (see IMPORTER::ImportMethod), drop any method prefixed // with "_VtblGap". They should be impossible to call/implement/etc. // BREAK: The native VB compiler does not drop such methods, but it produces unverfiable // code when they are called, so the break is acceptable. // TODO: Keep some record of vtable gaps (DevDiv #17472). var name = module.GetMethodDefNameOrThrow(methodDef); return !name.StartsWith(VTableGapMethodNamePrefix, StringComparison.Ordinal); } catch (BadImageFormatException) { return true; } }
/// <summary> /// Construct a comparer between NativeFormat metadata methods and native layouts /// </summary> /// <param name="metadataReader">Metadata reader for the method declaring type</param> /// <param name="methodHandle">Handle of method to compare</param> public MethodSignatureComparer( MetadataReader metadataReader, MethodHandle methodHandle) { _metadataReader = metadataReader; _methodHandle = methodHandle; _method = methodHandle.GetMethod(metadataReader); _methodSignature = _method.Signature.GetMethodSignature(_metadataReader); _isGeneric = (_methodSignature.GenericParameterCount != 0); // Precalculate initial method attributes used in signature queries _isStatic = (_method.Flags & MethodAttributes.Static) != 0; }
public IntPtrConstructorMethodInvoker(MetadataReader reader, MethodHandle methodHandle) { // Since we control the definition of System.IntPtr, we only do enough analysis of the signature to disambiguate the constructors we support. _id = IntPtrConstructorId.None; Method method = methodHandle.GetMethod(reader); ParameterTypeSignatureHandle[] parameterTypeSignatureHandles = method.Signature.GetMethodSignature(reader).Parameters.ToArray(); if (parameterTypeSignatureHandles.Length == 1) { ParameterTypeSignature parameterTypeSignature = parameterTypeSignatureHandles[0].GetParameterTypeSignature(reader); // If any parameter is a pointer type, bail as we don't support Invokes on pointers. if (parameterTypeSignature.Type.HandleType != HandleType.TypeDefinition) throw new PlatformNotSupportedException(SR.PlatformNotSupported_PointerArguments); TypeDefinition typeDefinition = parameterTypeSignature.Type.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader); String name = typeDefinition.Name.GetString(reader); switch (name) { case "Int32": _id = IntPtrConstructorId.Int32; break; case "Int64": _id = IntPtrConstructorId.Int64; break; case "UInt32": _id = IntPtrConstructorId.UInt32; break; case "UInt64": _id = IntPtrConstructorId.UInt64; break; default: break; } } }
public StringConstructorMethodInvoker(MetadataReader reader, MethodHandle methodHandle) { // Since we control the definition of System.String, we only do enough analysis of the signature to disambiguate the constructors we support. _id = StringConstructorId.None; Method method = methodHandle.GetMethod(reader); int parameterCount = 0; foreach (ParameterTypeSignatureHandle parameterTypeSignatureHandle in method.Signature.GetMethodSignature(reader).Parameters) { ParameterTypeSignature parameterTypeSignature = parameterTypeSignatureHandle.GetParameterTypeSignature(reader); // If any parameter is a pointer type, bail as we don't support Invokes on pointers. if (parameterTypeSignature.Type.HandleType == HandleType.TypeSpecification) { TypeSpecification typeSpecification = parameterTypeSignature.Type.ToTypeSpecificationHandle(reader).GetTypeSpecification(reader); if (typeSpecification.Signature.HandleType == HandleType.PointerSignature) return; } parameterCount++; } switch (parameterCount) { case 1: _id = StringConstructorId.CharArray; break; case 2: _id = StringConstructorId.Char_Int; break; case 3: _id = StringConstructorId.CharArray_Int_Int; break; default: break; } }
private void WriteMethod(MethodHandle methodHandle) { int token = metadataReader.GetToken(methodHandle); var symbolToken = new SymbolToken(token); byte[] bytes = pdbReader.RawSymbolReader.GetCustomDebugInfo(token); ISymbolMethod methodSymbol = pdbReader.SymbolReader.GetMethod(symbolToken); if (bytes == null && methodSymbol == null) { // no debug info for the method return; } writer.WriteStartElement("method"); WriteMethodAttributes(token, isReference: false); if (bytes != null) { WriteCustomDebugInfo(bytes); } if (methodSymbol != null) { WriteSequencePoints(methodSymbol); // TODO (tomat): Ideally this would be done in a separate test helper, not in PdbToXml. // verify ISymUnmanagedMethod APIs: ISymUnmanagedMethod rawMethod = pdbReader.RawSymbolReader.GetBaselineMethod(token); var expectedSlotNames = new Dictionary<int, ImmutableArray<string>>(); WriteLocals(rawMethod, expectedSlotNames); var actualSlotNames = rawMethod.GetLocalVariableSlots(); Debug.Assert(actualSlotNames.Length == (expectedSlotNames.Count == 0 ? 0 : expectedSlotNames.Keys.Max() + 1)); int i = 0; foreach (var slotName in actualSlotNames) { if (slotName == null) { Debug.Assert(!expectedSlotNames.ContainsKey(i)); } else { Debug.Assert(expectedSlotNames[i].Contains(slotName)); } i++; } ImmutableArray<ISymUnmanagedScope> children = rawMethod.GetRootScope().GetScopes(); if (children.Length != 0) { WriteScopes(children[0]); } WriteAsyncInfo(methodSymbol as ISymbolAsyncMethod); } writer.WriteEndElement(); // method }
public VolatileCallSite(MethodHandle arg0) : base(ProxyCtor.I) { Instance.CallConstructor("(Ljava/lang/invoke/MethodHandle;)V", arg0); }
public abstract IEnumerable<CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, ParameterHandle parameterHandle, MethodHandle declaringMethodHandle);
/// <summary> /// Dispatches the method. /// </summary> /// <param name="context">The context.</param> /// <param name="methodHandle">The method handle.</param> /// <param name="inputArguments">The input arguments.</param> /// <param name="inputArgumentResults">The input argument results.</param> /// <param name="outputArguments">The output arguments.</param> /// <returns></returns> public virtual StatusCode DispatchMethod( RequestContext context, MethodHandle methodHandle, IList<Variant> inputArguments, List<StatusCode> inputArgumentResults, List<Variant> outputArguments) { IWeatherStationMethods implemention = WeatherStationMethods; if (implemention == null) { implemention = this as IWeatherStationMethods; } if (implemention == null) { return StatusCodes.BadUserAccessDenied; } if (methodHandle.MethodDeclarationId.Equals(new ExpandedNodeId(OPCServer.Methods.WeatherStationType_getConditions, OPCServer.Namespaces.OPCServer).ToNodeId(context.NamespaceUris))) { StatusCode ret = implemention.getConditions(context, this); if (ret.IsGood()) { } return ret; } if (methodHandle.MethodDeclarationId.Equals(new ExpandedNodeId(OPCServer.Methods.WeatherStationType_getForecast, OPCServer.Namespaces.OPCServer).ToNodeId(context.NamespaceUris))) { StatusCode ret = implemention.getForecast(context, this); if (ret.IsGood()) { } return ret; } return StatusCodes.BadMethodInvalid; }
private bool GetAccessor(MethodSemanticsAttributes methodSemanticsAttribute, out MethodHandle methodHandle) { foreach (MethodSemanticsHandle methodSemanticsHandle in _property.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == methodSemanticsAttribute) { methodHandle = methodSemantics.Method; return true; } } methodHandle = default(MethodHandle); return false; }
public void setTarget(MethodHandle arg0) { Instance.CallMethod("setTarget", "(Ljava/lang/invoke/MethodHandle;)V", arg0); }
//============================================================================================== // Non-public methods //============================================================================================== internal MethodInvoker GetMethodInvoker(MetadataReader reader, RuntimeType declaringType, MethodHandle methodHandle, RuntimeType[] genericMethodTypeArguments, MemberInfo exceptionPertainant) { if (declaringType.InternalIsOpen) return new OpenMethodInvoker(); for (int i = 0; i < genericMethodTypeArguments.Length; i++) { if (genericMethodTypeArguments[i].InternalIsOpen) return new OpenMethodInvoker(); } RuntimeTypeHandle typeDefinitionHandle = declaringType.TypeHandle; RuntimeTypeHandle[] genericMethodTypeArgumentHandles = new RuntimeTypeHandle[genericMethodTypeArguments.Length]; for (int i = 0; i < genericMethodTypeArguments.Length; i++) { genericMethodTypeArgumentHandles[i] = genericMethodTypeArguments[i].TypeHandle; } MethodInvoker methodInvoker = TryGetMethodInvoker(reader, typeDefinitionHandle, methodHandle, genericMethodTypeArgumentHandles); if (methodInvoker == null) throw declaringType.GetReflectionDomain().CreateNonInvokabilityException(exceptionPertainant); return methodInvoker; }
public abstract IEnumerable<CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, MethodHandle methodHandle, TypeDefinitionHandle declaringTypeHandle);
private void WriteResolvedToken(MethodHandle methodHandle, bool isReference) { var method = metadataReader.GetMethod(methodHandle); // type name var containingTypeHandle = metadataReader.GetDeclaringType(methodHandle); var fullName = GetFullTypeName(metadataReader, containingTypeHandle); if (fullName != null) { writer.WriteAttributeString(isReference ? "declaringType" : "containingType", fullName); } // method name writer.WriteAttributeString(isReference ? "methodName" : "name", metadataReader.GetString(method.Name)); // parameters: var parameterNames = from paramHandle in method.GetParameters() let parameter = metadataReader.GetParameter(paramHandle) where parameter.SequenceNumber > 0 // exclude return parameter select parameter.Name.IsNil ? "?" : metadataReader.GetString(parameter.Name); writer.WriteAttributeString("parameterNames", string.Join(", ", parameterNames)); }
private static string GetQualifiedMethodName(MetadataReader metadataReader, MethodHandle methodHandle) { var method = metadataReader.GetMethod(methodHandle); var containingTypeHandle = metadataReader.GetDeclaringType(methodHandle); string fullTypeName = GetFullTypeName(metadataReader, containingTypeHandle); string methodName = metadataReader.GetString(method.Name); return fullTypeName != null ? fullTypeName + "." + methodName : methodName; }
public sealed override IEnumerable<CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, ParameterHandle parameterHandle, MethodHandle declaringMethodHandle) { ParameterAttributes attributes = parameterHandle.GetParameter(reader).Flags; if (0 != (attributes & ParameterAttributes.In)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(InAttribute), null, null); if (0 != (attributes & ParameterAttributes.Out)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(OutAttribute), null, null); if (0 != (attributes & ParameterAttributes.Optional)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(OptionalAttribute), null, null); }
internal abstract bool TryGetMethodHandle(IMethodDefinition def, out MethodHandle handle);
public sealed override IEnumerable<CustomAttributeData> GetPsuedoCustomAttributes(MetadataReader reader, MethodHandle methodHandle, TypeDefinitionHandle declaringTypeHandle) { MethodImplAttributes implAttributes = methodHandle.GetMethod(reader).ImplFlags; if (0 != (implAttributes & MethodImplAttributes.PreserveSig)) yield return ReflectionCoreExecution.ExecutionDomain.GetCustomAttributeData(typeof(PreserveSigAttribute), null, null); }
// // Retrieves the MethodBase for a given method handle. Helper to implement Delegate.GetMethodInfo() // public MethodBase GetMethod(RuntimeTypeHandle declaringTypeHandle, MethodHandle methodHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { RuntimeType declaringType = ReflectionCoreNonPortable.GetTypeForRuntimeTypeHandle(declaringTypeHandle); RuntimeTypeInfo contextTypeInfo = declaringType.GetRuntimeTypeInfo(); RuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers; MetadataReader reader = definingTypeInfo.Reader; if (methodHandle.IsConstructor(reader)) { return RuntimePlainConstructorInfo.GetRuntimePlainConstructorInfo(methodHandle, definingTypeInfo, contextTypeInfo); } else { RuntimeNamedMethodInfo runtimeNamedMethodInfo = RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(methodHandle, definingTypeInfo, contextTypeInfo); if (!runtimeNamedMethodInfo.IsGenericMethod) { return runtimeNamedMethodInfo; } else { RuntimeType[] genericTypeArguments = new RuntimeType[genericMethodTypeArgumentHandles.Length]; for (int i = 0; i < genericMethodTypeArgumentHandles.Length; i++) { genericTypeArguments[i] = ReflectionCoreNonPortable.GetTypeForRuntimeTypeHandle(genericMethodTypeArgumentHandles[i]); } return RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(runtimeNamedMethodInfo, genericTypeArguments); } } }
private bool TryGetMethodHandle(EmitBaseline baseline, Cci.IMethodDefinition def, out MethodHandle handle) { if (this.TryGetMethodHandle(def, out handle)) { return true; } def = (Cci.IMethodDefinition)this.mapToPrevious.MapDefinition(def); if (def != null) { uint methodIndex; if (baseline.MethodsAdded.TryGetValue(def, out methodIndex)) { handle = MetadataTokens.MethodHandle((int)methodIndex); return true; } } handle = default(MethodHandle); return false; }
// // methodHandle - the "tkMethodDef" that identifies the method. // definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // private RuntimePlainConstructorInfo(MethodHandle methodHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo) { _common = new RuntimeMethodCommon(methodHandle, definingTypeInfo, contextTypeInfo); }
internal override bool TryGetMethodHandle(Cci.IMethodDefinition def, out MethodHandle handle) { var other = this.mapToMetadata.MapDefinition(def) as PEMethodSymbol; if ((object)other != null) { handle = other.Handle; return true; } else { handle = default(MethodHandle); return false; } }
//============================================================================================== // Invoke and field access support. //============================================================================================== public abstract MethodInvoker TryGetMethodInvoker(MetadataReader reader, RuntimeTypeHandle declaringTypeHandle, MethodHandle methodHandle, RuntimeTypeHandle[] genericMethodTypeArgumentHandles);
public abstract bool TryGetMethodFromHandleAndType(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle, out MethodHandle methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles);