/// <summary>
 /// Add an assembly to the assembly cache
 /// </summary>
 /// <param name="asm">The assembly</param>
 /// <returns>
 /// <c>true</c> if <paramref name="asm" /> is cached, <c>false</c> if it's not
 /// cached because some other assembly with the exact same full name has already been
 /// cached or if <paramref name="asm" /> is <c>null</c>.
 /// </returns>
 public bool AddToCache(AssemblyDef asm)
 {
     if (_cache.ContainsKey(asm))
         return false;
     _cache[asm] = asm;
     return true;
 }
예제 #2
0
 public static bool isForm(AssemblyDef asm)
 {
     bool result = false;
     foreach (ModuleDef current in asm.Modules)
     {
         foreach (TypeDef current2 in current.Types)
         {
             foreach (TypeDef current3 in current2.NestedTypes)
             {
                 foreach (MethodDef current4 in current3.Methods)
                 {
                     if (current4.Name == "InitializeComponent")
                     {
                         result = true;
                     }
                 }
             }
             foreach (MethodDef current5 in current2.Methods)
             {
                 if (current5.Name == "InitializeComponent")
                 {
                     result = true;
                 }
             }
         }
     }
     return result;
 }
예제 #3
0
		string GetBaseDirectory(AssemblyDef asm, ModuleDef mod) {
			if (string.IsNullOrEmpty(mod.Location))
				return string.Empty;
			try {
				return Path.GetDirectoryName(mod.Location);
			}
			catch {
				return string.Empty;
			}
		}
예제 #4
0
        public override AssemblyDef DeobfuscateAssembly(AssemblyDef asmDef)
        {
            Ctx.Assembly = asmDef;
            Ctx.OriginalMD = (Ctx.Assembly.ManifestModule as ModuleDefMD);

            InitializePipelines();
            Pipelines["preRoutines"].Process();
            Pipelines["routines"].Process();

            return Ctx.Assembly;
        }
예제 #5
0
		public AssemblyOptions(AssemblyDef asm) {
			HashAlgorithm = asm.HashAlgorithm;
			Version = asm.Version;
			Attributes = asm.Attributes;
			PublicKey = asm.PublicKey;
			Name = asm.Name;
			Culture = asm.Culture;
			ClrVersion = Module.ClrVersion.DefaultVersion;
			CustomAttributes.AddRange(asm.CustomAttributes);
			DeclSecurities.AddRange(asm.DeclSecurities);
		}
예제 #6
0
 private void InjectSettings(AssemblyDef asm)
 {
     var ep = asm.ManifestModule.EntryPoint;
     var settingsMethod = ep.DeclaringType.FindMethod(new UTF8String("InitializeSettings"));
     if (settingsMethod == null)
         throw new ComponentMissingException("Failed to locate InitializeSettings method in stub");
     settingsMethod.Body.Instructions[0].Operand = _settings.Hostname;
     settingsMethod.Body.Instructions[2].OpCode = OpCodes.Ldc_I4;
     settingsMethod.Body.Instructions[2].Operand = _settings.Port;
     settingsMethod.Body.Instructions[4].OpCode = OpCodes.Ldc_I4;
     settingsMethod.Body.Instructions[4].Operand = _settings.ReconnectDelay*1000;
 }
예제 #7
0
		IEnumerable<string> ResolveCLRNamespaces(AssemblyDef assembly, string ns) {
			foreach (var attr in assembly.CustomAttributes.FindAll("System.Windows.Markup.XmlnsDefinitionAttribute")) {
				Debug.Assert(attr.ConstructorArguments.Count == 2);

				var xmlNs = attr.ConstructorArguments[0].Value;
				var clrNs = attr.ConstructorArguments[1].Value;
				Debug.Assert(xmlNs is UTF8String && clrNs is UTF8String);

				if ((UTF8String)xmlNs == ns)
					yield return (UTF8String)clrNs;
			}
		}
예제 #8
0
		public AssemblyDef CopyTo(AssemblyDef asm) {
			asm.HashAlgorithm = HashAlgorithm;
			asm.Version = Version;
			asm.Attributes = Attributes;
			asm.PublicKey = PublicKey;
			asm.Name = Name ?? UTF8String.Empty;
			asm.Culture = Culture;
			asm.CustomAttributes.Clear();
			asm.CustomAttributes.AddRange(CustomAttributes);
			asm.DeclSecurities.Clear();
			asm.DeclSecurities.AddRange(DeclSecurities);
			return asm;
		}
        private static DeobfuscatorBase FetchSubversion1_9(AssemblyDef asmDef)
        {
            foreach (var type in asmDef.ManifestModule.Types)
            {
                if (type.Name.String.StartsWith("Lzma") && type.HasNestedTypes && type.NestedTypes.Count == 6)
                {
                    // Weak 1.9L detection
                    return Activator.CreateInstance<Deobfuscator19L>();
                }
            }

            return Activator.CreateInstance<Deobfuscator19R>();
        }
		public override DocumentTreeNodeFilterResult GetResult(AssemblyDef asm) {
			var thisFlag = VisibleMembersFlags.AssemblyDef;
			var visibleFlags = thisFlag | VisibleMembersFlags.ModuleDef |
					VisibleMembersFlags.Namespace | VisibleMembersFlags.AnyTypeDef |
					VisibleMembersFlags.FieldDef | VisibleMembersFlags.MethodDef |
					VisibleMembersFlags.InstanceConstructor | VisibleMembersFlags.PropertyDef |
					VisibleMembersFlags.EventDef | VisibleMembersFlags.AssemblyRef |
					VisibleMembersFlags.BaseTypes | VisibleMembersFlags.DerivedTypes |
					VisibleMembersFlags.ModuleRef | VisibleMembersFlags.ResourceList |
					VisibleMembersFlags.MethodBody | VisibleMembersFlags.ParamDefs |
					VisibleMembersFlags.ParamDef | VisibleMembersFlags.Locals |
					VisibleMembersFlags.Local | VisibleMembersFlags.Resource |
					VisibleMembersFlags.ResourceElement | VisibleMembersFlags.Other |
					VisibleMembersFlags.Attributes;
			return FilterFile(thisFlag, visibleFlags);
		}
