public static void Main() { CodeGenerator myCodeGenerator = new CodeGenerator(); // Get the assembly builder for 'myCodeGenerator' object. AssemblyBuilder myAssemblyBuilder = myCodeGenerator.MyAssembly; // Get the module builder for the above assembly builder object . ModuleBuilder myModuleBuilder = myAssemblyBuilder. GetDynamicModule("TempModule"); Console.WriteLine("The fully qualified name and path to this " + "module is :" + myModuleBuilder.FullyQualifiedName); Type myType = myModuleBuilder.GetType("TempClass"); MethodInfo myMethodInfo = myType.GetMethod("MyMethod"); // Get the token used to identify the method within this module. MethodToken myMethodToken = myModuleBuilder.GetMethodToken(myMethodInfo); Console.WriteLine("Token used to identify the method of 'myType'" + " within the module is {0:x}", myMethodToken.Token); object[] args = { "Hello." }; object myObject = Activator.CreateInstance(myType, null, null); myMethodInfo.Invoke(myObject, args); }
public static void SetMethodBody(Type type, MethodToken somemethodToken, byte[] methodBytes) { //MethodToken somemethodToken = somemethod.GetToken(); // Get the pointer to the method body. GCHandle methodBytesHandle = GCHandle.Alloc((Object)methodBytes, GCHandleType.Pinned); IntPtr methodBytesAddress = methodBytesHandle.AddrOfPinnedObject(); int methodBytesLength = methodBytes.Length; // Swap the old method body with the new body. MethodRental.SwapMethodBody( type, somemethodToken.Token, methodBytesAddress, methodBytesLength, MethodRental.JitImmediate); ////// Verify that the modified method returns 1. ////int res2 = (int)tbBaked.GetMethod("My method Name").Invoke(null, new Object[] { }); ////if (res2 != 1) ////{ //// Console.WriteLine("Err_001b, should have returned 1"); ////} ////else ////{ //// Console.WriteLine("Swapped method body returned 1"); ////} }
private static bool CheckMethodSemantic(StatementToken statement, List <MethodDescription> methodDescriptions) { MethodToken currentMethod = statement.MethodToken; List <string> parametersNames = currentMethod.MethodParameters; for (int param = 0; param < parametersNames.Count; param++) { MyVariable methodVar = ProgramContextHolder.GetVariableFromContextByName(parametersNames[param]); if (methodVar == null) { Console.WriteLine(param + " param in method not exist in current variable context"); } else if (methodVar.Type == GetFunctionByName(currentMethod.MethodName, methodDescriptions) .Parameters[param]) { Console.WriteLine("Method : " + currentMethod.MethodName + " receive correct param type : " + parametersNames[param]); ProgramContextHolder.GetVariableFromContextByName(parametersNames[param]).usageCount++; Console.WriteLine(parametersNames[param] + " usage : " + ProgramContextHolder.GetVariableFromContextByName(parametersNames[param]).usageCount); } else { Console.WriteLine("Not suitable variable type at : " + param + " function parameter"); } } ProgramContextHolder.GetInstance().Functions.Add(new MyFunction(currentMethod.MethodName, parametersNames)); return(true); }
public MethodDesc GetGlobalMethod(MethodToken token) { MethodDesc result = null; _globalMethods.TryGetValue(token, out result); return(result); }
public void Execute(MethodContext context, MethodState state, object operand = null) { MethodToken methodDef = (operand as MethodToken); if (methodDef == null) { throw new ArgumentException("Incorrect or null method definition"); } MethodDesc method = null; if (methodDef.Owner != null) { TypeObject owner = context.TypesHeap.GetTypeObject(methodDef.Owner); method = owner.VTable.GetMethod(methodDef); } else { method = context.TypesHeap.GetGlobalMethod(methodDef); } if (method == null) { throw new InvalidOperationException("Method described by the provided metadata was not found in type's vtable"); } state.CallMethod = method; state.ExecutionInterruption = ExecutionInterruption.Call; }
public MethodDesc GetMethod(MethodToken methodMetadata) { MethodDesc res = null; if (_table.ContainsKey(methodMetadata)) { res = _table[methodMetadata]; } return(res); }
/// <inheritdoc/> public object Invoke(object target, MethodInfo methodInfo, object[] parameters) { var methodToken = new MethodToken(methodInfo); ExpectationBase expectation; if (_expectations.TryGetValue(methodToken, out expectation)) return expectation.Invoke(methodInfo, parameters); throw new ExpectationException(String.Format("Unexpected invocation for '{0}'", methodInfo)); }
public void EmitMethodToken(MethodToken token) { _internalEmitter.EmitBeginSet((int)PackedArgumentPosition.DeclaringType); _ilGenerator.Emit(OpCodes.Ldtoken, token.DeclaringType); _ilGenerator.Emit(OpCodes.Call, MethodReferences.GetTypeFromHandle); _internalEmitter.EmitEndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; _internalEmitter.EmitBeginSet((int)PackedArgumentPosition.MethodTokenKey); _ilGenerator.Emit(OpCodes.Ldc_I4, token.Key); _internalEmitter.EmitEndSet(typeof(int)); }
internal CodeGenerator() { AppDomain myCurrentDomain = AppDomain.CurrentDomain; AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "TempAssembly"; // Define a dynamic assembly in the current application domain. myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.RunAndSave); // <Snippet1> // <Snippet2> // Define a dynamic module in "TempAssembly" assembly. ModuleBuilder myModuleBuilder = myAssemblyBuilder. DefineDynamicModule("TempModule"); // Define a runtime class with specified name and attributes. TypeBuilder myTypeBuilder = myModuleBuilder.DefineType ("TempClass", TypeAttributes.Public); Type[] paramArray = { typeof(Array) }; // Add 'SortArray' method to the class, with the given signature. MethodBuilder myMethod = myTypeBuilder.DefineMethod("SortArray", MethodAttributes.Public, typeof(Array), paramArray); Type[] myArrayClass = new Type[1]; Type[] parameterTypes = { typeof(Array) }; // Get the 'MethodInfo' object corresponding to 'Sort' method of 'Array' class. MethodInfo myMethodInfo = myModuleBuilder.GetArrayMethod( myArrayClass.GetType(), "Sort", CallingConventions.Standard, null, parameterTypes); // Get the token corresponding to 'Sort' method of 'Array' class. MethodToken myMethodToken = myModuleBuilder.GetArrayMethodToken( myArrayClass.GetType(), "Sort", CallingConventions.Standard, null, parameterTypes); Console.WriteLine("Token used by module to identify the 'Sort' method" + " of 'Array' class is : {0:x} ", myMethodToken.Token); ILGenerator methodIL = myMethod.GetILGenerator(); methodIL.Emit(OpCodes.Ldarg_1); methodIL.Emit(OpCodes.Call, myMethodInfo); methodIL.Emit(OpCodes.Ldarg_1); methodIL.Emit(OpCodes.Ret); // Complete the creation of type. myTypeBuilder.CreateType(); // </Snippet1> // </Snippet2> }
public void TestSerializeErrors() { var result = new MethodToken() { CallFlags = (CallFlags)byte.MaxValue, Hash = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"), Method = "myLongMethod", ParametersCount = 123, HasReturnValue = true }; Assert.ThrowsException <FormatException>(() => result.ToArray().AsSerializable <MethodToken>()); result.CallFlags = CallFlags.All; result.Method += "-123123123123123123123123"; Assert.ThrowsException <FormatException>(() => result.ToArray().AsSerializable <MethodToken>()); }
public void GetToken() { ConstructorBuilder cb = genClass.DefineConstructor( 0, 0, new Type [1] { typeof(int) }); cb.GetILGenerator().Emit(OpCodes.Ret); MethodToken tokenA = cb.GetToken(); Assert.IsFalse(tokenA == MethodToken.Empty, "#1"); genClass.CreateType(); MethodToken tokenB = cb.GetToken(); Assert.AreEqual(tokenA, tokenB, "#2"); }
public void TestSerialize() { var result = new MethodToken() { CallFlags = CallFlags.AllowCall, Hash = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"), Method = "myMethod", ParametersCount = 123, HasReturnValue = true }; var copy = result.ToArray().AsSerializable <MethodToken>(); Assert.AreEqual(CallFlags.AllowCall, copy.CallFlags); Assert.AreEqual("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01", copy.Hash.ToString()); Assert.AreEqual("myMethod", copy.Method); Assert.AreEqual(123, copy.ParametersCount); Assert.AreEqual(true, copy.HasReturnValue); }
private void ParseInput() { string newInput = inputField.text.Substring(alreadyCheckedUntilIdx); alreadyCheckedUntilIdx = inputField.text.Length - 1; string[] arguments = newInput.Trim().Split(' '); if (arguments != null && arguments.Length > 0) { int argumentCount = arguments.Length; for (int i = 0; i < argumentCount; i++) { string arg = arguments[i]; bool isMethod = methods.ContainsKey(arg); bool isProperty = properties.ContainsKey(arg); bool isField = fields.ContainsKey(arg); if (isMethod) { MethodToken nextToken = new MethodToken(); if (commandBuilder.Last().Token.Match(nextToken)) { //commandBuilder.Add( } } if (isProperty) { } if (isField) { } } } }
public bool Equals(MethodToken obj) => obj.Token == Token;
internal extern void InternalSavePEFile(String fileName, MethodToken entryPoint, int isExe, bool isManifestFile);
public void AddGlobalMethod(MethodToken token, MethodDesc methodDesc) { _globalMethods.Add(token, methodDesc); }
internal void InternalSavePEFile(string fileName, MethodToken entryPoint, int isExe, bool isManifestFile) { this.InternalModule._InternalSavePEFile(fileName, entryPoint.Token, isExe, isManifestFile); }
// First make a method that returns 0. // Then swap the method body with a body that returns 1. public static void Main(String [] args) { // Construct a dynamic assembly Guid g = Guid.NewGuid(); AssemblyName asmname = new AssemblyName(); asmname.Name = "tempfile" + g; AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain(). DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); // Add a dynamic module that contains one type that has one method that // has no arguments. ModuleBuilder modbuild = asmbuild.DefineDynamicModule("test"); TypeBuilder tb = modbuild.DefineType("name of the Type"); MethodBuilder somemethod = tb.DefineMethod ("My method Name", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] {}); // Define the body of the method to return 0. ILGenerator ilg = somemethod.GetILGenerator(); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Ret); // Complete the type and verify that it returns 0. Type tbBaked = tb.CreateType(); int res1 = (int)tbBaked.GetMethod("My method Name").Invoke(null, new Object[] {}); if (res1 != 0) { Console.WriteLine("Err_001a, should have returned 0"); } else { Console.WriteLine("Original method returned 0"); } // Define a new method body that will return a 1 instead. Byte[] methodBytes = { 0x03, 0x30, 0x0A, 0x00, 0x02, // code size 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, // ldc_i4_1 0x2a // ret }; // Get the token for the method whose body you are replacing. MethodToken somemethodToken = somemethod.GetToken(); // Get the pointer to the method body. GCHandle hmem = GCHandle.Alloc((Object)methodBytes, GCHandleType.Pinned); IntPtr addr = hmem.AddrOfPinnedObject(); int cbSize = methodBytes.Length; // Swap the old method body with the new body. MethodRental.SwapMethodBody( tbBaked, somemethodToken.Token, addr, cbSize, MethodRental.JitImmediate); // Verify that the modified method returns 1. int res2 = (int)tbBaked.GetMethod("My method Name").Invoke(null, new Object[] {}); if (res2 != 1) { Console.WriteLine("Err_001b, should have returned 1"); } else { Console.WriteLine("Swapped method body returned 1"); } }
public bool Equals(MethodToken obj) {}
public bool Equals(MethodToken other) { return(this == other); }
public void TestSameAPI(Type syncInterface, Type asyncInterface) { TestContext.Out.WriteLine($"Comparing '{GetCSharpTypeName(syncInterface)}' and '{GetCSharpTypeName(asyncInterface)}'..."); var actual = new List <string>(); foreach (var method in asyncInterface.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var tok = new MethodToken(method); actual.Add(GetSignature(tok)); } var expected = new List <string>(); ParameterToken cancellationParameter = new ParameterToken("token", typeof(CancellationToken), ParameterAttributes.Optional); foreach (var method in syncInterface.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { AddExpected(method); } if (asyncInterface == typeof(IRedisSortedSetAsync) || asyncInterface == typeof(IRedisSetAsync) || asyncInterface == typeof(IRedisListAsync)) { AddFrom(typeof(ICollection <string>), nameof(ICollection <string> .Clear)); AddFrom(typeof(ICollection <string>), nameof(ICollection <string> .Add)); AddFrom(typeof(ICollection <string>), nameof(ICollection <string> .Remove)); AddFrom(typeof(ICollection <string>), nameof(ICollection <string> .Contains)); AddFrom(typeof(ICollection <string>), "get_" + nameof(ICollection <string> .Count), true); if (asyncInterface == typeof(IRedisListAsync)) { AddFrom(typeof(IList <string>), nameof(IList <string> .IndexOf)); AddFrom(typeof(IList <string>), nameof(IList <string> .RemoveAt)); AddFrom(typeof(IList <string>), "set_Item", true); AddFrom(typeof(IList <string>), "get_Item", true); } } else if (asyncInterface == typeof(IRedisSortedSetAsync <>) || asyncInterface == typeof(IRedisSetAsync <>) || asyncInterface == typeof(IRedisListAsync <>)) { AddFrom(typeof(ICollection <>), nameof(ICollection <string> .Clear)); AddFrom(typeof(ICollection <>), nameof(ICollection <string> .Add)); AddFrom(typeof(ICollection <>), nameof(ICollection <string> .Remove)); AddFrom(typeof(ICollection <>), nameof(ICollection <string> .Contains)); AddFrom(typeof(ICollection <>), "get_" + nameof(ICollection <string> .Count), true); if (asyncInterface == typeof(IRedisListAsync <>)) { AddFrom(typeof(IList <>), nameof(IList <string> .IndexOf)); AddFrom(typeof(IList <>), nameof(IList <string> .RemoveAt)); AddFrom(typeof(IList <>), "set_Item", true); AddFrom(typeof(IList <>), "get_Item", true); } } else if (asyncInterface == typeof(IRedisHashAsync <,>)) { AddFrom(typeof(ICollection <>).MakeGenericType(typeof(KeyValuePair <,>).MakeGenericType(asyncInterface.GetGenericArguments())), nameof(IDictionary <string, string> .Add)); AddFrom(typeof(IDictionary <,>), nameof(IDictionary <string, string> .Add)); AddFrom(typeof(ICollection <>), nameof(IDictionary <string, string> .Clear)); AddFrom(typeof(IDictionary <,>), nameof(IDictionary <string, string> .ContainsKey)); AddFrom(typeof(IDictionary <,>), nameof(IDictionary <string, string> .Remove)); AddFrom(typeof(ICollection <>), "get_" + nameof(IDictionary <string, string> .Count), true); } else if (asyncInterface == typeof(IRedisHashAsync)) { AddFrom(typeof(ICollection <KeyValuePair <string, string> >), nameof(IDictionary <string, string> .Add)); AddFrom(typeof(IDictionary <string, string>), nameof(IDictionary <string, string> .Add)); AddFrom(typeof(ICollection <string>), nameof(IDictionary <string, string> .Clear)); AddFrom(typeof(IDictionary <string, string>), nameof(IDictionary <string, string> .ContainsKey)); AddFrom(typeof(IDictionary <string, string>), nameof(IDictionary <string, string> .Remove)); AddFrom(typeof(ICollection <string>), "get_" + nameof(IDictionary <string, string> .Count), true); } else if (asyncInterface == typeof(IRedisNativeClientAsync)) { AddFrom(typeof(RedisClient), nameof(RedisClient.SlowlogReset)); AddFrom(typeof(RedisClient), nameof(RedisClient.BitCount)); AddFromTyped(typeof(RedisClient), nameof(RedisClient.ZCount), typeof(string), typeof(double), typeof(double)); // can't expose as SlowlogItem because of interface locations expected.Add("ValueTask<object[]> SlowlogGetAsync(int? top = default, CancellationToken token = default)"); // adding missing "exists" capability expected.Add("ValueTask<bool> SetAsync(string key, byte[] value, bool exists, long expirySeconds = 0, long expiryMilliseconds = 0, CancellationToken token = default)"); } else if (asyncInterface == typeof(IRedisClientAsync)) { expected.Add("ValueTask<SlowlogItem[]> GetSlowlogAsync(int? numberOfRecords = default, CancellationToken token = default)"); expected.Add("ValueTask SlowlogResetAsync(CancellationToken token = default)"); } else if (asyncInterface == typeof(ICacheClientAsync)) { AddFrom(typeof(ICacheClientExtended), nameof(ICacheClientExtended.GetKeysByPattern)); AddFrom(typeof(ICacheClientExtended), nameof(ICacheClientExtended.GetTimeToLive)); AddFrom(typeof(ICacheClientExtended), nameof(ICacheClientExtended.RemoveExpiredEntries)); } void AddFrom(Type syncInterface, string name, bool fromPropertyToMethod = false) => AddExpected(syncInterface.GetMethod(name), fromPropertyToMethod); void AddFromTyped(Type syncInterface, string name, params Type[] types)
public bool Equals(MethodToken obj) { }
public static bool op_Inequality(MethodToken a, MethodToken b) { }
internal MyConstructorBuilder() { // <Snippet1> // <Snippet3> MethodBuilder myMethodBuilder = null; AppDomain myCurrentDomain = AppDomain.CurrentDomain; // Create assembly in current CurrentDomain. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "TempAssembly"; // Create a dynamic assembly. myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Run); // Create a dynamic module in the assembly. myModuleBuilder = myAssemblyBuilder.DefineDynamicModule("TempModule"); // Create a type in the module. TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("TempClass", TypeAttributes.Public); FieldBuilder myGreetingField = myTypeBuilder.DefineField("Greeting", typeof(String), FieldAttributes.Public); Type[] myConstructorArgs = { typeof(String) }; // <Snippet2> // <Snippet4> // Define a constructor of the dynamic class. ConstructorBuilder myConstructorBuilder = myTypeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, myConstructorArgs); // Get a reference to the module that contains this constructor. Module myModule = myConstructorBuilder.GetModule(); Console.WriteLine("Module Name : " + myModule.Name); // Get the 'MethodToken' that represents the token for this constructor. MethodToken myMethodToken = myConstructorBuilder.GetToken(); Console.WriteLine("Constructor Token is : " + myMethodToken.Token); // Get the method implementation flags for this constructor. MethodImplAttributes myMethodImplAttributes = myConstructorBuilder.GetMethodImplementationFlags(); Console.WriteLine("MethodImplAttributes : " + myMethodImplAttributes); // </Snippet3> // </Snippet2> // </Snippet1> // Generate IL for the method, call its base class constructor and store the arguments // in the private field. ILGenerator myILGenerator3 = myConstructorBuilder.GetILGenerator(); myILGenerator3.Emit(OpCodes.Ldarg_0); ConstructorInfo myConstructorInfo = typeof(Object).GetConstructor(new Type[0]); myILGenerator3.Emit(OpCodes.Call, myConstructorInfo); myILGenerator3.Emit(OpCodes.Ldarg_0); myILGenerator3.Emit(OpCodes.Ldarg_1); myILGenerator3.Emit(OpCodes.Stfld, myGreetingField); myILGenerator3.Emit(OpCodes.Ret); // Add a method to the type. myMethodBuilder = myTypeBuilder.DefineMethod ("HelloWorld", MethodAttributes.Public, null, null); // Generate IL for the method. ILGenerator myILGenerator2 = myMethodBuilder.GetILGenerator(); myILGenerator2.EmitWriteLine("Hello World from global"); myILGenerator2.Emit(OpCodes.Ret); myModuleBuilder.CreateGlobalFunctions(); myType1 = myTypeBuilder.CreateType(); // Get the parameters of this constructor. ParameterInfo[] myParameterInfo = myConstructorBuilder.GetParameters(); for (int i = 0; i < myParameterInfo.Length; i++) { Console.WriteLine("Declaration type : " + myParameterInfo[i].Member.DeclaringType); } // </Snippet4> }
public static bool op_Inequality(MethodToken a, MethodToken b) {}
private static void TestReflectionEmit() { MethodToken t1 = default(MethodToken); MethodToken t2 = default(MethodToken); var ok = t1 == t2; }
public bool Equals(MethodToken other) { return this == other; }