本文整理汇总了C#中Mono.Cecil.MethodDefinition.AddLocal方法的典型用法代码示例。如果您正苦于以下问题:C# MethodDefinition.AddLocal方法的具体用法?C# MethodDefinition.AddLocal怎么用?C# MethodDefinition.AddLocal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mono.Cecil.MethodDefinition
的用法示例。
在下文中一共展示了MethodDefinition.AddLocal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddLocals
public void AddLocals(MethodDefinition hostMethod)
{
_constructorArguments = hostMethod.AddLocal<List<object>>();
_currentArgument = hostMethod.AddLocal<object>();
_methodContext = hostMethod.AddLocal<ITypeActivationContext>();
_currentActivator = hostMethod.AddLocal<ITypeActivator>();
}
示例2: AddLocals
/// <summary>
/// Adds local variables to the <paramref name="hostMethod"/>.
/// </summary>
/// <param name="hostMethod">The target method.</param>
public override void AddLocals(MethodDefinition hostMethod)
{
_exception = hostMethod.AddLocal<Exception>();
_invocationInfo = hostMethod.AddLocal<IInvocationInfo>();
_exceptionHandler = hostMethod.AddLocal<IExceptionHandler>();
_exceptionInfo = hostMethod.AddLocal<IExceptionHandlerInfo>();
var returnType = hostMethod.ReturnType.ReturnType;
if (returnType != _voidType)
_returnValue = hostMethod.AddLocal<object>();
}
示例3: Emit
/// <summary>
/// Emits the instructions that will instantiate the current implementation.
/// </summary>
/// <param name="dependency">The dependency that describes the service to be instantiated.</param>
/// <param name="serviceMap">The service map that contains the list of dependencies in the application.</param>
/// <param name="targetMethod">The target method.</param>
public void Emit(IDependency dependency, IDictionary<IDependency, IImplementation> serviceMap, MethodDefinition targetMethod)
{
var declaringType = targetMethod.DeclaringType;
var module = declaringType.Module;
var listType = typeof(List<>).MakeGenericType(_serviceType);
var listCtor = module.ImportConstructor(listType, new Type[0]);
var listVariable = targetMethod.AddLocal(listType);
var IL = targetMethod.GetILGenerator();
IL.Emit(OpCodes.Newobj, listCtor);
IL.Emit(OpCodes.Stloc, listVariable);
var targetDependencies = (from d in serviceMap.Keys
where d.ServiceType == _serviceType
select d).ToArray();
var addItem = module.ImportMethod("Add", listType);
var serviceType = module.Import(_serviceType);
var currentService = targetMethod.AddLocal(_serviceType);
foreach(var currentDependency in targetDependencies)
{
IL.Emit(OpCodes.Ldloc, listVariable);
// Instantiate the current service type
var implementation = new ContainerCall(currentDependency.ServiceType, currentDependency.ServiceName);
implementation.Emit(currentDependency, serviceMap, targetMethod);
IL.Emit(OpCodes.Isinst, serviceType);
IL.Emit(OpCodes.Stloc, currentService);
// Call IInitialize.Initialize(container) on the current service type
_initializer.Initialize(IL, module, currentService);
IL.Emit(OpCodes.Ldloc, currentService);
IL.Emit(OpCodes.Callvirt, addItem);
}
var enumerableType = typeof(IEnumerable<>).MakeGenericType(_serviceType);
var importedEnumerableType = module.Import(enumerableType);
IL.Emit(OpCodes.Ldloc, listVariable);
IL.Emit(OpCodes.Isinst, importedEnumerableType);
}
示例4: RewriteMethodBody
/// <summary>
/// Rewrites the instructions in the target method body.
/// </summary>
/// <param name="method">The target method.</param>
/// <param name="IL">The <see cref="CilWorker"/> instance that represents the method body.</param>
/// <param name="oldInstructions">The IL instructions of the original method body.</param>
protected override void RewriteMethodBody(MethodDefinition method, CilWorker IL,
IEnumerable<Instruction> oldInstructions)
{
if (IsExcluded(method))
{
AddOriginalInstructions(IL, oldInstructions);
return;
}
VariableDefinition interceptionDisabled = method.AddLocal<bool>();
VariableDefinition invocationInfo = method.AddLocal<IInvocationInfo>();
VariableDefinition aroundInvokeProvider = method.AddLocal<IAroundInvokeProvider>();
VariableDefinition methodReplacementProvider = method.AddLocal<IMethodReplacementProvider>();
VariableDefinition returnValue = method.AddLocal<object>();
VariableDefinition classMethodReplacementProvider = method.AddLocal<IMethodReplacementProvider>();
Func<ModuleDefinition, MethodReference> getInstanceMethodReplacementProviderMethod =
module => module.Import(typeof (IMethodReplacementHost).GetMethod("get_MethodBodyReplacementProvider"));
var parameters = new MethodBodyRewriterParameters(IL,
oldInstructions,
interceptionDisabled,
invocationInfo, returnValue,
aroundInvokeProvider,
methodReplacementProvider,
classMethodReplacementProvider,
getInstanceMethodReplacementProviderMethod,
typeof (AroundMethodBodyRegistry));
var emitter = new InvocationInfoEmitter(true);
IInstructionEmitter getMethodReplacementProvider =
new GetMethodReplacementProvider(methodReplacementProvider, method,
getInstanceMethodReplacementProviderMethod);
IInstructionEmitter getInterceptionDisabled = new GetInterceptionDisabled(parameters);
ISurroundMethodBody surroundMethodBody = new SurroundMethodBody(parameters, "AroundMethodBodyProvider");
IInstructionEmitter getClassMethodReplacementProvider = new GetClassMethodReplacementProvider(parameters,
module =>
module.Import(
typeof (
MethodBodyReplacementProviderRegistry
).
GetMethod
("GetProvider")));
IInstructionEmitter addMethodReplacement = new AddMethodReplacementImplementation(parameters);
var rewriter = new InterceptAndSurroundMethodBody(emitter, getInterceptionDisabled, surroundMethodBody,
getMethodReplacementProvider,
getClassMethodReplacementProvider, addMethodReplacement,
parameters);
// Determine whether or not the method should be intercepted
rewriter.Rewrite(method, IL, oldInstructions);
}
示例5: AddLocals
public override void AddLocals(MethodDefinition hostMethod)
{
var body = hostMethod.Body;
body.InitLocals = true;
_currentArguments = hostMethod.AddLocal<Stack<object>>("__arguments");
_currentArgument = hostMethod.AddLocal<object>("__currentArgument");
_parameterTypes = hostMethod.AddLocal<Type[]>("__parameterTypes");
_typeArguments = hostMethod.AddLocal<Type[]>("__typeArguments");
_invocationInfo = hostMethod.AddLocal<IInvocationInfo>("___invocationInfo");
_target = hostMethod.AddLocal<object>("__target");
_replacement = hostMethod.AddLocal<IInterceptor>("__interceptor");
_canReplaceFlag = hostMethod.AddLocal<bool>("__canReplace");
_staticProvider = hostMethod.AddLocal<IMethodReplacementProvider>("__staticProvider");
_instanceProvider = hostMethod.AddLocal<IMethodReplacementProvider>("__instanceProvider");
_interceptionDisabled = hostMethod.AddLocal<bool>();
_methodReplacementProvider = hostMethod.AddLocal<IMethodReplacementProvider>();
_aroundInvokeProvider = hostMethod.AddLocal<IAroundInvokeProvider>();
_returnValue = hostMethod.AddLocal<object>();
}
示例6: AddLocals
/// <summary>
/// Adds locals to the target method.
/// </summary>
/// <param name="hostMethod">The method to be modified</param>
public override void AddLocals(MethodDefinition hostMethod)
{
_fieldContext = hostMethod.AddLocal<IFieldInterceptionContext>("__<>FieldInterceptionContext<>__");
_fieldInterceptor = hostMethod.AddLocal<IFieldInterceptor>("__<>FieldInterceptor<>__");
_currentArgument = hostMethod.AddLocal<object>("__<>CurrentArgument<>__");
}
示例7: BuildDecryptMethod
/// <summary>
/// Builds the decrypt method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
private static MethodDefinition BuildDecryptMethod(ICloakContext context, AssemblyDefinition assembly)
{
var byteArrayType = assembly.Import(typeof (byte[]));
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("DecryptData",
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static, byteArrayType);
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static, assembly.Import(typeof(byte[])));
#endif
method.Body.InitLocals = true;
method.Body.MaxStackSize = 5;
method.Parameters.Add(new ParameterDefinition(byteArrayType));
method.Parameters.Add(new ParameterDefinition(byteArrayType));
method.Parameters.Add(new ParameterDefinition(byteArrayType));
//Declare the locals - first four have quick reference
method.AddLocal(assembly, typeof(Rijndael));
method.AddLocal(assembly, typeof(ICryptoTransform));
method.AddLocal(assembly, typeof(MemoryStream));
method.AddLocal(assembly, typeof(CryptoStream));
var paddedPlain = method.AddLocal(assembly, typeof(byte[]));
var length = method.AddLocal(assembly, typeof(int));
var plain = method.AddLocal(assembly, typeof(byte[]));
var returnArray = method.AddLocal(assembly, typeof(byte[]));
var inferredBool = method.AddLocal(assembly, typeof(bool));
//Add the body
var il = method.Body.GetILProcessor();
//Inject anti reflector code
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
//Start the body
var rijndaelCreate = typeof(Rijndael).GetMethod("Create", Type.EmptyTypes);
il.Append(il.Create(OpCodes.Call, assembly.Import(rijndaelCreate)));
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Ldloc_0);
il.Append(OpCodes.Ldc_I4_1);
var symmetricAlgMode = typeof(SymmetricAlgorithm).GetProperty("Mode");
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(symmetricAlgMode.GetSetMethod())));
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldloc_0);
il.Append(OpCodes.Ldarg_1);
il.Append(OpCodes.Ldarg_2);
var createDecryptor = typeof(SymmetricAlgorithm).GetMethod("CreateDecryptor",
new[] { typeof(byte[]), typeof(byte[]) });
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(createDecryptor)));
il.Append(OpCodes.Stloc_1);
var startOfThirdTry = il.Create(OpCodes.Nop);
il.Append(startOfThirdTry);
il.Append(OpCodes.Ldarg_0);
//New memory stream
var memoryStreamCtor = typeof(MemoryStream).GetConstructor(new [] { typeof(byte[]) });
il.Append(il.Create(OpCodes.Newobj, assembly.Import(memoryStreamCtor)));
il.Append(OpCodes.Stloc_2);
var startOfSecondTry = il.Create(OpCodes.Nop);
il.Append(startOfSecondTry);
il.Append(OpCodes.Ldloc_2);
il.Append(OpCodes.Ldloc_1);
il.Append(OpCodes.Ldc_I4_0);
//New crypto stream
var cryptoStreamCtor =
typeof(CryptoStream).GetConstructor(new[]
{
typeof (Stream), typeof (ICryptoTransform),
typeof (CryptoStreamMode)
});
il.Append(il.Create(OpCodes.Newobj, assembly.Import(cryptoStreamCtor)));
il.Append(OpCodes.Stloc_3);
var startOfFirstTry = il.Create(OpCodes.Nop);
il.Append(startOfFirstTry);
il.Append(OpCodes.Ldarg_0);
il.Append(OpCodes.Ldlen);
il.Append(OpCodes.Conv_I4);
il.Append(il.Create(OpCodes.Newarr, assembly.Import(typeof(byte))));
il.Append(il.Create(OpCodes.Stloc_S, paddedPlain));
il.Append(OpCodes.Ldloc_3);
il.Append(il.Create(OpCodes.Ldloc_S, paddedPlain));
il.Append(OpCodes.Ldc_I4_0);
il.Append(il.Create(OpCodes.Ldloc_S, paddedPlain));
il.Append(OpCodes.Ldlen);
il.Append(OpCodes.Conv_I4);
//Get the read method and read into this byte array (full length)
var read = typeof(Stream).GetMethod("Read", new[] { typeof(byte[]), typeof(int), typeof(int) });
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(read)));
il.Append(il.Create(OpCodes.Stloc_S, length));
il.Append(il.Create(OpCodes.Ldloc_S, length));
il.Append(il.Create(OpCodes.Newarr, assembly.Import(typeof(byte))));
//.........这里部分代码省略.........
示例8: BuildHashMethod
/// <summary>
/// Builds the hash method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <returns></returns>
private static MethodDefinition BuildHashMethod(ICloakContext context, AssemblyDefinition assembly)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("Hash",
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static, assembly.Import(typeof(string)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static, assembly.Import(typeof(string)));
#endif
method.Parameters.Add(new ParameterDefinition(assembly.Import(typeof(byte[]))));
method.Body.InitLocals = true;
method.Body.MaxStackSize = 2;
method.AddLocal(assembly, typeof(SHA256));
method.AddLocal(assembly, typeof(string));
//Easy method to output
var il = method.Body.GetILProcessor();
//Inject some anti reflector stuff
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
//Create the SHA256 object
var sha256Create = typeof(SHA256).GetMethod("Create", Type.EmptyTypes);
il.Append(il.Create(OpCodes.Call, assembly.Import(sha256Create)));
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Ldloc_0);
il.Append(OpCodes.Ldarg_0);
//Call the compute method
var compute = typeof(HashAlgorithm).GetMethod("ComputeHash", new[] { typeof(byte[]) });
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(compute)));
//Finally, convert to base 64
var toBase64 = typeof(Convert).GetMethod("ToBase64String", new[] { typeof(byte[]) });
il.Append(il.Create(OpCodes.Call, assembly.Import(toBase64)));
il.Append(OpCodes.Stloc_1);
var retVar = il.Create(OpCodes.Ldloc_1);
il.Append(il.Create(OpCodes.Br_S, retVar));
il.Append(retVar);
il.Append(OpCodes.Ret);
return method;
}
示例9: BuildLoadTypeMethod
/// <summary>
/// Builds the load type method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="loadAssembly">The load assembly.</param>
/// <returns></returns>
private static MethodDefinition BuildLoadTypeMethod(ICloakContext context, AssemblyDefinition assembly, MethodReference loadAssembly)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("LoadType",
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(Type)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(Type)));
#endif
//Declare the resource parameter
method.Parameters.Add(new ParameterDefinition(assembly.Import(typeof(string))));
method.Parameters.Add(new ParameterDefinition(assembly.Import(typeof(string))));
method.Body.InitLocals = true;
method.Body.MaxStackSize = 2;
method.AddLocal(assembly, typeof(Assembly)); //Assembly
method.AddLocal(assembly, typeof(Type)); //Temp variable for return type
method.AddLocal(assembly, typeof(bool)); //Temp variable for comparison
//Start with injection
var il = method.Body.GetILProcessor();
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
//Start the code
il.Append(OpCodes.Ldarg_0);
il.Append(OpCodes.Ldarg_1);
il.Append(il.Create(OpCodes.Call, loadAssembly));
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Ldloc_0);
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Ceq);
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
il.Append(OpCodes.Stloc_2);
il.Append(OpCodes.Ldloc_2);
//Get type
var getType = il.Create(OpCodes.Ldloc_0);
il.Append(il.Create(OpCodes.Brtrue_S, getType));
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Stloc_1);
//Prepare to return the temp type
var returnType = il.Create(OpCodes.Ldloc_1);
//Jump to it
il.Append(il.Create(OpCodes.Br_S, returnType));
il.Append(getType);
il.Append(OpCodes.Ldarg_2);
var getTypeMethod = typeof (Assembly).GetMethod("GetType", new[] {typeof (string)});
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(getTypeMethod)));
il.Append(OpCodes.Stloc_1);
il.Append(il.Create(OpCodes.Br_S, returnType));
il.Append(returnType);
il.Append(OpCodes.Ret);
return method;
}
示例10: BuildLoadAssemblyMethod
/// <summary>
/// Builds the load assembly method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="loadedAssemblies">The loaded assemblies.</param>
/// <param name="executingAssembly">The executing assembly.</param>
/// <param name="decryptData">The decrypt data.</param>
/// <param name="hashData">The hash data.</param>
/// <param name="passwordKey">The password key.</param>
/// <param name="salt">The salt.</param>
/// <returns></returns>
private static MethodDefinition BuildLoadAssemblyMethod(ICloakContext context, AssemblyDefinition assembly, FieldReference loadedAssemblies, FieldReference executingAssembly, MethodReference decryptData, MethodReference hashData, string passwordKey, Guid salt)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("LoadAssembly",
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(Assembly)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(Assembly)));
#endif
//Declare the resource parameter
method.Parameters.Add(new ParameterDefinition(assembly.Import(typeof(string))));
method.Body.InitLocals = true;
method.Body.MaxStackSize = 4;
method.AddLocal(assembly, typeof(string)); //Hash
method.AddLocal(assembly, typeof(Stream)); //Stream for loading
method.AddLocal(assembly, typeof(byte[])); //Hash data
method.AddLocal(assembly, typeof(byte[])); //Data
var password = method.AddLocal(assembly, typeof(Rfc2898DeriveBytes)); //Password
var keyBytes = method.AddLocal(assembly, typeof(byte[])); //Key bytes
var initVector = method.AddLocal(assembly, typeof(byte[])); //Init vector
var rawAssembly = method.AddLocal(assembly, typeof(byte[])); //Assembly raw bytes
var actualAssembly = method.AddLocal(assembly, typeof(Assembly)); //Actual Assembly
var tempAssembly = method.AddLocal(assembly, typeof(Assembly)); //Temp Assembly
var tempBool = method.AddLocal(assembly, typeof(bool)); //Temp bool
//Build the body
var il = method.Body.GetILProcessor();
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
#if VERBOSE_OUTPUT
DebugLine(assembly, il, "Loading ", il.Create(OpCodes.Ldarg_1));
#endif
//Check the cache first
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, loadedAssemblies));
il.Append(OpCodes.Ldarg_1);
var containsKey = typeof (Dictionary<string, Assembly>).GetMethod("ContainsKey");
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(containsKey)));
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
il.Append(il.Create(OpCodes.Stloc_S, tempBool));
il.Append(il.Create(OpCodes.Ldloc_S, tempBool));
//Jump if we don't have it, other wise return it
var startFindType = il.Create(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Brtrue_S, startFindType));
//Otherwise return the cached assembly
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, loadedAssemblies));
il.Append(OpCodes.Ldarg_1);
//We are retrieving the name item
var getItem = typeof (Dictionary<string, Assembly>).GetProperty("Item");
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(getItem.GetGetMethod())));
//Store the variable in our return arg
il.Append(il.Create(OpCodes.Stloc_S, tempAssembly));
//Branch to our return routine
var returnSequence = il.Create(OpCodes.Nop);
il.Append(il.Create(OpCodes.Br, returnSequence));
//Back to finding our type
//Let's check the hash first
il.Append(startFindType);
il.Append(il.Create(OpCodes.Ldfld, executingAssembly));
il.Append(OpCodes.Ldarg_1);
il.Append(il.Create(OpCodes.Ldstr, ".v0"));
//Concat the arg1 (resourceName) and v0
var concat = assembly.Import(typeof (String).GetMethod("Concat", new[] {typeof (string), typeof (string)}));
il.Append(il.Create(OpCodes.Call, concat));
//Now get this from the manifest
var getManifest = assembly.Import(typeof (Assembly).GetMethod("GetManifestResourceStream", new[] {typeof (string)}));
il.Append(il.Create(OpCodes.Callvirt, getManifest));
//Store the result in our temp local
il.Append(OpCodes.Stloc_1);
var try1Start = il.Create(OpCodes.Nop);
il.Append(try1Start);
//Make sure it's not null
il.Append(OpCodes.Ldloc_1);
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Ceq);
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
il.Append(il.Create(OpCodes.Stloc_S, tempBool));
il.Append(il.Create(OpCodes.Ldloc_S, tempBool));
//Return null if it is
var startDeclareArray = il.Create(OpCodes.Ldloc_1);
//.........这里部分代码省略.........
示例11: BuildLoadAssembliesMethod
/// <summary>
/// Builds the load assemblies method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="executingAssembly">The executing assembly.</param>
/// <param name="loadAssembly">The load assembly.</param>
/// <returns></returns>
private static MethodDefinition BuildLoadAssembliesMethod(ICloakContext context, AssemblyDefinition assembly, FieldReference executingAssembly, MethodReference loadAssembly)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("LoadAssemblies",
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#endif
method.Body.InitLocals = true;
method.Body.MaxStackSize = 2;
method.AddLocal(assembly, typeof (string)); //Resource name
method.AddLocal(assembly, typeof (string[])); //Foreach temp
method.AddLocal(assembly, typeof (int)); //Loop counter
method.AddLocal(assembly, typeof(bool));
//Build the body
var il = method.Body.GetILProcessor();
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, executingAssembly));
//Get the resources - foreach get's converted to a standard loop
var resourcesMethod = typeof (Assembly).GetMethod("GetManifestResourceNames");
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(resourcesMethod)));
il.Append(OpCodes.Stloc_1);
//Initialise the loop counter
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Stloc_2);
//For loop comparison (well create somewhere to jump to)
var loopComparisonStart = il.Create(OpCodes.Ldloc_2);
//Check the comparison now
il.Append(il.Create(OpCodes.Br_S, loopComparisonStart));
var startCode = il.Create(OpCodes.Ldloc_1);
il.Append(startCode);
il.Append(OpCodes.Ldloc_2);
il.Append(OpCodes.Ldelem_Ref);
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldloc_0);
//Make sure it doesn't end with .v0 or .e
il.Append(il.Create(OpCodes.Ldstr, ".v0"));
var endsWith = assembly.Import(typeof (String).GetMethod("EndsWith", new[] {typeof (string)}));
il.Append(il.Create(OpCodes.Callvirt, endsWith));
//Jump out as need be
var load0 = il.Create(OpCodes.Ldc_I4_0);
il.Append(il.Create(OpCodes.Brtrue_S, load0));
il.Append(OpCodes.Ldloc_0);
//Check the .e
il.Append(il.Create(OpCodes.Ldstr, ".e"));
il.Append(il.Create(OpCodes.Callvirt, endsWith));
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
var storeTempBool = il.Create(OpCodes.Stloc_3);
il.Append(il.Create(OpCodes.Br_S, storeTempBool));
il.Append(load0);
il.Append(storeTempBool);
il.Append(OpCodes.Ldloc_3);
var loadArg0 = il.Create(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Brtrue_S, loadArg0));
var loadLoopCounter = il.Create(OpCodes.Ldloc_2);
il.Append(il.Create(OpCodes.Br_S, loadLoopCounter));
il.Append(loadArg0);
il.Append(OpCodes.Ldloc_0);
//Finally load the assembly
il.Append(il.Create(OpCodes.Call, loadAssembly));
il.Append(OpCodes.Pop);
il.Append(OpCodes.Nop);
//Loop counter
il.Append(loadLoopCounter);
il.Append(OpCodes.Ldc_I4_1);
il.Append(OpCodes.Add);
il.Append(OpCodes.Stloc_2);
//Loop comparison
il.Append(loopComparisonStart);
il.Append(OpCodes.Ldloc_1);
il.Append(OpCodes.Ldlen);
il.Append(OpCodes.Conv_I4);
il.Append(OpCodes.Clt);
//Store the result
il.Append(OpCodes.Stloc_3);
//Load it and compare
//.........这里部分代码省略.........
示例12: BuildMainMethod
/// <summary>
/// Builds the main method.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="context">The context.</param>
/// <param name="programType">Type of the program.</param>
/// <param name="getExecutingAssembly">The get executing assembly.</param>
/// <param name="currentDomain">The current domain.</param>
/// <param name="eventHandler">The event handler.</param>
/// <param name="assemblyResolve">The assembly resolve.</param>
/// <param name="resolveMethod">The resolve method.</param>
/// <param name="startMethod">The start method.</param>
/// <returns></returns>
private static MethodDefinition BuildMainMethod(AssemblyDefinition assembly, ICloakContext context, TypeDefinition programType, MethodReference getExecutingAssembly, MethodReference currentDomain, MethodReference eventHandler, MethodReference assemblyResolve, MethodReference resolveMethod, MethodReference startMethod)
{
#if USE_FRIENDLY_NAMING
MethodDefinition entryPoint =
new MethodDefinition("Main",
MethodAttributes.Private | MethodAttributes.Static |
MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#else
MethodDefinition entryPoint =
new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Private | MethodAttributes.Static |
MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#endif
entryPoint.Body.InitLocals = true;
entryPoint.Body.MaxStackSize = 4;
#if USE_APPDOMAIN
//Initialise some locals
entryPoint.AddLocal(assembly, typeof(AppDomain));
entryPoint.AddLocal(assembly, typeof(Assembly));
#endif
VariableDefinition result = new VariableDefinition(programType);
entryPoint.Body.Variables.Add(result);
//Add the method
assembly.EntryPoint = entryPoint;
//Declare the il to build the code
ILProcessor il = entryPoint.Body.GetILProcessor();
//First of all add the anti reflector code
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
//Now output the code - essentially:
/*
AppDomain domain = AppDomain.CreateDomain("App");
Assembly executingAssembly = Assembly.GetExecutingAssembly();
ProgramRunner runner = (ProgramRunner)domain.CreateInstanceAndUnwrap(executingAssembly.FullName, "TestBootstrapper.ProgramRunner");
AppDomain.CurrentDomain.AssemblyResolve += runner.ResolveAssembly;
runner.Start();
*/
#if USE_APPDOMAIN
#if USE_FRIENDLY_NAMING
il.Append(il.Create(OpCodes.Ldstr, "AppDomainName"));
#else
il.Append(il.Create(OpCodes.Ldstr, context.NameManager.GenerateName(NamingTable.Type)));
#endif
//Get the AppDomain::Create(string) method
var appDomainCreate = assembly.Import(typeof(AppDomain).GetMethod("CreateDomain", new[] { typeof(string) }));
il.Append(il.Create(OpCodes.Call, appDomainCreate));
il.Append(OpCodes.Stloc_0);
//Get the Assembly::GetExecutingAssembly() method
il.Append(il.Create(OpCodes.Call, getExecutingAssembly));
il.Append(OpCodes.Stloc_1);
il.Append(OpCodes.Ldloc_0);
il.Append(OpCodes.Ldloc_1);
//Assembly::get_FullName()
var getFullName = typeof(Assembly).GetProperty("FullName");
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(getFullName.GetGetMethod())));
il.Append(il.Create(OpCodes.Ldstr,
String.Format("{0}.{1}", programType.Namespace, programType.Name)));
//AppDomain::CreateInstanceAndUnwrap(string, string)
var createInstanceAndUnwrap = typeof(AppDomain).GetMethod("CreateInstanceAndUnwrap",
new[]
{
typeof (string), typeof (string)
});
il.Append(il.Create(OpCodes.Callvirt, assembly.Import(createInstanceAndUnwrap)));
il.Append(il.Create(OpCodes.Castclass, programType));
il.Append(OpCodes.Stloc_2);
//AppDomain::get_CurrentDomain
il.Append(il.Create(OpCodes.Call, currentDomain));
il.Append(OpCodes.Ldloc_2);
//Get the function
il.Append(il.Create(OpCodes.Ldftn, resolveMethod));
il.Append(il.Create(OpCodes.Newobj, eventHandler));
il.Append(il.Create(OpCodes.Callvirt, assemblyResolve));
il.Append(OpCodes.Nop);
//.........这里部分代码省略.........
示例13: BuildStartMethod
/// <summary>
/// Builds the start method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="executingAssembly">The executing assembly.</param>
/// <param name="assembliesLoaded">The assemblies loaded.</param>
/// <param name="loadType">Type of the load.</param>
/// <param name="loadAssemblies">The load assemblies.</param>
/// <returns></returns>
private static MethodDefinition BuildStartMethod(ICloakContext context, AssemblyDefinition assembly, FieldReference executingAssembly, FieldReference assembliesLoaded, MethodReference loadType, MethodReference loadAssemblies)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("Start",
MethodAttributes.Public | MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Public | MethodAttributes.HideBySig, assembly.Import(typeof(void)));
#endif
method.Body.InitLocals = true;
method.Body.MaxStackSize = 3;
method.AddLocal(assembly, typeof(string)); //entryAssemblyResource
method.AddLocal(assembly, typeof(string)); //entryType
method.AddLocal(assembly, typeof(string)); //entryMethod
method.AddLocal(assembly, typeof(string)); //resourceName
var s = method.AddLocal(assembly, typeof(Stream)); //s
var sr = method.AddLocal(assembly, typeof(StreamReader)); //sr
var type = method.AddLocal(assembly, typeof(Type)); //type
var methodInfo = method.AddLocal(assembly, typeof(MethodInfo)); //method
var tempStringArray = method.AddLocal(assembly, typeof (string[]));
var tempInt = method.AddLocal(assembly, typeof(int));
var tempBool = method.AddLocal(assembly, typeof(bool));
//Get the il builder
var il = method.Body.GetILProcessor();
//Inject the anti reflector code
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
//Start it off - declare some variables
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Stloc_1);
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Stloc_2);
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldarg_0);
//We need to find the entry point so start a loop to find
il.Append(il.Create(OpCodes.Ldfld, executingAssembly));
var getManifestResourceNames = assembly.Import(typeof (Assembly).GetMethod("GetManifestResourceNames"));
il.Append(il.Create(OpCodes.Callvirt, getManifestResourceNames));
il.Append(il.Create(OpCodes.Stloc_S, tempStringArray));
//Init the loop counter
il.Append(OpCodes.Ldc_I4_0);
il.Append(il.Create(OpCodes.Stloc_S, tempInt));
//Jump to the loop comparison
var startLoopComparison = il.Create(OpCodes.Ldloc_S, tempInt);
il.Append(il.Create(OpCodes.Br, startLoopComparison));
//Load the current item in a temp variable
var getTempVar = il.Create(OpCodes.Ldloc_S, tempStringArray);
il.Append(getTempVar);
il.Append(il.Create(OpCodes.Ldloc_S, tempInt));
il.Append(OpCodes.Ldelem_Ref);
il.Append(OpCodes.Stloc_3);
//Now start the actual body
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldloc_3);
il.Append(il.Create(OpCodes.Ldstr, ".e"));
var endsWith = assembly.Import(typeof (String).GetMethod("EndsWith", new[] {typeof (string)}));
il.Append(il.Create(OpCodes.Callvirt, endsWith));
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
il.Append(il.Create(OpCodes.Stloc_S, tempBool));
il.Append(il.Create(OpCodes.Ldloc_S, tempBool));
//Branch to increment statement if not true (i.e. equal to 0/false)
var startIncrement = il.Create(OpCodes.Nop);
il.Append(il.Create(OpCodes.Brtrue, startIncrement));
//Get the stream
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, executingAssembly));
il.Append(OpCodes.Ldloc_3);
var getManifestResourceStream =
assembly.Import(typeof (Assembly).GetMethod("GetManifestResourceStream", new[] {typeof (string)}));
il.Append(il.Create(OpCodes.Callvirt, getManifestResourceStream));
il.Append(il.Create(OpCodes.Stloc_S, s));
//Make sure it's not null
il.Append(il.Create(OpCodes.Ldloc_S, s));
il.Append(OpCodes.Ldnull);
il.Append(OpCodes.Ceq);
il.Append(OpCodes.Ldc_I4_0);
il.Append(OpCodes.Ceq);
il.Append(il.Create(OpCodes.Stloc_S, tempBool));
//.........这里部分代码省略.........
示例14: BuildResolveMethod
/// <summary>
/// Builds the resolve method.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="assembly">The definition.</param>
/// <param name="assemblyLock">The assembly lock.</param>
/// <param name="assembliesLoaded">The assemblies loaded.</param>
/// <param name="loadAssemblies">The load assemblies.</param>
/// <returns></returns>
private static MethodDefinition BuildResolveMethod(ICloakContext context, AssemblyDefinition assembly, FieldReference assemblyLock, FieldReference assembliesLoaded, MethodReference loadAssemblies)
{
#if USE_FRIENDLY_NAMING
MethodDefinition method = new MethodDefinition("ResolveAssembly",
MethodAttributes.Public | MethodAttributes.HideBySig, assembly.Import(typeof(Assembly)));
#else
MethodDefinition method = new MethodDefinition(context.NameManager.GenerateName(NamingTable.Method),
MethodAttributes.Public | MethodAttributes.HideBySig, assembly.Import(typeof(Assembly)));
#endif
//Declare the resource parameter
method.Parameters.Add(new ParameterDefinition("sender", Mono.Cecil.ParameterAttributes.None, assembly.Import(typeof(object))));
method.Parameters.Add(new ParameterDefinition(assembly.Import(typeof(ResolveEventArgs))));
method.Body.InitLocals = true;
method.Body.MaxStackSize = 2;
method.AddLocal(assembly, typeof(Assembly[])); //currentAssemblies
method.AddLocal(assembly, typeof(Assembly)); //a
method.AddLocal(assembly, typeof(Assembly)); //temp assembly
method.AddLocal(assembly, typeof (object)); //temp object
var tempBool = method.AddLocal(assembly, typeof (bool)); //temp bool
var tempAssemblyArray = method.AddLocal(assembly, typeof(Assembly[])); //temp assembly array
var tempInt = method.AddLocal(assembly, typeof (int)); //temp int
//Get the il builder
var il = method.Body.GetILProcessor();
//Inject the anti reflector code
InjectAntiReflectorCode(il, il.Create(OpCodes.Nop));
#if VERBOSE_OUTPUT
DebugLine(assembly, il, "Resolving");
#endif
//Start a lock
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, assemblyLock));
il.Append(OpCodes.Dup);
il.Append(OpCodes.Stloc_3);
var monitorEnter = assembly.Import(typeof (Monitor).GetMethod("Enter", new[] {typeof (object)}));
il.Append(il.Create(OpCodes.Call, monitorEnter));
il.Append(OpCodes.Nop);
var tryStart = il.Create(OpCodes.Nop);
il.Append(tryStart);
//Check if the assemblies are loaded
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldfld, assembliesLoaded));
il.Append(il.Create(OpCodes.Stloc_S, tempBool));
il.Append(il.Create(OpCodes.Ldloc_S, tempBool));
//If it is set, skip to searching the current appdomain
var startSearchingCurrentAppDomain = il.Create(OpCodes.Nop);
il.Append(il.Create(OpCodes.Brtrue_S, startSearchingCurrentAppDomain));
il.Append(OpCodes.Nop);
il.Append(OpCodes.Ldarg_0);
il.Append(OpCodes.Ldc_I4_1);
il.Append(il.Create(OpCodes.Stfld, assembliesLoaded));
il.Append(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Call, loadAssemblies));
il.Append(OpCodes.Nop);
il.Append(OpCodes.Nop);
il.Append(startSearchingCurrentAppDomain);
//After the finally
var afterFinally = il.Create(OpCodes.Nop);
//Exit the finally
il.Append(il.Create(OpCodes.Leave_S, afterFinally));
//We're in the finally now
var finallyStart = il.Create(OpCodes.Ldloc_3);
il.Append(finallyStart);
var monitorExit = assembly.Import(typeof (Monitor).GetMethod("Exit", new[] {typeof (object)}));
il.Append(il.Create(OpCodes.Call, monitorExit));
il.Append(OpCodes.Nop);
il.Append(OpCodes.Endfinally);
il.Append(afterFinally);
//Get the current domains assemblies
var currentDomain = assembly.Import(typeof (AppDomain).GetProperty("CurrentDomain").GetGetMethod());
il.Append(il.Create(OpCodes.Call, currentDomain));
var getAssemblies = assembly.Import(typeof (AppDomain).GetMethod("GetAssemblies"));
il.Append(il.Create(OpCodes.Callvirt, getAssemblies));
il.Append(OpCodes.Stloc_0);
il.Append(OpCodes.Nop);
//Lets start a loop in lieu of foreach
il.Append(OpCodes.Ldloc_0);
il.Append(il.Create(OpCodes.Stloc_S, tempAssemblyArray));
il.Append(OpCodes.Ldc_I4_0);
il.Append(il.Create(OpCodes.Stloc_S, tempInt));
//Loop Condition
var loopCondition = il.Create(OpCodes.Ldloc_S, tempInt);
il.Append(il.Create(OpCodes.Br_S, loopCondition));
//.........这里部分代码省略.........
示例15: Emit
/// <summary>
/// Generates a method body for the <paramref name="targetMethod"/>.
/// </summary>
/// <param name="originalMethod">The method currently being intercepted.</param>
/// <param name="targetMethod">The target method that will contain the new method body.</param>
public void Emit(MethodInfo originalMethod, MethodDefinition targetMethod)
{
var invocationInfo = targetMethod.AddLocal<IInvocationInfo>();
invocationInfo.Name = "___invocationInfo___";
// Emit the code to generate the IInvocationInfo instance
// and save it into the invocationInfo local variable
if (InvocationInfoEmitter != null)
InvocationInfoEmitter.Emit(originalMethod, targetMethod, invocationInfo);
var declaringType = targetMethod.DeclaringType;
var module = declaringType.Module;
var proxyType = module.ImportType<IProxy>();
var getInterceptorMethod = module.ImportMethod("get_Interceptor", typeof (IProxy));
var interceptor = targetMethod.AddLocal<IInterceptor>();
var arguments = targetMethod.AddLocal<object[]>();
// if (!(this is IProxy))
var IL = targetMethod.GetILGenerator();
IL.Emit(OpCodes.Ldarg_0);
IL.Emit(OpCodes.Isinst, proxyType);
var noImplementationFound = IL.Create(OpCodes.Nop);
IL.Emit(OpCodes.Brfalse, noImplementationFound);
var endLabel = IL.Create(OpCodes.Nop);
EmitGetInterceptorInstruction(IL, proxyType, getInterceptorMethod);
IL.Emit(OpCodes.Stloc, interceptor);
//If (interceptor == null)
// throw a not implemented exception here
IL.Emit(OpCodes.Ldloc, interceptor);
IL.Emit(OpCodes.Brfalse, noImplementationFound);
// var returnValue = interceptor.Intercept(info);
var voidType = module.ImportType(typeof (void));
var interceptMethod = module.ImportMethod<IInterceptor>("Intercept", typeof (IInvocationInfo));
IL.Emit(OpCodes.Ldloc, interceptor);
IL.Emit(OpCodes.Ldloc, invocationInfo);
IL.Emit(OpCodes.Callvirt, interceptMethod);
// Save the ref arguments
var parameters = from ParameterDefinition param in targetMethod.Parameters
select param;
// Determine the return type
var returnType = targetMethod.ReturnType != null
? targetMethod.ReturnType.ReturnType
: voidType;
IL.PackageReturnValue(module, returnType);
SaveRefArguments(IL, parameters, invocationInfo, arguments);
IL.Emit(OpCodes.Br, endLabel);
// This code at this point will execute if no implementation
// is found
IL.Append(noImplementationFound);
ImplementNotFound(IL);
IL.Append(endLabel);
IL.Emit(OpCodes.Ret);
}