Exemple #1
0
		public byte[] Compile(out DSEELocalAndMethod[] locals, out string typeName, out string errorMessage) {
			if (generatedModule == null) {
				locals = Array.Empty<DSEELocalAndMethod>();
				typeName = string.Empty;
				errorMessage = null;
				return Array.Empty<byte>();
			}

			foreach (var p in sourceMethod.Parameters) {
				var name = language.GetVariableName(GetName(p), isThis: p.IsHiddenThisParameter);
				var kind = p.IsHiddenThisParameter ? LocalAndMethodKind.This : LocalAndMethodKind.Parameter;
				var (methodName, flags) = AddMethod(p.Type, p.Index, isLocal: false);
				localAndMethodBuilder.Add(new DSEELocalAndMethod(name, name, methodName, flags, kind, p.Index, Guid.Empty, null));
			}

			var body = sourceMethod.Body;
			if (body != null) {
				foreach (var l in body.Variables) {
					var name = language.GetVariableName(GetName(l), isThis: false);
					const LocalAndMethodKind kind = LocalAndMethodKind.Local;
					var (methodName, flags) = AddMethod(l.Type, l.Index, isLocal: true);
					localAndMethodBuilder.Add(new DSEELocalAndMethod(name, name, methodName, flags, kind, l.Index, Guid.Empty, null));
				}
			}

			var memStream = new MemoryStream();
			var writerOptions = new ModuleWriterOptions(generatedModule);
			generatedModule.Write(memStream, writerOptions);
			locals = localAndMethodBuilder.ToArray();
			typeName = getLocalsType.ReflectionFullName;
			errorMessage = null;
			return memStream.ToArray();
		}
Exemple #2
0
        public static void Run()
        {
            // Create a new module. The string passed in is the name of the module,
            // not the file name.
            var mod = new ModuleDefUser("MyModule.exe");

            // It's a console application
            mod.Kind = ModuleKind.Console;

            // Add the module to an assembly
            var asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, null);

            asm.Modules.Add(mod);

            // Add a .NET resource
            byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
                                                   ManifestResourceAttributes.Private));

            // Add the startup type. It derives from System.Object.
            var startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            var entryPoint = new MethodDefUser("Main",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create a TypeRef to System.Console
            var consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            var consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                  MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                  consoleRef);

            // Add a CIL method body to the entry point method
            var epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("Hello World!"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Save the assembly to a file on disk
            mod.Write(@"C:\saved-assembly.exe");
        }
Exemple #3
0
        public void TestInvalidOpCodeMap()
        {
            var random = new Random();

            var mod  = new ModuleDefUser("test");
            var type = new TypeDefUser("Constants");

            for (var i = 0; i < random.Next(0, 100); i++)
            {
                type.Fields.Add(new FieldDefUser("randomName" + random.Next(), new FieldSig(mod.CorLibTypes.Byte)));
            }

            mod.Types.Add(type);

            var ms = new MemoryStream();

            mod.Write(ms);

            var ctx = new RhydonContext {
                Module = ModuleDefMD.Load(ms), Logger = new DummyLogger()
            };

            OpCodeMap.Parse(ctx);
            Assert.IsNull(ctx.Constants);
        }
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <CompressorContext>(context, ContextKey);

            if (ctx == null)
            {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];

            ctx.OriginModuleDef = originModule;

            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            if (ctx.CompatMode)
            {
                var assembly = new AssemblyDefUser(originModule.Assembly);
                assembly.Name += ".cr";
                assembly.Modules.Add(stubModule);
            }
            else
            {
                ctx.Assembly.Modules.Insert(0, stubModule);
                ImportAssemblyTypeReferences(originModule, stubModule);
            }
            stubModule.Characteristics           = originModule.Characteristics;
            stubModule.Cor20HeaderFlags          = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics        = originModule.DllCharacteristics;
            stubModule.EncBaseId           = originModule.EncBaseId;
            stubModule.EncId               = originModule.EncId;
            stubModule.Generation          = originModule.Generation;
            stubModule.Kind                = ctx.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;

            InjectStub(context, ctx, parameters, stubModule);

            var snKey = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNKey);

            using (var ms = new MemoryStream()) {
                var options = new ModuleWriterOptions(stubModule)
                {
                    StrongNameKey = snKey
                };
                var injector = new KeyInjector(ctx);
                options.WriterEvent += injector.WriterEvent;

                stubModule.Write(ms, options);
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule));
            }
        }
Exemple #5
0
        public static Option <Type> CreateInterfaceTypeFrom(Option <MethodInfo> sourceMethod)
        {
            if (!sourceMethod.HasValue)
            {
                return(Option.None <Type>());
            }

            var methodInfo     = sourceMethod.ValueOrFailure();
            var parameterTypes = methodInfo.GetParameters();
            var returnType     = methodInfo.ReturnType;

            var typeId     = Guid.NewGuid().ToString();
            var methodName = $"AnonymousMethod_{typeId}";

            var module = new ModuleDefUser($"anonymous_module_{typeId}.dll")
            {
                Kind = ModuleKind.Dll
            };

            var assembly = new AssemblyDefUser($"anonymous_assembly_{typeId}");

            assembly.Modules.Add(module);

            var interfaceType = new TypeDefUser($"IAnonymousInterface_{typeId}")
            {
                Attributes = TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Interface |
                             TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass
            };

            module.Types.Add(interfaceType);

            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                   MethodAttributes.Abstract | MethodAttributes.Virtual;

            var methodImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;

            var importedReturnType     = module.ImportAsTypeSig(returnType);
            var importedParameterTypes = parameterTypes.Select(type => module.ImportAsTypeSig(type.ParameterType));
            var method = new MethodDefUser(methodName,
                                           MethodSig.CreateInstance(importedReturnType, importedParameterTypes.ToArray()),
                                           methodImplAttributes, methodAttributes);

            for (var paramNumber = 0; paramNumber < parameterTypes.Length; paramNumber++)
            {
                method.ParamDefs.Add(new ParamDefUser($"arg{paramNumber++}"));
            }

            interfaceType.Methods.Add(method);

            var stream = new MemoryStream();

            module.Write(stream);

            var loadedAssembly = Assembly.Load(stream.ToArray());

            return(loadedAssembly.GetTypes().FirstOrNone());
        }
Exemple #6
0
		public static void Run() {
			// Create a new module. The string passed in is the name of the module,
			// not the file name.
			ModuleDef mod = new ModuleDefUser("MyModule.exe");
			// It's a console application
			mod.Kind = ModuleKind.Console;

			// Add the module to an assembly
			AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, null);
			asm.Modules.Add(mod);

			// Add a .NET resource
			byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
			mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
							ManifestResourceAttributes.Private));

			// Add the startup type. It derives from System.Object.
			TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
			startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
									TypeAttributes.Class | TypeAttributes.AnsiClass;
			// Add the type to the module
			mod.Types.Add(startUpType);

			// Create the entry point method
			MethodDef entryPoint = new MethodDefUser("Main",
				MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
			entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
							MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
			entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
			// Name the 1st argument (argument 0 is the return type)
			entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
			// Add the method to the startup type
			startUpType.Methods.Add(entryPoint);
			// Set module entry point
			mod.EntryPoint = entryPoint;

			// Create a TypeRef to System.Console
			TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
			// Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
			MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
						MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
						consoleRef);

			// Add a CIL method body to the entry point method
			CilBody epBody = new CilBody();
			entryPoint.Body = epBody;
			epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("Hello World!"));
			epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
			epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
			epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly to a file on disk
			mod.Write(@"C:\saved-assembly.exe");
		}
