public MethodContext(Type type, Property method, PropertyDefinition methodDefinition) { Type = type; Property = method; PropertyDefinition = methodDefinition; Marker = new MethodMarker(); NameAlias = new NameAliasFactory(); Importer = new ImporterFactory(this); Cloning = new MethodCloneFactory(this); Mixin = new MethodMixinExtension(this); Scope = new MethodScopingExtension(this); Assemblies = new AssemblyFactory(); }
//Disabling warning 0169 because this code will be called at //runtime with glade. #pragma warning disable 0169 private void OnOpenToolButtonClicked(object sender, EventArgs args) { FileChooserDialog fileChooser = new FileChooserDialog( "Choose an assembly for measure", mainWindow, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept); fileChooser.Filter = CreateAssemblyFilter(); if (fileChooser.Run() == (int)ResponseType.Accept) { AssemblyDefinition assembly = AssemblyFactory.GetAssembly(fileChooser.Filename); measures = new MeasureCalculator().ProcessMeasures(assembly); FillTreeView(measures); findToolButton.Sensitive = true; CleanBin(frame1); frame1.Child = new AssemblyMeasureWidget(assembly).Widget; frame1.ShowAll(); } fileChooser.Destroy(); }
public void CecilShouldRemoveStrongNameFromAssembly() { var location = typeof(SampleHelloClass).Assembly.Location; var sourceAssembly = AssemblyFactory.GetAssembly(location); Assert.IsNotNull(sourceAssembly); sourceAssembly.RemoveStrongName(); var assembly = sourceAssembly.ToAssembly(); Assert.IsNotNull(assembly); var assemblyName = assembly.GetName(); // The public key should be empty var bytes = assemblyName.GetPublicKey(); Assert.IsTrue(bytes.Length == 0); return; }
public string runPostSharpOnAssembly() { var assemblyOriginal = compileFileToExe(); var assemblyCopy = Files.Copy(assemblyOriginal, assemblyOriginal + "_PS.exe"); var assembly = CecilUtils.getAssembly(assemblyCopy); InjectAttributes.addO2PostSharpHookAttribute(assembly); InjectAttributes.addOnMethodInvocationttribute(assembly, assembly.Name.Name, "*", "TestScript_MultipleCalls", "validate"); assembly.Name.PublicKey = null; AssemblyFactory.SaveAssembly(assembly, assemblyCopy); Hacks.patchAssemblyForCecilPostSharpBug(assemblyCopy); InjectAttributes.addO2PostSharpHookAttribute(assemblyCopy); Assert.That(PostSharpExecution.runPostSharpOnAssembly(assemblyCopy)); Assert.That(true == PostSharpUtils.arePostSharpDllsAddedAsReferences(assemblyCopy)); Assert.That(false == PostSharpUtils.arePostSharpDllsAddedAsReferences(assemblyOriginal)); log.info("runPostSharpOnAssembly executed ok"); return(assemblyCopy); }
public void ShouldSetAndGetTheSameFieldValue() { var myLibrary = AssemblyFactory.GetAssembly("SampleLibrary.dll"); var module = myLibrary.MainModule; foreach (TypeDefinition type in myLibrary.MainModule.Types) { if (!type.FullName.Contains("SampleClassWithReadOnlyField")) { continue; } type.InterceptAllFields(); } var loadedAssembly = myLibrary.ToAssembly(); var targetType = (from t in loadedAssembly.GetTypes() where t.Name.Contains("SampleClassWithReadOnlyField") select t).First(); var instance = Activator.CreateInstance(targetType); Assert.IsNotNull(instance); var host = (IFieldInterceptionHost)instance; Assert.IsNotNull(host); host.FieldInterceptor = new FieldInterceptorImpl(); var targetProperty = targetType.GetProperty("Value"); targetProperty.SetValue(instance, "OtherValue", null); var actualValue = targetProperty.GetValue(instance, null); Assert.AreEqual("freeze!", actualValue); }
protected override void Load(ContainerBuilder builder) { base.Load(builder); builder.RegisterType <Mediator>().As <IMediator>().InstancePerLifetimeScope(); builder.Register <ServiceFactory>(context => { var c = context.Resolve <IComponentContext>(); return(t => c.Resolve(t)); }); var assemblies = AssemblyFactory.GetAssemblies(); builder.RegisterAssemblyTypes(assemblies.ToArray()) .Where(x => x.Name.EndsWith("Handler")) .AsImplementedInterfaces() .PropertiesAutowired(); builder.RegisterAssemblyTypes(assemblies.ToArray()) .Where(x => x.Name.EndsWith("Listener")) .AsImplementedInterfaces() .PropertiesAutowired(); }
public static ReflectionProjectContent LoadAssembly(string fileName, ProjectContentRegistry registry) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (registry == null) { throw new ArgumentNullException("registry"); } LoggingService.Info("Cecil: Load from " + fileName); AssemblyDefinition asm = AssemblyFactory.GetAssembly(fileName); List <DomAssemblyName> referencedAssemblies = new List <DomAssemblyName>(); foreach (ModuleDefinition module in asm.Modules) { foreach (AssemblyNameReference anr in module.AssemblyReferences) { referencedAssemblies.Add(new DomAssemblyName(anr.FullName)); } } return(new CecilProjectContent(asm.Name.FullName, fileName, referencedAssemblies.ToArray(), asm, registry)); }
public void ScanFile(string app, string fileName, ICollection filters) { AssemblyDefinition targetAssembly = null; try { targetAssembly = AssemblyFactory.GetAssembly(fileName); } catch { return; } foreach (ModuleDefinition md in targetAssembly.Modules) { foreach (TypeDefinition td in md.Types) { foreach (MethodDefinition methd in td.Methods) { ScanMethodBody(app, methd); } } } }
public static IEnumerable <AssemblyLine> CompileMethod(MethodDefinition definition, IImmutableDictionary <string, ProcessedType> types, Assembly frameworkAssembly) { var instructionCompiler = new CilInstructionCompiler(definition, types); var instructions = definition.Body.Instructions; var compilationActions = ProcessInstructions(instructions, types, frameworkAssembly); var instructionsToLabel = GetInstructionsToEmitLabelsFor(instructions).ToArray(); var compiledBody = new List <AssemblyLine>(); var compilationContext = new CompilationContext(instructionCompiler); foreach (var action in compilationActions) { var needLabel = action.ConsumedInstructions.Where(i => instructionsToLabel.Contains(i)).ToArray(); foreach (var toLabel in needLabel) { compiledBody.Add(AssemblyFactory.Label(LabelGenerator.GetFromInstruction(toLabel))); } compiledBody.AddRange(action.Execute(compilationContext)); } compiledBody = OptimizeMethod(compiledBody).ToList(); return(compiledBody); }
public string Save(string sTargetDirectory, string fileName) { string fileToCreate = Path.Combine(sTargetDirectory, fileName); if (fileToCreate.IndexOf(".exe") == -1 && fileToCreate.IndexOf(".dll") == -1) { switch (assemblyKind) { case AssemblyKind.Console: case AssemblyKind.Windows: fileToCreate += ".exe"; break; case AssemblyKind.Dll: fileToCreate += ".dll"; break; } } AssemblyFactory.SaveAssembly(assemblyDefinition, fileToCreate); return(fileToCreate); }
protected override void ProcessAssembly(AssemblyDefinition assembly) { IEnumerable <string> typenames; try { var path = Path.Combine(Tools.GetTuningFolder(), "TuningInput/PreviouslyShipped/" + assembly.Name.Name + ".dll"); var previousShippedVersion = AssemblyFactory.GetAssembly(path); typenames = previousShippedVersion.MainModule.Types.Cast <TypeDefinition>().Where(t => t.IsPublic).Select(t => t.FullName); } catch (FileNotFoundException) { //that's cool. return; } var types = assembly.MainModule.Types; foreach (var requiredtype in typenames.Where(requiredtype => !types.Cast <TypeDefinition>().Any(type => type.FullName == requiredtype))) { throw new Exception("The type " + requiredtype + " was shipped in a previous version of Unity, but is currently being linked away"); } }
/// <summary> /// Constructor of AssemblyInjector /// </summary> /// <param name="HostFile"> /// A <see cref="System.String"/> /// The Host we will act upon and in which the code will be injected. /// </param> /// <param name="NewHostName"> /// A <see cref="System.String"/> /// You can specify a new filename for the new "patched" executable. /// </param> /// <param name="ReturnType"> /// A <see cref="System.Type"/> /// The returntype of the function you want to intect !ONLY TEMPORARY! /// </param> public AssemblyInjector(string HostFile, string NewHostName, System.Type ReturnType) { //lets get the definitions out of our way. AssemblyDefinition asm = AssemblyFactory.GetAssembly(HostFile); TypeReference returntype = asm.MainModule.Import(ReturnType); //Field and which type: MethodDefinition testmethod = new MethodDefinition("Test", MethodAttributes.Private | MethodAttributes.Static, returntype); Instruction msg = testmethod.Body.CilWorker.Create(OpCodes.Ldstr, "Hello from Test()"); MethodReference writeline = asm.MainModule.Import(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })); //Test() // << testmethod //{ // string="Hello from Test()"; // << msg // Console.WriteLine(string); // << writeline // return void; //} testmethod.Body.CilWorker.Append(msg); testmethod.Body.CilWorker.Append(testmethod.Body.CilWorker.Create(OpCodes.Call, writeline)); testmethod.Body.CilWorker.Append(testmethod.Body.CilWorker.Create(OpCodes.Ret)); Inject(testmethod, asm, GetTargetClass(asm)); }
public void PatchAssembly() { #if DEBUG File.Delete("dump.txt"); File.Delete("dump_changed.txt"); #endif foreach (TypeDefinition typeDefinition in m_assemblyDefinition.MainModule.Types) { if (ExcludeType(typeDefinition)) { continue; } foreach (MethodDefinition methodDefinition in typeDefinition.Methods) { MethodHook hook = m_hookProvider.GetMethodHook(methodDefinition); PatchMethod(methodDefinition, typeDefinition, hook); } } AssemblyFactory.SaveAssembly(m_assemblyDefinition, m_assemblyPath); }
/// <inheritdoc /> public Assembly InstrumentAndLoad(string assemblyPath, string instrumentedAssemblySavePath) { if (assemblyPath == null) { throw new ArgumentNullException(@"assemblyPath"); } // TODO: Cache the instrumented assembly on disk so we can reload it quickly later // if nothing has changed. AssemblyDefinition assemblyDefinition = AssemblyFactory.GetAssembly(assemblyPath); Rewrite(assemblyDefinition); MemoryStream stream = new MemoryStream(); AssemblyFactory.SaveAssembly(assemblyDefinition, stream); if (instrumentedAssemblySavePath != null) { AssemblyFactory.SaveAssembly(assemblyDefinition, instrumentedAssemblySavePath); } return(Assembly.Load(stream.ToArray())); }
internal static System.Reflection.AssemblyName GetAssemblyNameObj(string file) { try { AssemblyDefinition asm = AssemblyFactory.GetAssemblyManifest(file); return(new AssemblyName(asm.Name.FullName)); // Don't use reflection to get the name since it is a common cause for deadlocks // in Mono < 2.6. // return System.Reflection.AssemblyName.GetAssemblyName (file); } catch (FileNotFoundException) { // GetAssemblyName is not case insensitive in mono/windows. This is a workaround foreach (string f in Directory.GetFiles(Path.GetDirectoryName(file), Path.GetFileName(file))) { if (f != file) { return(GetAssemblyNameObj(f)); } } throw; } catch (BadImageFormatException) { AssemblyDefinition asm = AssemblyFactory.GetAssemblyManifest(file); return(new AssemblyName(asm.Name.FullName)); } }
public void CreateAndReadTopicTest() { // Arrange persistenceFactory = AssemblyFactory.LoadInstance <IPersistence>(Environment.CurrentDirectory, "EADN.Semester.QuizGame.Persistence.EF.dll"); Common.Topic readTopic; // Act using (DAL = persistenceFactory.GetDataAccesLayer()) { topicRepo = DAL.GetTopicRepository(); topicRepo.Create(testTopic); DAL.Save(); } using (DAL = persistenceFactory.GetDataAccesLayer()) { topicRepo = DAL.GetTopicRepository(); readTopic = topicRepo.Read(testTopic.Id); } // Assert Assert.AreEqual(testTopic.Id, readTopic.Id); Assert.AreEqual(testTopic.Name, readTopic.Name); Assert.AreEqual(testTopic.Text, readTopic.Text); }
public void CanLoadAndExecute() { var assemblyFactory = new AssemblyFactory(); var plugins = new[] { new { Name = "PluginOne", Framework = "netstandard2.0" }, new{ Name = "PluginTwo", Framework = "net6.0" }, }; var pluginPathFiles = plugins.Select(plugin => pathWrapper.Combine( PathToPlugins(), plugin.Name, "bin", "Debug", plugin.Framework, plugin.Name + ".dll") ); var assemblies = pluginPathFiles.Select(pluginPathFile => assemblyFactory.LoadFile(pluginPathFile)); var sut = PluginHandler.Create(); // Act. sut.Load(assemblies); var res = sut.Execute("a"); // Assert. res .Select(pr => new { pr.Name, Result = pr.Result.ToString() }) .Should() .BeEquivalentTo( new[] { new { Name = "Plugin one", Result = "<data plugin=\"Plugin one\">a</data>" }, new { Name = "Plugin two", Result = "<data plugin=\"Plugin two\">a</data>" }, } ); }
static void Process(MergeContext context) { AssemblyDefinition primary = null; try { primary = AssemblyFactory.GetAssembly(context.Assemblies [0]); for (int i = 1; i < context.Assemblies.Count; i++) { AssemblyDefinition asm = AssemblyFactory.GetAssembly(context.Assemblies [i]); asm.Accept(new StructureMerger(context, primary, asm)); } } catch (FileNotFoundException e) { Error(e.Message); } FixReflectionAfterMerge fix = new FixReflectionAfterMerge(context, primary, primary); fix.Process(); AssemblyFactory.SaveAssembly(primary, context.OutputPath); ConfigMerger.Process(context.Assemblies, context.OutputPath); }
private void ExpandAssembly(ExpandedAssembly ea, string assemblyFilename) { Console.WriteLine("Processing assembly '{0}'...", assemblyFilename); if (!File.Exists(assemblyFilename)) { throw new SigExpanderException("Assembly '" + assemblyFilename + "' does not exist"); } AssemblyDefinition ad = AssemblyFactory.GetAssembly(assemblyFilename); ModuleDefinition module = ad.MainModule; TypeResolver typeResolver = new TypeResolver(_assemblyResolver, ad); foreach (ExpandedType et in ea.Types) { TypeDefinition type = module.Types[et.Name]; if (type == null) { Console.WriteLine("Warning: could not find type {0}.", et.Name); return; } TypeExpander expander = new TypeExpander(type, typeResolver); foreach (MethodElement me in et.ExtraMethods) { expander.AddEmptyMethod(me); } } string target = GetTargetFileName(assemblyFilename); AssemblyFactory.SaveAssembly(ad, target); Console.WriteLine("Written '{0}'.", target); }
public void CreateAndReadQuizTest() { // Arrange persistenceFactory = AssemblyFactory.LoadInstance <IPersistence>(Environment.CurrentDirectory, "EADN.Semester.QuizGame.Persistence.EF.dll"); Common.Quiz readQuiz; // Act using (DAL = persistenceFactory.GetDataAccesLayer()) { quizRepo = DAL.GetQuizRepository(); quizRepo.Create(testQuiz); DAL.Save(); } using (DAL = persistenceFactory.GetDataAccesLayer()) { quizRepo = DAL.GetQuizRepository(); readQuiz = quizRepo.Read(testQuiz.Id); } // Assert Assert.AreEqual(testQuiz.Id, readQuiz.Id); Assert.AreEqual(testQuiz.Name, readQuiz.Name); Assert.AreEqual(testQuiz.QuizType, readQuiz.QuizType); }
public void ShouldBeAbleToDetermineIfMethodIsByRef() { var location = typeof(SampleClassWithByRefMethod).Assembly.Location; var assembly = AssemblyFactory.GetAssembly(location); var module = assembly.MainModule; var targetType = module.GetType("SampleClassWithByRefMethod"); var byRefMethod = targetType.GetMethod("ByRefMethod"); var regularMethod = targetType.GetMethod("NonByRefMethod"); Assert.IsNotNull(assembly); Assert.IsNotNull(targetType); Assert.IsNotNull(byRefMethod); Assert.IsNotNull(regularMethod); // Test the byref parameter var parameter = byRefMethod.Parameters[0]; Assert.IsTrue(parameter.IsByRef()); // Test the non-byref parameter parameter = regularMethod.Parameters[0]; Assert.IsFalse(parameter.IsByRef()); }
/// <summary> /// Reflects through the currently selected assembly and reflects the type tree /// in tvAssemblyGraph. /// </summary> public void LoadAssemblies(string[] fileNames) { BranchingOpCodes opCodes = new BranchingOpCodes(); treeView.Nodes.Clear(); for (int theAssembly = 0; theAssembly < fileNames.Length; theAssembly++) { // Load our input assembly and create its node in the tree AssemblyDefinition inputAssembly = AssemblyFactory.GetAssembly(fileNames[theAssembly]); TreeNode assemblyTreeNode = CreateTreeNode(fileNames[theAssembly], inputAssembly, Assembly); treeView.Nodes.Add(assemblyTreeNode); // Retrieve the modules from the assembly. Most assemblies only have one // module, but it is possible for assemblies to possess multiple modules for (int theModule = 0; theModule < inputAssembly.Modules.Count; theModule++) { // Add a node to the tree to represent the module TreeNode moduleTreeNode = CreateTreeNode(inputAssembly.Modules[theModule].Name, inputAssembly.Modules[theModule], Module); treeView.Nodes[theAssembly].Nodes.Add(moduleTreeNode); // Add the classes in each type for (int theType = 0; theType < inputAssembly.Modules[theModule].Types.Count; theType++) { // Add a node to the tree to represent the class treeView.Nodes[theAssembly].Nodes[theModule].Nodes.Add( CreateTreeNode(inputAssembly.Modules[theModule].Types[theType].FullName, inputAssembly.Modules[theModule].Types[theType], Class)); // Create a test method for each method in this type for (int theMethod = 0; theMethod < inputAssembly.Modules[theModule].Types[theType].Methods.Count; theMethod++) { MethodDefinition methodDefinition = inputAssembly.Modules[theModule].Types[theType].Methods[theMethod]; treeView.Nodes[theAssembly].Nodes[theModule].Nodes[theType].Nodes.Add( CreateTreeNode(methodDefinition.Name, methodDefinition, Method)); // Store the method's MethodInfo object in this node's tag // so that we may retrieve it later treeView.Nodes[theAssembly].Nodes[theModule].Nodes[theType].Nodes[ theMethod].Tag = methodDefinition; // Interfaces or abstract classes don't have a body so we should skip // them if (methodDefinition.HasBody) { MethodBody body = methodDefinition.Body; for (int theInstruction = 0; theInstruction < body.Instructions.Count; theInstruction++) { if (opCodes.ContainsKey( body.Instructions[theInstruction].OpCode)) { treeView. Nodes[theAssembly]. Nodes[theModule]. Nodes[theType]. Nodes[theMethod]. Nodes.Add( CreateTreeNode( opCodes[body.Instructions[theInstruction].OpCode].ToString(), new ConditionalDefinitionDto(methodDefinition, theInstruction), Branch)); } } } } } moduleTreeNode.Expand(); } assemblyTreeNode.Expand(); } }
static void Main(string[] args) { Assembly ass = Assembly.LoadFrom(@"D:\Nick Personal\Programming\GPU\Projects\Cudafy\Cudafy\bin\Debug\ESA.Dataflow.dll"); //(typeof(Program)); // ass. ////AssemblyDefinition. AssemblyDefinition ad = AssemblyFactory.GetAssembly(ass.Location); ModuleDefinitionCollection mdc = ad.Modules; StringBuilder sb = new StringBuilder(); StringWriter streamWriter = new StringWriter(sb); foreach (ModuleDefinition mod in mdc) { Console.WriteLine(mod.Name); foreach (TypeDefinition type in mod.Types) { Console.WriteLine(type.FullName); if (type.Name == "ControlVector") { foreach (MethodDefinition md in type.Methods) { //foreach (CustomAttribute ca in md.CustomAttributes) //{ // if (ca.Constructor.DeclaringType.Name == "GPUFunctionAttribute") // { if (md.Name == "Add") { Console.WriteLine(md.Name); ILanguage lan = Cecil.Decompiler.Languages.CSharp.GetLanguage(Cecil.Decompiler.Languages.CSharpVersion.V3); ILanguageWriter lanWriter = lan.GetWriter(new PlainTextFormatter(streamWriter)); lanWriter.Write(md); Console.WriteLine(sb.ToString()); } // } //} } } } } int size = 4; int[] myArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }; int[][] inputA = new int[size][]; int[][] inputB = new int[size][]; int[][] outputC = new int[size][]; for (int i = 0; i < size; i++) { inputB[i] = new int[size]; outputC[i] = new int[size]; inputA[i] = new int[size]; int cnt = i; for (int x = 0; x < size; x++) { inputA[i][x] = cnt; inputB[i][x] = cnt++; } } HCudafy cuda = new HCudafy(); cuda.Cudafy(typeof(Program)); Stopwatch sw = new Stopwatch(); sw.Start(); int[] devMyArray = cuda.CopyToDevice(myArray); int[][] devA = cuda.CopyToDevice(inputA); int[][] devB = cuda.CopyToDevice(inputB); int[][] devC = cuda.Allocate(outputC); Dim3 grid = new Dim3(1); Dim3 block = new Dim3(size / 1); cuda.Launch(grid, block, "doVecAdd", devA, devB, devC, 42, devMyArray); cuda.CopyFromDevice(devC, outputC); sw.Stop(); for (int i = 0; i < 4; i++) { for (int x = 0; x < 4; x++) { Console.Write("{0}\t", outputC[i][x]); } Console.WriteLine(); } int[] somestuff = new int[512]; for (int y = 0; y < 512; y++) { somestuff[y] = y * 10; } int[] data = cuda.CopyToDevice(somestuff); int[] res = new int[512]; cuda.CopyFromDevice(data, res); for (int y = 0; y < 512; y++) { if (res[y] != somestuff[y]) { throw new Exception(); } } int[][] deviceArray2D = cuda.Allocate <int>(4, 8); int[] deviceArray = cuda.Allocate <int>(7); Console.WriteLine(sw.ElapsedMilliseconds + "ms"); Console.WriteLine("Done"); Console.ReadKey(); return; #region scrap //Action<object> action = (object obj) => //{ // Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId); //}; //Task t = new Task(action, "hello"); //HThread ht = new HThread(action, "hello"); //HGrid grid = new HGrid( //HCudafy.Launch( int side = 1024; int[][] myJaggedArray = new int[side][]; for (int i = 0; i < side; i++) { myJaggedArray[i] = new int[side]; int cnt = i; for (int x = 0; x < side; x++) { myJaggedArray[i][x] = cnt++; } } int threads = Environment.ProcessorCount / 1; // _barrier = new Barrier(threads); //Console.WriteLine("Before"); //var po = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }; //Parallel.For(0, side, po, i => Process(myJaggedArray[i])); myJaggedArray.AsParallel().WithDegreeOfParallelism(threads).ForAll(x => Process(x)); //myJaggedArray.ToList().ForEach(x => Process(x)); //Console.WriteLine("Between"); //myJaggedArray.AsParallel().WithDegreeOfParallelism(threads).ForAll(x => Process(x)); sw.Stop(); // _barrier.Dispose(); Console.WriteLine(sw.ElapsedMilliseconds + "ms"); Console.WriteLine("Done"); Console.ReadKey(); #endregion }
/// <summary> /// Creates a proxy type using the given /// <paramref name="baseType"/> as the base class /// and ensures that the proxy type implements the given /// interface types. /// </summary> /// <param name="baseType">The base class from which the proxy type will be derived.</param> /// <param name="baseInterfaces">The list of interfaces that the proxy will implement.</param> /// <returns>A forwarding proxy.</returns> public Type CreateProxyType(Type baseType, IEnumerable <Type> baseInterfaces) { // Reuse the cached results, if possible Type[] originalInterfaces = baseInterfaces.ToArray(); if (Cache != null && Cache.Contains(baseType, originalInterfaces)) { return(Cache.Get(baseType, originalInterfaces)); } if (!baseType.IsPublic) { throw new ArgumentException("The proxy factory can only generate proxies from public base classes.", "baseType"); } bool hasNonPublicInterfaces = (from t in baseInterfaces where t.IsNotPublic select t).Count() > 0; if (hasNonPublicInterfaces) { throw new ArgumentException("The proxy factory cannot generate proxies from non-public interfaces.", "baseInterfaces"); } #region Determine which interfaces need to be implemented Type actualBaseType = baseType.IsInterface ? typeof(object) : baseType; var interfaces = new HashSet <Type>(baseInterfaces); // Move the base type into the list of interfaces // if the user mistakenly entered // an interface type as the base type if (baseType.IsInterface) { interfaces.Add(baseType); } if (InterfaceExtractor != null) { // Get the interfaces for the base type InterfaceExtractor.GetInterfaces(actualBaseType, interfaces); Type[] targetList = interfaces.ToArray(); // Extract the inherited interfaces foreach (Type type in targetList) { InterfaceExtractor.GetInterfaces(type, interfaces); } } #endregion #region Generate the assembly string assemblyName = "LinFu.Proxy"; AssemblyDefinition assembly = AssemblyFactory.DefineAssembly(assemblyName, AssemblyKind.Dll); ModuleDefinition mainModule = assembly.MainModule; TypeReference importedBaseType = mainModule.Import(actualBaseType); TypeAttributes attributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; #endregion #region Initialize the proxy type string guid = Guid.NewGuid().ToString().Replace("-", ""); string typeName = string.Format("{0}Proxy-{1}", baseType.Name, guid); string namespaceName = "LinFu.Proxy"; TypeDefinition proxyType = mainModule.DefineClass(typeName, namespaceName, attributes, importedBaseType); proxyType.AddDefaultConstructor(); #endregion if (ProxyBuilder == null) { throw new NullReferenceException("The 'ProxyBuilder' property cannot be null"); } // Add the list of interfaces to the target type foreach (Type interfaceType in interfaces) { if (!interfaceType.IsInterface) { continue; } TypeReference currentType = mainModule.Import(interfaceType); proxyType.Interfaces.Add(currentType); } // Hand it off to the builder for construction ProxyBuilder.Construct(actualBaseType, interfaces, mainModule, proxyType); // Verify the assembly, if possible if (Verifier != null) { Verifier.Verify(assembly); } #region Compile the results Assembly compiledAssembly = assembly.ToAssembly(); IEnumerable <Type> types = null; try { types = compiledAssembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { types = ex.Types; } Type result = (from t in types where t != null && t.IsClass select t).FirstOrDefault(); #endregion // Cache the result if (Cache != null) { Cache.Store(result, baseType, originalInterfaces); } return(result); }
public static void loadInjectAssembly(string name) { injectAssembly = AssemblyFactory.GetAssembly(name); }
public static void loadBaseAssembly(String name) { baseAssembly = AssemblyFactory.GetAssembly(name); baseAssemblySavePath = name; }
private void AsyncStartObfuscation() { List <string> assembliesPaths = new List <string>(); List <bool> assembliesToObfuscate = new List <bool>(); m_process = 0; SetProgress("Loading...", 0); //---- Create the Xml Document for mapping _xmlMapping = new XmlDocument(); _xmlMappingRoot = _xmlMapping.CreateElement("mappings"); _xmlMapping.AppendChild(_xmlMappingRoot); //---- Load the assemblies foreach (string assemblyPath in _assembliesPaths.Keys) { // Full load the assembly AssemblyDefinition assembly = AssemblyFactory.GetAssembly(assemblyPath); foreach (ModuleDefinition module in assembly.Modules) { module.FullLoad(); } assembliesDefinitions.Add(assembly); assembliesPaths.Add(Path.GetFileName(assemblyPath)); assembliesToObfuscate.Add(_assembliesPaths[assemblyPath]); } SetProgress("Obfuscate...", 0); //---- Obfuscate the assemblies int assemblyIndex = -1; foreach (AssemblyDefinition assembly in assembliesDefinitions) { assemblyIndex++; if (!assembliesToObfuscate[assemblyIndex]) { continue; } SetProgress("Obfuscate assembly: " + assembly.Name.Name, 0); m_types = assembly.MainModule.Types; //---- Obfuscate Types / Methods int i = 0; int count = assembly.MainModule.Types.Count; //先查出excludeType 中的所有filed 和property的 fullName foreach (TypeDefinition type in m_types) { RefToExcludeType(type); } foreach (TypeDefinition type in assembly.MainModule.Types) { m_process = (float)i / (float)count; ObfuscateType(type); i++; } //---- Obfuscate Namespaces if (_obfuscateNamespaces) { foreach (TypeDefinition type in assembly.MainModule.Types) { ObfuscateNamespace(type); } } //---- Obfuscate Resources foreach (Resource resource in assembly.MainModule.Resources) { ObfuscateResource(resource); } SetProgress("Obfuscate resource: " + assembly.Name.Name, 100); } SetProgress("Saving...", 0); //---- Save the modified assemblies assemblyIndex = -1; foreach (AssemblyDefinition assembly in assembliesDefinitions) { assemblyIndex++; //---- Create output directory if it doesn't exists if (Directory.Exists(_outputDirectory) == false) { Directory.CreateDirectory(_outputDirectory); } //---- Delete previous file string outputFileName = Path.Combine(_outputDirectory, assembliesPaths[assemblyIndex]); if (File.Exists(outputFileName)) { File.Delete(outputFileName); } //---- Save the modified assembly AssemblyFactory.SaveAssembly(assembly, outputFileName); } //---- Save mapping _xmlMapping.Save(Path.Combine(_outputDirectory, "Mapping.xml")); SetProgress("Complete.", 100); }
/// <summary> /// Saves customized Counter assembly to specified location /// </summary> /// <param name="path">Path</param> public void Save(string path) { var counterAssemblyFile = Path.Combine(path, CounterAssemblyDef.Name.Name + ".dll"); AssemblyFactory.SaveAssembly(CounterAssemblyDef, counterAssemblyFile); }
private void AsyncStartObfuscation() { List <string> assembliesPaths = new List <string>(); List <bool> assembliesToObfuscate = new List <bool>(); NSLinker.InitNSLinker(); SetProgress("Loading...", 0); //---- Create the Xml Document for mapping _xmlMapping = new XmlDocument(); _xmlMappingRoot = _xmlMapping.CreateElement("mappings"); _xmlMapping.AppendChild(_xmlMappingRoot); //---- Load the assemblies foreach (string assemblyPath in _assembliesPaths.Keys) { // Full load the assembly AssemblyDefinition assembly = AssemblyFactory.GetAssembly(assemblyPath); foreach (ModuleDefinition module in assembly.Modules) { module.FullLoad(); } assembliesDefinitions.Add(assembly); assembliesPaths.Add(Path.GetFileName(assemblyPath)); assembliesToObfuscate.Add(_assembliesPaths[assemblyPath]); } SetProgress("Obfuscate...", 0); //---- Obfuscate the assemblies int assemblyIndex = -1; foreach (AssemblyDefinition assembly in assembliesDefinitions) { assemblyIndex++; if (!assembliesToObfuscate[assemblyIndex]) { continue; } SetProgress("Obfuscate assembly: " + assembly.Name.Name, 0); //---- Obfuscate Namespaces if (_obfuscateNamespaces) { foreach (TypeDefinition type in assembly.MainModule.Types) { ObfuscateNamespace(type); } } // foreach (TypeDefinition type in assembly.MainModule.Types) { ObfuscateType(type); } //---- Obfuscate Resources foreach (Resource resource in assembly.MainModule.Resources) { ObfuscateResource(resource); } SetProgress("Obfuscate resource: " + assembly.Name.Name, 99); } SetProgress("Saving...", 0); //---- Save the modified assemblies assemblyIndex = -1; foreach (AssemblyDefinition assembly in assembliesDefinitions) { assemblyIndex++; //---- Create output directory if it doesn't exists if (Directory.Exists(_outputDirectory) == false) { Directory.CreateDirectory(_outputDirectory); } //---- Delete previous file string outputFileName = Path.Combine(_outputDirectory, "" + assembliesPaths[assemblyIndex]); if (File.Exists(outputFileName)) { File.Delete(outputFileName); } //---- Save the modified assembly AssemblyFactory.SaveAssembly(assembly, outputFileName); } //---- Save mapping //_xmlMapping.Save(Path.Combine(_outputDirectory, "Mapping.xml")); SetProgress("Complete.90%", 90); if (AllComplated != null) { AllComplated(null, null); } }
public IAssembly LoadAssembly(string path) { return(new AssemblyWrapper(AssemblyFactory.GetAssembly(path))); }
void SetAssemblies() { uwpAssembly = new AssemblyFactory("Windows.Foundation.UniversalApiContract", ModuleDefinition); kasayUwpAssembly = new AssemblyFactory("Kasay.DependencyProperty.UWP", ModuleDefinition); }