예제 #11
0
		protected void WriteAssembly(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) {
			DecompileInternal(asm, output, ctx);
			output.WriteLine();
			PrintEntryPoint(asm.ManifestModule, output);
			var peImage = TryGetPEImage(asm.ManifestModule);
			if (peImage != null) {
				WriteCommentBegin(output, true);
				uint ts = peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
				var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(ts);
				var dateString = date.ToString(CultureInfo.CurrentUICulture.DateTimeFormat);
				output.Write(string.Format(dnSpy_Decompiler_Resources.Decompile_Timestamp, ts, dateString), BoxedTextColor.Comment);
				WriteCommentEnd(output, true);
				output.WriteLine();
			}
			output.WriteLine();
		}
예제 #12
0
		IEnumerable<string> GetFiles(AssemblyDef asm, ModuleDef mod) {
			var baseDir = GetBaseDirectory(asm, mod);
			if (string.IsNullOrEmpty(baseDir))
				yield break;
			var baseDirs = new List<string>();
			baseDirs.Add(baseDir);
			//TODO: Add all privatePath dirs found in app.config
			foreach (var bd in baseDirs) {
				foreach (var dir in GetDirectories(baseDir)) {
					var name = Path.GetFileName(dir);
					if (!IsValidCulture(name))
						continue;
					yield return Path.Combine(dir, asm.Name + ".resources.dll");
					yield return Path.Combine(dir, asm.Name, asm.Name + ".resources.dll");
				}
			}
		}
예제 #13
0
        public void Write(ISyntaxHighlightOutput output, ILanguage language, AssemblyDef asm, bool showToken, bool showAssemblyVersion, bool showAssemblyPublicKeyToken)
        {
            output.Write(asm.Name, IsExe(asm.ManifestModule) ? TextTokenKind.AssemblyExe : TextTokenKind.Assembly);

            bool showAsmVer = showAssemblyVersion;
            bool showPublicKeyToken = showAssemblyPublicKeyToken && !PublicKeyBase.IsNullOrEmpty2(asm.PublicKeyToken);

            if (showAsmVer || showPublicKeyToken) {
                output.WriteSpace();
                output.Write("(", TextTokenKind.Operator);

                bool needComma = false;
                if (showAsmVer) {
                    if (needComma)
                        output.WriteCommaSpace();
                    needComma = true;

                    output.Write(asm.Version);
                }

                if (showPublicKeyToken) {
                    if (needComma)
                        output.WriteCommaSpace();
                    needComma = true;

                    var pkt = asm.PublicKeyToken;
                    if (PublicKeyBase.IsNullOrEmpty2(pkt))
                        output.Write("null", TextTokenKind.Keyword);
                    else
                        output.Write(pkt.ToString(), TextTokenKind.Number);
                }

                output.Write(")", TextTokenKind.Operator);
            }

            WriteToken(output, asm, showToken);
        }
예제 #14
0
		/// <summary>
		/// Writes an assembly
		/// </summary>
		/// <param name="output">Output</param>
		/// <param name="decompiler">Decompiler</param>
		/// <param name="asm">Assembly</param>
		/// <param name="showToken">true to write tokens</param>
		/// <param name="showAssemblyVersion">true to write version</param>
		/// <param name="showAssemblyPublicKeyToken">true to write public key token</param>
		public void Write(ITextColorWriter output, IDecompiler decompiler, AssemblyDef asm, bool showToken, bool showAssemblyVersion, bool showAssemblyPublicKeyToken) {
			output.Write(IsExe(asm.ManifestModule) ? BoxedTextColor.AssemblyExe : BoxedTextColor.Assembly, asm.Name);

			bool showAsmVer = showAssemblyVersion;
			bool showPublicKeyToken = showAssemblyPublicKeyToken && !PublicKeyBase.IsNullOrEmpty2(asm.PublicKeyToken);

			if (showAsmVer || showPublicKeyToken) {
				output.WriteSpace();
				output.Write(BoxedTextColor.Punctuation, "(");

				bool needComma = false;
				if (showAsmVer) {
					if (needComma)
						output.WriteCommaSpace();
					needComma = true;

					output.Write(asm.Version);
				}

				if (showPublicKeyToken) {
					if (needComma)
						output.WriteCommaSpace();
					needComma = true;

					var pkt = asm.PublicKeyToken;
					if (PublicKeyBase.IsNullOrEmpty2(pkt))
						output.Write(BoxedTextColor.Keyword, "null");
					else
						output.Write(BoxedTextColor.Number, pkt.ToString());
				}

				output.Write(BoxedTextColor.Punctuation, ")");
			}

			WriteToken(output, asm, showToken);
		}
 /// <summary>
 /// Returns <c>true</c> if <paramref name="asm"/> is inserted in <see cref="cachedAssemblies"/>
 /// </summary>
 /// <param name="asm">Assembly to check</param>
 bool IsCached(AssemblyDef asm)
 {
     if (asm == null)
         return false;
     AssemblyDef cachedAsm;
     return cachedAssemblies.TryGetValue(GetAssemblyNameKey(new AssemblyNameInfo(asm)), out cachedAsm) &&
             cachedAsm == asm;
 }
