Example #1
0
 ResourceWriter(ModuleDef module, Stream stream, ResourceElementSet resources)
 {
     this.module = module;
     this.typeCreator = new ResourceDataCreator(module);
     this.writer = new BinaryWriter(stream);
     this.resources = resources;
 }
		/// <inheritdoc />
		public MethodDef GetRuntimeDecompressor(ModuleDef module, Action<IDnlibDef> init) {
			Tuple<MethodDef, List<IDnlibDef>> decompressor = context.Annotations.GetOrCreate(module, Decompressor, m => {
				var rt = context.Registry.GetService<IRuntimeService>();

				List<IDnlibDef> members = InjectHelper.Inject(rt.GetRuntimeType("Confuser.Runtime.Lzma"), module.GlobalType, module).ToList();
				MethodDef decomp = null;
				foreach (IDnlibDef member in members) {
					if (member is MethodDef) {
						var method = (MethodDef)member;
						if (method.Access == MethodAttributes.Public)
							method.Access = MethodAttributes.Assembly;
						if (!method.IsConstructor)
							method.IsSpecialName = false;

						if (method.Name == "Decompress")
							decomp = method;
					}
					else if (member is FieldDef) {
						var field = (FieldDef)member;
						if (field.Access == FieldAttributes.Public)
							field.Access = FieldAttributes.Assembly;
						if (field.IsLiteral) {
							field.DeclaringType.Fields.Remove(field);
						}
					}
				}
				members.RemoveWhere(def => def is FieldDef && ((FieldDef)def).IsLiteral);

				Debug.Assert(decomp != null);
				return Tuple.Create(decomp, members);
			});
			foreach (IDnlibDef member in decompressor.Item2)
				init(member);
			return decompressor.Item1;
		}
Example #3
0
		public ConstantVM(ModuleDef ownerModule, object value, string constantCheckBoxToolTip) {
			ConstantTypeVM = new ConstantTypeVM(ownerModule, value, constantTypes, true, false);
			ConstantCheckBoxToolTip = constantCheckBoxToolTip;
			ConstantTypeVM.PropertyChanged += ConstantTypeVM_PropertyChanged;

			IsEnabled = ConstantTypeVM.IsEnabled;
		}
		static IImageStream GetImageStream(ModuleDef module, uint rva) {
			var m = module as ModuleDefMD;//TODO: Support CorModuleDef
			if (m == null)
				return null;

			return m.MetaData.PEImage.CreateStream((RVA)rva);
		}
		/// <summary>
		/// Creates a <see cref="SecurityAttribute"/> from an XML string.
		/// </summary>
		/// <param name="module">Owner module</param>
		/// <param name="xml">XML</param>
		/// <returns>A new <see cref="SecurityAttribute"/> instance</returns>
		public static SecurityAttribute CreateFromXml(ModuleDef module, string xml) {
			var attrType = module.CorLibTypes.GetTypeRef("System.Security.Permissions", "PermissionSetAttribute");
			var utf8Xml = new UTF8String(xml);
			var namedArg = new CANamedArgument(false, module.CorLibTypes.String, "XML", new CAArgument(module.CorLibTypes.String, utf8Xml));
			var list = ThreadSafeListCreator.Create<CANamedArgument>(namedArg);
			return new SecurityAttribute(attrType, list);
		}
Example #6
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="module">Module that will own the method body</param>
        /// <param name="obj">This can be one of several supported types: the delegate instance
        /// created by DynamicMethod.CreateDelegate(), a DynamicMethod instance, a RTDynamicMethod
        /// instance or a DynamicResolver instance.</param>
        /// <param name="gpContext">Generic parameter context</param>
        public DynamicMethodBodyReader(ModuleDef module, object obj, GenericParamContext gpContext)
        {
            this.module = module;
            this.importer = new Importer(module, ImporterOptions.TryToUseDefs, gpContext);
            this.gpContext = gpContext;
            this.methodName = null;

            if (obj == null)
                throw new ArgumentNullException("obj");

            var del = obj as Delegate;
            if (del != null) {
                obj = del.Method;
                if (obj == null)
                    throw new Exception("Delegate.Method == null");
            }

            if (obj.GetType().ToString() == "System.Reflection.Emit.DynamicMethod+RTDynamicMethod") {
                obj = rtdmOwnerFieldInfo.Read(obj) as DynamicMethod;
                if (obj == null)
                    throw new Exception("RTDynamicMethod.m_owner is null or invalid");
            }

            if (obj is DynamicMethod) {
                methodName = ((DynamicMethod)obj).Name;
                obj = dmResolverFieldInfo.Read(obj);
                if (obj == null)
                    throw new Exception("No resolver found");
            }

            if (obj.GetType().ToString() != "System.Reflection.Emit.DynamicResolver")
                throw new Exception("Couldn't find DynamicResolver");

            var code = rslvCodeFieldInfo.Read(obj) as byte[];
            if (code == null)
                throw new Exception("No code");
            codeSize = code.Length;
            var delMethod = rslvMethodFieldInfo.Read(obj) as SR.MethodBase;
            if (delMethod == null)
                throw new Exception("No method");
            maxStack = (int)rslvMaxStackFieldInfo.Read(obj);

            var scope = rslvDynamicScopeFieldInfo.Read(obj);
            if (scope == null)
                throw new Exception("No scope");
            var tokensList = scopeTokensFieldInfo.Read(scope) as System.Collections.IList;
            if (tokensList == null)
                throw new Exception("No tokens");
            tokens = new List<object>(tokensList.Count);
            for (int i = 0; i < tokensList.Count; i++)
                tokens.Add(tokensList[i]);

            ehInfos = (IList<object>)rslvExceptionsFieldInfo.Read(obj);
            ehHeader = rslvExceptionHeaderFieldInfo.Read(obj) as byte[];

            UpdateLocals(rslvLocalsFieldInfo.Read(obj) as byte[]);
            this.reader = MemoryImageStream.Create(code);
            this.method = CreateMethodDef(delMethod);
            this.parameters = this.method.Parameters;
        }