Exemple #7
0
        private static void Main(string[] args)
        {
            var file = "";

            Console.WriteLine("Origami by drakonia - https://github.com/dr4k0nia/Origami \r\n");
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: Origami.exe <file> or Origami.exe -inject <host> <payload>");
                Console.ReadKey();
                return;
            }

            file = args[0];

            if (!File.Exists(file))
            {
                throw new FileNotFoundException($"Could not find file: {file}");
            }

            var originModule = ModuleDefMD.Load(file);

            if (!Utils.IsExe(originModule))
            {
                throw new Exception("Invalid file format => supported are .net executables");
            }

            //input file as payload
            payload = File.ReadAllBytes(file);

            //Generate stub based on origin file
            Console.WriteLine("Generating new stub module");
            ModuleDefUser stubModule = CreateStub(originModule);

            ModifyModule(stubModule, false);


            //Rename Global Constructor
            var moduleGlobalType = stubModule.GlobalType;

            moduleGlobalType.Name = "Origami";

            var writerOptions = new ModuleWriterOptions(stubModule);

            writerOptions.WriterEvent += OnWriterEvent;

            stubModule.Write(file.Replace(".exe", "_origami.exe"), writerOptions);

            Console.WriteLine("Saving module...");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Finished");

            Console.ReadKey();
        }
Exemple #8
0
        public void TestNoKoiHeader()
        {
            var mod = new ModuleDefUser("test");
            var ms  = new MemoryStream();

            mod.Write(ms);

            var ctx = new RhydonContext {
                Module = ModuleDefMD.Load(ms), Logger = new DummyLogger()
            };

            KoiHeader.Parse(ctx);
            Assert.IsNull(ctx.Header);

            ms.Close();
        }
Exemple #9
0
        // Token: 0x060000B7 RID: 183 RVA: 0x0000E52C File Offset: 0x0000C72C
        public static void Pack(ModuleDef md, string directory)
        {
            string        s             = Convert.ToBase64String(File.ReadAllBytes(directory));
            ModuleDefUser moduleDefUser = new ModuleDefUser(Renamer.Random(25));

            moduleDefUser.Kind = ModuleKind.Console;
            AssemblyDefUser assemblyDefUser = new AssemblyDefUser(Renamer.Random(25), new Version(Packer.random.Next(1, 9), Packer.random.Next(1, 9), Packer.random.Next(1, 9), Packer.random.Next(1, 9)));

            assemblyDefUser.Modules.Add(moduleDefUser);
            TypeDefUser typeDefUser = new TypeDefUser(Renamer.Random(25), Renamer.Random(25), moduleDefUser.CorLibTypes.Object.TypeDefOrRef);

            typeDefUser.Attributes = dnlib.DotNet.TypeAttributes.NotPublic;
            moduleDefUser.Types.Add(typeDefUser);
            MethodDefUser methodDefUser = new MethodDefUser("Main", MethodSig.CreateStatic(moduleDefUser.CorLibTypes.Void, new SZArraySig(moduleDefUser.CorLibTypes.String)));

            methodDefUser.Attributes     = (dnlib.DotNet.MethodAttributes.Static | dnlib.DotNet.MethodAttributes.HideBySig);
            methodDefUser.ImplAttributes = dnlib.DotNet.MethodImplAttributes.IL;
            methodDefUser.ParamDefs.Add(new ParamDefUser("args", 1));
            typeDefUser.Methods.Add(methodDefUser);
            moduleDefUser.EntryPoint = methodDefUser;
            CilBody cilBody = new CilBody();

            methodDefUser.Body = cilBody;
            cilBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            cilBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(s));
            cilBody.Instructions.Add(OpCodes.Call.ToInstruction(methodDefUser.Module.Import(typeof(Convert).GetMethod("FromBase64String", new Type[]
            {
                typeof(string)
            }))));
            cilBody.Instructions.Add(OpCodes.Call.ToInstruction(methodDefUser.Module.Import(typeof(Assembly).GetMethod("Load", new Type[]
            {
                typeof(byte[])
            }))));
            cilBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(methodDefUser.Module.Import(typeof(Assembly).GetMethod("get_EntryPoint", new Type[0]))));
            cilBody.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            cilBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            cilBody.Instructions.Add(OpCodes.Newarr.ToInstruction(methodDefUser.Module.Import(typeof(object))));
            cilBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(methodDefUser.Module.Import(typeof(MethodBase).GetMethod("Invoke", new Type[]
            {
                typeof(object),
                typeof(object[])
            }))));
            cilBody.Instructions.Add(OpCodes.Pop.ToInstruction());
            cilBody.Instructions.Add(OpCodes.Ret.ToInstruction());
            moduleDefUser.Write(directory);
        }
Exemple #10
0
        private byte[] DecryptArray(MethodDef method, byte[] encryptedArray)
        {
            ModuleDefUser tempModule = new ModuleDefUser("TempModule");

            AssemblyDef tempAssembly = new AssemblyDefUser("TempAssembly");

            tempAssembly.Modules.Add(tempModule);

            var tempType = new TypeDefUser("", "TempType", tempModule.CorLibTypes.Object.TypeDefOrRef);

            tempType.Attributes = TypeAttributes.Public | TypeAttributes.Class;
            MethodDef tempMethod = Utils.Clone(method);

            tempMethod.ReturnType = new SZArraySig(tempModule.CorLibTypes.Byte);
            tempMethod.MethodSig.Params.Add(new SZArraySig(tempModule.CorLibTypes.Byte));
            tempMethod.Attributes = MethodAttributes.Public | MethodAttributes.Static;

            for (int i = 0; i < 5; i++)
            {
                tempMethod.Body.Instructions.RemoveAt(2); // read encrypted array from argument
            }
            tempMethod.Body.Instructions.Insert(2, OpCodes.Ldarg_0.ToInstruction());

            for (int i = 0; i < 2; i++)
            {
                tempMethod.Body.Instructions.RemoveAt(tempMethod.Body.Instructions.Count -
                                                      2); // make return decrypted array
            }
            tempType.Methods.Add(tempMethod);
            tempModule.Types.Add(tempType);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                ModuleWriterOptions moduleWriterOptions = new ModuleWriterOptions();
                moduleWriterOptions.MetaDataOptions = new MetaDataOptions();

                tempModule.Write(memoryStream, moduleWriterOptions);

                Assembly   patchedAssembly = Assembly.Load(memoryStream.ToArray());
                var        type            = patchedAssembly.ManifestModule.GetType("TempType");
                var        methods         = type.GetMethods();
                MethodInfo patchedMethod   = methods.First(m => m.IsPublic && m.IsStatic);
                byte[]     decryptedBytes  = (byte[])patchedMethod.Invoke(null, new object[] { encryptedArray });
                return(Lzma.Decompress(decryptedBytes));
            }
        }
