Пример #1
0
        static void Execute(ILSpyTreeNode[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var newModule = new ModuleDefUser();

            var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, MainWindow.Instance.CurrentLanguage);

            data.CanShowClrVersion = true;
            var win = new AssemblyOptionsDlg();

            win.Title       = CMD_NAME;
            win.DataContext = data;
            win.Owner       = MainWindow.Instance;
            if (win.ShowDialog() != true)
            {
                return;
            }

            var cmd = new CreateAssemblyCommand(newModule, data.CreateAssemblyOptions());

            UndoCommandManager.Instance.Add(cmd);
            MainWindow.Instance.JumpToReference(cmd.asmNodeCreator.AssemblyTreeNode);
        }
Пример #2
0
        static void Execute(Lazy <IUndoCommandService> undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var newModule = new ModuleDefUser();

            var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, appService.DecompilerService);

            data.CanShowClrVersion = true;
            var win = new AssemblyOptionsDlg();

            win.Title       = dnSpy_AsmEditor_Resources.CreateAssemblyCommand2;
            win.DataContext = data;
            win.Owner       = appService.MainWindow;
            if (win.ShowDialog() != true)
            {
                return;
            }

            var cmd = new CreateAssemblyCommand(undoCommandService.Value, appService.DocumentTreeView, newModule, data.CreateAssemblyOptions());

            undoCommandService.Value.Add(cmd);
            appService.DocumentTabService.FollowReference(cmd.fileNodeCreator.DocumentNode);
        }
Пример #3
0
        /// <summary>
        /// Generate a test assembly.
        /// </summary>
        /// <returns>Assembly</returns>
        public AssemblyDef Generate()
        {
            var module = new ModuleDefUser(_moduleName);

            module.Kind = ModuleKind.Console;

            var assembly = new AssemblyDefUser(_assemblyName, _assemblyVersion);

            assembly.Modules.Add(module);

            var mainType = this.CreateMainType(module);

            module.Types.Add(mainType);

            var generatedMethods = new List <MethodDef>();

            foreach (var kvp in _methods)
            {
                var name         = kvp.Key;
                var instructions = kvp.Value(module, mainType);
                var method       = CreateVirtualizableMethod(module, name, instructions);

                mainType.Methods.Add(method);
                generatedMethods.Add(method);
            }

            var entryPoint = this.CreateEntryPoint(module, generatedMethods);

            mainType.Methods.Add(entryPoint);

            return(assembly);
        }
Пример #4
0
        static ModuleDef CreateModuleDef(string name, Guid mvid, ClrVersion clrVersion, ModuleDef?existingModule)
        {
            var clrValues = ClrVersionValues.GetValues(clrVersion);

            if (clrValues is null)
            {
                throw new ArgumentNullException(nameof(clrVersion));
            }
            ModuleDef module;

            if (existingModule is null)
            {
                module = new ModuleDefUser(name, mvid, clrValues.CorLibRef);
            }
            else
            {
                module      = existingModule;
                module.Name = name;
                module.Mvid = mvid;
                OverwriteAssembly(module.CorLibTypes.AssemblyRef, clrValues.CorLibRef);
            }
            module.UpdateRowId(module);
            module.RuntimeVersion            = clrValues.RuntimeVersion;
            module.Cor20HeaderRuntimeVersion = clrValues.Cor20HeaderRuntimeVersion;
            module.TablesHeaderVersion       = clrValues.TablesHeaderVersion;
            module.Location = string.Empty;
            return(module);
        }
Пример #5
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];
            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;

            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();
                base.ProtectStub(context, context.OutputPaths[ctx.ModuleIndex], ms.ToArray(), snKey, new StubProtection(ctx));
            }
        }
