Inheritance: IAssemblyResolver
            public void ShouldNotReturnNonManagedAssemblies(
                [Frozen] Mock<IFileSystem> fileSystemMock,
                [Frozen] Mock<IPackageAssemblyResolver> packageAssemblyResolverMock,
                [Frozen] Mock<IAssemblyUtility> assemblyUtilityMock,
                AssemblyResolver resolver
            )
            {
                const string WorkingDirectory = @"C:\";

                var binFolder = Path.Combine(WorkingDirectory, "bin");
                var managed = Path.Combine(binFolder, "MyAssembly.dll");
                var nonManaged = Path.Combine(binFolder, "MyNonManagedAssembly.dll");

                fileSystemMock.Setup(x => x.DirectoryExists(binFolder)).Returns(true);
                fileSystemMock.SetupGet(x => x.PackagesFolder).Returns("packages");
                fileSystemMock.SetupGet(x => x.BinFolder).Returns("bin");
                fileSystemMock.Setup(x => x.EnumerateFiles(binFolder, It.IsAny<string>(), SearchOption.TopDirectoryOnly
                    ))
                    .Returns(new[] { managed, nonManaged });

                assemblyUtilityMock.Setup(x => x.IsManagedAssembly(managed)).Returns(true);
                assemblyUtilityMock.Setup(x => x.IsManagedAssembly(nonManaged)).Returns(false);

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory).ToList();

                assemblies.Count.ShouldEqual(1);
                assemblies[0].ShouldEqual(managed);
            }
            public void ShouldOnlyReturnBinariesWhenFlagIsSet(
                [Frozen] Mock<IPackageAssemblyResolver> packageAssemblyResolverMock, 
                [Frozen] Mock<IFileSystem> fileSystemMock, 
                [Frozen] Mock<IAssemblyUtility> assemblyUtilityMock,
                AssemblyResolver resolver)
            {
                const string WorkingDirectory = @"C:\";

                var binFolder = Path.Combine(WorkingDirectory, "bin");

                assemblyUtilityMock.Setup(a => a.IsManagedAssembly(It.IsAny<string>())).Returns(true);
                fileSystemMock.Setup(x => x.DirectoryExists(binFolder)).Returns(true);
                fileSystemMock.Setup(x => x.DirectoryExists(@"C:\packages")).Returns(true);
                fileSystemMock.SetupGet(x => x.PackagesFolder).Returns("packages");
                fileSystemMock.SetupGet(x => x.BinFolder).Returns("bin");
                fileSystemMock.Setup(x => x.EnumerateFiles(binFolder, It.IsAny<string>(), SearchOption.AllDirectories))
                    .Returns(Enumerable.Empty<string>());

                packageAssemblyResolverMock.Setup(p=>p.GetAssemblyNames(WorkingDirectory)).Returns(new string[] {"test.dll", "test.exe", "test.foo"});

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory, true).ToList();
                assemblies.ShouldNotContain("test.foo");
                assemblies.ShouldContain("test.dll");
                assemblies.ShouldContain("test.exe");
            }
Example #3
0
 public AssemblyLoaderImporter(ModuleReader moduleReader, AssemblyResolver assemblyResolver, EmbedTask embedTask)
 {
     instructionConstructorInfo = typeof (Instruction).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof (OpCode), typeof (object)}, null);
     this.moduleReader = moduleReader;
     this.assemblyResolver = assemblyResolver;
     this.embedTask = embedTask;
 }
 public void Should_exception_if_type_not_found()
 {
     var job = new PrivateJob { Type = "someType" };
     assemblyResolver = new AssemblyResolver(this.dir, log);
     //Test
     var ex = Assert.Throws<PluginNotFoundOrLoadedException>(() => assemblyResolver.ResolveType(job));
     //Assert
     Assert.That(ex.Message, Is.EqualTo(string.Format("The plugin someType is not found or loaded")));
 }
        public void DefaultResolve()
        {

            var resolver = new AssemblyResolver();
            resolver.Should().NotBeNull();

            var assemblies = resolver.Resolve().ToList();
            assemblies.Should().NotBeEmpty();
            assemblies.Should().Contain(a => a.FullName.StartsWith("System"));

        }
        public void IncludeAssemblyForTestCore()
        {
            var resolver = new AssemblyResolver();
            resolver.Should().NotBeNull();

            resolver.IncludeAssemblyFor<SampleWorker>();

            var assemblies = resolver.Resolve().ToList();
            assemblies.Should().NotBeEmpty();
            assemblies.Count.Should().Be(1);
            assemblies.Should().Contain(a => a == typeof(SampleWorker).Assembly);
        }
 public void Should_Resolve_type_sucessfuly()
 {
     var job = new WmiClient();
     var files = new List<string>() { string.Format(@"{0}\SqlToGraphite.Plugin.Wmi.dll", Directory.GetCurrentDirectory()) };
     dir.Expect(x => x.GetFilesInCurrentDirectory(AssemblyResolver.FilesToScan)).Return(files);
     //Test
     assemblyResolver = new AssemblyResolver(this.dir, log);
     var rtn = assemblyResolver.ResolveType(job);
     //Assert
     Assert.That(rtn.FullName, Is.EqualTo(job.GetType().FullName));
     dir.VerifyAllExpectations();
 }
        public void CreateAssemblyResolver(IEnumerable<string> paths)
        {
            string appDataKey = typeof (AssemblyResolver).FullName;
            resolver = (AssemblyResolver)AppDomain.CurrentDomain.GetData(appDataKey)
                       ?? new AssemblyResolver(new ConsoleLog());
            AppDomain.CurrentDomain.SetData(appDataKey, resolver);

            foreach (var path in paths)
            {
                resolver.AddDirectory(path);
            }
        }
        public void ExcludeSystem()
        {
            var domainAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            var resolver = new AssemblyResolver();
            resolver.Should().NotBeNull();

            resolver.ExcludeName("System");

            var assemblies = resolver.Resolve().ToList();
            assemblies.Should().NotBeEmpty();
            assemblies.Should().NotContain(a => a.FullName.StartsWith("System"));
        }
 public void Should_ignore_bad_image_exception_for_not_dot_net_dlls()
 {
     File.WriteAllText("bad.dll", "abc");
     var job = new WmiClient() { Type = "SqlToGraphite.Plugin.Wmi.WmiClient" };
     var files = new List<string>() { string.Format(@"{0}\bad.dll", Directory.GetCurrentDirectory()), string.Format(@"{0}\SqlToGraphite.Plugin.Wmi.dll", Directory.GetCurrentDirectory()) };
     dir.Expect(x => x.GetFilesInCurrentDirectory(AssemblyResolver.FilesToScan)).Return(files);
     //Test
     assemblyResolver = new AssemblyResolver(this.dir, log);
     //Test
     var type = assemblyResolver.ResolveType(job);
     //Assert
     Assert.That(type.FullName, Is.EqualTo(job.GetType().FullName));
     File.Delete("bad.dll");
 }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration"/> class.
        /// </summary>
        public Configuration()
        {
            _assemblies = new AssemblyResolver();

            // exclude system assemblies
            _assemblies.ExcludeName("mscorlib");
            _assemblies.ExcludeName("Microsoft");
            _assemblies.ExcludeName("System");
            
            // exclude self
            _assemblies.ExcludeName("KickStart");

            _starters = new List<IKickStarter>();
        }
        public SqlToGraphiteConfig()
        {
            var job = new JobImpl();
            this.WireUpLog4Net();
            var assemblyResolver = new AssemblyResolver(new DirectoryImpl(), log);
            jobTypes = assemblyResolver.ResolveTypes(job);
            alljobtypes = assemblyResolver.ResolveAllTypes(job);
            //JobTypes = GetJobTypes().ToArray();
            clientTypes = GetClientTypes().ToArray();

            this.Jobs = new List<Job>();
            this.Clients = new ListOfUniqueType<Client>();
            this.Hosts = new List<Host>();
            this.Templates = new List<Template>();
            this.genericSerializer = new GenericSerializer(Global.GetNameSpace());
        }
Example #13
0
        public CompilerBase(
            IFrontEnd frontEnd, IMiddleEnd middleEnd, IBackEnd backEnd,
            CompilerOptions options
            )
        {
            _options = options;

            _frontEnd = frontEnd;
            _middleEnd = middleEnd;
            _backEnd = backEnd;

            _frontEnd.Compiler = this;
            _middleEnd.Compiler = this;
            _backEnd.Compiler = this;

            _resolver = new AssemblyResolver(this);
        }
 public ConfigRepository(IConfigReader configReader, ICache cache, ISleep sleep, ILog log,
     int errorReadingConfigSleepTime, IGenericSerializer genericSerializer)
 {
     this.configReader = configReader;
     this.cache = cache;
     this.sleep = sleep;
     ConfigRepository.log = log;
     this.errorReadingConfigSleepTime = errorReadingConfigSleepTime;
     this.genericSerializer = genericSerializer;
     clientList = new GraphiteClients();
     var dir = new DirectoryImpl();
     if (ar == null)
     {
         ar = new AssemblyResolver(dir, log);
     }
     this.masterConfig = new SqlToGraphiteConfig(ar, log);
     this.Hash = "NotSet";
 }
		void Find() {
			var cflowDeobfuscator = new CflowDeobfuscator(new MethodCallInliner(true));

			foreach (var type in module.Types) {
				if (DotNetUtils.GetPInvokeMethod(type, "kernel32", "CloseHandle") == null)
					continue;

				var resolver = new AssemblyResolver(type, cflowDeobfuscator);
				if (!resolver.Detected)
					continue;
				var patcher = new MemoryPatcher(type, cflowDeobfuscator);
				if (!patcher.Detected)
					continue;

				assemblyResolver = resolver;
				memoryPatcher = patcher;
				return;
			}
		}
            public void ShouldReturnAssembliesFromPackagesFolder()
            {
                const string WorkingDirectory = @"C:\";

                var packagesFolder = Path.Combine(WorkingDirectory, Constants.PackagesFolder);
                var assemblyFile = Path.Combine(packagesFolder, "MyAssembly.dll");

                var fileSystem = new Mock<IFileSystem>();
                fileSystem.Setup(x => x.DirectoryExists(packagesFolder)).Returns(true);

                var packageAssemblyResolver = new Mock<IPackageAssemblyResolver>();
                packageAssemblyResolver.Setup(x => x.GetAssemblyNames(WorkingDirectory, It.IsAny<Action<string>>())).Returns(new[] { assemblyFile });

                var resolver = new AssemblyResolver(fileSystem.Object, packageAssemblyResolver.Object, Mock.Of<IAssemblyUtility>(), Mock.Of<ILog>());

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory).ToList();

                assemblies.Count.ShouldEqual(1);
                assemblies[0].ShouldEqual(assemblyFile);
            }
            public void ShouldReturnAssembliesFromBinFolder()
            {
                const string WorkingDirectory = @"C:\";

                var binFolder = Path.Combine(WorkingDirectory, Constants.BinFolder);
                var assemblyFile = Path.Combine(binFolder, "MyAssembly.dll");

                var fileSystem = new Mock<IFileSystem>();
                fileSystem.Setup(x => x.DirectoryExists(binFolder)).Returns(true);
                fileSystem.Setup(x => x.EnumerateFiles(binFolder, It.IsAny<string>(), SearchOption.AllDirectories)).Returns(new[] { assemblyFile });

                var assemblyUtility = new Mock<IAssemblyUtility>();
                assemblyUtility.Setup(x => x.IsManagedAssembly(assemblyFile)).Returns(true);

                var resolver = new AssemblyResolver(fileSystem.Object, Mock.Of<IPackageAssemblyResolver>(), assemblyUtility.Object, Mock.Of<ILog>());

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory).ToList();

                assemblies.Count.ShouldEqual(1);
                assemblies[0].ShouldEqual(assemblyFile);
            }