Exemple #11
0
        public void TestValidOpCodeMap()
        {
            var random = new Random();

            var mod  = new ModuleDefUser("test");
            var type = new TypeDefUser("Constants");

            for (var i = 0; i < 119; i++)
            {
                type.Fields.Add(new FieldDefUser("randomName" + random.Next(), new FieldSig(mod.CorLibTypes.Byte)));
            }

            mod.Types.Add(type);

            var ctor = type.FindOrCreateStaticConstructor();
            var body = new CilBody();

            for (var i = 1; i < 119; i++)
            {
                body.Instructions.Insert(0, Instruction.Create(OpCodes.Stfld, type.Fields[i]));
                body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldc_I4, random.Next(0, 0xFF)));
                body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldnull));
            }

            body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
            body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, 112));
            body.Instructions.Add(Instruction.Create(OpCodes.Stfld, type.Fields[0]));
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            ctor.Body = body;

            var ms = new MemoryStream();

            mod.Write(ms);

            var ctx = new RhydonContext {
                Module = ModuleDefMD.Load(ms), Logger = new DummyLogger()
            };

            OpCodeMap.Parse(ctx);
            Assert.IsNotNull(ctx.Constants);
            Assert.IsTrue(ctx.Constants.REG_R0 == 112);

            ms.Close();
        }
        public byte[] GetBrandNewAssemblyFromType(TypeDef typeToInject)
        {
            // First of all, a temporary assembly is created and methods are injected into this assembly.
            // Once this assembly is ready, this try to execute the method in order to replace all the references in
            // the original assembly with its result.
            // This is probably the weakest part of the deobfuscator but I doubt there's an easier way to do this.

            AssemblyDef   dummyAssembly = new AssemblyDefUser("DummyAssembly", new System.Version(1, 0, 0, 0), null);
            ModuleDefUser dummyModule   = new ModuleDefUser("DummyModule")
            {
                Kind = ModuleKind.Dll
            };
            TypeDef dummyType = new TypeDefUser("DummyNamespace", "DummyType", dummyModule.CorLibTypes.Object.TypeDefOrRef);

            dummyType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                   TypeAttributes.Class | TypeAttributes.AnsiClass;

            dummyModule.Types.Add(dummyType);
            dummyAssembly.Modules.Add(dummyModule);

            // Copy everything in dummyType
            Inject(typeToInject, dummyType, dummyModule, null);

            // Provide a default constructor
            if (dummyType.FindDefaultConstructor() == null)
            {
                var ctor = new MethodDefUser(".ctor",
                                             MethodSig.CreateInstance(dummyModule.CorLibTypes.Void),
                                             MethodImplAttributes.Managed,
                                             MethodAttributes.HideBySig | MethodAttributes.Public |
                                             MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
                ctor.Body          = new CilBody();
                ctor.Body.MaxStack = 0;
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                dummyType.Methods.Add(ctor);
            }

            // Save the assembly to a memorystream
            using (MemoryStream stream = new MemoryStream())
            {
                dummyModule.Write(stream);
                return(stream.ToArray());
            }
        }
        public static void Build(string fullPath, string outputPath)
        {
            var mod = new ModuleDefUser(ModuleName, null, ModuleDefMD.Load(typeof(void).Module).Assembly.ToAssemblyRef())
            {
                Kind = ModuleKind.Dll
            };

            var ass = new AssemblyDefUser(AssemblyName, Version.Parse("1.0.0.0"));

            ass.Modules.Add(mod);

            //get resourceset
            var set = new ResourceElementSet();

            foreach (ResourceElement re in FileFormatHelper.GetResourceElements(fullPath))
            {
                set.Add(re);
            }

            //write set to byte[] and add to module resources
            using (var ms = new MemoryStream()) {
                ResourceWriter.Write(mod, ms, set);
                mod.Resources.Add(new EmbeddedResource(Resources, ms.ToArray(), ManifestResourceAttributes.Private));
            }

            //create store type
            TypeDef store = new TypeDefUser(Namespace, ResourceStore, mod.CorLibTypes.Object.TypeDefOrRef)
            {
                Attributes = TypeAttributes.Public | TypeAttributes.BeforeFieldInit
            };

            //add the type to the module
            mod.Types.Add(store);

            //add code
            BuildStore(mod, ref store);

            //write module
            mod.Write(Path.Combine(outputPath, "osu!ui-rebuilt.dll"));
        }
Exemple #14
0
        //https://github.com/0xd4d/dnlib/blob/master/Examples/Example3.cs
        public static void Run(string encrypted, string writedir)
        {
            //create module
            var mod = new ModuleDefUser(RandomString()); mod.Kind = ModuleKind.Console;
            // create and add asm in module
            var asm = new AssemblyDefUser(RandomString(), new Version(random.Next(1, 9), random.Next(1, 9), random.Next(1, 9), random.Next(1, 9)));

            asm.Modules.Add(mod);
            // create startup class for ep
            var startUpType = new TypeDefUser(RandomString(), RandomString(), mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.AnsiClass;
            mod.Types.Add(startUpType);
            //create ep method main(string[] args)
            var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes     = MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            startUpType.Methods.Add(entryPoint);
            mod.EntryPoint = entryPoint;
            var epBody = new CilBody();

            entryPoint.Body = epBody;
            // add instructions in ep method
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(encrypted));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(entryPoint.Module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.Assembly).GetMethod("Load", new Type[] { typeof(byte[]) }))));
            epBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.Assembly).GetMethod("get_EntryPoint", new Type[0]))));
            epBody.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            epBody.Instructions.Add(OpCodes.Newarr.ToInstruction(entryPoint.Module.Import(typeof(System.Object))));
            epBody.Instructions.Add(OpCodes.Callvirt.ToInstruction(entryPoint.Module.Import(typeof(System.Reflection.MethodBase).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) }))));
            epBody.Instructions.Add(OpCodes.Pop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());
            // save new file
            mod.Write(writedir.Replace(".exe", "_packed.exe"));
        }
Exemple #15
0
        static void Main(string[] args)
        {
            string[]      file       = File.ReadAllLines("precomp.psnbin");
            ModuleDefUser mod        = newmod("PointySnakeModule");
            MethodDefUser entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            startUpType = new TypeDefUser("PointySnake", "Program", mod.CorLibTypes.Object.TypeDefOrRef);
            mod.Types.Add(startUpType);
            entryPoint.Attributes     = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.AggressiveOptimization;
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            var epBody = new CilBody();

            entryPoint.Body        = epBody;
            startUpType.Attributes = TypeAttributes.Public;
            startUpType.Methods.Add(entryPoint);
            mod.EntryPoint = entryPoint;
            currentfunc    = mod.EntryPoint;
            foreach (string line in file)
            {
                WriteInstruction(line, mod, currentfunc.Body);
            }
            if (epBody.Instructions.Count == 0 || epBody.Instructions[epBody.Instructions.Count - 1].OpCode != OpCodes.Ret)
            {
                entryPoint.Body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
                entryPoint.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
            }
            entryPoint.Body.OptimizeBranches();
            entryPoint.Body.OptimizeMacros();
            Console.WriteLine("done");
            var options = new ModuleWriterOptions(mod);

            options.PEHeadersOptions.Machine = dnlib.PE.Machine.AMD64;
            mod.Write("executable.exe", options);
            awaitbutton();
        }
        public static void Run()
        {
            // 创建一个新模块。 传入的字符串是模块的名称,而不是文件名。
            ModuleDef mod = new ModuleDefUser("MyModule.exe");

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;

            //将模块添加到装配中
            AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, "");

            asm.Modules.Add(mod);

            //添加.NET资源
            //         byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            //mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
            //				ManifestResourceAttributes.Private));

            // 添加启动类型。 它派生自System.Object。
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 将类型添加到模块
            mod.Types.Add(startUpType);

            // 创建入口点方法
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // 命名第一个参数(参数0是返回类型)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // 将方法添加到启动类型
            startUpType.Methods.Add(entryPoint);
            // 设置模块入口点
            mod.EntryPoint = entryPoint;

            // 创建TypeRef到System.Console
            TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // 创建方法ref为'System.Void System.Console :: WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                        MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                        consoleRef);


            TypeRef ConsoleKeyInfo = new TypeRefUser(mod, "System", "ConsoleKeyInfo", mod.CorLibTypes.AssemblyRef);
            //TypeRef stream = new TypeRefUser(mod, "System.IO", "Stream", mod.CorLibTypes.AssemblyRef);
            ClassSig classSig = new ClassSig(ConsoleKeyInfo);

            SZArraySig    array5 = new SZArraySig(classSig);
            ITypeDefOrRef type1  = array5.ToTypeDefOrRef();
            ITypeDefOrRef type2  = classSig.ToTypeDefOrRef();
            TypeSig       type11 = type1.ToTypeSig();
            TypeSig       type22 = type2.ToTypeSig();
            // 创建方法ref为'System.ConsoleKeyInfo
            //System.Console::ReadKey()'
            MemberRef consoleReadKey = new MemberRefUser(
                mod,
                "ReadLine",
                //MethodSig.CreateStatic(mod.CorLibTypes.Void),
                MethodSig.CreateStatic(mod.CorLibTypes.String),
                consoleRef
                );

            //LocalList localList=new LocalList(new LazyList<Local>());
            Local local = new Local(mod.CorLibTypes.String);
            //localList.Add(local);
            //SZArraySig SZArraySig = new SZArraySig(local);

            // 将CIL方法体添加到入口点方法
            CilBody epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Variables.Add(local);
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("小宇专属"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("xiaoyu"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleReadKey));
            //epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());

            epBody.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly.exe");
        }
