/// <summary> /// Mutates all conditionals found in a given assembly. /// </summary> /// <param name="e">The <see cref="RunEventArgs"/> instance containing the event data.</param> /// <param name="opCodes">The list of valid OP codes.</param> private void MutateAllConditionals(RunEventArgs e, BranchingOpCodes opCodes) { string outputFile = GetOutputAssemblyFileName(e.InputAssembly); AssemblyDefinition inputAssembly = AssemblyFactory.GetAssembly(e.InputAssembly); foreach (ModuleDefinition module in inputAssembly.Modules) { foreach (TypeDefinition type in module.Types) { if (type.IsInterface) { continue; } foreach (MethodDefinition method in type.Methods) { for (int i = 0; i < method.Body.Instructions.Count; i++) { Instruction instruction = method.Body.Instructions[i]; if (opCodes.Contains(instruction.OpCode)) { instruction.OpCode = opCodes.Invert(instruction.OpCode); } } // Replace the original target assembly with the mutated assembly File.Delete(e.InputAssembly); AssemblyFactory.SaveAssembly(method.DeclaringType.Module.Assembly, outputFile); File.Copy(outputFile, e.InputAssembly); // Run the unit tests again, this time against the mutated assembly var runner = new MbUnitTestRunner(); runner.Invoke(e.TestAssembly); if (_testComplete != null) { _testComplete(this, new TestCompleteEventArgs(runner.TestResults)); } } } } }
public void methodDef() { AssemblyDefinition assembly = AssemblyFactory.GetAssembly(Assembly.GetExecutingAssembly().Location); foreach (TypeDefinition definition in assembly.MainModule.Types) { if (definition.Name == typeof(Person).Name) { foreach (MethodDefinition method in definition.Methods) { if (method.Name == "SayHello") { changeMethod(method); return; } } } } }
public CecilWidgetLibrary(AssemblyResolver resolver, string path) { name = path; this.resolver = resolver; cache.Refresh(resolver, name); if (resolver != null) { filename = resolver.Resolve(path, null); } if (filename == null) { filename = path; } assembly = AssemblyFactory.GetAssembly(filename); }
static void Main(string[] args) { var targetAssembly = AssemblyFactory.GetAssembly("SampleLibrary.dll"); var module = targetAssembly.MainModule; //var scope = new TypeScope(targetType); IDependencyScope scope = new ModuleScope(module); var targetType = GetTargetType(module, t => t.Name == "Greeter"); var targetDependency = GetTargetType(module, t => t.Name == "Writer"); ExtractInterfaces(module, targetDependency, targetType, scope); //UpdateClientMethods(module, targetDependency, interfaceType, adapterType, clientMethods, modifiedMethods); // TODO: Add adapters to the client code AssemblyFactory.SaveAssembly(targetAssembly, "output.dll"); return; }
public static void UpdateAssembly(string ModulePath, string Type, List <String> caseFeilds) { AssemblyDefinition module = AssemblyFactory.GetAssembly(ModulePath); TypeDefinition def = module.MainModule.Types[Type]; string TypeName = def.FullName; /* This method renames the Variables to how we have them */ foreach (FieldDefinition field in def.Fields) { if (caseFeilds.Contains(field.Name) || caseFeilds.Contains("*")) { field.Name = ReplaceFirst(field.Name); } } //module.MainModule.Types["WorldGen"].IsPublic = true; AssemblyFactory.SaveAssembly(module, ModulePath); }
private void LoadAssembly(string filename) { this.filename = filename; try { definition = AssemblyFactory.GetAssembly(filename); if (definition.MainModule.Image.MetadataRoot.Header.Version.StartsWith("v4")) { //definition.MainModule.Image.MetadataRoot.Header.MajorVersion = 4; definition.Runtime = TargetRuntime.NET_4_0; } name = definition.Name.Name; } catch (System.IO.FileNotFoundException e) { throw new ApplicationException("Unable to find assembly: " + filename, e); } }
private Type GetModifiedTargetType(Action <string, TypeDefinition> modify) { var assembly = AssemblyFactory.GetAssembly("SampleLibrary.dll"); var module = assembly.MainModule; // Intercept all calls to the System.Console.WriteLine method from the DoSomething method var typeName = "SampleClassWithThirdPartyMethodCall"; var targetType = (from TypeDefinition t in module.Types where t.Name == typeName select t).First(); modify(typeName, targetType); var modifiedAssembly = assembly.ToAssembly(); return((from t in modifiedAssembly.GetTypes() where t.Name == typeName select t).First()); }
public void CecilShouldExtractSampleClassFromSignedAssembly() { var location = typeof(SampleHelloClass).Assembly.Location; var sourceAssembly = AssemblyFactory.GetAssembly(location); Assert.IsNotNull(sourceAssembly); var definition = AssemblyFactory.DefineAssembly("testAssembly", AssemblyKind.Dll); var targetModule = definition.MainModule; foreach (TypeDefinition typeDef in sourceAssembly.MainModule.Types) { // Copy the source type to the target assembly targetModule.Inject(typeDef); } // Convert the new assemblyDef into an actual assembly var assembly = definition.ToAssembly(); Assert.IsNotNull(assembly); var types = assembly.GetTypes(); Assert.IsTrue(types.Length > 0); // The imported type must match the original type var firstType = types.FirstOrDefault(); Assert.IsNotNull(firstType); Assert.AreEqual(firstType.Name, typeof(SampleHelloClass).Name); var instance = Activator.CreateInstance(firstType); Assert.IsNotNull(instance); var speakMethod = firstType.GetMethod("Speak"); Assert.IsNotNull(speakMethod); speakMethod.Invoke(instance, new object[] { }); }
static int Main(string [] arguments) { var args = new List <string> (arguments); if (args.Count > 0 && args [0] == "-q") { quiet = true; args.RemoveAt(0); } Header(); if (args.Count == 0) { Usage(); } string file = args [0]; string output = args.Count > 1 ? args [1] : file; try { AssemblyDefinition assembly = AssemblyFactory.GetAssembly(file); StripAssembly(assembly, output); if (!quiet) { if (file != output) { Console.WriteLine("Assembly {0} stripped out into {1}", file, output); } else { Console.WriteLine("Assembly {0} stripped", file); } } return(0); } catch (TargetInvocationException tie) { Console.WriteLine("Error: {0}", tie.InnerException); } catch (Exception e) { Console.WriteLine("Error: {0}", e); } return(1); }
public void FindPInvokesInAssembly(string assembly) { AssemblyDefinition ad = AssemblyFactory.GetAssembly(assembly); //Gets all types of the MainModule of the assembly foreach (TypeDefinition type in ad.MainModule.Types) { if (type.Name != "<Module>") { //Gets all methods of the current type foreach (MethodDefinition method in type.Methods) { if ((method.Attributes & MethodAttributes.PInvokeImpl) == MethodAttributes.PInvokeImpl) { data[method.ToString()] = new Method(method.ToString(), string.Format("{0} ({1})", method.PInvokeInfo.Module.Name, method.PInvokeInfo.EntryPoint)); } } } } }
public void VisitFile(string fileName) { AssemblyDefinition targetAssembly = null; try { targetAssembly = AssemblyFactory.GetAssembly(fileName); } catch { return; } foreach (ModuleDefinition md in targetAssembly.Modules) { foreach (TypeDefinition td in md.Types) { VisitTypes(td); } } }
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) { ScanTypes(app, td, filters); } } }
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 <AssemblyName> referencedAssemblies = new List <AssemblyName>(); foreach (AssemblyNameReference anr in asm.MainModule.AssemblyReferences) { referencedAssemblies.Add(new AssemblyName(anr.FullName)); } return(new CecilProjectContent(asm.Name.FullName, fileName, referencedAssemblies.ToArray(), asm.MainModule.Types, registry)); }
/// <inheritdoc /> public Assembly InstrumentAndLoad(string assemblyPath, string instrumentedAssemblySavePath) { if (assemblyPath == null) { throw new ArgumentNullException(@"assemblyPath"); } AssemblyDefinition assemblyDefinition = AssemblyFactory.GetAssembly(assemblyPath); DynamicAssemblyBuilder builder = new DynamicAssemblyBuilder(assemblyDefinition); DynamicAssembly dynamicAssembly = builder.Build(instrumentedAssemblySavePath); if (instrumentedAssemblySavePath != null) { dynamicAssembly.Save(); } return(dynamicAssembly.Builder); }
protected void RunVerifierTestCase(string file) { string boo = GetBooFile(file); string asm = GetTempFileName(); WriteAssemblyScript was = CompileBooFile <WriteAssemblyScript> (boo); was.DefineAssembly(file); was.Run(); AssemblyFactory.SaveAssembly(was.ASM, asm); IVerifier verifier = new ManagedVerifier(AssemblyFactory.GetAssembly(asm)); VerifierResult result = verifier.Run(); RunAndAssertOutput(boo, delegate { foreach (ResultItem item in result.GetItems()) { Console.WriteLine(item); } }); }
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); }
public void CecilShouldRemoveStrongNameFromAssembly() { string location = typeof(SampleHelloClass).Assembly.Location; AssemblyDefinition sourceAssembly = AssemblyFactory.GetAssembly(location); Assert.IsNotNull(sourceAssembly); sourceAssembly.RemoveStrongName(); Assembly assembly = sourceAssembly.ToAssembly(); Assert.IsNotNull(assembly); AssemblyName assemblyName = assembly.GetName(); // The public key should be empty byte[] bytes = assemblyName.GetPublicKey(); Assert.IsTrue(bytes.Length == 0); return; }
private static AssemblyDefinition SearchDirectory(AssemblyNameReference name, IEnumerable <String> directories) { AssemblyDefinition result; foreach (string dir in directories) { string[] extentions = _extentions; for (int i = 0; i < extentions.Length; i++) { string ext = extentions[i]; string file = Path.Combine(dir, name.Name + ext); if (File.Exists(file)) { result = AssemblyFactory.GetAssembly(file); return(result); } } } result = null; return(result); }
public int Run() { AssemblyDefinition library; Console.WriteLine("Loading `{0}'", corlib); library = AssemblyFactory.GetAssembly(corlib); foreach (ModuleDefinition module in library.Modules) { ScanModule(module); } Console.WriteLine("Finished scanning.\n"); foreach (MethodDefinition def in internalStubs) { Console.WriteLine(def.DeclaringType.FullName + "\t\t\t" + def); } return(0); }
public void ShouldSetAndGetTheSameFieldValue() { AssemblyDefinition myLibrary = AssemblyFactory.GetAssembly("SampleLibrary.dll"); var module = myLibrary.MainModule; foreach (TypeDefinition type in myLibrary.MainModule.Types) { if (!type.FullName.Contains("SampleClassWithReadOnlyField")) { continue; } type.InterceptFields(m => true, f => true); } var loadedAssembly = myLibrary.ToAssembly(); var targetType = (from t in loadedAssembly.GetTypes() where t.Name.Contains("SampleClassWithReadOnlyField") select t).First(); object instance = Activator.CreateInstance(targetType); Assert.IsNotNull(instance); var interfaces = targetType.GetInterfaces(); var host = (IFieldInterceptionHost)instance; Assert.IsNotNull(host); host.FieldInterceptor = new FieldInterceptorImpl(); var targetProperty = targetType.GetProperty("Value"); targetProperty.SetValue(instance, "OtherValue", null); object actualValue = targetProperty.GetValue(instance, null); Assert.AreEqual("freeze!", actualValue); }
AssemblyDefinition ResolveAssembly(AssemblyNameReference aref) { string bpath = Path.Combine(Path.GetDirectoryName(filename), aref.Name); string filePath = null; if (resolver != null) { filePath = resolver.Resolve(aref.FullName, null); } if (filePath != null) { if (File.Exists(bpath + ".dll")) { filePath = bpath + ".dll"; } if (File.Exists(bpath + ".exe")) { filePath = bpath + ".exe"; } } AssemblyDefinition adef = null; if (filePath != null) { adef = AssemblyFactory.GetAssembly(filePath); } else { try { adef = resolver.Resolve(aref); } catch { // If can't resolve, just return null return(null); } } return(adef); }
public void Link() { outputAssembly = AssemblyFactory.GetAssembly(Assemblies [0]); mainModule = outputAssembly.MainModule; if (mainModule.Name != MainModuleName) { Console.Error.WriteLine("Main module is not named \"" + MainModuleName + "\" in assembly " + outputAssembly.Name.FullName); Environment.Exit(1); } mainType = mainModule.Types [MainTypeName]; if (mainType == null) { Console.Error.WriteLine("Main module does not contain type \"" + MainTypeName + "\" in assembly " + outputAssembly.Name.FullName); Environment.Exit(1); } outputAssembly.Accept(new StructureMerger(this, outputAssembly, outputAssembly)); for (int i = 1; i < Assemblies.Count; i++) { AssemblyDefinition asm = AssemblyFactory.GetAssembly(Assemblies [i]); asm.Accept(new StructureMerger(this, outputAssembly, asm)); } FixReflectionAfterMerge fix = new FixReflectionAfterMerge(this, outputAssembly, outputAssembly); fix.Process(); nativeLibraries.AddExternalMethods(this); if (OutputIsExecutable) { outputAssembly.Kind = AssemblyKind.Console; outputAssembly.EntryPoint = InternalSymbols.EntryPoint; } else { outputAssembly.Kind = AssemblyKind.Dll; } AssemblyFactory.SaveAssembly(outputAssembly, OutputPath); }
public void ShouldLoadSymbols() { var assembly = AssemblyFactory.GetAssembly("DomainTestClasses.dll"); assembly.MainModule.LoadSymbols(); foreach (TypeDefinition t in assembly.MainModule.Types) { foreach (MethodDefinition m in t.Methods) { foreach (Instruction ins in m.Body.Instructions) { if (ins.SequencePoint != null) { System.Console.WriteLine(ins.SequencePoint.ToString()); } } } System.Console.WriteLine(t.ToString()); } }
public static MethodDefinition FindMethod(MethodReference mr) { Type[] types = new Type[mr.Parameters.Count]; for (int i = 0; i < types.Length; i++) { types[i] = Type.GetType(mr.Parameters[i].ParameterType.FullName); } AssemblyDefinition asm; string assemblyName = FindAssemblyName(mr); lock (_cacheLock) { _assemblyDefinitionCache.TryGetValue(assemblyName, out asm); if (asm == null) { _assemblyDefinitionCache.Add(assemblyName, asm = AssemblyFactory.GetAssembly(System.Reflection.Assembly.Load(new System.Reflection.AssemblyName(assemblyName)).Location)); } } return(FindMethod(asm, mr.DeclaringType.FullName + "::" + mr.Name, types)); }
//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(); }
private static IEnumerable <FunctionInformation> GetAllFunctionInformations(string projectFilePath, string dllPath) { AssemblyDefinition assembly = AssemblyFactory.GetAssembly(dllPath); var functionsFromSourceCode = GetFunctionsWithAttribute(projectFilePath, "ApiExtension"); foreach (TypeDefinition type in assembly.MainModule.Types) { // Gets all methods of the current type foreach (MethodDefinition method in type.Methods) { if (method.CustomAttributes.Count > 0) { string attributeName = method.CustomAttributes[0].Constructor.DeclaringType.Name; if (attributeName == "ApiExtensionAttribute") { yield return(SearchFunctions(functionsFromSourceCode, type, method)); } } } } }
/// <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)); }
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"); } }
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()); }
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); }