Пример #6
0
        static void Execute(Lazy <IUndoCommandManager> undoCommandManager, IAppWindow appWindow, IFileTreeNodeData[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var newModule = new ModuleDefUser();

            var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, appWindow.LanguageManager);

            data.CanShowClrVersion = true;
            var win = new AssemblyOptionsDlg();

            win.Title       = dnSpy_AsmEditor_Resources.CreateAssemblyCommand2;
            win.DataContext = data;
            win.Owner       = appWindow.MainWindow;
            if (win.ShowDialog() != true)
            {
                return;
            }

            var cmd = new CreateAssemblyCommand(undoCommandManager.Value, appWindow.FileTreeView, newModule, data.CreateAssemblyOptions());

            undoCommandManager.Value.Add(cmd);
            appWindow.FileTabManager.FollowReference(cmd.fileNodeCreator.DnSpyFileNode);
        }
Пример #7
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");
        }
Пример #8
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);
        }
Пример #9
0
        private static ModuleDefUser CreateStub(ModuleDef originModule)
        {
            var stubModule =
                new ModuleDefUser(originModule.Name, originModule.Mvid, originModule.CorLibTypes.AssemblyRef);

            originModule.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                = originModule.Kind;
            stubModule.Machine             = originModule.Machine;
            stubModule.TablesHeaderVersion = originModule.TablesHeaderVersion;
            stubModule.Win32Resources      = originModule.Win32Resources;
            stubModule.RuntimeVersion      = originModule.RuntimeVersion;
            stubModule.Is32BitRequired     = originModule.Is32BitRequired;
            stubModule.Is32BitPreferred    = originModule.Is32BitPreferred;

            return(stubModule);
        }
Пример #10
0
        /// <summary>
        /// Checks whether the type matches an expected type
        /// </summary>
        /// <param name="module">Module</param>
        /// <param name="name">Type name</param>
        /// <param name="expectedType">Expected type</param>
        /// <returns></returns>
        public static bool CheckType(ModuleDef?module, string name, TypeRef expectedType)
        {
            if (module is null)
            {
                module = new ModuleDefUser();
            }
            var tr = TypeNameParser.ParseReflection(module, name, null);

            if (tr is null)
            {
                return(false);
            }

            var flags = AssemblyNameComparerFlags.All & ~AssemblyNameComparerFlags.Version;

            if (!new AssemblyNameComparer(flags).Equals(tr.DefinitionAssembly, expectedType.DefinitionAssembly))
            {
                return(false);
            }

            if (!new SigComparer().Equals(tr, expectedType))
            {
                return(false);
            }

            return(true);
        }
Пример #11
0
 public GetLocalsAssemblyBuilder(LanguageExpressionCompiler language, MethodDef method, ImmutableArray <string> localVariableNames, ImmutableArray <string> parameterNames)
 {
     this.language           = language;
     sourceMethod            = method;
     this.localVariableNames = localVariableNames;
     this.parameterNames     = parameterNames;
     methodNameIndex         = 0;
     lastMethodSig           = null;
     localAndMethodBuilder   = new List <DSEELocalAndMethod>();
     if (method.Parameters.Count == 0 && (method.Body?.Variables.Count ?? 0) == 0)
     {
         generatedModule = null;
         getLocalsType   = null;
     }
     else
     {
         var methodModule = method.Module;
         generatedModule = new ModuleDefUser(Guid.NewGuid().ToString(), Guid.NewGuid(), methodModule.CorLibTypes.AssemblyRef);
         generatedModule.RuntimeVersion = methodModule.RuntimeVersion;
         generatedModule.Machine        = methodModule.Machine;
         var asm = new AssemblyDefUser(Guid.NewGuid().ToString());
         asm.Modules.Add(generatedModule);
         getLocalsType            = new TypeDefUser(getLocalsTypeNamespace, getLocalsTypeName, generatedModule.CorLibTypes.Object.TypeDefOrRef);
         getLocalsType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.SpecialName | TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass;
         generatedModule.Types.Add(getLocalsType);
         foreach (var gp in method.DeclaringType.GenericParameters)
         {
             getLocalsType.GenericParameters.Add(Clone(gp));
         }
     }
 }