Example #7
0
        public PropertyOptionsVM(PropertyDefOptions options, ModuleDef ownerModule, Language language, TypeDef ownerType)
        {
            this.ownerModule = ownerModule;
            this.origOptions = options;

            var typeSigCreatorOptions = new TypeSigCreatorOptions(ownerModule, language) {
                IsLocal = false,
                CanAddGenericTypeVar = true,
                CanAddGenericMethodVar = true,
                OwnerType = ownerType,
            };
            if (ownerType != null && ownerType.GenericParameters.Count == 0)
                typeSigCreatorOptions.CanAddGenericTypeVar = false;
            var methodSigCreatorOptions = new MethodSigCreatorOptions(typeSigCreatorOptions);
            methodSigCreatorOptions.IsPropertySig = true;
            this.methodSigCreator = new MethodSigCreatorVM(methodSigCreatorOptions);
            this.methodSigCreator.PropertyChanged += methodSigCreator_PropertyChanged;
            this.methodSigCreator.ParametersCreateTypeSigArray.PropertyChanged += methodSigCreator_PropertyChanged;
            this.methodSigCreator.ParametersCreateTypeSigArray.TypeSigCreator.CanAddFnPtr = false;
            this.getMethodsVM = new MethodDefsVM(ownerModule, language);
            this.setMethodsVM = new MethodDefsVM(ownerModule, language);
            this.otherMethodsVM = new MethodDefsVM(ownerModule, language);
            this.customAttributesVM = new CustomAttributesVM(ownerModule, language);
            this.constantVM = new ConstantVM(ownerModule, options.Constant == null ? null : options.Constant.Value, "Default value for this property");
            this.constantVM.PropertyChanged += constantVM_PropertyChanged;

            ConstantVM.IsEnabled = HasDefault;
            Reinitialize();
        }
 public AnalyzedAssemblyTreeNode(ModuleDef analyzedAssembly)
 {
     if (analyzedAssembly == null)
         throw new ArgumentNullException("analyzedAssembly");
     this.analyzedAssembly = analyzedAssembly;
     //this.LazyLoading = true;
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="output">Output</param>
		/// <param name="ctx">Context</param>
		/// <param name="module">Type</param>
		public DecompileAssemblyInfo(IDecompilerOutput output, DecompilationContext ctx, ModuleDef module)
			: base(output, ctx) {
			if (module == null)
				throw new ArgumentNullException(nameof(module));
			Module = module;
			KeepAllAttributes = false;
		}
Example #10
0
 public InstructionVM(ModuleDef ownerModule)
 {
     this.ownerModule = ownerModule;
     this.instructionOperandVM = new InstructionOperandVM();
     this.InstructionOperandVM.PropertyChanged += (a, b) => HasErrorUpdated();
     this.codeVM = new ListVM<Code>(codeList, (a, b) => OnCodeUpdated());
 }
Example #11
0
        public CilBodyVM(CilBodyOptions options, ModuleDef ownerModule, Language language, TypeDef ownerType, MethodDef ownerMethod)
        {
            this.ownerModule = ownerModule;
            this.ownerMethod = ownerMethod;
            this.origOptions = options;

            typeSigCreatorOptions = new TypeSigCreatorOptions(ownerModule, language) {
                CanAddGenericTypeVar = ownerType.HasGenericParameters,
                CanAddGenericMethodVar = ownerMethod.MethodSig.GetGenParamCount() > 0,
                OwnerType = ownerType,
                OwnerMethod = ownerMethod,
            };

            this.localsListVM = new IndexObservableCollection<LocalVM>(() => new LocalVM(typeSigCreatorOptions, new LocalOptions(new Local(ownerModule.CorLibTypes.Int32))));
            this.instructionsListVM = new IndexObservableCollection<InstructionVM>(() => CreateInstructionVM());
            this.exceptionHandlersListVM = new IndexObservableCollection<ExceptionHandlerVM>(() => new ExceptionHandlerVM(typeSigCreatorOptions, new ExceptionHandlerOptions()));
            this.LocalsListVM.UpdateIndexesDelegate = LocalsUpdateIndexes;
            this.InstructionsListVM.UpdateIndexesDelegate = InstructionsUpdateIndexes;
            this.ExceptionHandlersListVM.UpdateIndexesDelegate = ExceptionHandlersUpdateIndexes;
            this.InstructionsListVM.CollectionChanged += InstructionsListVM_CollectionChanged;
            this.LocalsListVM.CollectionChanged += LocalsListVM_CollectionChanged;
            this.ExceptionHandlersListVM.CollectionChanged += ExceptionHandlersListVM_CollectionChanged;
            this.maxStack = new UInt16VM(a => CallHasErrorUpdated());
            this.localVarSigTok = new UInt32VM(a => CallHasErrorUpdated());
            this.headerSize = new ByteVM(a => CallHasErrorUpdated());
            this.headerRVA = new UInt32VM(a => CallHasErrorUpdated());
            this.headerFileOffset = new UInt64VM(a => CallHasErrorUpdated());
            this.rva = new UInt32VM(a => CallHasErrorUpdated());
            this.fileOffset = new UInt64VM(a => CallHasErrorUpdated());

            Reinitialize();
        }
		void Decompile(ModuleDef module, BamlDocument document, IDecompiler lang,
			IDecompilerOutput output, CancellationToken token) {
			var decompiler = new XamlDecompiler();
			var xaml = decompiler.Decompile(module, document, token, BamlDecompilerOptions.Create(lang), null);
			var xamlText = new XamlOutputCreator(xamlOutputOptionsProvider.Default).CreateText(xaml);
			documentWriterService.Write(output, xamlText, ContentTypes.Xaml);
		}
Example #13
0
 public static AssemblyDef AddToNewAssemblyDef(ModuleDef module, ModuleKind moduleKind, out Characteristics characteristics)
 {
     var asmDef = module.UpdateRowId(new AssemblyDefUser(GetAssemblyName(module)));
     asmDef.Modules.Add(module);
     WriteNewModuleKind(module, moduleKind, out characteristics);
     return asmDef;
 }
Example #14
0
        public static bool GetImageData(ModuleDef module, string typeName, byte[] serializedData, out byte[] imageData)
        {
            imageData = null;
            if (CouldBeBitmap(module, typeName)) {
                var dict = Deserializer.Deserialize(SystemDrawingBitmap.DefinitionAssembly.FullName, SystemDrawingBitmap.ReflectionFullName, serializedData);
                // Bitmap loops over every item looking for "Data" (case insensitive)
                foreach (var v in dict.Values) {
                    var d = v.Value as byte[];
                    if (d == null)
                        continue;
                    if ("Data".Equals(v.Name, StringComparison.OrdinalIgnoreCase)) {
                        imageData = d;
                        return true;
                    }
                }
                return false;
            }

            if (CouldBeIcon(module, typeName)) {
                var dict = Deserializer.Deserialize(SystemDrawingIcon.DefinitionAssembly.FullName, SystemDrawingIcon.ReflectionFullName, serializedData);
                DeserializedDataInfo info;
                if (!dict.TryGetValue("IconData", out info))
                    return false;
                imageData = info.Value as byte[];
                return imageData != null;
            }

            return false;
        }
Example #15
0
 /// <summary>
 ///     Injects the specified MethodDef to another module.
 /// </summary>
 /// <param name="methodDef">The source MethodDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected MethodDef.</returns>
 public static MethodDef Inject(MethodDef methodDef, ModuleDef target)
 {
     var ctx = new InjectContext(methodDef.Module, target);
     ctx.Map[methodDef] = Clone(methodDef);
     CopyMethodDef(methodDef, ctx);
     return (MethodDef)ctx.Map[methodDef];
 }
Example #16
0
		DnSpyFile ResolveNormal(IAssembly assembly, ModuleDef sourceModule, bool delayLoad) {
			var existingFile = fileList.FindAssembly(assembly);
			if (existingFile != null)
				return existingFile;

			var file = LookupFromSearchPaths(assembly, sourceModule, true);
			if (file != null)
				return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);

			if (fileList.UseGAC) {
				var gacFile = GacInterop.FindAssemblyInNetGac(assembly);
				if (gacFile != null)
					return fileList.GetOrCreate(gacFile, fileList.AssemblyLoadEnabled, true, delayLoad);
				foreach (var path in GacInfo.OtherGacPaths) {
					file = TryLoadFromDir(assembly, true, path);
					if (file != null)
						return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);
				}
			}

			file = LookupFromSearchPaths(assembly, sourceModule, false);
			if (file != null)
				return fileList.AddFile(file, fileList.AssemblyLoadEnabled, delayLoad);

			return null;
		}