예제 #16
0
        private IEnumerable <Tuple <AssemblyDef, ITypeDefOrRef> > GetAssemblyAndAnyFriends(AssemblyDef asm, CancellationToken ct)
        {
            if (asm == null)
            {
                yield break;
            }
            yield return(new Tuple <AssemblyDef, ITypeDefOrRef>(asm, analyzedType));

            if (asm.HasCustomAttributes)
            {
                var attributes = asm.CustomAttributes
                                 .Where(attr => attr.TypeFullName == "System.Runtime.CompilerServices.InternalsVisibleToAttribute");
                var friendAssemblies = new HashSet <string>();
                foreach (var attribute in attributes)
                {
                    if (attribute.ConstructorArguments.Count == 0)
                    {
                        continue;
                    }
                    string assemblyName = attribute.ConstructorArguments[0].Value as UTF8String;
                    if (assemblyName == null)
                    {
                        continue;
                    }
                    assemblyName = assemblyName.Split(',')[0];                     // strip off any public key info
                    friendAssemblies.Add(assemblyName);
                }

                if (friendAssemblies.Count > 0)
                {
                    IEnumerable <LoadedAssembly> assemblies = MainWindow.Instance.CurrentAssemblyList.GetAssemblies().Where(assy => assy.AssemblyDefinition != null);

                    foreach (var assembly in assemblies)
                    {
                        ct.ThrowIfCancellationRequested();
                        if (friendAssemblies.Contains(assembly.AssemblyDefinition.Name))
                        {
                            var typeref = GetScopeTypeReferenceInAssembly(assembly.AssemblyDefinition);
                            if (typeref != null)
                            {
                                yield return(new Tuple <AssemblyDef, ITypeDefOrRef>(assembly.AssemblyDefinition, typeref));
                            }
                        }
                    }
                }
            }
        }
예제 #17
0
 public CompilerMetadataReference?Create(AssemblyDef asm) =>
 CompilerMetadataReferenceCreator.Create(rawModuleBytesProvider, tempAssembly, asm.ManifestModule, nonNestedEditedTypeOrNull, makeEverythingPublic);
예제 #18
0
 public SameAssemblyTreeViewNodeFilter(ModuleDef allowedMod, ITreeViewNodeFilter filter)
     : base(filter)
 {
     this.allowedAsm = allowedMod.Assembly;
     this.allowedMod = allowedMod;
 }
예제 #19
0
        private IEnumerable <Tuple <AssemblyDef, ITypeDefOrRef> > GetReferencingAssemblies(AssemblyDef asm, CancellationToken ct)
        {
            if (asm == null)
            {
                yield break;
            }
            yield return(new Tuple <AssemblyDef, ITypeDefOrRef>(asm, this.analyzedType));

            IEnumerable <LoadedAssembly> assemblies = MainWindow.Instance.CurrentAssemblyList.GetAssemblies().Where(assy => assy.AssemblyDefinition != null);

            foreach (var assembly in assemblies)
            {
                ct.ThrowIfCancellationRequested();
                bool found = false;
                foreach (var reference in assembly.AssemblyDefinition.Modules.OfType <ModuleDefMD>().SelectMany(module => module.GetAssemblyRefs()))
                {
                    if (AssemblyNameComparer.CompareAll.CompareTo(asm, reference) == 0)
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    var typeref = GetScopeTypeReferenceInAssembly(assembly.AssemblyDefinition);
                    if (typeref != null)
                    {
                        yield return(new Tuple <AssemblyDef, ITypeDefOrRef>(assembly.AssemblyDefinition, typeref));
                    }
                }
            }
        }
예제 #20
0
 /// <inheritdoc/>
 public bool AddToCache(AssemblyDef asm)
 {
     return(true);
 }
예제 #21
0
 /// <inheritdoc/>
 public bool Remove(AssemblyDef asm)
 {
     return(false);
 }
예제 #22
0
 public void AddNsMap(string clrNs, AssemblyDef assembly, string prefix) =>
 AddNsMap(Tuple.Create(assembly, clrNs), prefix);
예제 #23
0
 public ImageReference GetImageReference(AssemblyDef assembly) =>
 GetImageReference(assembly.ManifestModule?.Characteristics ?? Characteristics.Dll);