Пример #12
0
        internal object Invoke(object[] parameters)
        {
            var assemblyDef = new AssemblyDefUser("NoFuserExAssembly");

            Logger.Verbose($"Assembly created: {assemblyDef.Name}");
            var moduleDef = new ModuleDefUser("NoFuserExModule");

            Logger.Verbose($"Module created: {moduleDef.Name}");
            assemblyDef.Modules.Add(moduleDef);
            Logger.VeryVerbose("Module added to the assembly.");

            moduleDef.Types.Add(typeDef);
            Logger.VeryVerbose("Type injected to module.");

            foreach (var type in moduleDef.GetTypes())
            {
                foreach (var method in type.Methods)
                {
                    if (method.DeclaringType.Name != methodDef.DeclaringType.Name)
                    {
                        continue;
                    }
                    if (method.Name != methodDef.Name)
                    {
                        continue;
                    }
                    methodToInvoke = method.MDToken.ToInt32();
                    Logger.VeryVerbose($"Token found: {methodToInvoke}");
                }
            }

            if (methodToInvoke == 0)
            {
                Logger.Exception(new Exception("Error searching the token."));
            }

            using (var stream = new MemoryStream()) {
                assemblyDef.Write(stream, new ModuleWriterOptions {
                    Logger = DummyLogger.NoThrowInstance
                });
                Logger.VeryVerbose("Assembly writed.");

                var assembly = Assembly.Load(stream.ToArray());
                Logger.VeryVerbose("Created assembly loaded.");

                var module = assembly.ManifestModule;
                var method = module.ResolveMethod(methodToInvoke);
                Logger.VeryVerbose($"Method to invoke: {method.Name}");

                if (method.IsStatic)
                {
                    return(method.Invoke(null, parameters));
                }

                Logger.Verbose("Method is not static, creating instance...");
                var instance = Activator.CreateInstance(method.DeclaringType);
                return(method.Invoke(instance, parameters));
            }
        }
Пример #13
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);
            }
            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));
            }
        }
Пример #14
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());
        }
Пример #15
0
        public static MethodDef newfunc(ModuleDefUser mod, string name, CorLibTypeSig returntype, TypeSig[] arguments)
        {
            MethodDefUser newfunction = new MethodDefUser(name, MethodSig.CreateStatic(returntype, arguments));

            newfunction.Attributes     = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            newfunction.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.AggressiveOptimization;
            startUpType.Methods.Add(newfunction);
            newfunction.Body = new CilBody();
            return(newfunction);
        }
Пример #16
0
        public static TypeSig[] argumentsFromStrings(ModuleDefUser mod, string[] names)
        {
            List <TypeSig> arguments = new List <TypeSig>();

            foreach (string argname in names)
            {
                arguments.Add(typeFromString(mod, argname));
            }
            return(arguments.ToArray());
        }
Пример #17
0
        /// <summary>
        /// Creates a module.
        /// </summary>
        /// <returns></returns>
        public static ModuleDef CreateModule()
        {
            ModuleDef module = new ModuleDefUser(Guid.NewGuid().ToString());
            module.Kind = ModuleKind.Dll;

            // Add the module to an assembly
            AssemblyDef assembly = new AssemblyDefUser(Guid.NewGuid().ToString(), new Version(1, 0), null, CultureInfo.InvariantCulture.DisplayName);
            assembly.Modules.Add(module);

            return module;
        }
Пример #18
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");
		}
Пример #19
0
        public static ModuleDefUser newmod(string name)
        {
            var mod = new ModuleDefUser(name);

            mod.RuntimeVersion = "v4.0.30319";
            mod.Kind           = ModuleKind.Console;
            var asm = new AssemblyDefUser("PointySnakeAssembly", new Version(0, 0, 0, 0), null, "en_us");

            asm.Modules.Add(mod);
            return(mod);
        }
Пример #20
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();
        }