Exemple #17
0
		public static void Run() {
			// This is the file that will be created
			string newFileName = @"C:\ctor-test.exe";

			// Create the module
			var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(),
				new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
			// It's a console app
			mod.Kind = ModuleKind.Console;
			// Create the assembly and add the created module to it
			new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod);

			// Create System.Console type reference
			var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
			// Create 'void System.Console.WriteLine(string,object)' method reference
			var writeLine2 = new MemberRefUser(mod, "WriteLine",
							MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
												mod.CorLibTypes.Object),
							systemConsole);
			// Create System.Object::.ctor method reference. This is the default constructor
			var objectCtor = new MemberRefUser(mod, ".ctor",
							MethodSig.CreateInstance(mod.CorLibTypes.Void),
							mod.CorLibTypes.Object.TypeDefOrRef);

			CilBody body;
			// Create the base class
			var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef);
			// Add it to the module
			mod.Types.Add(bclass);
			// Create Ctor.Test.BaseClass constructor: BaseClass()
			var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to BaseClass
			bclass.Methods.Add(bctor);
			// Create method body and add a few instructions
			bctor.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called"));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create the Ctor.Test.Main type which derives from Ctor.Test.BaseClass
			var main = new TypeDefUser("Ctor.Test", "Main", bclass);
			// Add it to the module
			mod.Types.Add(main);
			// Create the static 'void Main()' method
			var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public | MethodAttributes.Static);
			// Set entry point to entryPoint and add it as a Ctor.Test.Main method
			mod.EntryPoint = entryPoint;
			main.Methods.Add(entryPoint);

			// Create first Ctor.Test.Main constructor: Main()
			var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to Main
			main.Methods.Add(ctor0);
			// Create method body and add a few instructions
			ctor0.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called"));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create second Ctor.Test.Main constructor: Main(int,string)
			var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String),
							MethodImplAttributes.IL | MethodImplAttributes.Managed,
							MethodAttributes.Public |
							MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
			// Add the method to Main
			main.Methods.Add(ctor1);
			// Create names for the arguments. This is optional. Since this is an instance method
			// (it's a constructor), the first arg is the 'this' pointer. The normal arguments
			// begin at index 1.
			ctor1.Parameters[1].CreateParamDef();
			ctor1.Parameters[1].ParamDef.Name = "count";
			ctor1.Parameters[2].CreateParamDef();
			ctor1.Parameters[2].ParamDef.Name = "name";
			// Create method body and add a few instructions
			ctor1.Body = body = new CilBody();
			// Make sure we call the base class' constructor
			body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
			body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}"));
			body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
			body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
			body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Create the entry point method body and add instructions to allocate a new Main()
			// object and call the two created ctors.
			entryPoint.Body = body = new CilBody();
			body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0));
			body.Instructions.Add(OpCodes.Pop.ToInstruction());
			body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345));
			body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
			body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1));
			body.Instructions.Add(OpCodes.Pop.ToInstruction());
			body.Instructions.Add(OpCodes.Ret.ToInstruction());

			// Save the assembly
			mod.Write(newFileName);
		}
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"C:\ctor-test.exe";

            // Create the module
            var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);
            // Create System.Object::.ctor method reference. This is the default constructor
            var objectCtor = new MemberRefUser(mod, ".ctor",
                                               MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                               mod.CorLibTypes.Object.TypeDefOrRef);

            CilBody body;
            // Create the base class
            var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef);

            // Add it to the module
            mod.Types.Add(bclass);
            // Create Ctor.Test.BaseClass constructor: BaseClass()
            var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to BaseClass
            bclass.Methods.Add(bctor);
            // Create method body and add a few instructions
            bctor.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create the Ctor.Test.Main type which derives from Ctor.Test.BaseClass
            var main = new TypeDefUser("Ctor.Test", "Main", bclass);

            // Add it to the module
            mod.Types.Add(main);
            // Create the static 'void Main()' method
            var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void),
                                               MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                               MethodAttributes.Public | MethodAttributes.Static);

            // Set entry point to entryPoint and add it as a Ctor.Test.Main method
            mod.EntryPoint = entryPoint;
            main.Methods.Add(entryPoint);

            // Create first Ctor.Test.Main constructor: Main()
            var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor0);
            // Create method body and add a few instructions
            ctor0.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create second Ctor.Test.Main constructor: Main(int,string)
            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor1);
            // Create names for the arguments. This is optional. Since this is an instance method
            // (it's a constructor), the first arg is the 'this' pointer. The normal arguments
            // begin at index 1.
            ctor1.Parameters[1].CreateParamDef();
            ctor1.Parameters[1].ParamDef.Name = "count";
            ctor1.Parameters[2].CreateParamDef();
            ctor1.Parameters[2].ParamDef.Name = "name";
            // Create method body and add a few instructions
            ctor1.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}"));
            body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create the entry point method body and add instructions to allocate a new Main()
            // object and call the two created ctors.
            entryPoint.Body = body = new CilBody();
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Save the assembly
            mod.Write(newFileName);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            // Create assembly and main module
            var assembly = new AssemblyDefUser("HelloWorld");
            var module   = new ModuleDefUser("HelloWorld.dll", null, new AssemblyRefUser("System.Runtime", new Version(4, 2, 2, 0)));

            module.RuntimeVersion = dnlib.DotNet.MD.MDHeaderRuntimeVersion.MS_CLR_40;

            // Create type Program
            var type = new TypeDefUser(
                @namespace: "HelloWorld",
                name: "Program",
                baseType: module.CorLibTypes.Object.TypeDefOrRef);

            // Set class attributes
            type.Attributes = TypeAttributes.Public | TypeAttributes.Class;

            // Create method Main
            var method = new MethodDefUser(
                name: "Main",
                methodSig: MethodSig.CreateStatic(
                    retType: module.CorLibTypes.Void,
                    argType1: new SZArraySig(module.CorLibTypes.String)));

            // Name parameter
            method.ParamDefs.Add(new ParamDefUser("args", 1));
            // Set method attributes
            method.Attributes = MethodAttributes.Public | MethodAttributes.Static;
            // Set attributes for method's implementation
            method.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;



            #region IMPLEMENTATION
            // Create reference to System.Console
            var consoleRef = new TypeRefUser(module, "System", "Console", new AssemblyRefUser("System.Console"));
            // Create reference to System.Console::WriteLine(string)
            var writeLineRef = new MemberRefUser(module, "WriteLine",
                                                 MethodSig.CreateStatic(
                                                     retType: module.CorLibTypes.Void,
                                                     argType1: module.CorLibTypes.String),
                                                 consoleRef);

            // Implement body of the Program::Main(string[]) method
            var body = new CilBody();
            body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "Hello World!"));
            body.Instructions.Add(Instruction.Create(OpCodes.Call, writeLineRef));
            body.Instructions.Add(Instruction.Create(OpCodes.Br, body.Instructions.First()));
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            method.Body = body;
            #endregion



            #region ASSEMBLE
            // Wire-it up!
            assembly.Modules.Add(module);
            module.Types.Add(type);
            type.Methods.Add(method);

            // Set entrypoint
            module.EntryPoint = method;

            // Store assembly
            module.Write(Path.Combine("Generated", "HelloWorld.dll"), new dnlib.DotNet.Writer.ModuleWriterOptions(module));
            #endregion
        }