예제 #24
0
        public static void Main(String?[]?args)
        {
            if (args is null || args.Length == 0)
            {
                Console.WriteLine("Invalid arguments");
                return;
            }

            String?path = args[0];

            if (path.IsNullOrWhiteSpace())
            {
                Console.WriteLine("Empty path provided");
                return;
            }

            var file = new FileInfo(path);

            if (!file.Exists)
            {
                Console.WriteLine("No file found");
                return;
            }
            ModuleContext ctx = ModuleDef.CreateModuleContext();
            AssemblyDef?  asm;

            try
            {
                Byte[]? b = File.ReadAllBytes(file.FullName);
                asm       = AssemblyDef.Load(b, ctx);
            } catch
            {
                Console.WriteLine("Error loading assembly");
                return;
            }

            if (asm is null)
            {
                Console.WriteLine("Error loading assembly");
                return;
            }

            String?loc = Assembly.GetExecutingAssembly().Location;

            if (!loc.IsNullOrWhiteSpace())
            {
                var f = new FileInfo(loc);
                LoadAssemblies(f.Directory.CreateSubdirectory("Extensions"));
            }

            for (Int32 i = 1; i < args.Length; ++i)
            {
                LoadAssemblies(new DirectoryInfo(args[i]));
            }


            if (PatchEntry.PatchAssembly(asm, ctx, new Logger()))
            {
                Console.WriteLine("Patch success, saving");
                var opt = new ModuleWriterOptions(asm.ManifestModule);
                asm.Write(path, opt);
                for (Int32 i = 0; i < asm.Modules.Count; ++i)
                {
                    ModuleDef?mod = asm.Modules[i];
                    if (mod.IsManifestModule)
                    {
                        continue;
                    }
                    var subOpt = new ModuleWriterOptions(mod);
                    mod.Write(path + mod.FullName + ".netmodule", subOpt);
                }
            }
            else
            {
                Console.WriteLine("Patch failed, will not save");
            }
        }
예제 #25
0
 bool IAssemblyResolver.AddToCache(AssemblyDef asm)
 {
     return(false);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AssemblyReflectionNode"/> class.
 /// </summary>
 /// <param name="assemblyDefinition">The assembly definition.</param>
 public AssemblyReflectionNode(AssemblyDef assemblyDefinition)
 {
     _assemblyDefinition = assemblyDefinition;
 }
예제 #27
0
		public EntryPointTreeViewNodeFilter(ModuleDef module) {
			this.module = module;
			this.assembly = module.Assembly;
		}
 public virtual DocumentTreeNodeFilterResult GetResult(AssemblyDef asm) => new DocumentTreeNodeFilterResult(FilterType.Hide, false);
예제 #29
0
 bool IAssemblyResolver.Remove(AssemblyDef asm)
 {
     return(false);
 }
예제 #30
0
        static void Inspection(ConfuserContext context)
        {
            context.Logger.Info("Resolving dependencies...");
            foreach (var dependency in context.Modules
                     .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module))))
            {
                try {
                    AssemblyDef assembly = context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
                }
                catch (AssemblyResolveException ex) {
                    context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex);
                    throw new ConfuserException(ex);
                }
            }

            context.Logger.Debug("Checking Strong Name...");
            foreach (ModuleDefMD module in context.Modules)
            {
                var snKey = context.Annotations.Get <StrongNameKey>(module, Marker.SNKey);
                if (snKey == null && module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", module.Name);
                }
                else if (snKey != null && !module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is provided for an unsigned module, the output may not be working.", module.Name);
                }
                else if (snKey != null && module.IsStrongNameSigned &&
                         !module.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey))
                {
                    context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", module.Name);
                }
            }

            var marker = context.Registry.GetService <IMarkerService>();

            context.Logger.Debug("Creating global .cctors...");
            foreach (ModuleDefMD module in context.Modules)
            {
                TypeDef modType = module.GlobalType;
                if (modType == null)
                {
                    modType            = new TypeDefUser("", "<Module>", null);
                    modType.Attributes = TypeAttributes.AnsiClass;
                    module.Types.Add(modType);
                    marker.Mark(modType, null);
                }
                MethodDef cctor = modType.FindOrCreateStaticConstructor();
                if (!marker.IsMarked(cctor))
                {
                    marker.Mark(cctor, null);
                }
            }

            context.Logger.Debug("Watermarking...");
            foreach (ModuleDefMD module in context.Modules)
            {
                TypeRef attrRef  = module.CorLibTypes.GetTypeRef("System", "Attribute");
                var     attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef);
                module.Types.Add(attrType);
                marker.Mark(attrType, null);

                var ctor = new MethodDefUser(
                    ".ctor",
                    MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.String),
                    MethodImplAttributes.Managed,
                    MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
                ctor.Body          = new CilBody();
                ctor.Body.MaxStack = 1;
                ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
                ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef)));
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                attrType.Methods.Add(ctor);
                marker.Mark(ctor, null);

                var attr = new CustomAttribute(ctor);
                attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, Version));

                module.CustomAttributes.Add(attr);
            }
        }