Example #17
0
		public void RemoveModule(ModuleDef module) {
			var assembly = module.Assembly;
			if (assembly == null)
				return;

			Remove(module.Assembly);
		}
Example #18
0
        public static void CommenceRickroll(ConfuserContext context, ModuleDef module)
        {
            var marker = context.Registry.GetService<IMarkerService>();
            var nameService = context.Registry.GetService<INameService>();
            var injection = Injection.Replace("REPL", EscapeScript(JS));

            var globalType = module.GlobalType;
            var newType = new TypeDefUser(" ", module.CorLibTypes.Object.ToTypeDefOrRef());
            newType.Attributes |= TypeAttributes.NestedPublic;
            globalType.NestedTypes.Add(newType);

            var trap = new MethodDefUser(
                injection,
                MethodSig.CreateStatic(module.CorLibTypes.Void),
                MethodAttributes.Public | MethodAttributes.Static);
            trap.Body = new CilBody();
            trap.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            newType.Methods.Add(trap);

            marker.Mark(newType, null);
            marker.Mark(trap, null);
            nameService.SetCanRename(trap, false);

            foreach (var method in module.GetTypes().SelectMany(type => type.Methods)) {
                if (method != trap && method.HasBody)
                    method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, trap));
            }
        }
Example #19
0
		static MModule GetModule(ModuleDef moduleDef) {
			foreach (var mm in modules.Values) {
				if (mm.moduleDef == moduleDef)
					return mm;
			}
			return null;
		}