Exemple #20
0
        void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e)
        {
            var writer = (ModuleWriterBase)sender;

            if (e.WriterEvent == ModuleWriterEvent.MDBeginAddResources)
            {
                ctx.Context.CheckCancellation();
                ctx.Context.Logger.Debug("Encrypting resources...");
                bool hasPacker = ctx.Context.Packer != null;

                List <EmbeddedResource> resources = ctx.Module.Resources.OfType <EmbeddedResource>().ToList();
                if (!hasPacker)
                {
                    ctx.Module.Resources.RemoveWhere(res => res is EmbeddedResource);
                }

                // move resources
                string    asmName = ctx.Name.RandomName(RenameMode.Letters);
                PublicKey pubKey  = null;
                if (writer.TheOptions.StrongNameKey != null)
                {
                    pubKey = PublicKeyBase.CreatePublicKey(writer.TheOptions.StrongNameKey.PublicKey);
                }
                var module = new ModuleDefUser(asmName + ".dll", Guid.NewGuid(), ctx.Module.CorLibTypes.AssemblyRef);
                module.Kind = ModuleKind.Dll;
                var assembly = new AssemblyDefUser(asmName, new Version(1, 0), pubKey);
                assembly.Modules.Add(module);

                module.Characteristics           = ctx.Module.Characteristics;
                module.Cor20HeaderFlags          = ctx.Module.Cor20HeaderFlags;
                module.Cor20HeaderRuntimeVersion = ctx.Module.Cor20HeaderRuntimeVersion;
                module.DllCharacteristics        = ctx.Module.DllCharacteristics;
                module.EncBaseId           = ctx.Module.EncBaseId;
                module.EncId               = ctx.Module.EncId;
                module.Generation          = ctx.Module.Generation;
                module.Machine             = ctx.Module.Machine;
                module.RuntimeVersion      = ctx.Module.RuntimeVersion;
                module.TablesHeaderVersion = ctx.Module.TablesHeaderVersion;
                module.RuntimeVersion      = ctx.Module.RuntimeVersion;

                var asmRef = new AssemblyRefUser(module.Assembly);
                if (pubKey == null)
                {
                    asmRef.Attributes &= ~AssemblyAttributes.PublicKey;             // ssdi: fix incorrect flags set in dnlib, "CS0009 .... -- Invalid public key." into VS2015, VS2017 msBuild
                }
                if (!hasPacker)
                {
                    foreach (var res in resources)
                    {
                        res.Attributes = ManifestResourceAttributes.Public;
                        module.Resources.Add(res);
                        ctx.Module.Resources.Add(new AssemblyLinkedResource(res.Name, asmRef, res.Attributes));
                    }
                }
                byte[] moduleBuff;
                using (var ms = new MemoryStream())
                {
                    module.Write(ms, new ModuleWriterOptions(ctx.Module)
                    {
                        StrongNameKey = writer.TheOptions.StrongNameKey
                    });
                    moduleBuff = ms.ToArray();
                }

                // compress
                moduleBuff = ctx.Context.Registry.GetService <ICompressionService>().Compress(
                    moduleBuff,
                    progress => ctx.Context.Logger.Progress((int)(progress * 10000), 10000));
                ctx.Context.Logger.EndProgress();
                ctx.Context.CheckCancellation();

                uint compressedLen = (uint)(moduleBuff.Length + 3) / 4;
                compressedLen = (compressedLen + 0xfu) & ~0xfu;
                var compressedBuff = new uint[compressedLen];
                Buffer.BlockCopy(moduleBuff, 0, compressedBuff, 0, moduleBuff.Length);
                Debug.Assert(compressedLen % 0x10 == 0);

                // encrypt
                uint keySeed = ctx.Random.NextUInt32() | 0x10;
                var  key     = new uint[0x10];
                uint state   = keySeed;
                for (int i = 0; i < 0x10; i++)
                {
                    state ^= state >> 13;
                    state ^= state << 25;
                    state ^= state >> 27;
                    key[i] = state;
                }

                var encryptedBuffer = new byte[compressedBuff.Length * 4];
                int buffIndex       = 0;
                while (buffIndex < compressedBuff.Length)
                {
                    uint[] enc = ctx.ModeHandler.Encrypt(compressedBuff, buffIndex, key);
                    for (int j = 0; j < 0x10; j++)
                    {
                        key[j] ^= compressedBuff[buffIndex + j];
                    }
                    Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40);
                    buffIndex += 0x10;
                }
                Debug.Assert(buffIndex == compressedBuff.Length);
                var size = (uint)encryptedBuffer.Length;

                TablesHeap tblHeap = writer.MetaData.TablesHeap;
                tblHeap.ClassLayoutTable[writer.MetaData.GetClassLayoutRid(ctx.DataType)].ClassSize = size;
                tblHeap.FieldTable[writer.MetaData.GetRid(ctx.DataField)].Flags |= (ushort)FieldAttributes.HasFieldRVA;
                encryptedResource = writer.Constants.Add(new ByteArrayChunk(encryptedBuffer), 8);

                // inject key values
                MutationHelper.InjectKeys(ctx.InitMethod,
                                          new[] { 0, 1 },
                                          new[] { (int)(size / 4), (int)(keySeed) });
            }
            else if (e.WriterEvent == ModuleWriterEvent.EndCalculateRvasAndFileOffsets)
            {
                TablesHeap tblHeap = writer.MetaData.TablesHeap;
                tblHeap.FieldRVATable[writer.MetaData.GetFieldRVARid(ctx.DataField)].RVA = (uint)encryptedResource.RVA;
            }
        }
Exemple #21
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample2.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample2", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample2", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);

            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            // Create 'System.Collections.ObjectModel.ReadOnlyCollection`1' type ref
            var roCollectionRef = new TypeRefUser(mod, "System.Collections.ObjectModel", "ReadOnlyCollection`1", assemblyRef);
            // Create 'ReadOnlyCollection<!!0>' signature for return type
            var roCollectionSig = new GenericInstSig(new ClassSig(roCollectionRef), new GenericMVar(0));             // Return type

            // Create 'ReadOnlyCollection<Int32>' type spec
            var roCollectionTypeSpec = new TypeSpecUser(new GenericInstSig(new ClassSig(roCollectionRef), mod.CorLibTypes.Int32));
            // Create 'ReadOnlyCollection<Int32>.get_Count()' method reference
            var roCollectionGetCount = new MemberRefUser(mod, "get_Count",
                                                         MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                                                         roCollectionTypeSpec);

            // Create 'System.Array' type ref
            var arrayRef = new TypeRefUser(mod, "System", "Array", assemblyRef);
            // Create 'ReadOnlyCollection<T> Array.AsReadOnly<T>(T[] array)' method reference
            // Apparently CreateStaticGeneric should be used only if at least one GenericMVar is used? Not 100% certain.
            var asReadOnly = new MemberRefUser(mod, "AsReadOnly",
                                               MethodSig.CreateStaticGeneric(1, roCollectionSig, new SZArraySig(new GenericMVar(0))),
                                               arrayRef);
            // Create 'Array.AsReadOnly<Int32>' method spec
            var asReadOnlySpec = new MethodSpecUser(asReadOnly,
                                                    new GenericInstMethodSig(mod.CorLibTypes.Int32));

            // Create 'ReadOnlyCollection<Int32>' signature for local
            var roCollectionInt32 = roCollectionTypeSpec.TryGetGenericInstSig();

            // Method body locals
            IList <Local> locals = new List <Local>();

            locals.Add(new Local(new SZArraySig(mod.CorLibTypes.Int32))); // local[0]: Int32[]
            locals.Add(new Local(roCollectionInt32));                     // local[1]: class [mscorlib]System.Collections.ObjectModel.ReadOnlyCollection`1<Int32>

            var body = new CilBody(true, new List <Instruction>(), new List <ExceptionHandler>(), locals);

            // array = new Int32[2];
            body.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction());
            body.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());             // Store array to local[0]

            // array[0] = 5;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction());
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // array[1] = 111;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(111));
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // collection = Array.AsReadOnly<Int32>(array)
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(asReadOnlySpec));
            body.Instructions.Add(OpCodes.Stloc_1.ToInstruction());

            // Console.WriteLine("Count: {0}", collection.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(roCollectionGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