예제 #31
0
        void PopulateReferences(BamlDocument document)
        {
            var clrNs = new Dictionary <string, List <Tuple <AssemblyDef, string> > >();

            assemblyRefs.Clear();
            foreach (AssemblyInfoRecord rec in document.OfType <AssemblyInfoRecord>())
            {
                AssemblyDef assembly = context.Resolver.ResolveThrow(rec.AssemblyFullName, Module);
                assemblyRefs.Add(rec.AssemblyId, assembly);

                if (!context.Modules.Any(m => m.Assembly == assembly))
                {
                    continue;
                }

                foreach (CustomAttribute attr in assembly.CustomAttributes.FindAll("System.Windows.Markup.XmlnsDefinitionAttribute"))
                {
                    clrNs.AddListEntry(
                        (UTF8String)attr.ConstructorArguments[0].Value,
                        Tuple.Create(assembly, (string)(UTF8String)attr.ConstructorArguments[1].Value));
                }
            }

            xmlnsCtx = new XmlNsContext(document, assemblyRefs);

            typeRefs.Clear();
            foreach (TypeInfoRecord rec in document.OfType <TypeInfoRecord>())
            {
                AssemblyDef assembly;
                var         asmId = (short)(rec.AssemblyId & 0xfff);
                if (asmId == -1)
                {
                    assembly = things.FrameworkAssembly;
                }
                else
                {
                    assembly = assemblyRefs[(ushort)asmId];
                }

                AssemblyDef assemblyRef = Module.Assembly == assembly ? null : assembly;

                TypeSig typeSig = TypeNameParser.ParseAsTypeSigReflectionThrow(Module, rec.TypeFullName, new DummyAssemblyRefFinder(assemblyRef));
                typeRefs[rec.TypeId] = typeSig;

                AddTypeSigReference(typeSig, new BAMLTypeReference(typeSig, rec));
            }

            attrRefs.Clear();
            foreach (AttributeInfoRecord rec in document.OfType <AttributeInfoRecord>())
            {
                TypeSig declType;
                if (typeRefs.TryGetValue(rec.OwnerTypeId, out declType))
                {
                    TypeDef type = declType.ToBasicTypeDefOrRef().ResolveTypeDefThrow();
                    attrRefs[rec.AttributeId] = AnalyzeAttributeReference(type, rec);
                }
                else
                {
                    Debug.Assert((short)rec.OwnerTypeId < 0);
                    TypeDef declTypeDef = things.Types((KnownTypes)(-(short)rec.OwnerTypeId));
                    attrRefs[rec.AttributeId] = AnalyzeAttributeReference(declTypeDef, rec);
                }
            }

            strings.Clear();
            foreach (StringInfoRecord rec in document.OfType <StringInfoRecord>())
            {
                strings[rec.StringId] = rec;
            }

            foreach (PIMappingRecord rec in document.OfType <PIMappingRecord>())
            {
                var         asmId = (short)(rec.AssemblyId & 0xfff);
                AssemblyDef assembly;
                if (asmId == -1)
                {
                    assembly = things.FrameworkAssembly;
                }
                else
                {
                    assembly = assemblyRefs[(ushort)asmId];
                }

                Tuple <AssemblyDef, string> scope = Tuple.Create(assembly, rec.ClrNamespace);
                clrNs.AddListEntry(rec.XmlNamespace, scope);
            }

            xmlns.Clear();
            foreach (XmlnsPropertyRecord rec in document.OfType <XmlnsPropertyRecord>())
            {
                List <Tuple <AssemblyDef, string> > clrMap;
                if (clrNs.TryGetValue(rec.XmlNamespace, out clrMap))
                {
                    xmlns[rec.Prefix] = clrMap;
                    foreach (var scope in clrMap)
                    {
                        xmlnsCtx.AddNsMap(scope, rec.Prefix);
                    }
                }
            }
        }
        public void Run(AstNode compilationUnit)
        {
            // First determine all the namespaces that need to be imported:
            compilationUnit.AcceptVisitor(new FindRequiredImports(this), null);

            importedNamespaces.Add("System");             // always import System, even when not necessary
            importedOrDeclaredNamespaces.Add("System");

            if (context.Settings.UsingDeclarations)
            {
                // Now add using declarations for those namespaces:
                foreach (string ns in GetNamespacesInReverseOrder())
                {
                    // we go backwards (OrderByDescending) through the list of namespaces because we insert them backwards
                    // (always inserting at the start of the list)
                    string[] parts  = ns.Split(namespaceSep);
                    AstType  nsType = new SimpleType(parts[0]).WithAnnotation(TextTokenKind.NamespacePart);
                    for (int i = 1; i < parts.Length; i++)
                    {
                        nsType = new MemberType {
                            Target = nsType, MemberNameToken = Identifier.Create(parts[i]).WithAnnotation(TextTokenKind.NamespacePart)
                        }.WithAnnotation(TextTokenKind.NamespacePart);
                    }
                    compilationUnit.InsertChildAfter(null, new UsingDeclaration {
                        Import = nsType
                    }, SyntaxTree.MemberRole);
                }
            }

            if (!context.Settings.FullyQualifyAmbiguousTypeNames && !context.Settings.FullyQualifyAllTypes)
            {
                return;
            }

            if (context.CurrentModule != null)
            {
                if (lastCheckedModule != context.CurrentModule)
                {
                    typesWithNamespace_currentModule.Clear();
                    BuildAmbiguousTypeNamesTable(typesWithNamespace_currentModule, context.CurrentModule.Types, true);
                }
                FindAmbiguousTypeNames(typesWithNamespace_currentModule, true);
                if (lastCheckedModule != context.CurrentModule)
                {
                    var asmDict = new Dictionary <AssemblyDef, List <AssemblyDef> >(AssemblyEqualityComparer.Instance);
                    lastCheckedModule = context.CurrentModule;
                    foreach (var r in context.CurrentModule.GetAssemblyRefs())
                    {
                        AssemblyDef d = context.CurrentModule.Context.AssemblyResolver.Resolve(r, context.CurrentModule);
                        if (d == null)
                        {
                            continue;
                        }
                        List <AssemblyDef> list;
                        if (!asmDict.TryGetValue(d, out list))
                        {
                            asmDict.Add(d, list = new List <AssemblyDef>());
                        }
                        list.Add(d);
                    }
                    typesWithNamespace_allAsms_list.Clear();
                    foreach (var list in asmDict.Values)
                    {
                        var dict = new Dictionary <string, List <TypeDef> >(StringComparer.Ordinal);
                        BuildAmbiguousTypeNamesTable(dict, GetTypes(list), false);
                        typesWithNamespace_allAsms_list.Add(dict);
                    }
                }
                foreach (var dict in typesWithNamespace_allAsms_list)
                {
                    FindAmbiguousTypeNames(dict, false);
                }
            }

            // verify that the SimpleTypes refer to the correct type (no ambiguities)
            compilationUnit.AcceptVisitor(new FullyQualifyAmbiguousTypeNamesVisitor(this), null);
        }
