// see mono Reflector Add-on since it contains this feature (so figure out how they do it) public void tryToFixPublicKey(String sAssemblyToFix) { AssemblyDefinition adAssembly = AssemblyFactory.GetAssembly(sAssemblyToFix); adAssembly.Name.PublicKey = null; AssemblyFactory.SaveAssembly(adAssembly, sAssemblyToFix + ".fix.dll"); }
public static bool setAttributeValueFromAssembly(String assemblyToLoad, String sAttributeToFetch, int iParameterValueIndex, Object oValue) { try { DI.log.info("getAttributeValueFromAssembly - assemblyToLoad: {0} sAttributeToFetch: {1} iParameterValueIndex: {2} oValue: {3}", assemblyToLoad, sAttributeToFetch, iParameterValueIndex, oValue); AssemblyDefinition assemblyDefinition = AssemblyFactory.GetAssembly(assemblyToLoad); foreach (ModuleDefinition moduleDefinition in assemblyDefinition.Modules) { foreach (TypeDefinition typeDefinition in moduleDefinition.Types) { foreach (MethodDefinition methodDefinition in typeDefinition.Methods) { foreach (CustomAttribute customAttribute in methodDefinition.CustomAttributes) { if (customAttribute.Constructor.DeclaringType.Name == sAttributeToFetch) { customAttribute.ConstructorParameters[iParameterValueIndex] = oValue; AssemblyFactory.SaveAssembly(assemblyDefinition, assemblyToLoad); return(true); } } } } } return(false); } catch (Exception ex) { DI.log.ex(ex, "in CecilUtils.setAttributeValueFromAssembly"); return(false); } }
static void Main(string[] args) { // dependency chain var inputName = args[0]; var oldName = args[1]; var linkedName = args[2]; var outputName = args[3]; var linked = AssemblyFactory.GetAssembly(linkedName); var target = AssemblyFactory.GetAssembly(inputName); var old = AssemblyFactory.GetAssembly(oldName); foreach (var module in target.GetModules()) { var obsolete = module .GetAssemblyReferences(old.Name.FullName) .ToArray(); foreach (var reference in obsolete) { reference.Name = linked.Name.Name; reference.Hash = linked.Name.Hash; reference.Version = linked.Name.Version; reference.PublicKeyToken = linked.Name.PublicKeyToken; } } AssemblyFactory.SaveAssembly(target, outputName); }
void OutputAssembly(AssemblyDefinition assembly) { string directory = Context.OutputDirectory; CopyConfigFileIfNeeded(assembly, directory); switch (Annotations.GetAction(assembly)) { case AssemblyAction.Link: SaveSymbols(assembly); AssemblyFactory.SaveAssembly(assembly, GetAssemblyFileName(assembly, directory)); break; case AssemblyAction.Copy: CopyAssembly(GetOriginalAssemblyFileInfo(assembly), directory); break; case AssemblyAction.Delete: var target = GetAssemblyFileName(assembly, directory); if (File.Exists(target)) { File.Delete(target); } break; } }
private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { AssemblyFactory.SaveAssembly(assembly, saveFileDialog.FileName); } }
public static void addO2PostSharpHookAttribute(string targetAssembly) { var assembly = CecilUtils.getAssembly(targetAssembly); addO2PostSharpHookAttribute(assembly); AssemblyFactory.SaveAssembly(assembly, targetAssembly); }
public override string Run(string tempFolder) { var assembly = Generate(); var resultPath = Path.Combine(tempFolder, assembly.Kind == AssemblyKind.Dll ? DllName : ExeName); AssemblyFactory.SaveAssembly(assembly, resultPath); return(resultPath); }
/// <summary> /// Saves the entire codebase to the specified folder. /// </summary> /// <param name="path">The path.</param> public void SaveTo(string path) { foreach (var def in _assemblies) { var fileName = Path.GetFileName(def.Key); var fullName = Path.Combine(path, fileName); AssemblyFactory.SaveAssembly(def.Value, fullName); } }
public void StartCilWork() { if (this.asm != null) { foreach (TypeDefinition type in this.asm.MainModule.Types) { if (type.Name != "<Module>") { foreach (MethodDefinition method in type.Methods) { if (this.Filter.Contains(method.Name)) { CilWorker worker = method.Body.CilWorker; string s = string.Concat("Code added in: ", method.Name); // Import StreamWriter constructor. ConstructorInfo ci = typeof(StreamWriter).GetConstructor(new Type[] { typeof(string) }); VariableReference streamw = asm.MainModule.Import(ci); streamw.Name = "sw"; // Get streamw's methods. WriteLine and Flush this.writeLine = streamw.GetType().GetMethod("WriteLine", new Type[] { typeof(string) }); this.flush = streamw.GetType().GetMethod("Flush"); // Create a MSIL instructions. Instruction fileName = worker.Create(OpCodes.Ldstr, "debug-methods.log"); Instruction insertText = worker.Create(OpCodes.Ldstr, s); // Create the streamwriter variable: Instruction createVar = worker.Create(OpCodes.Newobj, streamw); // CIL Instruction for calling StreamWriter.WriteLine() Instruction callWriteLine = worker.Create(OpCodes.Call, this.writeLine); // CIL Instruction for calling StreamWriter.Flush() Instruction callFlush = worker.Create(OpCodes.Call, this.flush); // Get the first instruction of the method. Instruction ins = method.Body.Instructions[0]; // Insert instructions to method body. method.Body.CilWorker.InsertBefore(ins, fileName); worker.InsertAfter(fileName, createVar); worker.InsertAfter(createVar, insertText); worker.InsertAfter(insertText, writeLine); worker.InsertAfter(writeLine, flush); } } } asm.MainModule.Import(type); } // Save the modified assembly. AssemblyFactory.SaveAssembly(this.asm, this.Path); Console.WriteLine("Deep Logging enabled"); } }
/// <summary> /// Execute injection /// </summary> public void Inject(MethodDefinition testmethod, AssemblyDefinition asm, int typearr) { MethodDefinition testmethod_def = asm.MainModule.Inject(testmethod, asm.MainModule.Types[typearr]); MethodReference testmethod_ref = asm.MainModule.Import(testmethod_def); Instruction call_test = testmethod.Body.CilWorker.Create(OpCodes.Call, testmethod_ref); asm.EntryPoint.Body.CilWorker.InsertBefore(asm.EntryPoint.Body.Instructions[0], call_test); AssemblyFactory.SaveAssembly(asm, NewHostName); Console.WriteLine("Injection: Done. \n Patched executable {0} written.", NewHostName); }
protected AssemblyDefinition RunWriteAssemblyTestCase(string file) { string boo = GetBooFile(file); string asm = GetTempFileName(); WriteAssemblyScript was = CompileBooFile <WriteAssemblyScript> (boo); was.DefineAssembly(file); was.Run(); AssemblyFactory.SaveAssembly(was.ASM, asm); RunAndAssertOutput(boo, delegate { AppDomain.CurrentDomain.ExecuteAssembly(asm); }); return(was.ASM); }
/// <summary> /// Modifies a given assembly prior to being loaded from disk. /// </summary> /// <param name="assemblyFile">The filename of the target assembly.</param> /// <returns>A valid assembly.</returns> public override Assembly Load(string assemblyFile) { var targetAssembly = AssemblyFactory.GetAssembly(assemblyFile); // Strongly-named assemblies cannot be modified if (targetAssembly.Name.HasPublicKey) { return(base.Load(assemblyFile)); } var assemblyFileName = Path.GetFileNameWithoutExtension(assemblyFile); string pdbFile = string.Format("{0}.pdb", assemblyFileName); bool hasSymbols = File.Exists(pdbFile); if (PdbLoader != null && hasSymbols) { PdbLoader.LoadSymbols(targetAssembly); } foreach (var action in AssemblyWeavers) { action(targetAssembly); // Verify the assembly at every step if (AssemblyVerifier == null) { continue; } AssemblyVerifier.Verify(targetAssembly); } var memoryStream = new MemoryStream(); if (PdbLoader != null && hasSymbols) { PdbLoader.SaveSymbols(targetAssembly); } // Save the modifed assembly AssemblyFactory.SaveAssembly(targetAssembly, memoryStream); if (PdbLoader == null || !hasSymbols) { return(targetAssembly.ToAssembly()); } var pdbBytes = File.ReadAllBytes(pdbFile); return(PdbLoader.LoadAssembly(memoryStream.ToArray(), pdbBytes)); }
static void Main(string[] args) { var filename = @"..\..\..\ConsoleClient\bin\Debug\SampleDomain.dll"; var assembly = AssemblyFactory.GetAssembly(filename); // Intercept all object instantiations in the target assembly assembly.InterceptNewInstances(ShouldInterceptNewOperator, ShouldInjectCurrentMethod); AssemblyFactory.SaveAssembly(assembly, filename); Console.WriteLine("{0} successfully modified.", filename); return; }
/// <summary> /// Mutates the only the conditionals specified in <see cref="RunEventArgs.SelectedMutations"/>. /// </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 MutateSelectedConditionals(RunEventArgs e, BranchingOpCodes opCodes) { foreach (MutationDto mutation in e.SelectedMutations) { // If the user has cancelled this since the last test, bail out if (_view.CancellationPending) { break; } string outputFile = GetOutputAssemblyFileName(e.InputAssembly); for (int i = 0; i < mutation.Conditional.MethodDefinition.Body.Instructions.Count; i++) { Instruction instruction = mutation.Conditional.MethodDefinition.Body.Instructions[i]; if (opCodes.Contains(instruction.OpCode)) { if (i == mutation.Conditional.InstructionNumber) { instruction.OpCode = opCodes.Invert(instruction.OpCode); } } } // Replace the original target assembly with the mutated assembly File.Delete(e.InputAssembly); AssemblyFactory.SaveAssembly(mutation.Conditional.MethodDefinition.DeclaringType.Module.Assembly, outputFile); File.Copy(outputFile, e.InputAssembly); // Run the unit tests again, this time against the mutated assembly MbUnitTestRunner runner = new MbUnitTestRunner(); runner.Invoke(e.TestAssembly); foreach (TestResult result in runner.TestResults) { if (result is SurvivingMutantTestResult) { mutation.TestResults.Add(new SurvivingMutantTestResultDto((SurvivingMutantTestResult)result, mutation)); } else { mutation.TestResults.Add(new KilledMutantTestResultDto((KilledMutantTestResult)result, mutation)); } } if (_testComplete != null) { _testComplete(this, new TestCompleteEventArgs(runner.TestResults)); } } }
/// <summary> /// Converts an <see cref="AssemblyDefinition"/> /// into a running <see cref="Assembly"/>. /// </summary> /// <param name="definition">The <see cref="AssemblyDefinition"/> to convert.</param> /// <returns>An <see cref="Assembly"/> that represents the <see cref="AssemblyDefinition"/> instance. /// </returns> public static Assembly ToAssembly(this AssemblyDefinition definition) { Assembly result = null; using (var stream = new MemoryStream()) { // Persist the assembly to the stream AssemblyFactory.SaveAssembly(definition, stream); var buffer = stream.GetBuffer(); result = Assembly.Load(buffer); } return(result); }
//public static void addAttributes(string assemblyName, string typeToHook, string methodToHook) //{ public static void InsertHooks(string sourceAssembly, string targetAssembly, string typeToHook, string methodToHook, bool backupFile) { // if requested back up the current targetAssembly if (backupFile && false == BackupRestoreFiles.doesBackupExist(sourceAssembly)) { BackupRestoreFiles.backup(sourceAssembly); } if (sourceAssembly != targetAssembly) { File.Copy(sourceAssembly, targetAssembly); } DI.log.info("Adding an attribute to current Assembly"); var assembly = CecilUtils.getAssembly(targetAssembly); addO2PostSharpHookAttribute(assembly); if (typeToHook == "" && methodToHook == "") { addOnMethodInvocationttribute(assembly, assembly.Name.Name, "*"); } else if (typeToHook != "" && methodToHook == "") { addOnMethodInvocationttribute(assembly, assembly.Name.Name, "*", typeToHook); } else { addOnMethodInvocationttribute(assembly, assembly.Name.Name, "*", typeToHook, methodToHook); } //addOnMethodBoundaryAttribute(assembly, assembly.Name.Name, "*"); //addOnMethodInvocationttribute(assembly, assembly.Name.Name, "*"); //var fileName = Path.GetFileName(targetAssembly); //var savedAssemby = assemblyName.Replace(fileName, fileName); //var savedAssemby = assemblyName; // remove publicKey assembly.Name.PublicKey = null; AssemblyFactory.SaveAssembly(assembly, targetAssembly); DI.log.info("\n _ Assembly saved to: " + targetAssembly + " \n"); Hacks.patchAssemblyForCecilPostSharpBug(targetAssembly); }
protected void RunCSharpRoundTripTestCase(string file) { string boo = GetBooFile(file); CSharpScript cs = CompileBooFile <CSharpScript> (boo); string asm = GetTempFileName(); cs.Run(); cs.CompileTo(asm); AssemblyDefinition assembly = AssemblyFactory.GetAssembly(asm); string roundtrip = GetTempFileName(); AssemblyFactory.SaveAssembly(assembly, roundtrip); RunAndAssertOutput(boo, delegate { AppDomain.CurrentDomain.ExecuteAssembly(roundtrip); }); }
private void changeMethod(MethodDefinition method) { ModuleDefinition module = method.DeclaringType.Module; MethodInfo writeline = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); MethodReference writeLineRef = module.Import(writeline); CilWorker cil = method.Body.CilWorker; Instruction op1 = cil.Create(OpCodes.Ldstr, "Say hello was called!"); Instruction op2 = cil.Create(OpCodes.Call, writeLineRef); cil.InsertBefore(method.Body.Instructions[0], op1); cil.InsertAfter(op1, op2); module.Import(method.DeclaringType); AssemblyFactory.SaveAssembly(module.Assembly, @"c:\temp\cilTemp\tempasm.dll"); }
public static void savePatchedAssembly() { //removing assemblies, that are part of the merged modloader assembly does crash, we need to add them manually /*List<AssemblyNameReference> names = new List<AssemblyNameReference>(); * foreach (AssemblyNameReference name in baseAssembly.MainModule.AssemblyReferences) { * if (name.FullName.Contains ("LinFu")) * names.Add (name); * } * foreach (AssemblyNameReference name in names) { * baseAssembly.MainModule.AssemblyReferences.Remove (name); * }*/ System.IO.File.Delete(baseAssemblySavePath); AssemblyFactory.SaveAssembly(baseAssembly, baseAssemblySavePath); }
static void Main(string [] args) { if (args.Length != 2) { Console.WriteLine("usage:mono cecil-roundtrip.exe assembly target"); return; } try { AssemblyDefinition asm = AssemblyFactory.GetAssembly(args [0]); AssemblyFactory.SaveAssembly(asm, args [1]); Console.WriteLine("Assembly {0}\n successfully roundtripped to {1}", asm.Name.FullName, args [1]); } catch (Exception e) { Console.WriteLine("Failed to roundtrip assembly {0}", args [0]); Console.WriteLine(e); } }
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); }
/// <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 InjectProlouge() { foreach (TypeDefinition tDef in _asmDef.MainModule.Types) { if (tDef.Name == "<Module>") { continue; } foreach (MethodDefinition mDef in tDef.Methods) { //process method PatchMethod(mDef, tDef); } //asmTarget.MainModule.Import(def2); //check } AssemblyFactory.SaveAssembly(_asmDef, _asmPath); }
/// <summary> /// Saves instrumented assembly /// </summary> public override void LastVisitAssembly(AssemblyDefinition assembly, Context context) { ///Save counter assembly near instrumented one var path = context.CurrentAssemblyPath; context.CounterAssemblyBuilder.Save(Path.GetDirectoryName(path)); ///Save instrumented assembly with respect to NamingMode: var oldExt = Path.GetExtension(path); if (Configuration.NamingMode == Configuration.NamingModes.MarkInstrumented) { AssemblyFactory.SaveAssembly(assembly, Path.ChangeExtension(path, "Instrumented" + oldExt)); return; } File.Move(path, Path.ChangeExtension(path, "bak" + oldExt)); File.Move(Path.ChangeExtension(path, "pdb"), Path.ChangeExtension(path, "bak.pdb")); AssemblyFactory.SaveAssembly(assembly, path); }
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 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 ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable <string> namespaces, ScriptPackSession scriptPackSession) { try { var def = Compiler.Compile("code", code, false, false, false); using (var exeStream = new MemoryStream()) { AssemblyFactory.SaveAssembly(def, exeStream); var exeBytes = exeStream.ToArray(); var assembly = Assembly.Load(exeBytes); assembly.EntryPoint.Invoke(null, new object[] { new string[0] }); } } catch (CompilerException e) { throw new Exception("Error compiling", e); } return(new ScriptResult()); }
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 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); }