Exemple #22
0
        public static void Run()
        {
            // 创建一个新模块。 传入的字符串是模块的名称,而不是文件名。
            ModuleDef mod = new ModuleDefUser("MyModule.exe");

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;

            //将模块添加到装配中
            AssemblyDef asm = new AssemblyDefUser("MyAssembly", new Version(1, 2, 3, 4), null, "");

            asm.Modules.Add(mod);

            //添加.NET资源
            //         byte[] resourceData = Encoding.UTF8.GetBytes("Hello, world!");
            //mod.Resources.Add(new EmbeddedResource("My.Resource", resourceData,
            //				ManifestResourceAttributes.Private));

            // 添加启动类型。 它派生自System.Object。
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // 将类型添加到模块
            mod.Types.Add(startUpType);

            // 创建入口点方法
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Void, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // 命名第一个参数(参数0是返回类型)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // 将方法添加到启动类型
            startUpType.Methods.Add(entryPoint);
            // 设置模块入口点
            mod.EntryPoint = entryPoint;

            // 创建TypeRef到System.Console
            TypeRef consoleRef = new TypeRefUser(mod, "System", "Console", mod.CorLibTypes.AssemblyRef);
            // 创建方法ref为'System.Void System.Console :: WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(mod, "WriteLine",
                                                        MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String),
                                                        consoleRef);

            //System.Console::ReadKey()'
            MemberRef memberRefReadLine = new MemberRefUser(
                mod,
                "ReadLine",
                //MethodSig.CreateStatic(mod.CorLibTypes.Void),
                MethodSig.CreateStatic(mod.CorLibTypes.String),
                consoleRef
                );

            // 创建TypeRef到System.Console
            TypeRef int32Ref = new TypeRefUser(mod, "System", "Int32", mod.CorLibTypes.AssemblyRef);

            MemberRef memberRefParse = new MemberRefUser(
                mod,
                "Parse",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, mod.CorLibTypes.String),
                int32Ref
                );

            //string[mscorlib] System.String::Concat(object[])
            TypeRef stringRef = new TypeRefUser(mod, "System", "String", mod.CorLibTypes.AssemblyRef);

            MemberRef memberRefSystemStringConcat = new MemberRefUser(
                mod,
                "Concat",
                MethodSig.CreateStatic(mod.CorLibTypes.String, new SZArraySig(mod.CorLibTypes.Object)),
                stringRef
                );


            // 将CIL方法体添加到入口点方法
            CilBody epBody = new CilBody();

            entryPoint.Body = epBody;
            epBody.Variables.Add(new Local(mod.CorLibTypes.String, "s1"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.Int32, "i1"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.Int32, "i2"));
            epBody.Variables.Add(new Local(mod.CorLibTypes.String, "s2"));


            //: nop
            //: ldstr     "xyzs"
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("小宇专属"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            //: call      string [mscorlib]System.Console::ReadLine()
            //: stloc.0
            //: ldloc.0
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            epBody.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: call      int32 [mscorlib]System.Int32::Parse(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefParse));
            //: stloc.1
            epBody.Instructions.Add(OpCodes.Stloc_1.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: call      int32 [mscorlib]System.Int32::Parse(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefParse));
            //: stloc.2
            epBody.Instructions.Add(OpCodes.Stloc_2.ToInstruction());
            //: ldc.i4.5
            epBody.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction());
            //: newarr    [mscorlib]System.Object
            epBody.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Object));
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.0
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            //: ldloc.1
            epBody.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.1
            epBody.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            //: ldstr     "+"
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("+"));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.2
            epBody.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction());
            //: ldloc.2
            epBody.Instructions.Add(OpCodes.Ldloc_2.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.3
            epBody.Instructions.Add(OpCodes.Ldc_I4_3.ToInstruction());
            //: ldstr     "="
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("="));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: dup
            epBody.Instructions.Add(OpCodes.Dup.ToInstruction());
            //: ldc.i4.4
            epBody.Instructions.Add(OpCodes.Ldc_I4_4.ToInstruction());
            //: ldloc.1
            epBody.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            //: ldloc.2
            epBody.Instructions.Add(OpCodes.Ldloc_2.ToInstruction());
            //: add
            epBody.Instructions.Add(OpCodes.Add.ToInstruction());
            //: box       [mscorlib]System.Int32
            epBody.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            //: stelem.ref
            epBody.Instructions.Add(OpCodes.Stelem_Ref.ToInstruction());
            //: call      string [mscorlib]System.String::Concat(object[])
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefSystemStringConcat));
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: ldstr     "xyzs"
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("xyzs"));
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: call      string [mscorlib]System.Console::ReadLine()
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(memberRefReadLine));
            //: stloc.3
            epBody.Instructions.Add(OpCodes.Stloc_3.ToInstruction());
            //: ldloc.3
            epBody.Instructions.Add(OpCodes.Ldloc_3.ToInstruction());
            //: call      void [mscorlib]System.Console::WriteLine(string)
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            //: nop
            epBody.Instructions.Add(OpCodes.Nop.ToInstruction());
            //: ret
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 将程序集保存到磁盘上的文件中
            mod.Write(@"saved-assembly31.exe");
        }
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = "GenericExample3.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample3", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample3", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create a type with 2 generic parameters, A and B
            // Would look like: public class GClass<A, B>
            var genericType = new TypeDefUser("My.Namespace", "GClass", mod.CorLibTypes.Object.TypeDefOrRef);
            genericType.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
                TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            genericType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add generic type to module
            mod.Types.Add(genericType);

            // Note: NestedPublic instead of Public, blank namespace
            // Would look like: public class GSubClass<A, B, C>
            var genericSubType = new TypeDefUser("", "GSubClass", mod.CorLibTypes.Object.TypeDefOrRef);
            genericSubType.Attributes = TypeAttributes.NestedPublic | TypeAttributes.AutoLayout |
                TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            // Need to add the 2 generic parameters from the nested-parent class, A and B
            genericSubType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericSubType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add a generic parameter specific to this nested class, C
            genericSubType.GenericParameters.Add(new GenericParamUser(2, GenericParamAttributes.NonVariant, "C"));

            // public void GSubClass<A, B, C>.SomeMethod(B arg1, C arg2) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeMethod(!1, !2) { ... }
            var someMethod = new MethodDefUser("SomeMethod",
                MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(1), new GenericVar(2)));
            someMethod.Attributes = MethodAttributes.Public;
            someMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            genericSubType.Methods.Add(someMethod);

            // Create method with a method generic parameter (GenericMVar)
            // public void GSubClass<A, B, C>.SomeOtherMethod<D>(D arg1, A arg2, C arg3) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeOtherMethod<!!0>(!!0, !0, !2) { ... }
            var someGenericMethod = new MethodDefUser("SomeOtherMethod",
                MethodSig.CreateInstanceGeneric(1, mod.CorLibTypes.Void, new GenericMVar(0), new GenericVar(0), new GenericVar(2)));
            someGenericMethod.Attributes = MethodAttributes.Public;
            someGenericMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Create GenericParam for !!0
            someGenericMethod.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "D"));
            genericSubType.Methods.Add(someGenericMethod);

            // Add as nested type
            genericType.NestedTypes.Add(genericSubType);

            someMethod.Body = new CilBody();
            someMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            someGenericMethod.Body = new CilBody();
            someGenericMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = new CilBody();
            entryPoint.Body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            entryPoint.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            mod.Write(newFileName);
        }
        public static void Run()
        {
            // 这是将要创建的文件
            string newFileName = @"ctor-test.exe";

            // 创建模块
            var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // 这是一个控制台应用程序
            mod.Kind = ModuleKind.Console;
            // 创建程序集并将创建的模块添加到它
            new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // 创建System.Console类型引用
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // 创建'void System.Console.WriteLine(string,object)'方法引用
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);
            // 创建System.Object ::.ctor方法引用。这是默认构造函数
            var objectCtor = new MemberRefUser(mod, ".ctor",
                                               MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                               mod.CorLibTypes.Object.TypeDefOrRef);

            CilBody body;
            // 创建基类
            var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef);

            // 将其添加到模块中
            mod.Types.Add(bclass);
            // 创建Ctor.Test.Base类构造函数:Base Class()
            var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // 将方法添加到BaseClass
            bclass.Methods.Add(bctor);
            // 创建方法体并添加一些指令
            bctor.Body = body = new CilBody();
            // 确保我们调用基类的构造函数
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // 创建从Ctor.Test.BaseClass派生的Ctor.Test.Main类型
            var main = new TypeDefUser("Ctor.Test", "Main", bclass);

            //将其添加到模块中
            mod.Types.Add(main);
            //创建静态'void Main()'方法
            var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void),
                                               MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                               MethodAttributes.Public | MethodAttributes.Static);

            // Set entry point to entryPoint and add it as a Ctor.Test.Main method
            mod.EntryPoint = entryPoint;
            main.Methods.Add(entryPoint);

            // Create first Ctor.Test.Main constructor: Main()
            var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor0);
            // Create method body and add a few instructions
            ctor0.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create second Ctor.Test.Main constructor: Main(int,string)
            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor1);
            // Create names for the arguments. This is optional. Since this is an instance method
            // (it's a constructor), the first arg is the 'this' pointer. The normal arguments
            // begin at index 1.
            ctor1.Parameters[1].CreateParamDef();
            ctor1.Parameters[1].ParamDef.Name = "count";
            ctor1.Parameters[2].CreateParamDef();
            ctor1.Parameters[2].ParamDef.Name = "name";
            // Create method body and add a few instructions
            ctor1.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}"));
            body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create the entry point method body and add instructions to allocate a new Main()
            // object and call the two created ctors.
            entryPoint.Body = body = new CilBody();
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Save the assembly
            mod.Write(newFileName);
        }
