4 using System.Collections.Generic;
8 using Mono.Cecil.Rocks;
9 using SiliconStudio.AssemblyProcessor;
11 namespace SiliconStudio.AssemblyProcessor
17 var assembly = context.Assembly;
18 var moduleInitializers =
new List<MethodReference>();
21 foreach (var type
in assembly.EnumerateTypes())
23 foreach (var method
in type.Methods)
25 if (method.CustomAttributes.Any(x => x.AttributeType.FullName ==
"SiliconStudio.Core.ModuleInitializerAttribute"))
27 moduleInitializers.Add(method);
32 if (moduleInitializers.Count == 0)
36 Instruction returnInstruction;
37 var staticConstructor = OpenModuleConstructor(assembly, out returnInstruction);
39 var il = staticConstructor.Body.GetILProcessor();
41 var newReturnInstruction = Instruction.Create(returnInstruction.OpCode);
42 newReturnInstruction.Operand = returnInstruction.Operand;
44 returnInstruction.OpCode = OpCodes.Nop;
45 returnInstruction.Operand = null;
47 staticConstructor.Body.SimplifyMacros();
48 foreach (var moduleInitializer
in moduleInitializers)
50 il.Append(Instruction.Create(OpCodes.Call, moduleInitializer));
52 il.Append(newReturnInstruction);
53 staticConstructor.Body.OptimizeMacros();
58 public static MethodDefinition
OpenModuleConstructor(AssemblyDefinition assembly, out Instruction returnInstruction)
60 var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly);
61 if (mscorlibAssembly == null)
62 throw new InvalidOperationException(
"Missing mscorlib.dll from assembly");
65 var voidType = assembly.MainModule.Import(mscorlibAssembly.MainModule.GetTypeResolved(typeof(
void).FullName));
66 var moduleClass = assembly.MainModule.Types.First(t => t.Name ==
"<Module>");
67 var staticConstructor = moduleClass.GetStaticConstructor();
68 if (staticConstructor == null)
70 staticConstructor =
new MethodDefinition(
".cctor",
73 staticConstructor.Body.GetILProcessor().Append(Instruction.Create(OpCodes.Ret));
75 moduleClass.Methods.Add(staticConstructor);
77 returnInstruction = staticConstructor.Body.Instructions.Last();
79 return staticConstructor;
bool Process(AssemblyProcessorContext context)
Mono.Cecil.MethodAttributes MethodAttributes
static MethodDefinition OpenModuleConstructor(AssemblyDefinition assembly, out Instruction returnInstruction)