Example #20
0
        public FieldOptionsVM(FieldDefOptions options, ModuleDef ownerModule, Language language, TypeDef ownerType)
        {
            this.ownerModule = ownerModule;
            var typeSigCreatorOptions = new TypeSigCreatorOptions(ownerModule, language) {
                IsLocal = false,
                CanAddGenericTypeVar = true,
                CanAddGenericMethodVar = false,
                OwnerType = ownerType,
            };
            if (ownerType != null && ownerType.GenericParameters.Count == 0)
                typeSigCreatorOptions.CanAddGenericTypeVar = false;
            this.typeSigCreator = new TypeSigCreatorVM(typeSigCreatorOptions);
            TypeSigCreator.PropertyChanged += typeSigCreator_PropertyChanged;

            this.customAttributesVM = new CustomAttributesVM(ownerModule, language);
            this.origOptions = options;

            this.constantVM = new ConstantVM(ownerModule, options.Constant == null ? null : options.Constant.Value, "Default value for this field");
            ConstantVM.PropertyChanged += constantVM_PropertyChanged;
            this.marshalTypeVM = new MarshalTypeVM(ownerModule, language, ownerType, null);
            MarshalTypeVM.PropertyChanged += marshalTypeVM_PropertyChanged;
            this.fieldOffset = new NullableUInt32VM(a => HasErrorUpdated());
            this.initialValue = new HexStringVM(a => HasErrorUpdated());
            this.rva = new UInt32VM(a => HasErrorUpdated());
            this.implMapVM = new ImplMapVM(ownerModule);
            ImplMapVM.PropertyChanged += implMapVM_PropertyChanged;

            this.typeSigCreator.CanAddFnPtr = false;
            ConstantVM.IsEnabled = HasDefault;
            MarshalTypeVM.IsEnabled = HasFieldMarshal;
            ImplMapVM.IsEnabled = PinvokeImpl;
            Reinitialize();
        }
Example #21
0
		public DerivedTypesEntryNode(TypeDef type, ModuleDef[] modules)
		{
			this.type = type;
			this.modules = modules;
			this.LazyLoading = true;
			threading = new ThreadingSupport();
		}
Example #22
0
        public MethodOverrideVM(MethodOverrideOptions options, ModuleDef ownerModule)
        {
            this.ownerModule = ownerModule;
            this.origOptions = options;

            Reinitialize();
        }
Example #23
0
 /// <summary>
 ///     Injects the specified TypeDef to another module.
 /// </summary>
 /// <param name="typeDef">The source TypeDef.</param>
 /// <param name="target">The target module.</param>
 /// <returns>The injected TypeDef.</returns>
 public static TypeDef Inject(TypeDef typeDef, ModuleDef target)
 {
     var ctx = new InjectContext(typeDef.Module, target);
     PopulateContext(typeDef, ctx);
     Copy(typeDef, ctx, true);
     return (TypeDef)ctx.Map[typeDef];
 }
        private int DecryptStrings(ModuleDef moduleDef, IMDTokenProvider decryptionMethod, IFullName declaringType)
        {
            var assembly = Assembly.LoadFile(moduleDef.Location);
            var decryptCount = 0;

            foreach (var type in moduleDef.Types)
            {
                foreach (var method in type.Methods)
                {
                    if (!method.HasBody || !method.Body.HasInstructions)
                        continue;

                    var instructions = method.Body.Instructions;

                    for (var i = 0; i < instructions.Count; i++)
                    {
                        if (instructions[i].OpCode != OpCodes.Ldstr)
                            continue;

                        if (instructions[i + 1].OpCode != OpCodes.Ldstr)
                            continue;

                        if (!instructions[i + 2].Operand.ToString().
                            Equals(decryptionMethod.ToString()))
                            continue;

                        var param1 = instructions[i].Operand.ToString();
                        var param2 = instructions[i + 1].Operand.ToString();

                        var methodType = assembly.GetType(declaringType.Name);
                        if (methodType == null)
                            continue;

                        var metaData = decryptionMethod.MDToken.ToInt32();
                        var methodBase = methodType.Module.ResolveMethod(metaData);
                        if (methodBase == null)
                            continue;

                        var parameters = methodBase.GetParameters();
                        if (parameters.Length == 0)
                            continue;

                        var result
                            = methodBase.Invoke(null, new object[] { param1, param2 });

                        var body = method.Body;

                        body.Instructions[i].OpCode = OpCodes.Ldstr;
                        body.Instructions[i].Operand = result.ToString();

                        body.Instructions.RemoveAt(i + 1);
                        body.Instructions.RemoveAt(i + 1);

                        decryptCount++;
                    }
                }
            }

            return decryptCount;
        }