Пример #21
0
        /// <summary>
        /// Creates a module.
        /// </summary>
        /// <returns></returns>
        public static ModuleDef CreateModule()
        {
            ModuleDef module = new ModuleDefUser(Guid.NewGuid().ToString());

            module.Kind = ModuleKind.Dll;

            // Add the module to an assembly
            AssemblyDef assembly = new AssemblyDefUser(Guid.NewGuid().ToString(), new Version(1, 0), null, CultureInfo.InvariantCulture.DisplayName);

            assembly.Modules.Add(module);

            return(module);
        }
Пример #22
0
        private static bool CompareTypes(Func <ModuleDef, TypeSig> a, Func <ModuleDef, TypeSig> b)
        {
            if (a == b)
            {
                return(true);
            }
            if (a == null || b == null)
            {
                return(false);
            }
            ModuleDef module = new ModuleDefUser();

            return(new SigComparer(SigComparerOptions.IgnoreModifiers | SigComparerOptions.DontCompareReturnType | SigComparerOptions.DontCompareTypeScope).Equals(a(module), b(module)));
        }
Пример #23
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();
        }
Пример #24
0
		/// <summary>
		/// Checks whether the type matches an expected type
		/// </summary>
		/// <param name="module">Module</param>
		/// <param name="name">Type name</param>
		/// <param name="expectedType">Expected type</param>
		/// <returns></returns>
		public static bool CheckType(ModuleDef module, string name, TypeRef expectedType) {
			if (module == null)
				module = new ModuleDefUser();
			var tr = TypeNameParser.ParseReflection(module, name, null);
			if (tr == null)
				return false;

			var flags = AssemblyNameComparerFlags.All & ~AssemblyNameComparerFlags.Version;
			if (!new AssemblyNameComparer(flags).Equals(tr.DefinitionAssembly, expectedType.DefinitionAssembly))
				return false;

			if (!new SigComparer().Equals(tr, expectedType))
				return false;

			return true;
		}
Пример #25
0
        static IEnumerable <TypeDef> GetTypeEquivalentTypes(AssemblyDef?assembly, ModuleDef?module, TypeDef type)
        {
            Debug.Assert(TIAHelper.IsTypeDefEquivalent(type));
            var typeRef = new ModuleDefUser("dummy").Import(type);

            foreach (var mod in GetModules(assembly, module))
            {
                var otherType = mod.Find(typeRef);
                if (otherType != type && TIAHelper.IsTypeDefEquivalent(otherType) &&
                    new SigComparer().Equals(otherType, type) &&
                    !new SigComparer(SigComparerOptions.DontCheckTypeEquivalence).Equals(otherType, type))
                {
                    yield return(otherType);
                }
            }
        }
Пример #26
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));
            }
        }
Пример #27
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);
        }
Пример #28
0
        void CreateTargetModule()
        {
            ModuleDef targetModule = null;
            var       mainmod      = _mainSourceModule;

            if (mainmod != null)
            {
                var targetAssembly = new AssemblyDefUser(mainmod.Assembly.Name, mainmod.Assembly.Version,
                                                         mainmod.Assembly.PublicKey, mainmod.Assembly.Culture)
                {
                    Attributes    = mainmod.Assembly.Attributes,
                    HashAlgorithm = mainmod.Assembly.HashAlgorithm,
                };
                targetModule = new ModuleDefUser(mainmod.Name, mainmod.Mvid, mainmod.CorLibTypes.AssemblyRef)
                {
                    RuntimeVersion            = mainmod.RuntimeVersion,
                    Cor20HeaderRuntimeVersion = mainmod.Cor20HeaderRuntimeVersion,
                    Cor20HeaderFlags          = mainmod.Cor20HeaderFlags,
                    DllCharacteristics        = mainmod.DllCharacteristics,
                    TablesHeaderVersion       = mainmod.TablesHeaderVersion,
                    Machine = mainmod.Machine,
                    Context = mainmod.Context,
                    Kind    = mainmod.Kind
                };
                if (mainmod.PdbState != null)
                {
                    targetModule.CreatePdbState(mainmod.PdbState.PdbFileKind);
                }
                targetAssembly.Modules.Add(targetModule);
            }

            var ev = Fire(new NetfuserEvent.CreateTargetModule(this)
            {
                Target = targetModule
            });

            _targetModule = ev.Target;
            if (_targetModule == null)
            {
                throw Error("could not create target module");
            }
            var mapper = new Mapper(this);

            mapper.Init(_basicImporter = new Importer(_targetModule, ImporterOptions.TryToUseDefs,
                                                      new GenericParamContext(), mapper));
        }