예제 #33
0
 public override void Decompile(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) => WriteError(output);
예제 #34
0
 public DummyAssemblyRefFinder(AssemblyDef assemblyDef)
 {
     this.assemblyDef = assemblyDef;
 }
예제 #35
0
 public CompilerMetadataReference?Create(AssemblyDef asm) =>
 CompilerMetadataReferenceCreator.Create(rawModuleBytesProvider, asm.ManifestModule, makeEverythingPublic);
예제 #36
0
			public bool Remove(AssemblyDef asm) {
				IAssemblyResolver ar = DnSpyFileList.AssemblyResolver;
				return ar.Remove(asm);
			}
예제 #37
0
        public void InitialiseAssemblyDefFileUsedForTests()
        {
            string dir = System.AppDomain.CurrentDomain.BaseDirectory;

            _assemblyDef = AssemblyDef.Create(System.IO.Path.Combine(dir, TestFile));
        }
예제 #38
0
		void DecompileInternal(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) {
			this.WriteCommentLine(output, asm.ManifestModule.Location);
			if (asm.IsContentTypeWindowsRuntime)
				this.WriteCommentLine(output, asm.Name + " [WinRT]");
			else
				this.WriteCommentLine(output, asm.FullName);
		}
예제 #39
0
 public virtual FileTreeNodeFilterResult GetResult(AssemblyDef asm)
 {
     return(new FileTreeNodeFilterResult(FilterType.Hide, false));
 }
		public virtual DocumentTreeNodeFilterResult GetResult(AssemblyDef asm) => new DocumentTreeNodeFilterResult();
        AssemblyDef FindClosestAssembly(AssemblyNameInfo assembly, AssemblyDef closest, IEnumerable<string> paths, ModuleContext moduleContext)
        {
            if (paths == null)
                return closest;
            var asmComparer = new AssemblyNameComparer(AssemblyNameComparerFlags.All);
            foreach (var path in paths) {
                ModuleDefMD mod = null;
                try {
                    mod = ModuleDefMD.Load(path, moduleContext);
                    var asm = mod.Assembly;
                    if (asm != null && asmComparer.CompareClosest(assembly, new AssemblyNameInfo(closest), new AssemblyNameInfo(asm)) == 1) {
                        if (!IsCached(closest) && closest != null && closest.ManifestModule != null)
                            closest.ManifestModule.Dispose();
                        closest = asm;
                        mod = null;
                    }
                }
                catch {
                }
                finally {
                    if (mod != null)
                        mod.Dispose();
                }
            }

            return closest;
        }
 public virtual AssemblyDef DeobfuscateAssembly(AssemblyDef asmDef)
 {
     return null;
 }
예제 #43
0
		public ImageReference GetImageReference(AssemblyDef assembly) {
			var mod = assembly.ManifestModule;
			return GetImageReference(mod != null ? mod.Characteristics : Characteristics.Dll);
		}
예제 #44
0
 bool IAssemblyResolver.AddToCache(AssemblyDef asm)
 {
     return false;
 }
예제 #45
0
        IEnumerable <AnalyzerTreeNodeData> FindReferencesInModule(IEnumerable <ModuleDef> modules, ITypeDefOrRef tr, CancellationToken ct)
        {
            var checkedAsms = new HashSet <AssemblyDef>();

            foreach (var module in modules)
            {
                if ((usage & AttributeTargets.Assembly) != 0)
                {
                    AssemblyDef asm = module.Assembly;
                    if (asm != null && !checkedAsms.Contains(asm) && asm.HasCustomAttributes)
                    {
                        checkedAsms.Add(asm);
                        foreach (var attribute in asm.CustomAttributes)
                        {
                            if (new SigComparer().Equals(attribute.AttributeType, tr))
                            {
                                yield return(new AssemblyNode(asm)
                                {
                                    Context = Context
                                });

                                break;
                            }
                        }
                    }
                }

                ct.ThrowIfCancellationRequested();

                if ((usage & AttributeTargets.Module) != 0)
                {
                    if (module.HasCustomAttributes)
                    {
                        foreach (var attribute in module.CustomAttributes)
                        {
                            if (new SigComparer().Equals(attribute.AttributeType, tr))
                            {
                                yield return(new ModuleNode(module)
                                {
                                    Context = Context
                                });

                                break;
                            }
                        }
                    }
                }

                ct.ThrowIfCancellationRequested();

                foreach (TypeDef type in TreeTraversal.PreOrder(module.Types, t => t.NestedTypes))
                {
                    ct.ThrowIfCancellationRequested();
                    foreach (var result in FindReferencesWithinInType(type, tr))
                    {
                        ct.ThrowIfCancellationRequested();
                        yield return(result);
                    }
                }
            }
        }