Exemple #25
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = "GenericExample3.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample3", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample3", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create a type with 2 generic parameters, A and B
            // Would look like: public class GClass<A, B>
            var genericType = new TypeDefUser("My.Namespace", "GClass", mod.CorLibTypes.Object.TypeDefOrRef);

            genericType.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            genericType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add generic type to module
            mod.Types.Add(genericType);

            // Note: NestedPublic instead of Public, blank namespace
            // Would look like: public class GSubClass<A, B, C>
            var genericSubType = new TypeDefUser("", "GSubClass", mod.CorLibTypes.Object.TypeDefOrRef);

            genericSubType.Attributes = TypeAttributes.NestedPublic | TypeAttributes.AutoLayout |
                                        TypeAttributes.Class | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit;
            // Need to add the 2 generic parameters from the nested-parent class, A and B
            genericSubType.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "A"));
            genericSubType.GenericParameters.Add(new GenericParamUser(1, GenericParamAttributes.NonVariant, "B"));
            // Add a generic parameter specific to this nested class, C
            genericSubType.GenericParameters.Add(new GenericParamUser(2, GenericParamAttributes.NonVariant, "C"));

            // public void GSubClass<A, B, C>.SomeMethod(B arg1, C arg2) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeMethod(!1, !2) { ... }
            var someMethod = new MethodDefUser("SomeMethod",
                                               MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(1), new GenericVar(2)));

            someMethod.Attributes     = MethodAttributes.Public;
            someMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            genericSubType.Methods.Add(someMethod);

            // Create method with a method generic parameter (GenericMVar)
            // public void GSubClass<A, B, C>.SomeOtherMethod<D>(D arg1, A arg2, C arg3) { ... }
            // or: public void GSubClass<!0, !1, !2>.SomeOtherMethod<!!0>(!!0, !0, !2) { ... }
            var someGenericMethod = new MethodDefUser("SomeOtherMethod",
                                                      MethodSig.CreateInstanceGeneric(1, mod.CorLibTypes.Void, new GenericMVar(0), new GenericVar(0), new GenericVar(2)));

            someGenericMethod.Attributes     = MethodAttributes.Public;
            someGenericMethod.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Create GenericParam for !!0
            someGenericMethod.GenericParameters.Add(new GenericParamUser(0, GenericParamAttributes.NonVariant, "D"));
            genericSubType.Methods.Add(someGenericMethod);

            // Add as nested type
            genericType.NestedTypes.Add(genericSubType);

            someMethod.Body = new CilBody();
            someMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            someGenericMethod.Body = new CilBody();
            someGenericMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = new CilBody();
            entryPoint.Body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            entryPoint.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            mod.Write(newFileName);
        }
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample2.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample2", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample2", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                            MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                mod.CorLibTypes.Object),
                            systemConsole);

            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            // Create 'System.Collections.ObjectModel.ReadOnlyCollection`1' type ref
            var roCollectionRef = new TypeRefUser(mod, "System.Collections.ObjectModel", "ReadOnlyCollection`1", assemblyRef);
            // Create 'ReadOnlyCollection<!!0>' signature for return type
            var roCollectionSig = new GenericInstSig(new ClassSig(roCollectionRef), new GenericMVar(0)); // Return type

            // Create 'ReadOnlyCollection<Int32>' type spec
            var roCollectionTypeSpec = new TypeSpecUser(new GenericInstSig(new ClassSig(roCollectionRef), mod.CorLibTypes.Int32));
            // Create 'ReadOnlyCollection<Int32>.get_Count()' method reference
            var roCollectionGetCount = new MemberRefUser(mod, "get_Count",
                MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                roCollectionTypeSpec);

            // Create 'System.Array' type ref
            var arrayRef = new TypeRefUser(mod, "System", "Array", assemblyRef);
            // Create 'ReadOnlyCollection<T> Array.AsReadOnly<T>(T[] array)' method reference
            // Apparently CreateStaticGeneric should be used only if at least one GenericMVar is used? Not 100% certain.
            var asReadOnly = new MemberRefUser(mod, "AsReadOnly",
                            MethodSig.CreateStaticGeneric(1, roCollectionSig, new SZArraySig(new GenericMVar(0))),
                            arrayRef);
            // Create 'Array.AsReadOnly<Int32>' method spec
            var asReadOnlySpec = new MethodSpecUser(asReadOnly,
                new GenericInstMethodSig(mod.CorLibTypes.Int32));

            // Create 'ReadOnlyCollection<Int32>' signature for local
            var roCollectionInt32 = roCollectionTypeSpec.TryGetGenericInstSig();

            // Method body locals
            IList<Local> locals = new List<Local>();
            locals.Add(new Local(new SZArraySig(mod.CorLibTypes.Int32))); // local[0]: Int32[]
            locals.Add(new Local(roCollectionInt32)); // local[1]: class [mscorlib]System.Collections.ObjectModel.ReadOnlyCollection`1<Int32>

            var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals);

            // array = new Int32[2];
            body.Instructions.Add(OpCodes.Ldc_I4_2.ToInstruction());
            body.Instructions.Add(OpCodes.Newarr.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store array to local[0]

            // array[0] = 5;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_5.ToInstruction());
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // array[1] = 111;
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4_1.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(111));
            body.Instructions.Add(OpCodes.Stelem_I4.ToInstruction());

            // collection = Array.AsReadOnly<Int32>(array)
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(asReadOnlySpec));
            body.Instructions.Add(OpCodes.Stloc_1.ToInstruction());

            // Console.WriteLine("Count: {0}", collection.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_1.ToInstruction());
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(roCollectionGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample1.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(),
                new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));
            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                    TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                            MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                            MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                mod.CorLibTypes.Object),
                            systemConsole);

            //
            // Method 1: Create List<String> inst signature by importing (easy way)
            // --------------------------------------------------------------------
            //Importer importer = new Importer(mod);
            //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>));

            //
            // Method 2: Create List<String> inst signature manually (harder way)
            // ------------------------------------------------------------------
            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            var listRef = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef);
            // Create the GenericInstSig from a ClassSig with <String> generic arg
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String);

            // Create TypeSpec from GenericInstSig
            var listTypeSpec = new TypeSpecUser(listGenericInstSig);
            // Create System.Collections.Generic.List<String>::.ctor method reference
            var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                listTypeSpec);

            // Create Add(!0) method reference, !0 signifying first generic argument of declaring type
            // In this case, would be Add(String item)
            // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0))
            var listAdd = new MemberRefUser(mod, "Add",
                MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)),
                listTypeSpec);

            var listGetCount = new MemberRefUser(mod, "get_Count",
                MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                listTypeSpec);

            IList<Local> locals = new List<Local>();
            locals.Add(new Local(listGenericInstSig)); // local[0]: class [mscorlib]System.Collections.Generic.List`1<string>

            var body = new CilBody(true, new List<Instruction>(), new List<ExceptionHandler>(), locals);
            // Call the list .ctor
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store list to local[0]

            // list.Add("Item 1")
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd));

            // WriteLine("Array: {0}", list.ToArray());
            //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}"));
            //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray));
            //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // WriteLine("Count: {0}", list.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample1.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);

            //
            // Method 1: Create List<String> inst signature by importing (easy way)
            // --------------------------------------------------------------------
            //Importer importer = new Importer(mod);
            //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>));

            //
            // Method 2: Create List<String> inst signature manually (harder way)
            // ------------------------------------------------------------------
            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            var listRef     = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef);
            // Create the GenericInstSig from a ClassSig with <String> generic arg
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String);

            // Create TypeSpec from GenericInstSig
            var listTypeSpec = new TypeSpecUser(listGenericInstSig);
            // Create System.Collections.Generic.List<String>::.ctor method reference
            var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                             listTypeSpec);

            // Create Add(!0) method reference, !0 signifying first generic argument of declaring type
            // In this case, would be Add(String item)
            // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0))
            var listAdd = new MemberRefUser(mod, "Add",
                                            MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)),
                                            listTypeSpec);

            var listGetCount = new MemberRefUser(mod, "get_Count",
                                                 MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                                                 listTypeSpec);

            IList <Local> locals = new List <Local>();

            locals.Add(new Local(listGenericInstSig));             // local[0]: class [mscorlib]System.Collections.Generic.List`1<string>

            var body = new CilBody(true, new List <Instruction>(), new List <ExceptionHandler>(), locals);

            // Call the list .ctor
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());             // Store list to local[0]

            // list.Add("Item 1")
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd));

            // WriteLine("Array: {0}", list.ToArray());
            //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}"));
            //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray));
            //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // WriteLine("Count: {0}", list.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());             // Load list from local[0]
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get<CompressorContext>(context, ContextKey);
            if (ctx == null) {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];
            ctx.OriginModuleDef = originModule;
            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);
            ctx.Assembly.Modules.Insert(0, stubModule);
            stubModule.Characteristics = originModule.Characteristics;
            stubModule.Cor20HeaderFlags = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics = originModule.DllCharacteristics;
            stubModule.EncBaseId = originModule.EncBaseId;
            stubModule.EncId = originModule.EncId;
            stubModule.Generation = originModule.Generation;
            stubModule.Kind = ctx.Kind;
            stubModule.Machine = originModule.Machine;
            stubModule.RuntimeVersion = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources = originModule.Win32Resources;
            ImportAssemblyTypeReferences(originModule, stubModule);

            InjectStub(context, ctx, parameters, stubModule);

            var snKey = context.Annotations.Get<StrongNameKey>(originModule, Marker.SNKey);
            using (var ms = new MemoryStream()) {
                stubModule.Write(ms, new ModuleWriterOptions(stubModule, new KeyInjector(ctx)) {
                    StrongNameKey = snKey
                });
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx, originModule));
            }
        }