Пример #29
0
		static ModuleDef CreateModuleDef(string name, Guid mvid, ClrVersion clrVersion, ModuleDef existingModule) {
			var clrValues = ClrVersionValues.GetValues(clrVersion);
			ModuleDef module;
			if (existingModule == null)
				module = new ModuleDefUser(name, mvid, clrValues.CorLibRef);
			else {
				module = existingModule;
				module.Name = name;
				module.Mvid = mvid;
				OverwriteAssembly(module.CorLibTypes.AssemblyRef, clrValues.CorLibRef);
			}
			module.UpdateRowId(module);
			module.RuntimeVersion = clrValues.RuntimeVersion;
			module.Cor20HeaderRuntimeVersion = clrValues.Cor20HeaderRuntimeVersion;
			module.TablesHeaderVersion = clrValues.TablesHeaderVersion;
			module.Location = string.Empty;
			return module;
		}
Пример #30
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();
        }
Пример #31
0
        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());
            }
        }
Пример #32
0
        protected override void Pack(ConfuserContext context, ProtectionParameters parameters)
        {
            var ctx = context.Annotations.Get <XorCryptorContext>(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 += ".mpx";
                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;

            byte[] executableModuleBytes = null; // TODO: LOL!
        }
Пример #33
0
        public static CorLibTypeSig typeFromString(ModuleDefUser mod, string name)
        {
            switch (name)
            {
            case "int":
                return(mod.CorLibTypes.Int32);

            case "str":
                return(mod.CorLibTypes.String);

            case "bool":
                return(mod.CorLibTypes.Boolean);

            case "var":
                return(mod.CorLibTypes.String);

            case "void":
                return(mod.CorLibTypes.Void);
            }
            throw new Exception("invalid type");
        }
Пример #34
0
        public void ExceptionHandlerWithHandlerEndNull()
        {
            // https://github.com/Washi1337/Echo/issues/101

            // Set up test case.
            var module = new ModuleDefUser("Module");
            var method = new MethodDefUser("MyMethod", MethodSig.CreateStatic(module.CorLibTypes.Void), MethodAttributes.Static);
            var body   = method.Body = new CilBody();

            var start        = Instruction.Create(OpCodes.Nop);
            var tryStart     = Instruction.Create(OpCodes.Nop);
            var handlerStart = Instruction.Create(OpCodes.Pop);

            body.Instructions.Add(start);
            body.Instructions.Add(tryStart);
            body.Instructions.Add(Instruction.Create(OpCodes.Leave_S, start));
            body.Instructions.Add(handlerStart);
            body.Instructions.Add(Instruction.Create(OpCodes.Leave_S, start));

            body.ExceptionHandlers.Add(new ExceptionHandler(ExceptionHandlerType.Catch)
            {
                TryStart     = tryStart,
                TryEnd       = handlerStart,
                HandlerStart = handlerStart,
                HandlerEnd   = null, // End of method.
                CatchType    = module.CorLibTypes.Object.ToTypeDefOrRef()
            });

            body.UpdateInstructionOffsets();

            // Verify.
            var cfg = method.ConstructStaticFlowGraph();

            Assert.NotNull(cfg);
            Assert.Equal(3, cfg.Nodes.Count);
            var region = Assert.Single(cfg.Regions);
            var eh     = Assert.IsAssignableFrom <ExceptionHandlerRegion <Instruction> >(region);

            Assert.Single(eh.Handlers);
        }
Пример #35
0
        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"));
        }