예제 #46
0
파일: AssemblyNode.cs 프로젝트: zz110/dnSpy
 public AssemblyNode(AssemblyDef analyzedAssembly) => this.analyzedAssembly = analyzedAssembly;
예제 #47
0
 public string GetPrefix(string clrNs, AssemblyDef assembly)
 {
     string prefix;
     if (!xmlNsMap.TryGetValue(Tuple.Create(assembly, clrNs), out prefix)) {
         prefix = "_" + x++;
         ushort assemblyId = assemblyRefs[assembly];
         doc.Insert(rootIndex, new XmlnsPropertyRecord {
             AssemblyIds = new[] { assemblyId },
             Prefix = prefix,
             XmlNamespace = "clr-namespace:" + clrNs
         });
         doc.Insert(rootIndex - 1, new PIMappingRecord {
             AssemblyId = assemblyId,
             ClrNamespace = clrNs,
             XmlNamespace = "clr-namespace:" + clrNs
         });
         rootIndex++;
     }
     return prefix;
 }
예제 #48
0
 public virtual DocumentTreeNodeFilterResult GetResult(AssemblyDef asm) => new DocumentTreeNodeFilterResult();
예제 #49
0
			public bool AddToCache(AssemblyDef asm) {
				IAssemblyResolver ar = DnSpyFileList.AssemblyResolver;
				return ar.AddToCache(asm);
			}
예제 #50
0
        DocumentTabReferenceResult Create(AssemblyDef asm)
        {
            var node = documentTreeView.FindNode(asm);

            return(node == null ? null : Create(node));
        }
예제 #51
0
		public virtual void Decompile(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) => DecompileInternal(asm, output, ctx);
예제 #52
0
        /// <summary>
        /// Utilises the information provided to create instances of specific Page classes.
        /// </summary>
        /// <param name="forItem">The item to create the Page for</param>
        /// <param name="commentsXml">The comments file where the code comments can be obtained</param>
        /// <param name="mapReference">The DocumentMap to use and to add to</param>
        /// <returns>A new Page instance that can be displayed in the LiveDocumentor</returns>
        public static Page Create(Entry entry, ICommentSource commentsXml)
        {
            TraceHelper.WriteLine("create page");
            TraceHelper.Indent();
            object forItem = entry.Item;

            Page created = null;

            if (forItem is AssemblyDef)
            {
                AssemblyDef ass = forItem as AssemblyDef;
                TraceHelper.WriteLine("assemblydef ({0})", ass.Name);
                created = new AssemblyPage(ass, commentsXml);
            }
            else if (forItem is MethodDef)
            {
                MethodDef method = forItem as MethodDef;
                TraceHelper.WriteLine("method ({0}.{1}.{2})", method.Type.Namespace, method.Type.Name, method.Name);
                created = new MethodPage(method, commentsXml);
            }
            else if (forItem is List <MethodDef> )
            {
                TraceHelper.WriteLine("methods page");
                created = new TypeMethodsPage(forItem as List <MethodDef>, commentsXml);
            }
            else if (forItem is TypeDef)
            {
                TypeDef typeDef = forItem as TypeDef;
                TraceHelper.WriteLine("typedef ({0}.{1})", typeDef.Namespace, typeDef.Name);
                if (typeDef.InheritsFrom != null && typeDef.InheritsFrom.GetFullyQualifiedName() == "System.Enum")
                {
                    created = new EnumerationPage(forItem as TypeDef, commentsXml);
                }
                else if (typeDef.IsDelegate)
                {
                    created = new DelegatePage(forItem as TypeDef, commentsXml);
                }
                else
                {
                    created = new TypePage(forItem as TypeDef, commentsXml);
                }
            }
            else if (forItem is KeyValuePair <string, List <TypeDef> > )
            {
                TraceHelper.WriteLine("namespace {0}", ((KeyValuePair <string, List <TypeDef> >)forItem).Key);
                created = new NamespacePage((KeyValuePair <string, List <TypeDef> >)forItem, commentsXml);
            }
            else if (forItem is List <FieldDef> )
            {
                TraceHelper.WriteLine("fields page");
                created = new TypeFieldsPage(forItem as List <FieldDef>, commentsXml);
            }
            else if (forItem is FieldDef)
            {
                FieldDef field = forItem as FieldDef;
                TraceHelper.WriteLine("field ({0}.{1}.{2})", field.Type.Namespace, field.Type.Name, field.Name);
                created = new FieldPage(field, commentsXml);
            }
            else if (forItem is List <PropertyDef> )
            {
                TraceHelper.WriteLine("properties page");
                created = new TypePropertiesPage(forItem as List <PropertyDef>, commentsXml);
            }
            else if (forItem is PropertyDef)
            {
                PropertyDef property = forItem as PropertyDef;
                TraceHelper.WriteLine("property ({0}.{1}.{2})", property.OwningType.Namespace, property.OwningType.Name, property.Name);
                created = new PropertyPage(property, commentsXml);
            }
            else if (forItem is List <EventDef> )
            {
                TraceHelper.WriteLine("events page");
                created = new TypeEventsPage(forItem as List <EventDef>, commentsXml);
            }
            else if (forItem is EventDef)
            {
                EventDef ev = forItem as EventDef;
                TraceHelper.WriteLine("event ({0}.{1}.{2})", ev.Type.Namespace, ev.Type.Name, ev.Name);
                created = new EventPage(ev, commentsXml);
            }
            else if (forItem is TheBoxSoftware.Documentation.EntryTypes)
            {
                TheBoxSoftware.Documentation.EntryTypes type = (Documentation.EntryTypes)forItem;
                switch (type)
                {
                case Documentation.EntryTypes.NamespaceContainer:
                    created = new NamespaceContainerPage(entry);
                    break;
                }
            }
            else
            {
                created = new Page(forItem.ToString());
            }

            TraceHelper.Unindent();

            return(created);
        }