Exemple #30
0
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <CompressorContext>(context, ContextKey);

            if (ctx == null)
            {
                context.Logger.Error("No executable module!");
                throw new ConfuserException(null);
            }

            ModuleDefMD originModule = context.Modules[ctx.ModuleIndex];

            ctx.OriginModuleDef = originModule;

            var stubModule = new ModuleDefUser(ctx.ModuleName, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            if (ctx.CompatMode)
            {
                var assembly = new AssemblyDefUser(originModule.Assembly);
                assembly.Name += ".cr";
                assembly.Modules.Add(stubModule);
                var targetFramework = originModule.Assembly.CustomAttributes.FirstOrDefault(ca => ca.TypeFullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
                if (targetFramework != null)
                {
                    var attrType = stubModule.CorLibTypes.GetTypeRef("System.Runtime.Versioning", "TargetFrameworkAttribute");
                    var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void, stubModule.CorLibTypes.String);
                    assembly.CustomAttributes.Add(new CustomAttribute(
                                                      new MemberRefUser(stubModule, ".ctor", ctorSig, attrType), new CAArgument[] { new CAArgument(stubModule.CorLibTypes.String, targetFramework.ConstructorArguments[0].Value) }));
                }
            }
            else
            {
                ctx.Assembly.Modules.Insert(0, stubModule);
                ImportAssemblyTypeReferences(originModule, stubModule);
            }
            stubModule.Characteristics           = originModule.Characteristics;
            stubModule.Context                   = originModule.Context;
            stubModule.Cor20HeaderFlags          = originModule.Cor20HeaderFlags;
            stubModule.Cor20HeaderRuntimeVersion = originModule.Cor20HeaderRuntimeVersion;
            stubModule.DllCharacteristics        = originModule.DllCharacteristics;
            stubModule.EncBaseId                 = originModule.EncBaseId;
            stubModule.EncId               = originModule.EncId;
            stubModule.Generation          = originModule.Generation;
            stubModule.Kind                = ctx.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;

            InjectStub(context, ctx, parameters, stubModule);

            var snKey       = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNKey);
            var snPubKey    = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNPubKey);
            var snDelaySig  = context.Annotations.Get <bool>(originModule, Marker.SNDelaySig, false);
            var snSigKey    = context.Annotations.Get <StrongNameKey>(originModule, Marker.SNSigKey);
            var snPubSigKey = context.Annotations.Get <StrongNamePublicKey>(originModule, Marker.SNSigPubKey);

            using (var ms = new MemoryStream()) {
                var options = new ModuleWriterOptions(stubModule)
                {
                    StrongNameKey       = snKey,
                    StrongNamePublicKey = snPubKey,
                    DelaySign           = snDelaySig
                };
                var injector = new KeyInjector(ctx);
                options.WriterEvent += injector.WriterEvent;

                stubModule.Write(ms, options);
                context.CheckCancellation();
                ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, snPubKey, snSigKey, snPubKey, snDelaySig, new StubProtection(ctx, originModule));
            }
        }