Example #18
0
            public void ShouldNotReturnScriptDll()
            {
                const string WorkingDirectory = @"C:\";

                var binFolder = Path.Combine(WorkingDirectory, "bin");
                var scriptDll = Path.Combine(binFolder, "script.dll");

                var fileSystem = new Mock<IFileSystem>();
                fileSystem.Setup(x => x.DirectoryExists(binFolder)).Returns(true);
                fileSystem.Setup(x => x.EnumerateFiles(binFolder, It.IsAny<string>(), SearchOption.AllDirectories))
                    .Returns(new[] { scriptDll });

                var assemblyUtility = new Mock<IAssemblyUtility>();
                assemblyUtility.Setup(x => x.IsManagedAssembly(scriptDll)).Returns(true);

                var resolver = new AssemblyResolver(fileSystem.Object, Mock.Of<IPackageAssemblyResolver>(), assemblyUtility.Object, Mock.Of<ILog>());

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory, "script.csx").ToList();

                assemblies.Count.ShouldEqual(0);
            }
Example #19
0
            public void ShouldReturnAssembliesFromPackagesFolder(
                [Frozen] Mock<IFileSystem> fileSystemMock,
                [Frozen] Mock<IPackageAssemblyResolver> packageAssemblyResolverMock,
                AssemblyResolver resolver
            )
            {
                const string WorkingDirectory = @"C:\";

                var packagesFolder = Path.Combine(WorkingDirectory, "packages");
                var assemblyFile = Path.Combine(packagesFolder, "MyAssembly.dll");

                fileSystemMock.Setup(x => x.DirectoryExists(packagesFolder)).Returns(true);
                fileSystemMock.SetupGet(x => x.PackagesFolder).Returns("packages");
                fileSystemMock.SetupGet(x => x.BinFolder).Returns("bin");

                packageAssemblyResolverMock.Setup(x => x.GetAssemblyNames(WorkingDirectory)).Returns(new[] { assemblyFile });

                var assemblies = resolver.GetAssemblyPaths(WorkingDirectory).ToList();

                assemblies.Count.ShouldEqual(1);
                assemblies[0].ShouldEqual(assemblyFile);
            }
Example #20
0
        public static TaskManager CreateTaskManager(SqlToGraphiteSection configuration)
        {
            var cacheLength = new TimeSpan(0, configuration.ConfigCacheLengthMinutes, 0);
            var stop = new Stop();
            var directoryImpl = new DirectoryImpl();
            var assemblyResolver = new AssemblyResolver(directoryImpl, log);
            IEncryption encryption = new Encryption();
            IDataClientFactory dataClientFactory = new DataClientFactory(log, assemblyResolver, encryption);
            IGraphiteClientFactory graphiteClientFactory = new GraphiteClientFactory(log);

            var configReader = new ConfigHttpReader(configuration.ConfigUri, configuration.ConfigUsername, configuration.ConfigPassword);
            var cache = new Cache(cacheLength, log);
            var sleeper = new Sleeper();
            var genericSer = new GenericSerializer(Global.GetNameSpace());
            var cr = new ConfigRepository(configReader, cache, sleeper, log, configuration.MinutesBetweenRetryToGetConfigOnError, genericSer);
            var configMapper = new ConfigMapper(configuration.Hostname, stop, dataClientFactory, graphiteClientFactory, log, cr);
            var roleConfigFactory = new RoleConfigFactory();
            var environment = new Environment();
            var taskSetBuilder = new TaskSetBuilder();
            var configController = new ConfigController(configMapper, log, cr, roleConfigFactory, environment, taskSetBuilder);
            return new TaskManager(log, configController, configuration.ConfigUri, stop, sleeper, configuration.CheckConfigUpdatedEveryMinutes);
        }
Example #21
0
 protected override void scanForObfuscator()
 {
     methodsDecrypter = new MethodsDecrypter(module);
     methodsDecrypter.find();
     stringDecrypter = new StringDecrypter(module);
     stringDecrypter.find(DeobfuscatedFile);
     booleanDecrypter = new BooleanDecrypter(module);
     booleanDecrypter.find();
     assemblyResolver = new AssemblyResolver(module);
     assemblyResolver.find(DeobfuscatedFile);
     obfuscatorName = detectVersion();
     resourceResolver = new ResourceResolver(module);
     resourceResolver.find(DeobfuscatedFile);
 }
Example #22
0
		public ResolveAssemblyReference ()
		{
			assembly_resolver = new AssemblyResolver ();
		}
Example #23
0
 public static void Main(string[] args)
 {
     AssemblyResolver.Init();
     Instance().Load();
 }
Example #24
0
        public App()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                var requestedAssembly = new AssemblyName(args.Name);

                try
                {
                    if (string.Equals(requestedAssembly.Name, "chocolatey", StringComparison.OrdinalIgnoreCase))
                    {
                        var installDir = Environment.GetEnvironmentVariable("ChocolateyInstall");
                        if (string.IsNullOrEmpty(installDir))
                        {
                            var rootDrive = Path.GetPathRoot(Assembly.GetExecutingAssembly().Location);
                            if (string.IsNullOrEmpty(rootDrive))
                            {
                                return(null); // TODO: Maybe return the chocolatey.dll file instead?
                            }

                            installDir = Path.Combine(rootDrive, "ProgramData", "chocolatey");
                        }

                        var assemblyLocation = Path.Combine(installDir, "choco.exe");

                        return(AssemblyResolver.ResolveOrLoadAssembly("choco", string.Empty, assemblyLocation));
                    }

#if FORCE_CHOCOLATEY_OFFICIAL_KEY
                    var chocolateyGuiPublicKey = Bootstrapper.OfficialChocolateyPublicKey;
#else
                    var chocolateyGuiPublicKey = Bootstrapper.UnofficialChocolateyPublicKey;
#endif

                    if (AssemblyResolver.DoesPublicKeyTokenMatch(requestedAssembly, chocolateyGuiPublicKey) &&
                        string.Equals(requestedAssembly.Name, Bootstrapper.ChocolateyGuiCommonAssemblySimpleName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(AssemblyResolver.ResolveOrLoadAssembly(
                                   Bootstrapper.ChocolateyGuiCommonAssemblySimpleName,
                                   AssemblyResolver.GetPublicKeyToken(requestedAssembly),
                                   Bootstrapper.ChocolateyGuiCommonAssemblyLocation));
                    }

                    if (AssemblyResolver.DoesPublicKeyTokenMatch(requestedAssembly, chocolateyGuiPublicKey) &&
                        string.Equals(requestedAssembly.Name, Bootstrapper.ChocolateyGuiCommonWindowsAssemblySimpleName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(AssemblyResolver.ResolveOrLoadAssembly(
                                   Bootstrapper.ChocolateyGuiCommonWindowsAssemblySimpleName,
                                   AssemblyResolver.GetPublicKeyToken(requestedAssembly),
                                   Bootstrapper.ChocolateyGuiCommonWindowsAssemblyLocation));
                    }
                }
                catch (Exception ex)
                {
                    // TODO: Possibly make these values translatable, do not use Resources directly, instead Use L(nameof(Resources.KEY_NAME));
                    var errorMessage = string.Format("Unable to load Chocolatey GUI assembly. {0}", ex.Message);
                    ChocolateyMessageBox.Show(errorMessage);
                    throw new ApplicationException(errorMessage);
                }

                return(null);
            };

            InitializeComponent();
        }
Example #25
0
 static GitHubPackage()
 {
     AssemblyResolver.InitializeAssemblyResolver();
 }
Example #26
0
 public virtual IEnumerable <Type> GetWorkflowActivityTypes()
 {
     return(AssemblyResolver.GetCurrentModuleTypes(GetType(), new[] { TralusAssemblyType.Module })
            .Where(e => e.IsSubclassOf(typeof(Activity))));
 }
Example #27
0
    public void Execute()
    {
        try
        {
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            LogDebug($"Starting AutoDI Weaver v{GetType().Assembly.GetCustomAttribute<AssemblyVersionAttribute>()?.Version}");

            Settings settings = LoadSettings();

            AssemblyDefinition           autoDIAssembly;
            ICollection <TypeDefinition> allTypes = GetAllTypes(settings, out autoDIAssembly);

            InternalLogDebug($"Found types:\r\n{string.Join("\r\n", allTypes.Select(x => x.FullName))}", DebugLogLevel.Verbose);

            if (autoDIAssembly == null)
            {
                var assemblyName = typeof(DependencyAttribute).Assembly.GetName();
                autoDIAssembly = AssemblyResolver.Resolve(new AssemblyNameReference(assemblyName.Name, assemblyName.Version));
                if (autoDIAssembly == null)
                {
                    LogError("Could not find AutoDI assembly");
                    return;
                }
                else
                {
                    LogWarning($"Failed to find AutoDI assembly. Manually injecting '{autoDIAssembly.MainModule.FileName}'");
                }
            }

            LoadRequiredData(autoDIAssembly);

            if (settings.GenerateRegistrations)
            {
                Mapping mapping = GetMapping(settings, allTypes);

                InternalLogDebug($"Found potential map:\r\n{mapping}", DebugLogLevel.Verbose);

                ModuleDefinition.Types.Add(GenerateAutoDIClass(mapping, out MethodDefinition initMethod));

                if (settings.AutoInit)
                {
                    InjectInitCall(initMethod);
                }
            }
            else
            {
                InternalLogDebug("Skipping registration", DebugLogLevel.Verbose);
            }

            //We only update types in our module
            foreach (TypeDefinition type in allTypes.Where(type => type.Module == ModuleDefinition))
            {
                ProcessType(type);
            }
        }
        catch (Exception ex)
        {
            var sb = new StringBuilder();
            for (Exception e = ex; e != null; e = e.InnerException)
            {
                sb.AppendLine(e.ToString());
            }
            LogError(sb.ToString());
        }
        finally
        {
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainOnAssemblyResolve;
        }
    }
 static AssemblyExtensions()
 {
     AssemblyResolver.Initialize();
 }
Example #29
0
    public void ShouldGuessTheAssemblyNameFromTheFileNameIfTheAssemblyCannotBeLoaded()
    {
        var resolver = new AssemblyResolver(logger, new[] { @"Fody\BadAssembly.dll" });

        Assert.ThrowsAny <Exception>(() => resolver.Resolve("BadAssembly"));
    }
Example #30
0
    public void ShouldReturnNullWhenTheAssemblyIsNotFound()
    {
        var resolver = new AssemblyResolver(logger, Enumerable.Empty <string>());

        Assert.Null(resolver.Resolve("SomeNonExistingAssembly"));
    }