예제 #53
0
 public DummyAssemblyRefFinder(AssemblyDef assemblyDef)
 {
     this.assemblyDef = assemblyDef;
 }
예제 #54
0
 public virtual void Decompile(AssemblyDef asm, IDecompilerOutput output, DecompilationContext ctx) => DecompileInternal(asm, output, ctx);
예제 #55
0
 public AssemblyTreeNode FindAssemblyNode(AssemblyDef asm)
 {
     if (asm == null)
         return null;
     App.Current.Dispatcher.VerifyAccess();
     foreach (AssemblyTreeNode node in this.Children) {
         if (node.LoadedAssembly.IsLoaded && node.LoadedAssembly.AssemblyDefinition == asm)
             return node;
     }
     return null;
 }
예제 #56
0
        static (string framework, string version, string profile) TryGetTargetFrameworkAttribute(AssemblyDef asm)
        {
            var ca = asm?.CustomAttributes.Find("System.Runtime.Versioning.TargetFrameworkAttribute");

            if (ca == null)
            {
                return(default);
예제 #57
0
        /// <summary>
        /// Reads a module
        /// </summary>
        /// <param name="fileRid">File rid</param>
        /// <param name="owner">The assembly owning the module we should read</param>
        /// <returns>A new <see cref="ModuleDefMD"/> instance or <c>null</c> if <paramref name="fileRid"/>
        /// is invalid or if it's not a .NET module.</returns>
        internal ModuleDefMD ReadModule(uint fileRid, AssemblyDef owner)
        {
            var fileDef = ResolveFile(fileRid);
            if (fileDef == null)
                return null;
            if (!fileDef.ContainsMetaData)
                return null;
            var fileName = GetValidFilename(GetBaseDirectoryOfImage(), UTF8String.ToSystemString(fileDef.Name));
            if (fileName == null)
                return null;
            ModuleDefMD module;
            try {
                module = ModuleDefMD.Load(fileName);
            }
            catch {
                module = null;
            }
            if (module != null) {
                // share context
                module.context = context;

                var asm = module.Assembly;
                if (asm != null && asm != owner)
                    asm.Modules.Remove(module);
            }
            return module;
        }
예제 #58
0
        public ImageReference GetImageReference(AssemblyDef assembly)
        {
            var mod = assembly.ManifestModule;

            return(GetImageReference(mod != null ? mod.Characteristics : Characteristics.Dll));
        }
예제 #59
0
 bool IAssemblyResolver.Remove(AssemblyDef asm)
 {
     return false;
 }
예제 #60
0
        private IEnumerable <AnalyzerTreeNode> FindReferencesInAssembly(IEnumerable <ModuleDef> modules, ITypeDefOrRef tr, CancellationToken ct)
        {
            foreach (var module in modules)
            {
                //since we do not display modules as separate entities, coalesce the assembly and module searches
                bool foundInAssyOrModule = false;

                if ((usage & AttributeTargets.Assembly) != 0)
                {
                    AssemblyDef asm = module.Assembly;
                    if (asm != null && asm.HasCustomAttributes)
                    {
                        foreach (var attribute in asm.CustomAttributes)
                        {
                            if (new SigComparer().Equals(attribute.AttributeType, tr))
                            {
                                foundInAssyOrModule = true;
                                break;
                            }
                        }
                    }
                }

                if (!foundInAssyOrModule)
                {
                    ct.ThrowIfCancellationRequested();

                    //search module
                    if ((usage & AttributeTargets.Module) != 0)
                    {
                        if (module.HasCustomAttributes)
                        {
                            foreach (var attribute in module.CustomAttributes)
                            {
                                if (new SigComparer().Equals(attribute.AttributeType, tr))
                                {
                                    foundInAssyOrModule = true;
                                    break;
                                }
                            }
                        }
                    }
                }

                if (foundInAssyOrModule)
                {
                    yield return(new AnalyzedAssemblyTreeNode(module));
                }

                ct.ThrowIfCancellationRequested();

                foreach (TypeDef type in TreeTraversal.PreOrder(module.Types, t => t.NestedTypes).OrderBy(t => t.FullName))
                {
                    ct.ThrowIfCancellationRequested();
                    foreach (var result in FindReferencesWithinInType(type, tr))
                    {
                        ct.ThrowIfCancellationRequested();
                        yield return(result);
                    }
                }
            }
        }