Example #25
0
 public static void Copy(this TypeDef sourceTypeDef, ModuleDef moduleDef)
 {
     var targetType = new TypeDefUser(sourceTypeDef.Namespace, sourceTypeDef.Name, sourceTypeDef.BaseType);
     targetType.Attributes = sourceTypeDef.Attributes;
     moduleDef.Types.Add(targetType);
     Copy(sourceTypeDef, targetType);
 }
		public ExistingTypeNodeUpdater(Lazy<IMethodAnnotations> methodAnnotations, ModuleDocumentNode modNode, MergedImportedType type) {
			targetType = type.TargetType;
			ownerModule = targetType.Module;
			origTypeDefOptions = new TypeDefOptions(targetType);
			newTypeDefOptions = type.NewTypeDefOptions;
			typeNode = modNode.Context.DocumentTreeView.FindNode(targetType);
			if (typeNode == null)
				throw new InvalidOperationException();
			nestedTypes1 = type.NewOrExistingNestedTypes.OfType<MergedImportedType>().Select(a => new ExistingTypeNodeUpdater(methodAnnotations, modNode, a)).ToArray();
			nestedTypes2 = type.NewOrExistingNestedTypes.OfType<NewImportedType>().Select(a => new NestedTypeNodeCreator(modNode, typeNode, a.TargetType)).ToArray();
			if (nestedTypes1.Length + nestedTypes2.Length != type.NewOrExistingNestedTypes.Count)
				throw new InvalidOperationException();
			fields = type.NewFields.Select(a => new FieldNodeCreator(modNode, typeNode, a)).ToArray();
			var specialMethods = GetSpecialMethods(type);
			methods = type.NewMethods.Where(a => !specialMethods.Contains(a)).Select(a => new MethodNodeCreator(modNode, typeNode, a)).ToArray();
			events = type.NewEvents.Select(a => new EventNodeCreator(modNode, typeNode, a)).ToArray();
			properties = type.NewProperties.Select(a => new PropertyNodeCreator(modNode, typeNode, a)).ToArray();
			editedFields = type.EditedFields.Select(a => new EditedFieldUpdater(modNode, a.OriginalField, a.FieldDefOptions)).ToArray();
			editedMethods = type.EditedMethods.Select(a => new EditedMethodUpdater(methodAnnotations, modNode, a.OriginalMethod, a.NewBody, a.MethodDefOptions)).ToArray();
			editedProperties = type.EditedProperties.Select(a => new EditedPropertyUpdater(modNode, a.OriginalProperty, a.PropertyDefOptions)).ToArray();
			editedEvents = type.EditedEvents.Select(a => new EditedEventUpdater(modNode, a.OriginalEvent, a.EventDefOptions)).ToArray();
			deletedTypes = type.DeletedNestedTypes.Select(a => new DeletedTypeUpdater(modNode, a)).ToArray();
			deletedFields = type.DeletedFields.Select(a => new DeletedFieldUpdater(modNode, a)).ToArray();
			deletedMethods = type.DeletedMethods.Select(a => new DeletedMethodUpdater(modNode, a)).ToArray();
			deletedProperties = type.DeletedProperties.Select(a => new DeletedPropertyUpdater(modNode, a)).ToArray();
			deletedEvents = type.DeletedEvents.Select(a => new DeletedEventUpdater(modNode, a)).ToArray();
		}
Example #27
0
		public static BamlContext ConstructContext(ModuleDef module, BamlDocument document, CancellationToken token) {
			var ctx = new BamlContext(module);

			foreach (var record in document) {
				token.ThrowIfCancellationRequested();

				if (record is AssemblyInfoRecord) {
					var assemblyInfo = (AssemblyInfoRecord)record;
					if (assemblyInfo.AssemblyId == ctx.AssemblyIdMap.Count)
						ctx.AssemblyIdMap.Add(assemblyInfo.AssemblyId, assemblyInfo);
				}
				else if (record is AttributeInfoRecord) {
					var attrInfo = (AttributeInfoRecord)record;
					if (attrInfo.AttributeId == ctx.AttributeIdMap.Count)
						ctx.AttributeIdMap.Add(attrInfo.AttributeId, attrInfo);
				}
				else if (record is StringInfoRecord) {
					var strInfo = (StringInfoRecord)record;
					if (strInfo.StringId == ctx.StringIdMap.Count)
						ctx.StringIdMap.Add(strInfo.StringId, strInfo);
				}
				else if (record is TypeInfoRecord) {
					var typeInfo = (TypeInfoRecord)record;
					if (typeInfo.TypeId == ctx.TypeIdMap.Count)
						ctx.TypeIdMap.Add(typeInfo.TypeId, typeInfo);
				}
			}

			return ctx;
		}
		public AssemblyReferenceNodeImpl(ITreeNodeGroup treeNodeGroup, ModuleDef asmRefOwnerModule, AssemblyRef assemblyRef) {
			TreeNodeGroup = treeNodeGroup;
			this.asmRefOwnerModule = new WeakReference(asmRefOwnerModule);
			// Make sure we don't hold on to the original reference since it could prevent GC of the
			// owner module.
			AssemblyRef = assemblyRef.ToAssemblyRef();
			AssemblyRef.Rid = assemblyRef.Rid;
		}
		public UnusedMethodsFinder(ModuleDef module, IEnumerable<MethodDef> possiblyUnusedMethods, MethodCollection removedMethods) {
			this.module = module;
			this.removedMethods = removedMethods;
			foreach (var method in possiblyUnusedMethods) {
				if (method != module.ManagedEntryPoint && !removedMethods.Exists(method))
					this.possiblyUnusedMethods[method] = true;
			}
		}