Example #31
0
        private string injectDeepTrace(List <string> MethodToken, string assemblyPath, string outputDirectory, bool WithTrace = false)
        {
            AssemblyDef asmDef;

            // New assembly path
            string fileName = Path.GetFileName(assemblyPath);

            // Append Date and Time to new filename
            string newPath = Path.Combine(outputDirectory, DateTime.UtcNow.ToString("yyyy-MM-dd HH.mm.ss.fff", CultureInfo.InvariantCulture) + "_" + fileName);

            // Check if Output directory already exists, if not, create one
            if (!Directory.Exists(outputDirectory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                }
            }

            try
            {
                // AssemblyResolver
                if (_AssmeblyResolver == null)
                {
                    _AssmeblyResolver = new AssemblyResolver();
                }
                if (Directory.Exists(Path.GetDirectoryName(assemblyPath)))
                {
                    AddSearchPath(Path.GetDirectoryName(assemblyPath));
                }

                // how to use AssemblyResolver with dnLib?
                //_AssmeblyResolver

                // Load assembly
                //asmDef = AssemblyDef.Load(assemblyPath);
                ModuleDefMD mod = ModuleDefMD.Load(assemblyPath);

                // import our pritObj Class
                Importer      importer         = new Importer(mod);
                Type          PrintObjType     = typeof(PrintObj);
                ITypeDefOrRef _printObjTypeRef = importer.Import(PrintObjType);

                // This creates a new namespace Logging and class PrintObj in the new assembly, we don't want that
                //TypeDef _printObj = new TypeDefUser("Logging", "PrintObj", mod.CorLibTypes.Object.TypeDefOrRef);
                //var _printObjCtor = _printObj.FindDefaultConstructor();
                //mod.Types.Add(_printObj);



                Type    t          = typeof(System.Reflection.MethodBase);
                string  methodname = "GetCurrentMethod";
                IMethod _methodGetCurrentMethod = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentMethod";
                IMethod _methodSetMethod = importer.Import(PrintObjType.GetMethod(methodname));


                t          = typeof(System.Reflection.Assembly);
                methodname = "GetExecutingAssembly";
                IMethod _methodGetExecutingAssembly = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentAssembly";
                IMethod _methodSetExecutingAssembly = importer.Import(PrintObjType.GetMethod(methodname));


                methodname = "get_CurrentArguments";
                IMethod _methodGetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "set_CurrentArguments";
                IMethod _methodSetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "PrintArgs";
                IMethod _methodPrintArgs = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = ".ctor";
                IMethod _printObjCtor = importer.Import(PrintObjType.GetMethod(methodname));

                foreach (ModuleDef modDef in mod.Assembly.Modules)
                {
                    foreach (TypeDef typDef in modDef.Types)
                    {
                        foreach (MethodDef metDef in typDef.Methods)
                        {
                            //if (MethodToken.Contains(metDef.MDToken.ToString()) && metDef.Name == "About1_Closed")
                            if (MethodToken.Contains(metDef.MDToken.ToString()))
                            {
                                if (WithTrace)
                                {
                                    Trace.WriteLine("Found method " + metDef.ToString() + " Token: " + metDef.MDToken.ToString());
                                }

                                try
                                {
                                    string variablesInfo = string.Empty;
                                    if (metDef.Body != null && metDef.Body.Variables != null && metDef.Body.Variables.Count > 0)
                                    {
                                        foreach (var variable in metDef.Body.Variables)
                                        {
                                            string varInfo = "            Variable - Type: " + variable.Type.ToString() + " Name: " + variable.Name + NewLine;
                                            varInfo += "            Index: " + variable.Index.ToString();
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine(varInfo);
                                            }
                                            variablesInfo += varInfo;
                                        }
                                    }

                                    /*
                                     * if we want to skip anything
                                     * if (metDef.IsConstructor ||
                                     *  metDef.IsAbstract ||
                                     *  metDef.IsSetter ||
                                     *  (metDef.IsSpecialName && !metDef.IsGetter) || // to allow getter methods
                                     *  metDef.IsInstanceConstructor ||
                                     *  metDef.IsManaged == false
                                     *  )
                                     * {
                                     *  if (WithTrace) Trace.WriteLine("Skipped unsupported metDef " + metDef.Name);
                                     * }
                                     * else if (metDef != null && metDef.Body != null)
                                     */

                                    if (metDef != null && metDef.Body != null)
                                    {
                                        var instructions    = metDef.Body.Instructions;
                                        var newInstructions = new List <Instruction>();

                                        Instruction firstExistingInstruction        = metDef.Body.Instructions[0];
                                        uint        firstExistingInstrunctionOffset = firstExistingInstruction.Offset;
                                        int         fIndex = (int)firstExistingInstrunctionOffset; // not working

                                        // nop Test
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));

                                        ///
                                        /// Simple TraceLine
                                        ///

                                        // Load fully qualified method name as string
                                        //not working: (int)firstExistingInstruction.Offset

                                        //newInstructions.Add(new Instruction(OpCodes.Ldstr, metDef.ToString() + variablesInfo));
                                        //newInstructions.Add(new Instruction(OpCodes.Call, metDef.Module.Import(typeof(Trace).GetMethod("WriteLine", new[] { typeof(string) }))));



                                        ///
                                        /// PrintObj (injected Logging.dll)
                                        /// extended by using code and comments from CInject
                                        /// https://codeinject.codeplex.com/
                                        ///

                                        /*
                                         * 0	0000	nop
                                         * 1	0001	newobj	instance void [Logging]Logging.PrintObj::.ctor()
                                         * 2	0006	stloc	V_0 (0)
                                         * 3	000A	ldloc	V_0 (0)
                                         * 4	000E	call	class [mscorlib]System.Reflection.MethodBase [mscorlib]System.Reflection.MethodBase::GetCurrentMethod()
                                         * 5	0013	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentMethod(class [mscorlib]System.Reflection.MethodBase)
                                         * 6	0018	nop
                                         * 7	0019	ldloc.s	V_0 (0)
                                         * 8	001B	ldc.i4	2
                                         * 9	0020	newarr	[mscorlib]System.Object
                                         * 10	0025	stloc.s	V_1 (1)
                                         * 11	0027	ldloc.s	V_1 (1)
                                         * 12	0029	ldc.i4	0
                                         * 13	002E	ldarg	sender (1)
                                         * 14	0032	box	[mscorlib]System.Object
                                         * 15	0037	stelem.ref
                                         * 16	0038	ldloc.s	V_1 (1)
                                         * 17	003A	ldc.i4	1
                                         * 18	003F	ldarg	e (2)
                                         * 19	0043	stelem.ref
                                         * 20	0044	ldloc.s	V_1 (1)
                                         * 21	0046	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentArguments(object[])
                                         * 22	004B	ldloc.s	V_0 (0)
                                         * 23	004D	callvirt	instance void [Logging]Logging.PrintObj::PrintArgs()
                                         * 24	0052	nop
                                         *
                                         */

                                        // Add new variables
                                        metDef.Body.InitLocals = true;

                                        Local printO = new Local(_printObjTypeRef.ToTypeSig());
                                        metDef.Body.Variables.Add(printO);



                                        var   objType    = mod.CorLibTypes.Object.ToTypeDefOrRef();
                                        var   objTypeArr = importer.Import(typeof(object[]));
                                        Local oArray     = new Local(objTypeArr.ToTypeSig());
                                        metDef.Body.Variables.Add(oArray);


                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        // using MemberRef cTor will create the logging.PrintObj: new Logging.PrintObj()
                                        var objectCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), _printObjTypeRef);
                                        newInstructions.Add(new Instruction(OpCodes.Newobj, objectCtor));



                                        newInstructions.Add(OpCodes.Stloc.ToInstruction(printO));
                                        newInstructions.Add(OpCodes.Ldloc.ToInstruction(printO));

                                        newInstructions.Add(new Instruction(OpCodes.Call, _methodGetCurrentMethod));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetMethod));

                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));

                                        // DNlib counts additionally hidden "this"
                                        List <Parameter> pList = new List <Parameter>();
                                        for (int i = 0; i < metDef.Parameters.Count; i++)
                                        {
                                            if (!metDef.Parameters[i].IsHiddenThisParameter)
                                            {
                                                pList.Add(metDef.Parameters[i]);
                                            }
                                        }

                                        newInstructions.Add(new Instruction(OpCodes.Ldc_I4, pList.Count));


                                        newInstructions.Add(new Instruction(OpCodes.Newarr, objType));
                                        newInstructions.Add(new Instruction(OpCodes.Stloc_S, oArray));


                                        //for (int i = 0; i < metDef.Parameters.Count; i++)
                                        for (int i = 0; i < pList.Count; i++)
                                        {
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine("Found Parameter " + pList[i].Name.ToString());
                                            }

                                            bool processAsNormal = true;

                                            //if (metDef.Parameters[i].Type.IsByRef)
                                            if (pList[i].Type.IsByRef)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsByRef) " + pList[i].Name.ToString());
                                                }

                                                //* Sample Instruction set:
                                                //* L_002a: ldloc.2
                                                //* L_002b: ldc.i4.0
                                                //* L_002c: ldarg.1
                                                //* L_002d: ldind.ref
                                                //* L_002e: stelem.ref
                                                //*

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));

                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Ldind_Ref));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            //else if (pList[i].IsHiddenThisParameter)
                                            //{
                                            //processAsNormal = false;
                                            //}

                                            else if (pList[i].Type.IsClassSig)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsClassSig) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.ClassSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"

                                                ClassSig cSig = new ClassSig(pList[i].Type.ToTypeDefOrRef());
                                                Trace.WriteLine("(IsClassSig) cSig: " + cSig.ToString());

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            else if (pList[i].Type.IsCorLibType)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ElementType: " + pList[i].Type.ElementType + " Type.FullName: " + pList[i].Type.FullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " Module: " + pList[i].Type.Module + " Type.Next: " + pList[i].Type.Next);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ReflectionName: " + pList[i].Type.ReflectionName + " Type.ReflectionNamespace: " + pList[i].Type.ReflectionNamespace);
                                                }
                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));

                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.CorLibTypeSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"
                                                //newInstructions.Add(new Instruction(OpCodes.Box, mod.CorLibTypes.Int32)); // working for Int32 as example
                                                CorLibTypeSig cLibTypeSig = new CorLibTypeSig(pList[i].Type.ToTypeDefOrRef(), pList[i].Type.ElementType);
                                                newInstructions.Add(OpCodes.Box.ToInstruction(cLibTypeSig));

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }


                                            //else if (metDef.Parameters[i].ParameterType.IsArray)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].ParameterType.IsDefinition) // delegate needs no seperate handling
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsFunctionPointer)
                                            else if (pList[i].Type.IsFunctionPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsFunctionPointer) " + pList[i].Name.ToString());
                                                }
                                            }

                                            //else if (metDef.Parameters[i].ParameterType.IsOptionalModifier)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsPointer)
                                            else if (pList[i].Type.IsPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsPointer) " + pList[i].Name.ToString());
                                                }
                                            }
                                            else
                                            {
                                                processAsNormal = true;
                                            }

                                            //if (processAsNormal && !metDef.Parameters[i].Type.IsClassSig && !metDef.Parameters[i].Type.IsCorLibType)
                                            if (processAsNormal)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("processAsNormal: " + pList[i].Name.ToString());
                                                }

                                                // Sample Instruction set: for simple PARAMETER
                                                //* L_0036: ldloc.s objArray
                                                //* L_0038: ldc.i4 0
                                                //* L_003d: ldarg array
                                                //* L_0041: box Int32    <-------------- anything can be here
                                                //* L_0046: stelem.ref


                                                // Sample Instruction set: for ARRAY
                                                // L_0036: ldloc.s objArray
                                                // L_0038: ldc.i4 0
                                                // L_003d: ldarg array
                                                // L_0041: box string[]
                                                // L_0046: stelem.ref


                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, metDef.Parameters[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));
                                            }
                                        }

                                        // fill Arguments array
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetArguments));

                                        // call PrintArgs
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodPrintArgs));


                                        // Finally add instructions to beginning
                                        for (int j = 0; j < newInstructions.Count; j++)
                                        {
                                            instructions.Insert(j, newInstructions[j]);
                                        }
                                    }
                                    else
                                    {
                                        if (WithTrace)
                                        {
                                            Trace.WriteLine("metDef or metDef.Body was null");
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex.ToString());
                                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                                }
                            }
                        }
                    }
                }


                // Save modified assembly
                //asmDef.Write(newPath);

                var wopts = new dnlib.DotNet.Writer.ModuleWriterOptions(mod);
                wopts.WritePdb = true;

                //write assembly
                if (mod.IsILOnly)
                {
                    mod.Write(newPath);
                }
                else
                {
                    mod.NativeWrite(newPath);
                }
            }
            catch (Exception ex)
            {
                if (WithTrace)
                {
                    Trace.WriteLine(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
                }

                return(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
            }

            InjectedFile = newPath;
            Text         = "Injector finished: " + newPath;

            return(newPath);
        }
 private static void AssertResolverCaller(AssemblyResolver resolver)
 {
     resolver.ResolverCalled.Should().BeTrue("Expected the assembly resolver to have been called");
 }
Example #33
0
 static IsRestoreRequired()
 {
     AssemblyResolver.Enable();
 }
Example #34
0
        protected override void ProcessRecord()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => Assembly.Load(AssemblyResolver.ResolveAssembly(args));
            ChefConfigurator chefConfigurator = new ChefConfigurator();

            chefConfigurator.LoadConfig();

            // Disable API log to console
            // ChefConfig.apiLog = false;

            // Default values for Node, Path and Format parameters
            if (Select == null)
            {
                if (string.IsNullOrEmpty(ChefConfig.NodeName))
                {
                    Select = "nodes/" + ChefConfig.NodeName;
                }
                else
                {
                    Select = "nodes";
                }
            }
            else
            {
                // Trim the first / from -Endpoint
                Select = Select.TrimStart('/');
            }

            if (Format == null)
            {
                Format = "DICTIONARY";
            }
            if (Path == null)
            {
                Path = "/";
            }

            ReturnType rt = ChefEndpoint.Get(Select, Path);

            if (rt.Result == 0)
            {
                // Determine if data is encrypted
                string key = String.Empty;
                if (Secret != null)
                {
                    Format = "SECRET";
                    key    = Secret;
                }
                else if (SecretFile != null)
                {
                    Format = "SECRET";
                    key    = File.ReadAllText(ChefConfig.Root + "\\" + SecretFile);
                }

                switch (Format.ToUpper())
                {
                case "JSON":
                    WriteObject(rt.Data);
                    break;

                case "DICTIONARY":
                    WriteObject(rt.Object);
                    break;

                default:
                    Logger.log("error", "Output format is not recognized. Accepted values are 'Json', 'Dictionary'");
                    Terminate("Unrecognized Format");
                    break;
                }
            }
            else
            {
                Terminate(rt.Message);
            }
        }
