private TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { var tr = new TypeRefUser(module, string.Empty, "<Module>", mr); if (module != null) { module.UpdateRowId(tr); } return(tr); }
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"); }
ITypeDefOrRef CreateCorLibTypeRef(bool isCorLib, string name) { var tr = new TypeRefUser(module, "System", name, corLibAssemblyRef); if (isCorLib) { var td = module.Find(tr); if (td != null) { return(td); } } return(module.UpdateRowId(tr)); }
public void Run(XamlContext ctx, XDocument document) { var xClass = document.Root.Elements().First().Attribute(ctx.GetXamlNsName("Class")); if (xClass == null) return; var type = ctx.Module.Find(xClass.Value, true); if (type == null) return; var wbAsm = new AssemblyNameInfo("WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35").ToAssemblyRef(); var ifaceRef = new TypeRefUser(ctx.Module, "System.Windows.Markup", "IComponentConnector", wbAsm); var iface = ctx.Module.Context.Resolver.ResolveThrow(ifaceRef); var connect = iface.FindMethod("Connect"); foreach (MethodDef method in type.Methods) { if (Impl(method, connect)) { connect = method; iface = null; break; } } if (iface != null) return; Dictionary<int, Action<XamlContext, XElement>> connIds = null; try { connIds = ExtractConnectionId(ctx, connect); } catch { } if (connIds == null) { var msg = dnSpy_BamlDecompiler_Resources.Error_IComponentConnectorConnetCannotBeParsed; document.Root.AddBeforeSelf(new XComment(string.Format(msg, type.ReflectionFullName))); return; } foreach (var elem in document.Elements()) { ProcessElement(ctx, elem, connIds); } }
ITypeDefOrRef CreateCorLibTypeRef(bool isCorLib, string name) { var tr = new TypeRefUser(module, "System", name, corLibAssemblyRef); if (isCorLib) { var td = module.Find(tr); if (td != null) return td; } return module.UpdateRowId(tr); }
public void Find() { foreach (var tmp in module.Resources) { var resource = tmp as EmbeddedResource; if (resource == null) continue; if (!resource.Name.String.EndsWith(".resources", StringComparison.Ordinal)) continue; string ns, name; SplitTypeName(resource.Name.String.Substring(0, resource.Name.String.Length - 10), out ns, out name); var type = new TypeRefUser(module, ns, name, module).Resolve(); if (type == null) continue; if (!CheckDecrypterType(type)) continue; encryptedResource = resource; decrypterType = type; break; } }
/// <summary> /// Resolve a TypeDef or TypeRef from its name. If neither a TypeDef or TypeRef are found /// in the module, search its references (AssemblyRefs) and if a match is found, add a TypeRef /// for it to the module and return that. /// </summary> /// <param name="fullName">Name of TypeDef or TypeRef as found in the resource</param> /// <param name="isReflectionName">Whether or not the name is a reflection name</param> /// <returns>TypeDef or TypeRef, or null if none found</returns> public ITypeDefOrRef ResolveTypeDefOrRef(TypeName typeName) { String fullName = typeName.Name; // Return TypeDef if found TypeDef typeDef = _module.Find(fullName, false); if (typeDef != null) return typeDef; // Return existing TypeRef if found var typeRefs = _module.GetTypeRefs(); foreach(var typeRef in typeRefs) { if (typeRef.FullName.Equals(fullName)) return typeRef; } // Get the AssemblyRef from the type name and make our own TypeRef AssemblyRef asmRef = this.FindAssemblyRef(typeName); if(!typeName.IsNested) return new TypeRefUser(_module, typeName.Namespace, typeName.NameWithoutNamespace, asmRef); else { // Lazy... var parentName = typeName.ParentName.Split('.').Last(); TypeRef resolutionRef = new TypeRefUser(_module, typeName.Namespace, parentName, asmRef); return new TypeRefUser(_module, "", typeName.NestedName, resolutionRef); } }
TypeSig ReadTypeRef() { string ns, name; ParseReflectionTypeName(ReadString(), out ns, out name); var asmRef = assemblyNames[ReadVariableLengthInt32()]; var declaringType = ReadTypeSig(); var typeRef = new TypeRefUser(module, ns, name); if (declaringType != null) typeRef.ResolutionScope = GetTypeRef(declaringType); else typeRef.ResolutionScope = asmRef; return memberRefConverter.Convert(typeRef); }
TypeRefUser CreateDefaultGlobalTypeRef(ModuleRef mr) { var tr = new TypeRefUser(module, string.Empty, "<Module>", mr); if (module != null) module.UpdateRowId(tr); return tr; }
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); }
private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { int instructionIndex = dgBody.SelectedRows.TopmostRow().Index + 1; foreach (Instruction instruction in _copiedInstructions.OrderByDescending(i => i.Offset)) { var newInstruction = new Instruction(instruction.OpCode); if (instruction.Operand != null) switch (instruction.OpCode.OperandType) { case OperandType.InlineField: var field = instruction.Operand as IField; if (field.DeclaringType.DefinitionAssembly != CurrentAssembly.ManifestModule.Assembly || field.Module != CurrentAssembly.ManifestModule) { var fieldRef = new MemberRefUser(field.Module, field.Name, field.FieldSig, field.DeclaringType); newInstruction.Operand = CurrentAssembly.ManifestModule.Import(fieldRef); } else { newInstruction.Operand = CurrentAssembly.ManifestModule.ResolveField(field.Rid); } break; case OperandType.InlineMethod: var method = instruction.Operand as IMethod; if (method.DeclaringType.DefinitionAssembly != CurrentAssembly.ManifestModule.Assembly || method.Module != CurrentAssembly.ManifestModule) { var methodRef = new MemberRefUser(method.Module, method.Name, method.MethodSig, method.DeclaringType); newInstruction.Operand = CurrentAssembly.ManifestModule.Import(methodRef); } else { newInstruction.Operand = CurrentAssembly.ManifestModule.ResolveMethod(method.Rid); } break; case OperandType.InlineType: var type = instruction.Operand as ITypeDefOrRef; if (type.DefinitionAssembly != CurrentAssembly.ManifestModule.Assembly || type.Module != CurrentAssembly.ManifestModule) { var typeRef = new TypeRefUser(type.Module, type.Namespace, type.Name, CurrentAssembly.ManifestModule.CorLibTypes.AssemblyRef); newInstruction.Operand = CurrentAssembly.ManifestModule.Import(typeRef); } else { newInstruction.Operand = CurrentAssembly.ManifestModule.ResolveTypeDefOrRef(type.Rid); } break; default: newInstruction.Operand = instruction.Operand; break; } CurrentAssembly.Method.Body.Instructions.Insert(instructionIndex, newInstruction); } FixBranches(); CurrentAssembly.Method.Body.Instructions.UpdateInstructionOffsets(); DataGridViewHandler.ReadMethod(CurrentAssembly.Method); }
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); }
/// <summary> /// Creates a custom ObfuscationAttribute that can be added to a method. /// </summary> /// <param name="module">Module</param> /// <param name="feature">Obfuscation feature name</param> /// <param name="exclude">true if exclude, false if include</param> /// <returns>CustomAttribute</returns> CustomAttribute CreateAttribute(ModuleDef module, String feature, Boolean exclude) { TypeSig stringSig = module.CorLibTypes.String; TypeSig booleanSig = module.CorLibTypes.Boolean; CANamedArgument[] args = new CANamedArgument[] { // Feature new CANamedArgument( false, stringSig, "Feature", new CAArgument(stringSig, feature)), // Exclude new CANamedArgument( false, booleanSig, "Exclude", new CAArgument(booleanSig, exclude)) }; TypeRef obfuscationRef = new TypeRefUser( module, "System.Reflection", "ObfuscationAttribute", module.CorLibTypes.AssemblyRef); MemberRef obfuscationCtor = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), obfuscationRef); CustomAttribute attr = new CustomAttribute( obfuscationCtor, new CAArgument[0], args ); return attr; }
/// <summary> /// Calli. /// </summary> /// <param name="module">Module</param> /// <param name="mainType">Main type</param> /// <returns>Instructions</returns> static IList<Instruction> GetCalliInstructions(ModuleDef module, TypeDef mainType) { TypeRef consoleRef = new TypeRefUser(module, "System", "Console", module.CorLibTypes.AssemblyRef); MemberRef consoleWrite0 = new MemberRefUser(module, "WriteLine", MethodSig.CreateStatic(module.CorLibTypes.Void), consoleRef); var all = new List<Instruction>(); all.Add(OpCodes.Ldftn.ToInstruction(consoleWrite0)); all.Add(OpCodes.Calli.ToInstruction(consoleWrite0.MethodSig)); all.Add(OpCodes.Ret.ToInstruction()); return all; }