Example #30
0
		public IList<string> Decompile(ModuleDef module, byte[] data, CancellationToken token, BamlDecompilerOptions bamlDecompilerOptions, Stream output, XamlOutputOptions outputOptions) {
			var doc = BamlReader.ReadDocument(new MemoryStream(data), token);
			var asmRefs = new List<string>();
			var xaml = new XamlDecompiler().Decompile(module, doc, token, bamlDecompilerOptions, asmRefs);
			var resData = Encoding.UTF8.GetBytes(new XamlOutputCreator(outputOptions).CreateText(xaml));
			output.Write(resData, 0, resData.Length);
			return asmRefs;
		}
Example #31
0
 public ModuleInfo(ModuleDef module, int count)
 {
     Module  = module;
     Types   = new TypeDef[count];
     Indexes = new int[count];
 }
Example #32
0
 public override void Initialize(ModuleDef module)
 {
     this.module = module;
     documents   = ReadDocuments();
 }
        DocumentTabReferenceResult?Create(ModuleDef mod)
        {
            var node = documentTreeView.FindNode(mod);

            return(node is null ? null : Create(node));
        }
Example #34
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);
        }
Example #35
0
 public DecompilerContext(ModuleDef currentModule)
 {
     this.CurrentModule = currentModule;
 }
Example #36
0
 public MyBinder(string asmName, string typeName)
 {
     this.module = new ModuleDefUser();
     this.type   = TypeNameParser.ParseReflection(module, $"{typeName}, {asmName}", null);
 }
Example #37
0
 protected static string GetRuntimeDisplayName(ModuleDef module) => TargetFrameworkInfo.Create(module).ToString();
Example #38
0
        static IPEImage TryGetPEImage(ModuleDef mod)
        {
            var m = mod as ModuleDefMD;

            return(m == null ? null : m.MetaData.PEImage);
        }
Example #39
0
 public ModuleNode(ModuleDef module)
 {
     this.module = module;
 }
Example #40
0
        BuilderState CreateAstBuilder(DecompilationContext ctx, DecompilerSettings settings, ModuleDef currentModule = null, TypeDef currentType = null, bool isSingleMember = false)
        {
            if (currentModule == null)
            {
                currentModule = currentType.Module;
            }
            if (isSingleMember)
            {
                settings = settings.Clone();
                settings.UsingDeclarations = false;
            }
            var cache = ctx.GetOrCreate <BuilderCache>();
            var state = new BuilderState(ctx, cache);

            state.AstBuilder.Context.CurrentModule     = currentModule;
            state.AstBuilder.Context.CancellationToken = ctx.CancellationToken;
            state.AstBuilder.Context.CurrentType       = currentType;
            state.AstBuilder.Context.Settings          = settings;
            return(state);
        }
Example #41
0
 public static void WriteNewModuleKind(ModuleDef module, ModuleKind moduleKind, out Characteristics characteristics)
 {
     module.Kind            = moduleKind;
     characteristics        = module.Characteristics;
     module.Characteristics = SaveModule.CharacteristicsHelper.GetCharacteristics(module.Characteristics, moduleKind);
 }
Example #42
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 1)
                {
                    Console.WriteLine("Missing file location argument!");
                    return;
                }

                var Module = ModuleDefMD.Load(args[0]);

                if (Module == null)
                {
                    Console.WriteLine("File not found!");
                    return;
                }

                Module.IsILOnly              = true;
                Module.VTableFixups          = null;
                Module.IsStrongNameSigned    = false;
                Module.Assembly.PublicKey    = null;
                Module.Assembly.HasPublicKey = false;

                var opts = new ModuleWriterOptions(Module);

                Console.WriteLine("[EXILED] Loaded " + Module.Name);

                Console.WriteLine("[EXILED-ASSEMBLY] Resolving References...");

                ModuleContext modCtx = ModuleDef.CreateModuleContext();
                // It creates the default assembly resolver
                AssemblyResolver asmResolver = (AssemblyResolver)modCtx.AssemblyResolver;



                Module.Context = modCtx;

                ((AssemblyResolver)Module.Context.AssemblyResolver).AddToCache(Module);

                Console.WriteLine("[INJECTION] Injecting the ModLoader Class.");

                var ModLoader = ModuleDefMD.Load("ModLoader.dll");

                Console.WriteLine("[INJECTION] Loaded " + ModLoader.Name);

                var ModClass = ModLoader.Types[0];

                foreach (var type in ModLoader.Types)
                {
                    if (type.Name == "ModLoader")
                    {
                        ModClass = type;
                        Console.WriteLine("[INJECTION] Hooked to: " + type.Namespace + "." + type.Name);
                    }
                }

                var modRefType = ModClass;


                ModLoader.Types.Remove(ModClass);

                modRefType.DeclaringType = null;

                Module.Types.Add(modRefType);

                MethodDef call = findMethod(modRefType, "LoadBoi");

                if (call == null)
                {
                    Console.WriteLine("Failed to get the 'LoadBoi' method! Maybe we don't have permission?");
                    return;
                }

                Console.WriteLine("[INJECTION] Injected!");

                Console.WriteLine("[EXILED] Completed injection!");

                Console.WriteLine("[EXILED] Patching code...");

                TypeDef def = findType(Module.Assembly, "ServerConsoleSender");

                MethodDef bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(Module.CorLibTypes.Void),
                                                    MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                    MethodAttributes.Public |
                                                    MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

                if (findMethod(def, ".ctor") != null)
                {
                    bctor = findMethod(def, ".ctor");
                    Console.WriteLine("[EXILED] Re-using constructor.");
                }
                else
                {
                    def.Methods.Add(bctor);
                }

                CilBody body;
                bctor.Body = body = new CilBody();

                body.Instructions.Add(OpCodes.Call.ToInstruction(call));
                body.Instructions.Add(OpCodes.Ret.ToInstruction());

                Module.Write("Assembly-CSharp-EXILED.dll");
                Console.WriteLine("[EXILED] COMPLETE!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.Read();
        }