Пример #36
0
		static void Execute(ILSpyTreeNode[] nodes)
		{
			if (!CanExecute(nodes))
				return;

			var newModule = new ModuleDefUser();

			var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, MainWindow.Instance.CurrentLanguage);
			data.CanShowClrVersion = true;
			var win = new AssemblyOptionsDlg();
			win.Title = "Create Assembly";
			win.DataContext = data;
			win.Owner = MainWindow.Instance;
			if (win.ShowDialog() != true)
				return;

			UndoCommandManager.Instance.Add(new CreateAssemblyCommand(newModule, data.CreateAssemblyOptions()));
		}
Пример #37
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);
        }
Пример #38
0
		static DebugSignatureReader() {
			noOwnerModule = new ModuleDefUser();
			corLibTypes = new CorLibTypes(noOwnerModule);
		}
Пример #39
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);
        }
Пример #40
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);
		}
Пример #41
0
		static void Execute(Lazy<IUndoCommandManager> undoCommandManager, IAppWindow appWindow, IFileTreeNodeData[] nodes) {
			if (!CanExecute(nodes))
				return;

			var newModule = new ModuleDefUser();

			var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, appWindow.LanguageManager);
			data.CanShowClrVersion = true;
			var win = new AssemblyOptionsDlg();
			win.Title = dnSpy_AsmEditor_Resources.CreateAssemblyCommand2;
			win.DataContext = data;
			win.Owner = appWindow.MainWindow;
			if (win.ShowDialog() != true)
				return;

			var cmd = new CreateAssemblyCommand(undoCommandManager.Value, appWindow.FileTreeView, newModule, data.CreateAssemblyOptions());
			undoCommandManager.Value.Add(cmd);
			appWindow.FileTabManager.FollowReference(cmd.fileNodeCreator.DnSpyFileNode);
		}
Пример #42
0
		static void Execute(Lazy<IUndoCommandService> undoCommandService, IAppService appService, DocumentTreeNodeData[] nodes) {
			if (!CanExecute(nodes))
				return;

			var newModule = new ModuleDefUser();

			var data = new AssemblyOptionsVM(AssemblyOptions.Create("MyAssembly"), newModule, appService.DecompilerService);
			data.CanShowClrVersion = true;
			var win = new AssemblyOptionsDlg();
			win.Title = dnSpy_AsmEditor_Resources.CreateAssemblyCommand2;
			win.DataContext = data;
			win.Owner = appService.MainWindow;
			if (win.ShowDialog() != true)
				return;

			var cmd = new CreateAssemblyCommand(undoCommandService.Value, appService.DocumentTreeView, newModule, data.CreateAssemblyOptions());
			undoCommandService.Value.Add(cmd);
			appService.DocumentTabService.FollowReference(cmd.fileNodeCreator.DocumentNode);
		}
Пример #43
0
        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);
        }
		/// <summary>
		/// Generate a test assembly.
		/// </summary>
		/// <returns>Assembly</returns>
		public AssemblyDef Generate()
		{
			var module = new ModuleDefUser(_moduleName);
			module.Kind = ModuleKind.Console;

			var assembly = new AssemblyDefUser(_assemblyName, _assemblyVersion);
			assembly.Modules.Add(module);

			var mainType = this.CreateMainType(module);
			module.Types.Add(mainType);

			var generatedMethods = new List<MethodDef>();
			foreach (var kvp in _methods)
			{
				var name = kvp.Key;
				var instructions = kvp.Value(module, mainType);
				var method = CreateVirtualizableMethod(module, name, instructions);

				mainType.Methods.Add(method);
				generatedMethods.Add(method);
			}

			var entryPoint = this.CreateEntryPoint(module, generatedMethods);
			mainType.Methods.Add(entryPoint);

			return assembly;
		}