Example #35
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                return;
            }

            try
            {
                var filePath = Path.GetFullPath(args[0]);

                if (!File.Exists(filePath))
                {
                    return;
                }

                filePath = args[0];

                AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => Assembly.LoadFile(Path.Combine(Path.GetDirectoryName(filePath), e.Name.Split(',').FirstOrDefault() + ".dll"));

                Module   = ModuleDefMD.Load(filePath);
                Assembly = Assembly.LoadFrom(filePath);

                var asmResolver = new AssemblyResolver {
                    EnableTypeDefCache = true
                };

                Module.Context  = asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                Module.Location = filePath;

                var asmRefs = Module.GetAssemblyRefs().ToList();

                var notFound = new List <string>();

                foreach (var asmRef in asmRefs)
                {
                    if (asmRef == null)
                    {
                        continue;
                    }

                    var asmDef = asmResolver.Resolve(asmRef.FullName, Module);

                    if (asmDef == null)
                    {
                        notFound.Add(asmRef.FullName);
                    }
                    else
                    {
                        ((AssemblyResolver)Module.Context.AssemblyResolver).AddToCache(asmDef);
                    }
                }

                if (notFound.Count > 0)
                {
                    Console.WriteLine("Could not load file or assembly or one of its dependencies:");

                    foreach (var item in notFound)
                    {
                        Console.WriteLine(item);
                    }

                    Console.WriteLine();
                }

                RuntimeHelpers.RunModuleConstructor(Assembly.ManifestModule.ModuleHandle);

                GlobalType = Module.GlobalType;

                var invokeField = GlobalType.Fields.FirstOrDefault(x => x.Name == "Invoke");
                var stringField = GlobalType.Fields.FirstOrDefault(x => x.Name == "String");

                var invokeMethodToken    = invokeField?.FieldType.TryGetTypeDef().Methods.FirstOrDefault(x => x.Name == "Invoke")?.MDToken.ToInt32();
                var strInvokeMethodToken = stringField?.FieldType.TryGetTypeDef().Methods.FirstOrDefault(x => x.Name == "Invoke")?.MDToken.ToInt32();

                if (invokeMethodToken == null)
                {
                    throw new Exception("Cannot find Invoke field!");
                }

                var invokeMethod   = Assembly.ManifestModule.ResolveMethod(invokeMethodToken.Value);
                var invokeInstance = Assembly.ManifestModule.ResolveField(invokeField.MDToken.ToInt32());

                FieldInfo  strInstance     = null;
                MethodBase strInvokeMethod = null;

                if (strInvokeMethodToken != null)
                {
                    strInstance     = Assembly.ManifestModule.ResolveField(stringField.MDToken.ToInt32());
                    strInvokeMethod = Assembly.ManifestModule.ResolveMethod(strInvokeMethodToken.Value);
                }

                Hooks.ApplyHook();

                foreach (var type in Module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        DecryptMethods(method, invokeMethod, invokeInstance.GetValue(invokeInstance));

                        if (strInstance != null)
                        {
                            DecryptStrings(method, strInvokeMethod, strInstance.GetValue(strInstance));
                        }
                    }
                }

                JunkTypes.Add(invokeField);
                JunkTypes.Add(stringField);

                var methods = GlobalType.Methods.Where(x => x.IsPrivate && x.IsStatic && x.Name.Length == 1).ToList();

                JunkTypes.AddRange(methods);

                CleanCctor();

                RemoveJunkTypes();

                RemoveEmbeddedAssemblies();

                Save(filePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Example #36
0
        /// <summary>
        /// Starts NAnt. This is the Main entry point.
        /// </summary>
        /// <param name="args">Command Line args, or whatever you want to pass it. They will treated as Command Line args.</param>
        /// <returns>
        /// The exit code.
        /// </returns>
        public static int Main(string[] args)
        {
            CommandLineParser commandLineParser = null;
            Project           project           = null;
            Level             projectThreshold  = Level.Info;

            // create assembly resolver
            AssemblyResolver assemblyResolver = new AssemblyResolver();

            // attach assembly resolver to the current domain
            assemblyResolver.Attach();

            try {
                CommandLineOptions cmdlineOptions = new CommandLineOptions();
                commandLineParser = new CommandLineParser(typeof(CommandLineOptions), true);
                commandLineParser.Parse(args, cmdlineOptions);

                if (!cmdlineOptions.NoLogo)
                {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.WriteLine();
                }

                if (cmdlineOptions.ShowHelp)
                {
                    ConsoleDriver.ShowHelp(commandLineParser);
                    return(0);
                }

                // determine the project message threshold
                if (cmdlineOptions.Debug)
                {
                    projectThreshold = Level.Debug;
                }
                else if (cmdlineOptions.Verbose)
                {
                    projectThreshold = Level.Verbose;
                }
                else if (cmdlineOptions.Quiet)
                {
                    projectThreshold = Level.Warning;
                }

                if (cmdlineOptions.BuildFile != null)
                {
                    if (project != null)
                    {
                        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Buildfile has already been loaded! Using new value '{0}'; discarding old project file '{1}'", cmdlineOptions.BuildFile, project.BuildFileUri));
                        // insert empty line
                        Console.WriteLine();
                    }

                    project = new Project(cmdlineOptions.BuildFile, projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // get build file name if the project has not been created.
                // If a build file was not specified on the command line.
                if (project == null)
                {
                    project = new Project(GetBuildFileName(Environment.CurrentDirectory, null, cmdlineOptions.FindInParent), projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // load extension asseemblies
                LoadExtensionAssemblies(cmdlineOptions.ExtensionAssemblies, project);

                PropertyDictionary buildOptionProps = new PropertyDictionary(project);

                // add build logger and build listeners to project
                ConsoleDriver.AddBuildListeners(cmdlineOptions, project);

                // copy cmd line targets
                foreach (string target in cmdlineOptions.Targets)
                {
                    project.BuildTargets.Add(target);
                }

                // build collection of valid properties that were specified on
                // the command line.
                foreach (string key in cmdlineOptions.Properties)
                {
                    buildOptionProps.AddReadOnly(key,
                                                 cmdlineOptions.Properties.Get(key));
                }

                // add valid properties to the project.
                foreach (System.Collections.DictionaryEntry de in buildOptionProps)
                {
                    project.Properties.AddReadOnly((string)de.Key, (string)de.Value);
                }

                //add these here and in the project .ctor
                Assembly ass = Assembly.GetExecutingAssembly();

                project.Properties.AddReadOnly(Project.NAntPropertyFileName, ass.Location);
                project.Properties.AddReadOnly(Project.NAntPropertyVersion, ass.GetName().Version.ToString());
                project.Properties.AddReadOnly(Project.NAntPropertyLocation, Path.GetDirectoryName(ass.Location));

                if (cmdlineOptions.TargetFramework != null)
                {
                    FrameworkInfo frameworkInfo = project.Frameworks[cmdlineOptions.TargetFramework];

                    if (frameworkInfo != null)
                    {
                        project.TargetFramework = frameworkInfo;
                    }
                    else
                    {
                        Console.Error.WriteLine("Invalid framework '{0}' specified.",
                                                cmdlineOptions.TargetFramework);

                        // insert empty line
                        Console.Error.WriteLine();

                        if (project.Frameworks.Count == 0)
                        {
                            Console.Error.WriteLine("There are no supported frameworks available on your system.");
                        }
                        else
                        {
                            Console.Error.WriteLine("Possible values include:");
                            // insert empty line
                            Console.Error.WriteLine();

                            foreach (string framework in project.Frameworks.Keys)
                            {
                                Console.Error.WriteLine(" {0} ({1})", framework, project.Frameworks[framework].Description);
                            }
                        }
                        // signal error
                        return(1);
                    }
                }

                if (cmdlineOptions.ShowProjectHelp)
                {
                    Console.WriteLine();
                    ConsoleDriver.ShowProjectHelp(project.Document);
                }
                else
                {
                    if (!project.Run())
                    {
                        return(1);
                    }
                }
                // signal success
                return(0);
            } catch (CommandLineArgumentException ex) {
                // Write logo banner to console if parser was created successfully
                if (commandLineParser != null)
                {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.Error.WriteLine();
                }
                // Write message of exception to console
                Console.Error.WriteLine(ex.Message);
                // get first nested exception
                Exception nestedException = ex.InnerException;
                // set initial indentation level for the nested exceptions
                int exceptionIndentationLevel = 0;
                while (nestedException != null && !StringUtils.IsNullOrEmpty(nestedException.Message))
                {
                    // indent exception message with 4 extra spaces
                    // (for each nesting level)
                    exceptionIndentationLevel += 4;
                    // output exception message
                    Console.Error.WriteLine(new string(' ', exceptionIndentationLevel)
                                            + nestedException.Message);
                    // move on to next inner exception
                    nestedException = nestedException.InnerException;
                }
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return(1);
            } catch (ApplicationException ex) {
                // insert empty line
                Console.Error.WriteLine();
                // output build result
                Console.Error.WriteLine("BUILD FAILED");
                // insert empty line
                Console.Error.WriteLine();
                // output message of exception
                Console.Error.WriteLine(ex.Message);
                // get first nested exception
                Exception nestedException = ex.InnerException;
                // set initial indentation level for the nested exceptions
                int exceptionIndentationLevel = 0;
                while (nestedException != null && !StringUtils.IsNullOrEmpty(nestedException.Message))
                {
                    // indent exception message with 4 extra spaces
                    // (for each nesting level)
                    exceptionIndentationLevel += 4;
                    // output exception message
                    Console.Error.WriteLine(new string(' ', exceptionIndentationLevel)
                                            + nestedException.Message);
                    // move on to next inner exception
                    nestedException = nestedException.InnerException;
                }
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                else
                {
                    // insert empty line
                    Console.WriteLine(string.Empty);
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                                      "build failure, run the build again in debug mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return(1);
            } catch (Exception ex) {
                // insert empty line
                Console.Error.WriteLine();
                // all other exceptions should have been caught
                Console.Error.WriteLine("INTERNAL ERROR");
                // insert empty line
                Console.Error.WriteLine();
                // output message of exception
                Console.Error.WriteLine(ex.Message);
                // output full stacktrace when NAnt is started in verbose mode
                if (Level.Verbose >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                else
                {
                    // insert xempty line
                    Console.WriteLine();
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                                      "build failure, run the build again in verbose mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to report this problem
                Console.WriteLine("Please send a bug report (including the version of NAnt you're using) to [email protected]");
                // signal fatal error
                return(2);
            } finally {
                if (project != null)
                {
                    project.DetachBuildListeners();
                }
                // detach assembly resolver from the current domain
                assemblyResolver.Detach();
            }
        }
Example #37
0
 protected virtual IEnumerable <Type> GetModuleExportedTypes()
 {
     return(AssemblyResolver.GetCurrentModuleTypes(GetType())
            .Where(e => e.IsSubclassOf(typeof(EntityBase))));
 }
Example #38
0
		}

		protected ResolveEventHandler InstallAssemblyResolver(string path)
		{
			ResolveEventHandler handler = new AssemblyResolver(path).AssemblyResolve;
			AppDomain.CurrentDomain.AssemblyResolve += handler;
Example #39
0
        public void Generate_AssemblyGiven_TypeScriptContentGenerated(string outputPath)
        {
            //arrange

            const string assemblyPath = ProjectPath + "bin/Debug/netcoreapp2.0/TypeGen.TestWebApp.dll";

            var generator = new Core.Generator.Generator(new GeneratorOptions {
                BaseOutputDirectory = outputPath, CreateIndexFile = true
            }, _fileSystem);

            Assembly assembly         = Assembly.LoadFrom(assemblyPath);
            var      assemblyResolver = new AssemblyResolver(new FileSystem(), new ConsoleLogger(false), ProjectPath);

            //act

            assemblyResolver.Register();
            generator.Generate(assembly);
            assemblyResolver.Unregister();

            //assert

            _fileSystem.Received().SaveFile(outputPath + "foo-constants.ts", Content["foo-constants.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "bar.ts", Content["bar.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "base-class.ts", Content["base-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "base-class2.ts", Content["base-class2.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "c.ts", Content["c.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "custom-base-class.ts", Content["custom-base-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "custom-base-custom-import.ts", Content["custom-base-custom-import.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "custom-empty-base-class.ts", Content["custom-empty-base-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "d.ts", Content["d.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "default-member-values.ts", Content["default-member-values.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "e-class.ts", Content["e-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "extended-primitives-class.ts", Content["extended-primitives-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "external-deps-class.ts", Content["external-deps-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "f-class.ts", Content["f-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "foo-type.ts", Content["foo-type.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "foo.ts", Content["foo.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "generic-base-class.ts", Content["generic-base-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "generic-class.ts", Content["generic-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "generic-with-restrictions.ts", Content["generic-with-restrictions.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "index.ts", Arg.Any <string>()); // any content, because file order in index.ts is different each time
            _fileSystem.Received().SaveFile(outputPath + "lite-db-entity.ts", Content["lite-db-entity.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "readonly-interface.ts", Content["readonly-interface.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "standalone-enum.ts", Content["standalone-enum.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "enum-short-values.ts", Content["enum-short-values.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "static-readonly.ts", Content["static-readonly.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "strict-nulls-class.ts", Content["strict-nulls-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "type-unions.ts", Content["type-unions.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "with-generic-base-class-custom-type.ts", Content["with-generic-base-class-custom-type.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "with-ignored-base-and-custom-base.ts", Content["with-ignored-base-and-custom-base.ts"]);
            _fileSystem.Received().SaveFile(outputPath + "with-ignored-base.ts", Content["with-ignored-base.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"no/slash/output/dir/no-slash-output-dir.ts", Content[@"no\slash\output\dir\no-slash-output-dir.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"test-classes/base-class.ts", Content[@"test-classes\base-class.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"test-classes/base-class2.ts", Content[@"test-classes\base-class2.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"test-classes/circular-ref-class1.ts", Content[@"test-classes\circular-ref-class1.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"test-classes/circular-ref-class2.ts", Content[@"test-classes\circular-ref-class2.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"test-classes/test-class.ts", Content[@"test-classes\test-class.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"test-enums/test-enum.ts", Content[@"test-enums\test-enum.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"test-interfaces/test-interface.ts", Content[@"test-interfaces\test-interface.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"./very/nested/directory/nested-entity.ts", Content[@"very\nested\directory\nested-entity.ts"]);

            _fileSystem.Received().SaveFile(outputPath + @"default-export/class-with-default-export.ts", Content[@"default-export\class-with-default-export.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"default-export/generic-class-with-default-export.ts", Content[@"default-export\generic-class-with-default-export.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"default-export/class-with-imports.ts", Content[@"default-export\class-with-imports.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"default-export/class-without-default-export.ts", Content[@"default-export\class-without-default-export.ts"]);
            _fileSystem.Received().SaveFile(outputPath + @"default-export/interface-with-default-export.ts", Content[@"default-export\interface-with-default-export.ts"]);
        }
Example #40
0
 protected override void ScanForObfuscator()
 {
     FindBabelAttribute();
     var resourceDecrypterCreator = new ResourceDecrypterCreator(Module, DeobfuscatedFile);
     resourceResolver = new ResourceResolver(Module, resourceDecrypterCreator.Create(), DeobfuscatedFile);
     resourceResolver.Find();
     assemblyResolver = new AssemblyResolver(Module, resourceDecrypterCreator.Create());
     assemblyResolver.Find();
     stringDecrypter = new StringDecrypter(Module, resourceDecrypterCreator.Create());
     stringDecrypter.Find(DeobfuscatedFile);
     constantsDecrypter = new ConstantsDecrypter(Module, resourceDecrypterCreator.Create(), initializedDataCreator);
     constantsDecrypter.Find();
     proxyCallFixer = new ProxyCallFixer(Module);
     proxyCallFixer.FindDelegateCreator();
     methodsDecrypter = new MethodsDecrypter(Module, resourceDecrypterCreator.Create(), DeobfuscatedFile.DeobfuscatorContext);
     methodsDecrypter.Find();
 }
Example #41
0
        protected override void ProcessRecord()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => Assembly.Load(AssemblyResolver.ResolveAssembly(args));
            ChefConfigurator chefConfigurator = new ChefConfigurator();

            chefConfigurator.LoadConfig();
            // ChefConfig.apiLog = false;

            // Default -Version to _latest
            if (Version == null)
            {
                Version = "_latest";
            }

            Cookbook   cookbook = new Cookbook();
            ReturnType rt       = cookbook.Download(Name, Version);

            if (rt.Result == 0)
            {
                Logger.log("ok", "Added cookbook: " + Name + "[" + Version + "] to cookbook path.");
            }
            else
            {
                Logger.log("error", rt.Message);
                Logger.log("error", "There is an error adding cookbook: " + Name + "[" + Version + "].");
                Terminate(rt.Message);
            }
        }
Example #42
0
        /// <summary>
        /// Main Processing function of the CmdLet
        /// </summary>
        protected override void ProcessRecord()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => Assembly.Load(AssemblyResolver.ResolveAssembly(args));
            ChefConfigurator chefConfigurator = new ChefConfigurator();

            chefConfigurator.LoadConfig();

            // 01. Testing BuildRunList method
            // BuildRunList();

            // 02. Testing Compilation
            TestCompile();
        }
Example #43
0
            /// <summary>
            /// Retrieves the specified <see cref="Type" /> corresponding with the specified
            /// type name from a list of assemblies.
            /// </summary>
            /// <param name="assemblies">The collection of assemblies that the type should tried to be instantiated from.</param>
            /// <param name="imports">The list of imports that can be used to resolve the type name to a full type name.</param>
            /// <param name="typename">The type name that should be used to determine the type to which the specified value should be converted.</param>
            /// <param name="value">The <see cref="string" /> value that should be converted to a typed value.</param>
            /// <returns></returns>
            /// <exception cref="BuildException">
            /// <para><paramref name="value" /> is <see langword="null" /> and the <see cref="Type" /> identified by <paramref name="typename" /> has no default public constructor.</para>
            /// <para>-or-</para>
            /// <para><paramref name="value" /> cannot be converted to a value that's suitable for one of the constructors of the <see cref="Type" /> identified by <paramref name="typename" />.</para>
            /// <para>-or-</para>
            /// <para>The <see cref="Type" /> identified by <paramref name="typename" /> has no suitable constructor.</para>
            /// <para>-or-</para>
            /// <para>A <see cref="Type" /> identified by <paramref name="typename" /> could not be located or loaded.</para>
            /// </exception>
            public object GetTypedValue(StringCollection assemblies, StringCollection imports, string typename, string value)
            {
                // create assembly resolver
                AssemblyResolver assemblyResolver = new AssemblyResolver();

                // attach assembly resolver to the current domain
                assemblyResolver.Attach();

                try {
                    // Try to find the type from typename parameter.
                    Type type = FindType(assemblies, imports, typename);

                    if (type != null)
                    {
                        object typedValue = null;
                        if (value == null)
                        {
                            ConstructorInfo defaultConstructor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance, null,
                                new Type[0], new ParameterModifier[0]);
                            if (defaultConstructor == null)
                            {
                                throw new BuildException(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             ResourceUtils.GetString("NA2005"), type.FullName), Location.UnknownLocation);
                            }
                            typedValue = null;
                        }
                        else
                        {
                            ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
                            for (int counter = 0; counter < constructors.Length; counter++)
                            {
                                ParameterInfo[] parameters = constructors[counter].GetParameters();
                                if (parameters.Length == 1)
                                {
                                    if (parameters[0].ParameterType.IsPrimitive || parameters[0].ParameterType == typeof(string))
                                    {
                                        try {
                                            // convert value to type of constructor parameter
                                            typedValue = Convert.ChangeType(value, parameters[0].ParameterType, CultureInfo.InvariantCulture);
                                            break;
                                        } catch (Exception ex) {
                                            throw new BuildException(string.Format(
                                                                         CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2006"),
                                                                         value, parameters[0].ParameterType.FullName, type.FullName),
                                                                     Location.UnknownLocation, ex);
                                        }
                                    }
                                }
                            }

                            if (typedValue == null)
                            {
                                throw new BuildException(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             ResourceUtils.GetString("NA2003"), typename),
                                                         Location.UnknownLocation);
                            }
                        }

                        return(typedValue);
                    }
                    else
                    {
                        if (!typename.EndsWith("Attribute"))
                        {
                            throw new BuildException(string.Format(
                                                         CultureInfo.InvariantCulture,
                                                         ResourceUtils.GetString("NA2039"), typename),
                                                     Location.UnknownLocation);
                        }
                        else
                        {
                            throw new BuildException(string.Format(
                                                         CultureInfo.InvariantCulture,
                                                         ResourceUtils.GetString("NA2001"), typename),
                                                     Location.UnknownLocation);
                        }
                    }
                } finally {
                    // detach assembly resolver from the current domain
                    assemblyResolver.Detach();
                }
            }
Example #44
0
        /// <summary>
        /// Starts NAnt. This is the Main entry point.
        /// </summary>
        /// <param name="args">Command Line args, or whatever you want to pass it. They will treated as Command Line args.</param>
        /// <returns>
        /// The exit code.
        /// </returns>
        public static int Main(string[] args)
        {
            CommandLineParser commandLineParser = null;
            Project           project           = null;
            Level             projectThreshold  = Level.Info;

            // create assembly resolver
            AssemblyResolver assemblyResolver = new AssemblyResolver();

            // attach assembly resolver to the current domain
            assemblyResolver.Attach();

            CommandLineOptions cmdlineOptions = new CommandLineOptions();

            try {
                commandLineParser = new CommandLineParser(typeof(CommandLineOptions), true);
                commandLineParser.Parse(args, cmdlineOptions);

                if (!cmdlineOptions.NoLogo)
                {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.WriteLine();
                }

                if (cmdlineOptions.ShowHelp)
                {
                    ConsoleDriver.ShowHelp(commandLineParser);
                    return(0);
                }

                // determine the project message threshold
                if (cmdlineOptions.Debug)
                {
                    projectThreshold = Level.Debug;
                }
                else if (cmdlineOptions.Verbose)
                {
                    projectThreshold = Level.Verbose;
                }
                else if (cmdlineOptions.Quiet)
                {
                    projectThreshold = Level.Warning;
                }

                if (cmdlineOptions.BuildFile != null)
                {
                    if (project != null)
                    {
                        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Buildfile has already been loaded! Using new value '{0}'; discarding old project file '{1}'", cmdlineOptions.BuildFile, project.BuildFileUri));
                        // insert empty line
                        Console.WriteLine();
                    }

                    project = new Project(cmdlineOptions.BuildFile, projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // get build file name if the project has not been created.
                // If a build file was not specified on the command line.
                if (project == null)
                {
                    project = new Project(GetBuildFileName(Environment.CurrentDirectory, null, cmdlineOptions.FindInParent), projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // load extension asseemblies
                LoadExtensionAssemblies(cmdlineOptions.ExtensionAssemblies, project);

                var buildOptionProps = new Dictionary <String, String>();

                // add build logger and build listeners to project
                ConsoleDriver.AddBuildListeners(cmdlineOptions, project);

                // copy cmd line targets
                foreach (string target in cmdlineOptions.Targets)
                {
                    project.BuildTargets.Add(target);
                }

                // build collection of valid properties that were specified on
                // the command line.
                foreach (string key in cmdlineOptions.Properties)
                {
                    buildOptionProps[key] = cmdlineOptions.Properties.Get(key);
                }

                // add valid properties to the project.
                foreach (var kvp in buildOptionProps)
                {
                    project.SetGlobalProperty(kvp.Key, kvp.Value, true);
                }

                //add these here and in the project .ctor
                Assembly ass = Assembly.GetExecutingAssembly();

                project.SetGlobalProperty(Project.NAntPropertyFileName, ass.Location, true);
                project.SetGlobalProperty(Project.NAntPropertyVersion, ass.GetName().Version.ToString(), true);
                project.SetGlobalProperty(Project.NAntPropertyLocation, Path.GetDirectoryName(ass.Location), true);

                if (cmdlineOptions.TargetFramework != null)
                {
                    FrameworkInfo framework = project.Frameworks[cmdlineOptions.TargetFramework];

                    if (framework != null)
                    {
                        try {
                            framework.Validate();
                            project.TargetFramework = framework;
                        } catch (Exception ex) {
                            // write message of exception to console
                            WriteException(ex);
                            // output full stacktrace when NAnt is started in debug mode
                            if (Level.Debug >= projectThreshold)
                            {
                                // insert empty line
                                Console.Error.WriteLine();
                                // output header
                                Console.Error.WriteLine("Stacktrace:");
                                // insert empty line
                                Console.Error.WriteLine();
                                // output full stacktrace
                                Console.Error.WriteLine(ex.ToString());
                            }
                            // signal error
                            return(1);
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Invalid framework '{0}' specified.",
                                                cmdlineOptions.TargetFramework);

                        // insert empty line
                        Console.Error.WriteLine();

                        FrameworkInfo[] installedFrameworks = project.GetFrameworks(
                            FrameworkTypes.Installed);

                        if (installedFrameworks.Length == 0)
                        {
                            Console.Error.WriteLine("There are no supported frameworks available on your system.");
                        }
                        else
                        {
                            Console.Error.WriteLine("Possible values include:");
                            // insert empty line
                            Console.Error.WriteLine();

                            foreach (FrameworkInfo fi in installedFrameworks)
                            {
                                Console.Error.WriteLine("{0} ({1})",
                                                        fi.Name, fi.Description);
                            }
                        }
                        // signal error
                        return(1);
                    }
                }

                // Enable parallel execution of targets
                project.ForceSequential = cmdlineOptions.ForceSequential;

                if (cmdlineOptions.ShowProjectHelp)
                {
                    Console.WriteLine();
                    ConsoleDriver.ShowProjectHelp(project.Document);
                }
                else
                {
                    if (!project.Run(project.RootTargetCallStack).Success)
                    {
                        return(1);
                    }
                }
                // signal success
                return(0);
            } catch (CommandLineArgumentException ex) {
                // Write logo banner to console if parser was created successfully
                if (commandLineParser != null)
                {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.Error.WriteLine();
                }
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return(1);
            } catch (ApplicationException ex) {
                // insert empty line
                Console.Error.WriteLine();
                // output build result
                Console.Error.WriteLine("BUILD FAILED");
                // insert empty line
                Console.Error.WriteLine();
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                else
                {
                    // insert empty line
                    Console.WriteLine(string.Empty);
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                                      "build failure, run the build again in debug mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return(1);
            } catch (Exception ex) {
                // insert empty line
                Console.Error.WriteLine();
                // all other exceptions should have been caught
                Console.Error.WriteLine("INTERNAL ERROR");
                // insert empty line
                Console.Error.WriteLine();
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in verbose mode
                if (Level.Verbose >= projectThreshold)
                {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                else
                {
                    // insert xempty line
                    Console.WriteLine();
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                                      "build failure, run the build again in verbose mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to report this problem
                Console.WriteLine("Please send a bug report (including the version of NAnt you're using) to [email protected]");
                // signal fatal error
                return(2);
            } finally {
                if (project != null)
                {
                    project.DetachBuildListeners();
                }
                // detach assembly resolver from the current domain
                assemblyResolver.Detach();
                if (cmdlineOptions.Pause)
                {
                    Console.ReadKey();
                }
            }
        }
Example #45
0
		public override void DeobfuscateBegin() {
			base.DeobfuscateBegin();

			AddTypeToBeRemoved(killType, "KILL type");

			mainType.Initialize();
			foreach (var initMethod in mainType.OtherInitMethods) {
				AddCctorInitCallToBeRemoved(initMethod);
				AddCtorInitCallToBeRemoved(initMethod);
			}

			if (Operations.DecryptStrings != OpDecryptString.None) {
				stringDecrypter.Initialize();
				staticStringInliner.Add(stringDecrypter.DecryptMethod, (method, gim, args) => {
					return stringDecrypter.Decrypt((int)args[0]);
				});
				DeobfuscatedFile.StringDecryptersAdded();
				AddModuleCctorInitCallToBeRemoved(stringDecrypter.InitMethod);
				AddCallToBeRemoved(mainType.GetInitStringDecrypterMethod(stringDecrypter.InitMethod), stringDecrypter.InitMethod);
			}

			assemblyResolver = new AssemblyResolver(module);
			assemblyResolver.Initialize();
			DumpEmbeddedAssemblies();

			RemoveTamperDetection();

			proxyCallFixer.Initialize();
			proxyCallFixer.Find();

			resourceDecrypter = new ResourceDecrypter(module);
			resourceDecrypter.Initialize();
			resourceDecrypter.Decrypt();
			if (resourceDecrypter.CanRemoveTypes) {
				AddTypeToBeRemoved(resourceDecrypter.ResourceFlagsType, "Obfuscator ResourceFlags type");
				AddTypeToBeRemoved(resourceDecrypter.ResType, "Obfuscator Res type");
				AddTypeToBeRemoved(resourceDecrypter.ResourceEnumeratorType, "Obfuscator ResourceEnumerator type");
				AddTypeToBeRemoved(resourceDecrypter.EncryptedResourceReaderType, "Obfuscator EncryptedResourceReader type");
				AddTypeToBeRemoved(resourceDecrypter.EncryptedResourceSetType, "Obfuscator EncryptedResourceSet type");
				AddTypeToBeRemoved(resourceDecrypter.EncryptedResourceStreamType, "Obfuscator EncryptedResourceStream type");
			}
		}
Example #46
0
        private void LoadMEF(ICatalogueRepository catalogueRepository, ICheckNotifier notifier)
        {
            DirectoryInfo downloadDirectory = catalogueRepository.MEF.DownloadDirectory;

            //make sure the MEF directory exists
            if (!downloadDirectory.Exists)
            {
                downloadDirectory.Create();
            }

            var compatiblePlugins = catalogueRepository.PluginManager.GetCompatiblePlugins();

            List <DirectoryInfo> dirs   = new List <DirectoryInfo>();
            List <DirectoryInfo> toLoad = new List <DirectoryInfo>();

            //always load the current application directory
            toLoad.Add(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory));

            for (int i = 0; i < compatiblePlugins.Length; i++)
            {
                var subDirName = compatiblePlugins[i].GetPluginDirectoryName(downloadDirectory);
                var subdir     = Directory.CreateDirectory(subDirName);

                dirs.Add(subdir);

                var existingFiles = subdir.GetFiles("*" + PackPluginRunner.PluginPackageSuffix).ToList();

                //if we have not downloaded this yet
                if (!existingFiles.Any(f => f.Name.Equals(compatiblePlugins[i].Name)))
                {
                    compatiblePlugins[i].LoadModuleAssemblies.SingleOrDefault()?.DownloadAssembly(subdir);
                }
                else
                {
                    notifier.OnCheckPerformed(new CheckEventArgs("Found existing file '" + compatiblePlugins[i].Name + "' so didn't bother downloading it.", CheckResult.Success));
                }

                foreach (var archive in  subdir.GetFiles("*" + PackPluginRunner.PluginPackageSuffix).ToList())
                {
                    //get rid of any old out dirs
                    var outDir = subdir.EnumerateDirectories("out").SingleOrDefault();

                    bool mustUnzip = true;

                    //if there's already an unpacked version
                    if (outDir != null && outDir.Exists)
                    {
                        //if the directory has no files we have to unzip - otherwise it has an unzipped version already yay
                        mustUnzip = !outDir.GetFiles("*.dll", SearchOption.AllDirectories).Any();

                        if (mustUnzip)
                        {
                            outDir.Delete(true);
                        }
                    }
                    else
                    {
                        outDir = subdir.CreateSubdirectory("out");
                    }

                    if (mustUnzip)
                    {
                        using (var zf = ZipFile.OpenRead(archive.FullName))
                            try
                            {
                                zf.ExtractToDirectory(outDir.FullName);
                            }
                            catch (Exception ex)
                            {
                                notifier.OnCheckPerformed(new CheckEventArgs("Could not extract Plugin to '" + outDir.FullName + "'", CheckResult.Warning, ex));
                            }
                    }
                    else
                    {
                        notifier.OnCheckPerformed(new CheckEventArgs("Found existing directory '" + outDir.FullName + "' so didn't bother unzipping.", CheckResult.Success));
                    }

                    var dir = _environmentInfo.GetPluginSubDirectory(outDir.CreateSubdirectory("lib"), notifier);

                    //it is a UI only plugin? or plugin doesn't support the current runtime/platform
                    if (dir == null)
                    {
                        continue;
                    }

                    toLoad.Add(dir);

                    //tell them we downloaded it
                    MEFFileDownloaded(this,
                                      new MEFFileDownloadProgressEventArgs(subdir, compatiblePlugins.Length, i + 1,
                                                                           archive.Name, false, MEFFileDownloadEventStatus.Success));
                }
            }

            //The only Directories in MEF folder should be Plugin subdirectories, any that don't correspond with a plugin should be deleted
            foreach (DirectoryInfo unexpectedDirectory in downloadDirectory.GetDirectories().Where(expected => !dirs.Any(d => d.FullName.Equals(expected.FullName))))
            {
                try
                {
                    unexpectedDirectory.Delete(true);
                    notifier.OnCheckPerformed(new CheckEventArgs("Deleted unreferenced plugin folder " + unexpectedDirectory.FullName, CheckResult.Success));
                }
                catch (Exception ex)
                {
                    notifier.OnCheckPerformed(
                        new CheckEventArgs(
                            "Found unreferenced (no Plugin) folder " + unexpectedDirectory.FullName +
                            " but we were unable to delete it (possibly because it is in use, try closing all your local RDMP applications and restarting this one)",
                            CheckResult.Fail, ex));
                }
            }

            AssemblyResolver.SetupAssemblyResolver(toLoad.ToArray());

            MEFSafeDirectoryCatalog = new SafeDirectoryCatalog(notifier, toLoad.Select(d => d.FullName).ToArray());
            catalogueRepository.MEF.Setup(MEFSafeDirectoryCatalog);

            notifier.OnCheckPerformed(new CheckEventArgs("Loading Help...", CheckResult.Success));
            var sw = Stopwatch.StartNew();

            if (!CatalogueRepository.SuppressHelpLoading)
            {
                catalogueRepository.CommentStore.ReadComments(Environment.CurrentDirectory, "SourceCodeForSelfAwareness.zip");
            }

            sw.Stop();
            notifier.OnCheckPerformed(new CheckEventArgs("Help loading took:" + sw.Elapsed, CheckResult.Success));
        }
Example #47
0
        private static void Generate(object[] args)
        {
            CastleProxyGenerator proxyGenerator = (CastleProxyGenerator)args[0];
            CastleProxyGeneratorOptions generatorOptions = (CastleProxyGeneratorOptions)args[1];

            using (AssemblyResolver resolver = new AssemblyResolver(generatorOptions.InputAssemblyPaths))
            {
                generatorOptions.InputAssemblies = resolver.LoadFrom(generatorOptions.InputAssemblyPaths);
                proxyGenerator.Generate(generatorOptions);
            }
        }
Example #48
0
 public VuserClass()
 {
     AssemblyResolver.AddSTPathsToResolutionPaths();
     AssemblyResolver.AttachToAppdomain();
 }
Example #49
0
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            // 1. Setup context
            var context = new ConfuserContext
            {
                Logger          = parameters.GetLogger(),
                Project         = parameters.Project.Clone(),
                PackerInitiated = parameters.PackerInitiated,
                token           = token
            };

            PrintInfo(context);

            var ok = false;

            try {
                var asmResolver = new AssemblyResolver
                {
                    EnableTypeDefCache = true
                };
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.Resolver        = asmResolver;
                context.BaseDirectory   = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar);
                foreach (var probePath in parameters.Project.ProbePaths)
                {
                    asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));
                }

                context.CheckCancellation();

                var marker = parameters.GetMarker();

                // 2. Discover plugins
                context.Logger.Debug("Discovering plugins...");
                parameters.GetPluginDiscovery().GetPlugins(context, out var prots, out var packers, out var components);

                context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", prots.Count, packers.Count);

                context.CheckCancellation();

                // 3. Resolve dependency
                context.Logger.Debug("Resolving component dependency...");
                try {
                    var resolver = new DependencyResolver(prots);
                    prots = resolver.SortDependency();
                }
                catch (CircularDependencyException ex) {
                    context.Logger.ErrorException("", ex);
                    throw new ConfuserException(ex);
                }

                components.Insert(0, new CoreComponent(parameters, marker));
                foreach (var prot in prots)
                {
                    components.Add(prot);
                }

                foreach (var packer in packers)
                {
                    components.Add(packer);
                }

                context.CheckCancellation();

                // 4. Load modules
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                var markings = marker.MarkProject(parameters.Project, context);
                context.Modules = new ModuleSorter(markings.Modules).Sort().ToList().AsReadOnly();
                foreach (var module in context.Modules)
                {
                    module.EnableTypeDefFindCache = false;
                }

                context.OutputModules   = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray();
                context.OutputSymbols   = Enumerable.Repeat <byte[]>(null, context.Modules.Count).ToArray();
                context.OutputPaths     = Enumerable.Repeat <string>(null, context.Modules.Count).ToArray();
                context.Packer          = markings.Packer;
                context.ExternalModules = markings.ExternalModules;

                context.CheckCancellation();

                // 5. Initialize components
                context.Logger.Info("Initializing...");
                foreach (var comp in components)
                {
                    try {
                        comp.Initialize(context);
                    }
                    catch (Exception ex) {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex);
                        throw new ConfuserException(ex);
                    }
                    context.CheckCancellation();
                }

                context.CheckCancellation();

                // 6. Build pipeline
                context.Logger.Debug("Building pipeline...");
                var pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (var comp in components)
                {
                    comp.PopulatePipeline(pipeline);
                }

                context.CheckCancellation();

                //7. Run pipeline
                RunPipeline(pipeline, context);

                ok = true;
            }
            catch (AssemblyResolveException ex) {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex) {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex);
                PrintEnvironmentInfo(context);
            }
            catch (IOException ex) {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex);
            }
            catch (OperationCanceledException) {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException) {
                // Exception is already handled/logged, so just ignore and report failure
            }
            catch (Exception ex) {
                context.Logger.ErrorException("Unknown error occurred.", ex);
            }
            finally {
                if (context.Resolver != null)
                {
                    context.Resolver.Clear();
                }

                context.Logger.Finish(ok);
            }
        }
Example #50
0
 private void AddAssemblyResolver()
 {
     AssemblyResolver.AddTestPathToResolutionPaths(GetTestPath());
     AssemblyResolver.AddPathsForAssemblyResolution(DotNetResolverPaths);
 }
 public ResourceResolver(ModuleDefMD module, AssemblyResolver assemblyResolver)
 {
     this.module = module;
     this.assemblyResolver = assemblyResolver;
 }
Example #52
0
        /// <summary>
        ///     Runs the engine.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="token">The cancellation token.</param>
        // Token: 0x0600010A RID: 266 RVA: 0x000088B4 File Offset: 0x00006AB4
        private static void RunInternal(ConfuserParameters parameters, CancellationToken token)
        {
            ConfuserContext context = new ConfuserContext();

            context.Logger          = parameters.GetLogger();
            context.Project         = parameters.Project;
            context.PackerInitiated = parameters.PackerInitiated;
            context.token           = token;
            ConfuserEngine.PrintInfo(context);
            bool ok = false;

            try
            {
                AssemblyResolver asmResolver = new AssemblyResolver();
                asmResolver.EnableTypeDefCache   = true;
                asmResolver.DefaultModuleContext = new ModuleContext(asmResolver);
                context.Resolver      = asmResolver;
                context.BaseDirectory = Path.Combine(Environment.CurrentDirectory, parameters.Project.BaseDirectory.TrimEnd(new char[]
                {
                    Path.DirectorySeparatorChar
                }) + Path.DirectorySeparatorChar);
                context.OutputDirectory = Path.Combine(parameters.Project.BaseDirectory, parameters.Project.OutputDirectory.TrimEnd(new char[]
                {
                    Path.DirectorySeparatorChar
                }) + Path.DirectorySeparatorChar);
                foreach (string probePath in parameters.Project.ProbePaths)
                {
                    asmResolver.PostSearchPaths.Insert(0, Path.Combine(context.BaseDirectory, probePath));
                }
                context.CheckCancellation();
                Marker marker = parameters.GetMarker();
                context.Logger.Debug("Discovering plugins...");
                IList <Protection>        prots;
                IList <Packer>            packers;
                IList <ConfuserComponent> components;
                parameters.GetPluginDiscovery().GetPlugins(context, out prots, out packers, out components);
                context.Logger.InfoFormat("Discovered {0} protections, {1} packers.", new object[]
                {
                    prots.Count,
                    packers.Count
                });
                context.CheckCancellation();
                context.Logger.Debug("Resolving component dependency...");
                try
                {
                    DependencyResolver resolver = new DependencyResolver(prots);
                    prots = resolver.SortDependency();
                }
                catch (CircularDependencyException ex)
                {
                    context.Logger.ErrorException("", ex);
                    throw new ConfuserException(ex);
                }
                components.Insert(0, new CoreComponent(parameters, marker));
                foreach (Protection prot in prots)
                {
                    components.Add(prot);
                }
                foreach (Packer packer in packers)
                {
                    components.Add(packer);
                }
                context.CheckCancellation();
                context.Logger.Info("Loading input modules...");
                marker.Initalize(prots, packers);
                MarkerResult markings = marker.MarkProject(parameters.Project, context);
                context.Modules = markings.Modules.ToList <ModuleDefMD>().AsReadOnly();
                foreach (ModuleDefMD module in context.Modules)
                {
                    module.EnableTypeDefFindCache = true;
                }
                context.OutputModules   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputSymbols   = Enumerable.Repeat <byte[]>(null, markings.Modules.Count).ToArray <byte[]>();
                context.OutputPaths     = Enumerable.Repeat <string>(null, markings.Modules.Count).ToArray <string>();
                context.Packer          = markings.Packer;
                context.ExternalModules = markings.ExternalModules;
                context.CheckCancellation();
                context.Logger.Info("Initializing...");
                foreach (ConfuserComponent comp in components)
                {
                    try
                    {
                        comp.Initialize(context);
                    }
                    catch (Exception ex2)
                    {
                        context.Logger.ErrorException("Error occured during initialization of '" + comp.Name + "'.", ex2);
                        throw new ConfuserException(ex2);
                    }
                    context.CheckCancellation();
                }
                context.CheckCancellation();
                context.Logger.Debug("Building pipeline...");
                ProtectionPipeline pipeline = new ProtectionPipeline();
                context.Pipeline = pipeline;
                foreach (ConfuserComponent comp2 in components)
                {
                    comp2.PopulatePipeline(pipeline);
                }
                context.CheckCancellation();
                ConfuserEngine.RunPipeline(pipeline, context);
                ok = true;
            }
            catch (AssemblyResolveException ex3)
            {
                context.Logger.ErrorException("Failed to resolve an assembly, check if all dependencies are present in the correct version.", ex3);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (TypeResolveException ex4)
            {
                context.Logger.ErrorException("Failed to resolve a type, check if all dependencies are present in the correct version.", ex4);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (MemberRefResolveException ex5)
            {
                context.Logger.ErrorException("Failed to resolve a member, check if all dependencies are present in the correct version.", ex5);
                ConfuserEngine.PrintEnvironmentInfo(context);
            }
            catch (IOException ex6)
            {
                context.Logger.ErrorException("An IO error occurred, check if all input/output locations are readable/writable.", ex6);
            }
            catch (OperationCanceledException)
            {
                context.Logger.Error("Operation cancelled.");
            }
            catch (ConfuserException)
            {
            }
            catch (Exception ex7)
            {
                context.Logger.ErrorException("Unknown error occurred.", ex7);
            }
            finally
            {
                if (context.Resolver != null)
                {
                    context.Resolver.Clear();
                }
                context.Logger.Finish(ok);
            }
        }
Example #53
0
 public MonoMacLinkContext(Pipeline pipeline, AssemblyResolver resolver) : base(pipeline, resolver)
 {
 }
Example #54
0
 public static void Main()
 {
     AssemblyResolver.Init();
     Instance().Load();
 }
Example #55
0
		void InitDecrypters() {
			assemblyResolverInfo = new AssemblyResolverInfo(module, DeobfuscatedFile, this);
			assemblyResolverInfo.FindTypes();
			resourceDecrypterInfo = new ResourceDecrypterInfo(module, assemblyResolverInfo.SimpleZipTypeMethod, DeobfuscatedFile);
			resourceResolverInfo = new ResourceResolverInfo(module, DeobfuscatedFile, this, assemblyResolverInfo);
			resourceResolverInfo.FindTypes();
			resourceDecrypter = new ResourceDecrypter(resourceDecrypterInfo);
			assemblyResolver = new AssemblyResolver(resourceDecrypter, assemblyResolverInfo);
			resourceResolver = new ResourceResolver(module, assemblyResolver, resourceResolverInfo);

			InitStringDecrypterInfos();
			assemblyResolverInfo.FindTypes();
			resourceResolverInfo.FindTypes();

			AddModuleCctorInitCallToBeRemoved(assemblyResolverInfo.CallResolverMethod);
			AddCallToBeRemoved(module.EntryPoint, assemblyResolverInfo.CallResolverMethod);
			AddModuleCctorInitCallToBeRemoved(resourceResolverInfo.CallResolverMethod);
			AddCallToBeRemoved(module.EntryPoint, resourceResolverInfo.CallResolverMethod);

			resourceDecrypterInfo.SetSimpleZipType(GetGlobalSimpleZipTypeMethod(), DeobfuscatedFile);

			if (!DecryptResources())
				throw new ApplicationException("Could not decrypt resources");

			DumpEmbeddedAssemblies();
		}
Example #56
0
        bool Execute(DirectoryAssemblyResolver res)
        {
            // Put every assembly we'll need in the resolver
            foreach (var assembly in ResolvedAssemblies)
            {
                res.Load(Path.GetFullPath(assembly.ItemSpec));
            }

            var resolver = new AssemblyResolver(res.ToResolverCache());

            // Set up for linking
            var options = new LinkerOptions();

            options.MainAssembly     = res.GetAssembly(MainAssembly);
            options.OutputDirectory  = Path.GetFullPath(OutputDirectory);
            options.LinkSdkOnly      = string.Compare(LinkMode, "SdkOnly", true) == 0;
            options.LinkNone         = false;
            options.Resolver         = resolver;
            options.LinkDescriptions = LinkDescriptions.Select(item => Path.GetFullPath(item.ItemSpec)).ToArray();
            options.I18nAssemblies   = Linker.ParseI18nAssemblies(I18nAssemblies);
            if (!options.LinkSdkOnly)
            {
                options.RetainAssemblies = GetRetainAssemblies(res);
            }
            options.DumpDependencies          = DumpDependencies;
            options.HttpClientHandlerType     = HttpClientHandlerType;
            options.TlsProvider               = TlsProvider;
            options.PreserveJniMarshalMethods = PreserveJniMarshalMethods;
            options.DeterministicOutput       = Deterministic;

            var skiplist = new List <string> ();

            if (string.Compare(UseSharedRuntime, "true", true) == 0)
            {
                skiplist.AddRange(Profile.SharedRuntimeAssemblies.Where(a => a.EndsWith(".dll")).Select(a => Path.GetFileNameWithoutExtension(a)));
            }

            // Add LinkSkip options
            if (!string.IsNullOrWhiteSpace(LinkSkip))
            {
                skiplist.AddRange(LinkSkip.Split(',', ';'));
            }

            options.SkippedAssemblies = skiplist;

            if (EnableProguard)
            {
                options.ProguardConfiguration = ProguardConfiguration;
            }

            // Link!
            try {
                LinkContext link_context;
                Linker.Process(options, this, out link_context);

                foreach (var assembly in ResolvedAssemblies)
                {
                    var copysrc             = assembly.ItemSpec;
                    var filename            = Path.GetFileName(assembly.ItemSpec);
                    var assemblyDestination = Path.Combine(OutputDirectory, filename);

                    if (!MonoAndroidHelper.IsForceRetainedAssembly(filename))
                    {
                        continue;
                    }

                    MonoAndroidHelper.CopyAssemblyAndSymbols(copysrc, assemblyDestination);
                }
            } catch (ResolutionException ex) {
                Diagnostic.Error(2006, ex, "Could not resolve reference to '{0}' (defined in assembly '{1}') with scope '{2}'. When the scope is different from the defining assembly, it usually means that the type is forwarded.", ex.Member, ex.Member.Module.Assembly, ex.Scope);
            }

            return(true);
        }
Example #57
0
		protected override void ScanForObfuscator() {
			staticStringInliner.UseUnknownArgs = true;
			arrayBlockState = new ArrayBlockState(module);
			arrayBlockState.Initialize(DeobfuscatedFile);
			stringDecrypter = new StringDecrypter(module);
			stringDecrypter.Find(DeobfuscatedFile);
			resourceResolver = new ResourceResolver(module, DeobfuscatedFile, this);
			resourceResolver.Find();
			assemblyResolver = new AssemblyResolver(module, DeobfuscatedFile, this);
			assemblyResolver.Find();
			obfuscatorName = DetectVersion();
		}
Example #58
0
        /// <summary>
        /// Main Processing function of the CmdLet
        /// </summary>
        protected override void ProcessRecord()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => Assembly.Load(AssemblyResolver.ResolveAssembly(args));
            ChefConfigurator chefConfigurator = new ChefConfigurator();
            ReturnType       rt = chefConfigurator.LoadConfig();

            if (rt.Result == 0)
            {
                // Configuration is loaded from registry, try to connect
                Connect();
            }
            else
            {
                ProcessConfiguration();
            }
        }
        public override void deobfuscateBegin()
        {
            base.deobfuscateBegin();

            resourceDecrypter = new ResourceDecrypter(module, DeobfuscatedFile);
            resourceResolver = new ResourceResolver(module, resourceDecrypter);
            assemblyResolver = new AssemblyResolver(module);
            resourceResolver.find();
            assemblyResolver.find();

            decryptResources();
            stringDecrypter.init(resourceDecrypter);
            if (stringDecrypter.Method != null) {
                staticStringInliner.add(stringDecrypter.Method, (method, gim, args) => {
                    return stringDecrypter.decrypt((int)args[0]);
                });
                DeobfuscatedFile.stringDecryptersAdded();
            }

            methodsDecrypter.decrypt(resourceDecrypter);

            if (methodsDecrypter.Detected) {
                if (!assemblyResolver.Detected)
                    assemblyResolver.find();
                if (!tamperDetection.Detected)
                    tamperDetection.find();
            }
            antiDebugger = new AntiDebugger(module, DeobfuscatedFile, this);
            antiDebugger.find();

            if (options.DecryptConstants) {
                constantsDecrypter.init(resourceDecrypter);
                int32ValueInliner = new Int32ValueInliner();
                int32ValueInliner.add(constantsDecrypter.Int32Decrypter, (method, gim, args) => constantsDecrypter.decryptInt32((int)args[0]));
                int64ValueInliner = new Int64ValueInliner();
                int64ValueInliner.add(constantsDecrypter.Int64Decrypter, (method, gim, args) => constantsDecrypter.decryptInt64((int)args[0]));
                singleValueInliner = new SingleValueInliner();
                singleValueInliner.add(constantsDecrypter.SingleDecrypter, (method, gim, args) => constantsDecrypter.decryptSingle((int)args[0]));
                doubleValueInliner = new DoubleValueInliner();
                doubleValueInliner.add(constantsDecrypter.DoubleDecrypter, (method, gim, args) => constantsDecrypter.decryptDouble((int)args[0]));
                addTypeToBeRemoved(constantsDecrypter.Type, "Constants decrypter type");
                addResourceToBeRemoved(constantsDecrypter.Resource, "Encrypted constants");
            }

            addModuleCctorInitCallToBeRemoved(resourceResolver.Method);
            addModuleCctorInitCallToBeRemoved(assemblyResolver.Method);
            addCallToBeRemoved(module.EntryPoint, tamperDetection.Method);
            addModuleCctorInitCallToBeRemoved(tamperDetection.Method);
            addCallToBeRemoved(module.EntryPoint, antiDebugger.Method);
            addModuleCctorInitCallToBeRemoved(antiDebugger.Method);
            addTypeToBeRemoved(resourceResolver.Type, "Resource resolver type");
            addTypeToBeRemoved(assemblyResolver.Type, "Assembly resolver type");
            addTypeToBeRemoved(tamperDetection.Type, "Tamper detection type");
            addTypeToBeRemoved(antiDebugger.Type, "Anti-debugger type");
            addTypeToBeRemoved(methodsDecrypter.Type, "Methods decrypter type");
            addTypesToBeRemoved(methodsDecrypter.DelegateTypes, "Methods decrypter delegate type");
            addResourceToBeRemoved(methodsDecrypter.Resource, "Encrypted methods");

            proxyCallFixer.find();

            dumpEmbeddedAssemblies();
        }
Example #60
0
        public static string GetScriptString(AssetPreloadData assetPreloadData)
        {
            if (!moduleLoaded)
            {
                var openFolderDialog = new OpenFolderDialog();
                openFolderDialog.Title = "Select Assembly Folder";
                if (openFolderDialog.ShowDialog() == DialogResult.OK)
                {
                    var files         = Directory.GetFiles(openFolderDialog.Folder, "*.dll");
                    var moduleContext = new ModuleContext();
                    var asmResolver   = new AssemblyResolver(moduleContext, true);
                    var resolver      = new Resolver(asmResolver);
                    moduleContext.AssemblyResolver = asmResolver;
                    moduleContext.Resolver         = resolver;
                    try
                    {
                        foreach (var file in files)
                        {
                            var module = ModuleDefMD.Load(file, moduleContext);
                            LoadedModuleDic.Add(Path.GetFileName(file), module);
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }

                moduleLoaded = true;
            }
            var m_MonoBehaviour = new MonoBehaviour(assetPreloadData);
            var sb = new StringBuilder();

            sb.AppendLine("PPtr<GameObject> m_GameObject");
            sb.AppendLine($"\tint m_FileID = {m_MonoBehaviour.m_GameObject.m_FileID}");
            sb.AppendLine($"\tint64 m_PathID = {m_MonoBehaviour.m_GameObject.m_PathID}");
            sb.AppendLine($"UInt8 m_Enabled = {m_MonoBehaviour.m_Enabled}");
            sb.AppendLine("PPtr<MonoScript> m_Script");
            sb.AppendLine($"\tint m_FileID = {m_MonoBehaviour.m_Script.m_FileID}");
            sb.AppendLine($"\tint64 m_PathID = {m_MonoBehaviour.m_Script.m_PathID}");
            sb.AppendLine($"string m_Name = \"{m_MonoBehaviour.m_Name}\"");
            if (m_MonoBehaviour.m_Script.TryGetPD(out var script))
            {
                var m_Script = new MonoScript(script);
                if (!LoadedModuleDic.TryGetValue(m_Script.m_AssemblyName, out var module))
                {
                    /*using (var openFileDialog = new OpenFileDialog())
                     * {
                     *  openFileDialog.Title = $"Select {m_Script.m_AssemblyName}";
                     *  openFileDialog.FileName = m_Script.m_AssemblyName;
                     *  openFileDialog.Filter = $"{m_Script.m_AssemblyName}|{m_Script.m_AssemblyName}";
                     *  if (openFileDialog.ShowDialog() == DialogResult.OK)
                     *  {
                     *      var moduleContext = new ModuleContext();
                     *      var asmResolver = new AssemblyResolver(moduleContext, true);
                     *      var resolver = new Resolver(asmResolver);
                     *      moduleContext.AssemblyResolver = asmResolver;
                     *      moduleContext.Resolver = resolver;
                     *      module = ModuleDefMD.Load(openFileDialog.FileName, moduleContext);
                     *      LoadedModule.Add(m_Script.m_AssemblyName, module);
                     *  }
                     *  else
                     *  {
                     *      return sb.ToString();
                     *  }
                     * }*/
                    return(sb.ToString());
                }
                var typeDef = module.Assembly.Find(m_Script.m_Namespace != "" ? $"{m_Script.m_Namespace}.{m_Script.m_ClassName}" : m_Script.m_ClassName, false);
                if (typeDef != null)
                {
                    try
                    {
                        DumpType(typeDef.ToTypeSig(), sb, assetPreloadData.sourceFile, null, -1, true);
                    }
                    catch
                    {
                        sb = new StringBuilder();
                        sb.AppendLine("PPtr<GameObject> m_GameObject");
                        sb.AppendLine($"\tint m_FileID = {m_MonoBehaviour.m_GameObject.m_FileID}");
                        sb.AppendLine($"\tint64 m_PathID = {m_MonoBehaviour.m_GameObject.m_PathID}");
                        sb.AppendLine($"UInt8 m_Enabled = {m_MonoBehaviour.m_Enabled}");
                        sb.AppendLine("PPtr<MonoScript> m_Script");
                        sb.AppendLine($"\tint m_FileID = {m_MonoBehaviour.m_Script.m_FileID}");
                        sb.AppendLine($"\tint64 m_PathID = {m_MonoBehaviour.m_Script.m_PathID}");
                        sb.AppendLine($"string m_Name = \"{m_MonoBehaviour.m_Name}\"");
                    }
                }
            }
            return(sb.ToString());
        }