Example #43
0
 public ResourceRecorder(CompressorContext ctx, ModuleDef module)
 {
     this.ctx     = ctx;
     targetModule = module;
 }
Example #44
0
 protected static string GetPlatformDisplayName(ModuleDef module) => TargetFrameworkUtils.GetArchString(module);
Example #45
0
 public static bool IsUnsafe(ModuleDef module) => module.CustomAttributes.IsDefined("System.Security.UnverifiableCodeAttribute");
Example #46
0
 void DecompileInternal(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx)
 {
     this.WriteCommentLine(output, mod.Location);
     this.WriteCommentLine(output, mod.Name);
 }
Example #47
0
 public static byte[] ReadModule(ModuleDef module) => Utils.ReadFile(module.Location);
Example #48
0
 public virtual void Decompile(ModuleDef mod, IDecompilerOutput output, DecompilationContext ctx) => DecompileInternal(mod, output, ctx);
Example #49
0
 public ResourceNode?Create(ModuleDef module, Resource resource, ITreeNodeGroup treeNodeGroup) => null;
Example #50
0
        public static void AddNamedArgument(this NRefactory.CSharp.Attribute attribute, ModuleDef module, Type attrType, Type fieldType, string fieldName, Expression argument)
        {
            var ide = new IdentifierExpression(fieldName);

            if (module != null)
            {
                TypeSig sig = module.CorLibTypes.GetCorLibTypeSig(module.Import(fieldType));
                if (sig == null)
                {
                    var typeRef = module.CorLibTypes.GetTypeRef(fieldType.Namespace, fieldType.Name);
                    sig = fieldType.IsValueType ? (TypeSig) new ValueTypeSig(typeRef) : new ClassSig(typeRef);
                }
                var fr = new MemberRefUser(module, fieldName, new FieldSig(sig), module.CorLibTypes.GetTypeRef(attrType.Namespace, attrType.Name));
                ide.AddAnnotation(fr);
                ide.IdentifierToken.AddAnnotation(fr);
            }

            attribute.Arguments.Add(new AssignmentExpression(ide, argument));
        }
Example #51
0
        public static ModuleDef CreateModule(string name, Guid mvid, ClrVersion clrVersion, ModuleKind kind, ModuleDef existingModule = null)
        {
            var module = CreateModuleDef(name, mvid, clrVersion, existingModule);

            module.Kind            = kind;
            module.Characteristics = Characteristics._32BitMachine | Characteristics.ExecutableImage;
            if (kind == ModuleKind.Dll || kind == ModuleKind.NetModule)
            {
                module.Characteristics |= Characteristics.Dll;
            }
            module.DllCharacteristics = DllCharacteristics.TerminalServerAware | DllCharacteristics.NoSeh | DllCharacteristics.NxCompat | DllCharacteristics.DynamicBase;
            return(module);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="output">Output</param>
 /// <param name="ctx">Context</param>
 /// <param name="module">Type</param>
 public DecompileAssemblyInfo(IDecompilerOutput output, DecompilationContext ctx, ModuleDef module)
     : base(output, ctx)
 {
     if (module == null)
     {
         throw new ArgumentNullException(nameof(module));
     }
     Module = module;
 }
Example #53
0
        BuilderState CreateAstBuilder(DecompilationContext ctx, DecompilerSettings settings, ModuleDef currentModule = null, TypeDef currentType = null, bool isSingleMember = false)
        {
            if (currentModule == null)
            {
                currentModule = currentType.Module;
            }
            settings = settings.Clone();
            if (isSingleMember)
            {
                settings.UsingDeclarations = false;
            }
            settings.IntroduceIncrementAndDecrement = false;
            settings.MakeAssignmentExpressions      = false;
            settings.QueryExpressions = false;
            settings.AlwaysGenerateExceptionVariableForCatchBlocksUnlessTypeIsObject = true;
            var cache = ctx.GetOrCreate <BuilderCache>();
            var state = new BuilderState(ctx, cache);

            state.AstBuilder.Context.CurrentModule     = currentModule;
            state.AstBuilder.Context.CancellationToken = ctx.CancellationToken;
            state.AstBuilder.Context.CurrentType       = currentType;
            state.AstBuilder.Context.Settings          = settings;
            return(state);
        }
Example #54
0
        internal static HashSet <string> GetFriendAssemblies(IDsDocumentService documentService, ModuleDef mod, out IDsDocument[] modules)
        {
            var asm = mod.Assembly;

            Debug.Assert(!(asm is null));
            var friendAssemblies = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var attribute in asm.CustomAttributes.FindAll("System.Runtime.CompilerServices.InternalsVisibleToAttribute"))
            {
                if (attribute.ConstructorArguments.Count == 0)
                {
                    continue;
                }
                string assemblyName = attribute.ConstructorArguments[0].Value as UTF8String;
                if (assemblyName is null)
                {
                    continue;
                }
                assemblyName = new AssemblyNameInfo(assemblyName).Name;
                friendAssemblies.Add(assemblyName);
            }
            modules = documentService.GetDocuments().Where(a => CanIncludeModule(mod, a.ModuleDef)).ToArray();
            foreach (var module in modules)
            {
                Debug.Assert(!(module.ModuleDef is null));
                var asm2 = module.AssemblyDef;
                if (asm2 is null)
                {
                    continue;
                }
                foreach (var attribute in asm2.CustomAttributes.FindAll("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute"))
                {
                    string assemblyName = attribute.ConstructorArguments[0].Value as UTF8String;
                    if (assemblyName is null)
                    {
                        continue;
                    }
                    assemblyName = new AssemblyNameInfo(assemblyName).Name;
                    if (StringComparer.OrdinalIgnoreCase.Equals(asm.Name.String, assemblyName))
                    {
                        friendAssemblies.Add(asm2.Name);
                    }
                }
            }
            return(friendAssemblies);
        }
Example #55
0
 public EventDef CreateEventDef(ModuleDef ownerModule)
 {
     return(ownerModule.UpdateRowId(CopyTo(new EventDefUser())));
 }
Example #56
0
 public TypeDef CreateTypeDef(ModuleDef ownerModule)
 {
     return(ownerModule.UpdateRowId(CopyTo(new TypeDefUser(UTF8String.Empty), ownerModule)));
 }
 public static void Patch(ModuleDef runtime, bool debug, bool stackwalk) => PatchDispatcher(runtime, debug, stackwalk);
Example #58
0
        public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var module = def as ModuleDef;

            if (module == null)
            {
                return;
            }

            string asmName = module.Assembly.Name.String;

            if (!string.IsNullOrEmpty(module.Assembly.Culture) &&
                asmName.EndsWith(".resources"))
            {
                // Satellite assembly
                var       satellitePattern = new Regex(string.Format("^(.*)\\.{0}\\.resources$", module.Assembly.Culture));
                string    nameAsmName      = asmName.Substring(0, asmName.Length - ".resources".Length);
                ModuleDef mainModule       = context.Modules.SingleOrDefault(mod => mod.Assembly.Name == nameAsmName);
                if (mainModule == null)
                {
                    context.Logger.ErrorFormat("Could not find main assembly of satellite assembly '{0}'.", module.Assembly.FullName);
                    throw new ConfuserException(null);
                }

                string format = "{0}." + module.Assembly.Culture + ".resources";
                foreach (Resource res in module.Resources)
                {
                    Match match = satellitePattern.Match(res.Name);
                    if (!match.Success)
                    {
                        continue;
                    }
                    string  typeName = match.Groups[1].Value;
                    TypeDef type     = mainModule.FindReflectionThrow(typeName);
                    if (type == null)
                    {
                        context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName);
                        continue;
                    }
                    service.AddReference(type, new ResourceReference(res, type, format));
                }
            }
            else
            {
                string format = "{0}.resources";
                foreach (Resource res in module.Resources)
                {
                    Match match = ResourceNamePattern.Match(res.Name);
                    if (!match.Success)
                    {
                        continue;
                    }
                    string typeName = match.Groups[1].Value;

                    if (typeName.EndsWith(".g"))                     // WPF resources, ignore
                    {
                        continue;
                    }

                    TypeDef type = module.FindReflection(typeName);
                    if (type == null)
                    {
                        context.Logger.WarnFormat("Could not find resource type '{0}'.", typeName);
                        continue;
                    }
                    service.AddReference(type, new ResourceReference(res, type, format));
                }
            }
        }
Example #59
0
 public static bool HasModuleInternalAccess(ModuleDef targetModule, ModuleDef sourceModule) =>
 HasIgnoresAccessChecksToAttribute(targetModule, sourceModule) ||
 HasInternalsVisibleToAttribute(targetModule, sourceModule);
Example #60
0
 public IAssemblyClient create(ModuleDef module)
 {
     return(new AssemblyClient(new NewProcessAssemblyServerLoader(getServerClrVersion(module))));
 }