private void VerifyIL(AssemblyDefinition assembly) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ar_test.exe"); assembly.Write(path); string peverify = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\PEVerify.exe" ); var process = Process.Start(new ProcessStartInfo { FileName = peverify, Arguments = $"\"{path}\"", CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true }); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if(process.ExitCode != 0) { throw new VerifyFailedException(process.ExitCode, output); } }
void OutputAssembly (AssemblyDefinition assembly) { string directory = Context.OutputDirectory; CopyConfigFileIfNeeded (assembly, directory); switch (Annotations.GetAction (assembly)) { case AssemblyAction.Link: assembly.Write (GetAssemblyFileName (assembly, directory), SaveSymbols (assembly)); break; case AssemblyAction.Copy: CloseSymbols (assembly); CopyAssembly (GetOriginalAssemblyFileInfo (assembly), directory, Context.LinkSymbols); break; case AssemblyAction.Delete: CloseSymbols (assembly); var target = GetAssemblyFileName (assembly, directory); if (File.Exists (target)) File.Delete (target); break; default: CloseSymbols (assembly); break; } }
static void WriteAssembly( AssemblyDefinition assembly, string targetPath, StrongNameKeyPair snk ) { WriterParameters wp = new WriterParameters() { WriteSymbols = true, StrongNameKeyPair = snk }; assembly.Write( targetPath, wp ); }
private void ExecuteModifiedAssembly(AssemblyDefinition greeterAssembly) { var memoryStream = new MemoryStream(); greeterAssembly.Write(memoryStream); // Convert the modified assembly into // an assembly that will be loaded by System.Reflection var bytes = memoryStream.GetBuffer(); var assembly = Assembly.Load(bytes); var modifiedGreeterType = assembly.GetTypes()[0]; var greeter = (IGreeter)Activator.CreateInstance(modifiedGreeterType); greeter.Greet("NDC"); }
private void ExecuteModifiedAssembly(AssemblyDefinition targetAssembly) { var memoryStream = new MemoryStream(); targetAssembly.Write(memoryStream); // Convert the modified assembly into // an assembly that will be loaded by System.Reflection var bytes = memoryStream.GetBuffer(); var assembly = Assembly.Load(bytes); var modifiedGreeterType = assembly.GetTypes()[0]; var printer = (IPrinter)Activator.CreateInstance(modifiedGreeterType); for(var i = 0; i < 100; i++) { printer.Print(i); } }
/// <summary> /// Verify an assembly with peverify /// </summary> /// <param name="adef">Assembly definition</param> public static void VerifyAssembly(AssemblyDefinition adef) { if (adef != null) { var originalLocation = adef.MainModule.Image.FileName; if (PEVerifyUtility.PEVerifyToolPresent) { // We must create a temporary filename in the same path, so PEVerify can resolve dependencies var tempDirectory = Path.GetDirectoryName(originalLocation) ?? string.Empty; var tempFilename = Path.Combine(tempDirectory, Path.GetRandomFileName()); try { adef.Write(tempFilename); AssemblyVerification.Verify(tempFilename); MessageBox.Show(@"All Classes and Methods Verified."); } catch (VerificationException ex) { using (var form = new VerifierForm()) form.ShowDialog(ex.Errors); } catch (Exception ex) { MessageBox.Show(String.Format("Reflexil is unable to verify this assembly: {0}", ex.Message)); } finally { File.Delete(tempFilename); } } else { MessageBox.Show( @"Warning, PEVerify Utility (peverify.exe) not found. Update your PATH environment variable or install .NET SDK"); } } else { MessageBox.Show(@"Assembly definition is not loaded (not a CLI image?)"); } }
/// <summary> /// Save an assembly /// </summary> /// <param name="adef">Assembly definition</param> /// <param name="originalLocation">Original location</param> public static void SaveAssembly(AssemblyDefinition adef, string originalLocation) { if (adef != null) { using (var dialog = new SaveFileDialog()) { dialog.Filter = @"Assembly files (*.exe, *.dll)|*.exe;*.dll"; dialog.InitialDirectory = Path.GetDirectoryName(originalLocation); dialog.FileName = Path.GetFileNameWithoutExtension(originalLocation) + ".Patched" + Path.GetExtension(originalLocation); if (dialog.ShowDialog() == DialogResult.OK) { try { adef.Write(dialog.FileName); if (!adef.Name.HasPublicKey) return; // Reload the assembly to have a proper Image.Filename var plugin = PluginFactory.GetInstance() as BasePlugin; if (plugin != null) adef = plugin.LoadAssembly(dialog.FileName, false); using (var snform = new StrongNameForm()) { snform.AssemblyDefinition = adef; snform.DelaySignedFileName = dialog.FileName; snform.ShowDialog(); } } catch (Exception ex) { MessageBox.Show(String.Format("Reflexil is unable to save this assembly: {0}", ex.Message)); } } } } else { MessageBox.Show(@"Assembly definition is not loaded (not a CLI image?)"); } }
internal static void Start() { asm = AssemblyDefinition.ReadAssembly("Terraria.exe"); mod = asm.MainModule; HookKeys(); HookMain(); HookNetMessage(); HookMessageBuffer(); GameHooks.OnHook(); MemoryStream ms = new MemoryStream(); asm.Write(ms); #if DEBUG File.WriteAllBytes("debug.exe", ms.GetBuffer()); #endif Assembly terraria = Assembly.Load(ms.GetBuffer()); Item.instance = new Item() { type = terraria.GetType("Terraria.Item") }; Lighting.instance = new Lighting() { type = terraria.GetType("Terraria.Lighting") }; NPC.instance = new NPC() { type = terraria.GetType("Terraria.NPC") }; NetMessage.instance = new NetMessage() { type = terraria.GetType("Terraria.NetMessage") }; Netplay.instance = new Netplay() { type = terraria.GetType("Terraria.Netplay") }; Player.instance = new Player() { type = terraria.GetType("Terraria.Player") }; Projectile.instance = new Projectile() { type = terraria.GetType("Terraria.Projectile") }; Tile.instance = new Tile() { type = terraria.GetType("Terraria.Tile") }; WorldGen.instance = new WorldGen() { type = terraria.GetType("Terraria.WorldGen") }; Main.instance = new Main(terraria.GetType("Terraria.Main").GetConstructor(new Type[] { }).Invoke(null)); Locked = false; try { Main.Run(); } finally { Main.Dispose(); } }
/// <summary> /// Moves the original assembly aside, and writes the mutated copy in /// its place before returning the test meta data to allow the test /// suite to be run. /// </summary> /// <param name="assembly"> /// An <see cref="AssemblyDefinition" /> for the containing assembly. /// </param> /// <param name="method"> </param> /// <param name="fileName"> /// The path to the assembly file, so that the turtle can overwrite it /// with mutated versions. /// </param> /// <param name="output"> /// The string describing the mutation, returned to calling code with /// <c>yield return</c>. /// </param> /// <returns> /// A <see cref="MutationTestMetaData" /> instance. /// </returns> protected MutationTestMetaData PrepareTests(AssemblyDefinition assembly, MethodDefinition method, string fileName, string output) { string sourceFolder = Path.GetDirectoryName(fileName); string targetFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); CopyDirectory(sourceFolder, targetFolder); string targetFileName = Path.Combine(targetFolder, Path.GetFileName(fileName)); assembly.Write(targetFileName); var metaData = new MutationTestMetaData { TestFolder = targetFolder, Description = output, DiffRepresentation = ConstructEstimateCodeDiff(method) }; Monitor.Exit(method); return metaData; }
/// <summary> /// Save an assembly in place /// </summary> /// <param name="adef">Assembly definition</param> /// <param name="assemblyLocation">Original location</param> public static void SaveAssemblyInPlace(AssemblyDefinition adef, string assemblyLocation) { if (adef != null) { string fileName = assemblyLocation; try { adef.Write(fileName, new WriterParameters()); if (!adef.Name.HasPublicKey) { // No StrongNameKey, we're done here. return; } else { // Show the user the StrongNameKey removal dialog using (var snform = new StrongNameForm()) { snform.AssemblyDefinition = adef; snform.DelaySignedFileName = fileName; snform.ShowDialog(); } } } catch (Exception ex) { MessageBox.Show(String.Format("Reflexil is unable to save this assembly: {0}", ex.Message)); throw; } } else { MessageBox.Show(@"Assembly definition is not loaded (not a CLI image?)"); } }
public byte[] ConvertAssemblyToByteArray(AssemblyDefinition assembly) { using(var stream = new MemoryStream()) { assembly.Write(stream); return stream.ToArray(); } }
public static int Main(string[] args) { bool interactive = true; if (args.Length > 0) interactive = false; Console.WriteLine(string.Format("[( Pluton Patcher v{0} )]", version)); try { plutonAssembly = AssemblyDefinition.ReadAssembly("Pluton.dll"); rustAssembly = AssemblyDefinition.ReadAssembly("Assembly-CSharp.dll"); } catch (FileNotFoundException ex) { Console.WriteLine("You are missing " + ex.FileName + " did you moved the patcher to the managed folder ?"); if (interactive) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } return (int)ExitCode.DLL_MISSING; } catch (Exception ex) { Console.WriteLine("An error occured while reading the assemblies :"); Console.WriteLine(ex.ToString()); if (interactive) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } return (int)ExitCode.DLL_READ_ERROR; } bNPC = rustAssembly.MainModule.GetType("BaseNPC"); bPlayer = rustAssembly.MainModule.GetType("BasePlayer"); codeLock = rustAssembly.MainModule.GetType("CodeLock"); hooksClass = plutonAssembly.MainModule.GetType("Pluton.Hooks"); itemCrafter = rustAssembly.MainModule.GetType("ItemCrafter"); pLoot = rustAssembly.MainModule.GetType("PlayerLoot"); //Check if patching is required TypeDefinition plutonClass = rustAssembly.MainModule.GetType("Pluton"); if (plutonClass == null) { try { PatchASMCSharp(); Console.WriteLine("Patched Assembly-CSharp !"); } catch (Exception ex) { interactive = true; Console.WriteLine("An error occured while patching Assembly-CSharp :"); Console.WriteLine(); Console.WriteLine(ex.Message.ToString()); //Normal handle for the others Console.WriteLine(); Console.WriteLine(ex.StackTrace.ToString()); Console.WriteLine(); if (interactive) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } return (int)ExitCode.ACDLL_GENERIC_PATCH_ERR; } } else { Console.WriteLine("Assembly-CSharp.dll is already patched!"); return (int)ExitCode.ACDLL_ALREADY_PATCHED; } try { rustAssembly.Write("Assembly-CSharp.dll"); } catch (Exception ex) { Console.WriteLine("An error occured while writing the assembly :"); Console.WriteLine("Error at: " + ex.TargetSite.Name); Console.WriteLine("Error msg: " + ex.Message); if (interactive) { Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } return (int)ExitCode.DLL_WRITE_ERROR; } //Successfully patched the server Console.WriteLine("Completed !"); if (interactive) System.Threading.Thread.Sleep(250); return (int)ExitCode.SUCCESS; }
/// <summary> /// Patches the file. /// </summary> /// <param name="file">The file.</param> public bool PatchFile(string file) { var fileTime = new FileTime(file); //var fileTimeInteropBuilder = new FileTime(Assembly.GetExecutingAssembly().Location); string checkFile = Path.GetFullPath(file) + ".check"; //string checkInteropBuilderFile = "InteropBuild.check"; // If checkFile and checkInteropBuilderFile up-to-date, then nothing to do if (fileTime.CheckFileUpToDate(checkFile)) { Log("Nothing to do. SharpDX patch was already applied for assembly [{0}]", file); return false; } // Copy PDB from input assembly to output assembly if any var readerParameters = new ReaderParameters(); var writerParameters = new WriterParameters(); var pdbName = Path.ChangeExtension(file, "pdb"); if (File.Exists(pdbName)) { var symbolReaderProvider = new PdbReaderProvider(); readerParameters.SymbolReaderProvider = symbolReaderProvider; readerParameters.ReadSymbols = true; writerParameters.WriteSymbols = true; } // Read Assembly assembly = AssemblyDefinition.ReadAssembly(file, readerParameters); ((BaseAssemblyResolver)assembly.MainModule.AssemblyResolver).AddSearchDirectory(Path.GetDirectoryName(file)); foreach (var assemblyNameReference in assembly.MainModule.AssemblyReferences) { if (assemblyNameReference.Name.ToLower() == "mscorlib") { mscorlibAssembly = assembly.MainModule.AssemblyResolver.Resolve(assemblyNameReference); break; } } // TODO: Temporary patch to handle correctly 4.5 Core profile if (mscorlibAssembly == null) { foreach (var assemblyNameReference in assembly.MainModule.AssemblyReferences) { if (assemblyNameReference.Name == "System.Runtime") { ((BaseAssemblyResolver)assembly.MainModule.AssemblyResolver).AddSearchDirectory( Path.Combine(ProgramFilesx86(),@"Reference Assemblies\Microsoft\Framework\.NETCore\v4.5")); mscorlibAssembly = assembly.MainModule.AssemblyResolver.Resolve(assemblyNameReference); break; } } } if (mscorlibAssembly == null) { LogError("Missing mscorlib.dll from assembly {0}", file); throw new InvalidOperationException("Missing mscorlib.dll from assembly"); } // Import void* and int32 from assembly using mscorlib specific version (2.0 or 4.0 depending on assembly) voidType = mscorlibAssembly.MainModule.GetType("System.Void"); voidPointerType = new PointerType(assembly.MainModule.Import(voidType)); intType = assembly.MainModule.Import( mscorlibAssembly.MainModule.GetType("System.Int32")); // Remove CompilationRelaxationsAttribute for (int i = 0; i < assembly.CustomAttributes.Count; i++) { var customAttribute = assembly.CustomAttributes[i]; if (customAttribute.AttributeType.FullName == typeof(CompilationRelaxationsAttribute).FullName) { assembly.CustomAttributes.RemoveAt(i); i--; } } Log("SharpDX interop patch for assembly [{0}]", file); foreach (var type in assembly.MainModule.Types) PatchType(type); // Remove All Interop classes foreach (var type in classToRemoveList) assembly.MainModule.Types.Remove(type); var outputFilePath = file; assembly.Write(outputFilePath, writerParameters); fileTime = new FileTime(file); // Update Check file fileTime.UpdateCheckFile(checkFile); //fileTimeInteropBuilder.UpdateCheckFile(checkInteropBuilderFile); Log("SharpDX patch done for assembly [{0}]", file); return true; }
/// <summary> /// Patches the file. /// </summary> /// <param name="file">The file.</param> public bool PatchFile(string file) { file = Path.Combine(Environment.CurrentDirectory, file); var fileTime = new FileTime(file); //var fileTimeInteropBuilder = new FileTime(Assembly.GetExecutingAssembly().Location); string checkFile = Path.GetFullPath(file) + ".check"; //string checkInteropBuilderFile = "InteropBuild.check"; // If checkFile and checkInteropBuilderFile up-to-date, then nothing to do if (fileTime.CheckFileUpToDate(checkFile)) { Log("Nothing to do. SharpDX patch was already applied for assembly [{0}]", file); return false; } // Copy PDB from input assembly to output assembly if any var readerParameters = new ReaderParameters(); var resolver = new DefaultAssemblyResolver(); readerParameters.AssemblyResolver = resolver; var writerParameters = new WriterParameters(); var pdbName = Path.ChangeExtension(file, "pdb"); if (File.Exists(pdbName)) { var symbolReaderProvider = new PdbReaderProvider(); readerParameters.SymbolReaderProvider = symbolReaderProvider; readerParameters.ReadSymbols = true; writerParameters.WriteSymbols = true; } // Read Assembly assembly = AssemblyDefinition.ReadAssembly(file, readerParameters); resolver.AddSearchDirectory(Path.GetDirectoryName(file)); // Query the target framework in order to resolve correct assemblies and type forwarding var targetFrameworkAttr = assembly.CustomAttributes.FirstOrDefault( attribute => attribute.Constructor.FullName.Contains("System.Runtime.Versioning.TargetFrameworkAttribute")); if(targetFrameworkAttr != null && targetFrameworkAttr.ConstructorArguments.Count > 0 && targetFrameworkAttr.ConstructorArguments[0].Value != null) { var targetFramework = new FrameworkName(targetFrameworkAttr.ConstructorArguments[0].Value.ToString()); var netcoreAssemblyPath = string.Format(@"Reference Assemblies\Microsoft\Framework\{0}\v{1}", targetFramework.Identifier, targetFramework.Version); netcoreAssemblyPath = Path.Combine(ProgramFilesx86(), netcoreAssemblyPath); if(Directory.Exists(netcoreAssemblyPath)) { resolver.AddSearchDirectory(netcoreAssemblyPath); } } // Import void* and int32 voidType = assembly.MainModule.TypeSystem.Void.Resolve(); voidPointerType = new PointerType(assembly.MainModule.Import(voidType)); intType = assembly.MainModule.Import( assembly.MainModule.TypeSystem.Int32.Resolve()); // Remove CompilationRelaxationsAttribute for (int i = 0; i < assembly.CustomAttributes.Count; i++) { var customAttribute = assembly.CustomAttributes[i]; if (customAttribute.AttributeType.FullName == typeof(CompilationRelaxationsAttribute).FullName) { assembly.CustomAttributes.RemoveAt(i); i--; } } Log("SharpDX interop patch for assembly [{0}]", file); foreach (var type in assembly.MainModule.Types) PatchType(type); // Remove All Interop classes foreach (var type in classToRemoveList) assembly.MainModule.Types.Remove(type); var outputFilePath = file; assembly.Write(outputFilePath, writerParameters); fileTime = new FileTime(file); // Update Check file fileTime.UpdateCheckFile(checkFile); //fileTimeInteropBuilder.UpdateCheckFile(checkInteropBuilderFile); Log("SharpDX patch done for assembly [{0}]", file); return true; }
static void Main() { Console.WriteLine("RowPatcher " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("Need to patch client or server?\n1. Legacy client\n2. Legacy server"); int mode = 0; string answer = Console.ReadLine(); if (!int.TryParse(answer, out mode)) { Console.Clear(); Main(); } try { rustAssembly = AssemblyDefinition.ReadAssembly("Assembly-CSharp.dll"); if (mode == 1) { rowacAssembly = AssemblyDefinition.ReadAssembly("RGuard.dll"); ClientBootstrapAttachPatch(); Console.WriteLine("Client patched"); } else if (mode == 2) { rowacAssembly = AssemblyDefinition.ReadAssembly("RowAC.dll"); hooksType = rowacAssembly.MainModule.GetType("RowAC", "Hooks"); BootstrapAttachPatch(); //PlayerSpawnHookPatch(); Console.WriteLine("Server patched"); } rustAssembly.Write("Assembly-CSharp.dll"); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("END"); Console.ReadLine(); }
public bool Run(ref AssemblyDefinition assemblyDefinition, ref bool readWriteSymbols, out bool modified) { modified = false; try { var assemblyResolver = (CustomAssemblyResolver)assemblyDefinition.MainModule.AssemblyResolver; var processors = new List<IAssemblyDefinitionProcessor>(); // We are no longer using it so we are deactivating it for now to avoid processing //if (AutoNotifyProperty) //{ // processors.Add(new NotifyPropertyProcessor()); //} if (ParameterKey) { processors.Add(new ParameterKeyProcessor()); } if (NewAssemblyName != null) { processors.Add(new RenameAssemblyProcessor(NewAssemblyName)); } //processors.Add(new AsyncBridgeProcessor()); // Always applies the interop processor processors.Add(new InteropProcessor()); processors.Add(new AssemblyVersionProcessor()); if (SerializationAssembly) { processors.Add(new SerializationProcessor(SignKeyFile, SerializationProjectReferences)); } if (GenerateUserDocumentation) { processors.Add(new GenerateUserDocumentationProcessor(assemblyDefinition.MainModule.FullyQualifiedName)); } if (ModuleInitializer) { processors.Add(new ModuleInitializerProcessor()); } processors.Add(new OpenSourceSignProcessor()); // Check if pdb was actually read readWriteSymbols = assemblyDefinition.MainModule.HasDebugHeader; // Check if there is already a AssemblyProcessedAttribute (in which case we can skip processing, it has already been done). // Note that we should probably also match the command line as well so that we throw an error if processing is different (need to rebuild). if (assemblyDefinition.CustomAttributes.Any(x => x.AttributeType.FullName == "SiliconStudio.Core.AssemblyProcessedAttribute")) { OnInfoAction("Assembly has already been processed, skip it."); return true; } var targetFrameworkAttribute = assemblyDefinition.CustomAttributes .FirstOrDefault(x => x.AttributeType.FullName == typeof(TargetFrameworkAttribute).FullName); var targetFramework = targetFrameworkAttribute != null ? (string)targetFrameworkAttribute.ConstructorArguments[0].Value : null; // Special handling for MonoAndroid // Default frameworkFolder var frameworkFolder = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\"); switch (Platform) { case PlatformType.Android: { if (string.IsNullOrEmpty(TargetFramework)) { throw new InvalidOperationException("Expecting option target framework for Android"); } var monoAndroidPath = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Reference Assemblies\Microsoft\Framework\MonoAndroid"); frameworkFolder = Path.Combine(monoAndroidPath, "v1.0"); var additionalFrameworkFolder = Path.Combine(monoAndroidPath, TargetFramework); assemblyResolver.AddSearchDirectory(additionalFrameworkFolder); assemblyResolver.AddSearchDirectory(frameworkFolder); break; } case PlatformType.iOS: { if (string.IsNullOrEmpty(TargetFramework)) { throw new InvalidOperationException("Expecting option target framework for iOS"); } var monoTouchPath = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Reference Assemblies\Microsoft\Framework\Xamarin.iOS"); frameworkFolder = Path.Combine(monoTouchPath, "v1.0"); var additionalFrameworkFolder = Path.Combine(monoTouchPath, TargetFramework); assemblyResolver.AddSearchDirectory(additionalFrameworkFolder); assemblyResolver.AddSearchDirectory(frameworkFolder); break; } case PlatformType.WindowsStore: { if (string.IsNullOrEmpty(TargetFramework)) { throw new InvalidOperationException("Expecting option target framework for WindowsStore"); } frameworkFolder = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Reference Assemblies\Microsoft\Framework\.NETCore", TargetFramework); assemblyResolver.AddSearchDirectory(frameworkFolder); // Add path to look for WinRT assemblies (Windows.winmd) var windowsAssemblyPath = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Windows Kits\8.1\References\CommonConfiguration\Neutral\", "Windows.winmd"); var windowsAssembly = AssemblyDefinition.ReadAssembly(windowsAssemblyPath, new ReaderParameters { AssemblyResolver = assemblyResolver, ReadSymbols = false }); assemblyResolver.Register(windowsAssembly); break; } case PlatformType.WindowsPhone: { if (string.IsNullOrEmpty(TargetFramework)) { throw new InvalidOperationException("Expecting option target framework for WindowsPhone"); } // Note: v8.1 is hardcoded because we currently receive v4.5.x as TargetFramework (different from TargetPlatformVersion) frameworkFolder = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Reference Assemblies\Microsoft\Framework\WindowsPhoneApp", "v8.1"); assemblyResolver.AddSearchDirectory(frameworkFolder); // Add path to look for WinRT assemblies (Windows.winmd) var windowsAssemblyPath = Path.Combine(CecilExtensions.ProgramFilesx86(), @"Windows Phone Kits\8.1\References\CommonConfiguration\Neutral\", "Windows.winmd"); var windowsAssembly = AssemblyDefinition.ReadAssembly(windowsAssemblyPath, new ReaderParameters { AssemblyResolver = assemblyResolver, ReadSymbols = false }); assemblyResolver.Register(windowsAssembly); break; } } if (SerializationAssembly) { // Resave a first version of assembly with [InteralsVisibleTo] for future serialization assembly. // It will be used by serialization assembly compilation. // It's recommended to do it in the original code to avoid this extra step. var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assemblyDefinition); var stringType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(string).FullName); var internalsVisibleToAttribute = mscorlibAssembly.MainModule.GetTypeResolved(typeof(InternalsVisibleToAttribute).FullName); var serializationAssemblyName = assemblyDefinition.Name.Name + ".Serializers"; bool internalsVisibleAlreadyApplied = false; // Check if already applied foreach (var customAttribute in assemblyDefinition.CustomAttributes.Where(x => x.AttributeType.FullName == internalsVisibleToAttribute.FullName)) { var assemblyName = (string)customAttribute.ConstructorArguments[0].Value; int publicKeyIndex; if ((publicKeyIndex = assemblyName.IndexOf(", PublicKey=", StringComparison.InvariantCulture)) != -1 || (publicKeyIndex = assemblyName.IndexOf(",PublicKey=", StringComparison.InvariantCulture)) != -1) { assemblyName = assemblyName.Substring(0, publicKeyIndex); } if (assemblyName == serializationAssemblyName) { internalsVisibleAlreadyApplied = true; break; } } if (!internalsVisibleAlreadyApplied) { // Apply public key if (assemblyDefinition.Name.HasPublicKey) serializationAssemblyName += ", PublicKey=" + ByteArrayToString(assemblyDefinition.Name.PublicKey); // Add [InteralsVisibleTo] attribute var internalsVisibleToAttributeCtor = assemblyDefinition.MainModule.Import(internalsVisibleToAttribute.GetConstructors().Single()); var internalsVisibleAttribute = new CustomAttribute(internalsVisibleToAttributeCtor) { ConstructorArguments = { new CustomAttributeArgument(assemblyDefinition.MainModule.Import(stringType), serializationAssemblyName) } }; assemblyDefinition.CustomAttributes.Add(internalsVisibleAttribute); var assemblyFilePath = assemblyDefinition.MainModule.FullyQualifiedName; if (string.IsNullOrEmpty(assemblyFilePath)) { assemblyFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".dll"); } // Save updated file assemblyDefinition.Write(assemblyFilePath, new WriterParameters() { WriteSymbols = readWriteSymbols }); // Reread file (otherwise it seems Mono Cecil is buggy and generate invalid PDB) assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyFilePath, new ReaderParameters { AssemblyResolver = assemblyResolver, ReadSymbols = readWriteSymbols }); // Check if pdb was actually read readWriteSymbols = assemblyDefinition.MainModule.HasDebugHeader; } } var assemblyProcessorContext = new AssemblyProcessorContext(assemblyResolver, assemblyDefinition, Platform); foreach (var processor in processors) modified = processor.Process(assemblyProcessorContext) || modified; // Assembly might have been recreated (i.e. il-repack), so let's use it from now on assemblyDefinition = assemblyProcessorContext.Assembly; if (modified) { // In case assembly has been modified, // add AssemblyProcessedAttribute to assembly so that it doesn't get processed again var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assemblyDefinition); if (mscorlibAssembly == null) { OnErrorAction("Missing mscorlib.dll from assembly"); return false; } var attributeType = mscorlibAssembly.MainModule.GetTypeResolved(typeof (Attribute).FullName); var attributeTypeRef = assemblyDefinition.MainModule.Import(attributeType); var attributeCtorRef = assemblyDefinition.MainModule.Import(attributeType.GetConstructors().Single(x => x.Parameters.Count == 0)); var voidType = assemblyDefinition.MainModule.Import(mscorlibAssembly.MainModule.GetTypeResolved("System.Void")); // Create custom attribute var assemblyProcessedAttributeType = new TypeDefinition("SiliconStudio.Core", "AssemblyProcessedAttribute", TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass | TypeAttributes.AutoClass | TypeAttributes.Public, attributeTypeRef); // Add constructor (call parent constructor) var assemblyProcessedAttributeConstructor = new MethodDefinition(".ctor", MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, voidType); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Call, attributeCtorRef)); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); assemblyProcessedAttributeType.Methods.Add(assemblyProcessedAttributeConstructor); // Add AssemblyProcessedAttribute to assembly assemblyDefinition.MainModule.Types.Add(assemblyProcessedAttributeType); assemblyDefinition.CustomAttributes.Add(new CustomAttribute(assemblyProcessedAttributeConstructor)); } } catch (Exception e) { OnErrorAction(e.Message, e); return false; } return true; }
public static void Save(AssemblyDefinition definition, string path) { foreach (var t in definition.MainModule.Types) { foreach (var m in t.Methods) { Console.WriteLine(m.Name); if (m.Name == "GetMessage") { var processor = m.Body.GetILProcessor(); var instructions = processor.Body.Instructions.Skip(1).ToList(); foreach (var i in instructions) { processor.Remove(i); } processor.Append(processor.Create(OpCodes.Ldstr, NewMessage)); processor.Append(processor.Create(OpCodes.Ret)); } } } definition.Write(path); }
/// <summary> /// Save an assembly /// </summary> /// <param name="adef">Assembly definition</param> /// <param name="originallocation">Original location</param> public static bool TrySaveAssembly(AssemblyDefinition adef, string originallocation) { if (adef != null) { using (var SaveFileDialog = new SaveFileDialog()) { SaveFileDialog.Filter = "Assembly files (*.exe, *.dll)|*.exe;*.dll"; SaveFileDialog.InitialDirectory = Path.GetDirectoryName(originallocation); SaveFileDialog.FileName = Path.GetFileNameWithoutExtension(originallocation) + ".Patched" + Path.GetExtension(originallocation); if (SaveFileDialog.ShowDialog() == DialogResult.OK) { try { adef.Write(SaveFileDialog.FileName); if (adef.Name.HasPublicKey) { using (StrongNameForm snform = new StrongNameForm()) { snform.AssemblyDefinition = adef; snform.DelaySignedFileName = SaveFileDialog.FileName; snform.ShowDialog(); } } return true; } catch (Exception ex) { MessageBox.Show(String.Format("Reflexil is unable to save this assembly: {0}", ex.Message)); } } } } else { MessageBox.Show("Assembly definition is not loaded (not a CLI image?)"); } return false; }
void WriteAssembly(RoleEngineParameters parameters, AssemblyDefinition assembly) { var assemblyPath = parameters.AssemblyPath; var writerParameters = new WriterParameters(); var pdbPath = Path.ChangeExtension(assemblyPath, "pdb"); if (File.Exists(pdbPath)) { writerParameters.WriteSymbols = true; } else { var mdbPath = assemblyPath + ".mdb"; if (File.Exists(mdbPath)) { writerParameters.WriteSymbols = true; } } assembly.Write(parameters.OutputAssemblyPath, writerParameters); }
public bool Run(ref AssemblyDefinition assemblyDefinition, ref bool readWriteSymbols, out bool modified, ILogger logger) { log = new Logger(assemblyDefinition.Name.Name, TreatWarningsAsErrors, logger); modified = false; try { var assemblyResolver = (CustomAssemblyResolver)assemblyDefinition.MainModule.AssemblyResolver; // Register self assemblyResolver.Register(assemblyDefinition); var processors = new List<IAssemblyDefinitionProcessor>(); // We are no longer using it so we are deactivating it for now to avoid processing //if (AutoNotifyProperty) //{ // processors.Add(new NotifyPropertyProcessor()); //} processors.Add(new AddReferenceProcessor(ReferencesToAdd)); if (ParameterKey) { processors.Add(new ParameterKeyProcessor()); } if (NewAssemblyName != null) { processors.Add(new RenameAssemblyProcessor(NewAssemblyName)); } //processors.Add(new AsyncBridgeProcessor()); // Always applies the interop processor processors.Add(new InteropProcessor()); processors.Add(new AssemblyVersionProcessor()); if (SerializationAssembly) { processors.Add(new SerializationProcessor(SignKeyFile, References, MemoryReferences, log)); } if (DocumentationFile != null) { processors.Add(new GenerateUserDocumentationProcessor(DocumentationFile)); } if (ModuleInitializer) { processors.Add(new ModuleInitializerProcessor()); } processors.Add(new OpenSourceSignProcessor()); // Check if pdb was actually read readWriteSymbols = assemblyDefinition.MainModule.HasDebugHeader; // Check if there is already a AssemblyProcessedAttribute (in which case we can skip processing, it has already been done). // Note that we should probably also match the command line as well so that we throw an error if processing is different (need to rebuild). if (assemblyDefinition.CustomAttributes.Any(x => x.AttributeType.FullName == "SiliconStudio.Core.AssemblyProcessedAttribute")) { OnInfoAction("Assembly has already been processed, skip it."); return true; } // Register references so that our assembly resolver can use them foreach (var reference in References) { assemblyResolver.RegisterReference(reference); } if (SerializationAssembly) { // Resave a first version of assembly with [InteralsVisibleTo] for future serialization assembly. // It will be used by serialization assembly compilation. // It's recommended to do it in the original code to avoid this extra step. var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assemblyDefinition); var stringType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(string).FullName); var internalsVisibleToAttribute = mscorlibAssembly.MainModule.GetTypeResolved(typeof(InternalsVisibleToAttribute).FullName); var serializationAssemblyName = assemblyDefinition.Name.Name + ".Serializers"; bool internalsVisibleAlreadyApplied = false; // Check if already applied foreach (var customAttribute in assemblyDefinition.CustomAttributes.Where(x => x.AttributeType.FullName == internalsVisibleToAttribute.FullName)) { var assemblyName = (string)customAttribute.ConstructorArguments[0].Value; int publicKeyIndex; if ((publicKeyIndex = assemblyName.IndexOf(", PublicKey=", StringComparison.InvariantCulture)) != -1 || (publicKeyIndex = assemblyName.IndexOf(",PublicKey=", StringComparison.InvariantCulture)) != -1) { assemblyName = assemblyName.Substring(0, publicKeyIndex); } if (assemblyName == serializationAssemblyName) { internalsVisibleAlreadyApplied = true; break; } } if (!internalsVisibleAlreadyApplied) { // Apply public key if (assemblyDefinition.Name.HasPublicKey) serializationAssemblyName += ", PublicKey=" + ByteArrayToString(assemblyDefinition.Name.PublicKey); // Add [InteralsVisibleTo] attribute var internalsVisibleToAttributeCtor = assemblyDefinition.MainModule.Import(internalsVisibleToAttribute.GetConstructors().Single()); var internalsVisibleAttribute = new CustomAttribute(internalsVisibleToAttributeCtor) { ConstructorArguments = { new CustomAttributeArgument(assemblyDefinition.MainModule.Import(stringType), serializationAssemblyName) } }; assemblyDefinition.CustomAttributes.Add(internalsVisibleAttribute); var assemblyFilePath = assemblyDefinition.MainModule.FullyQualifiedName; if (string.IsNullOrEmpty(assemblyFilePath)) { assemblyFilePath = Path.ChangeExtension(Path.GetTempFileName(), ".dll"); } // Save updated file assemblyDefinition.Write(assemblyFilePath, new WriterParameters() { WriteSymbols = readWriteSymbols }); // Reread file (otherwise it seems Mono Cecil is buggy and generate invalid PDB) assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyFilePath, new ReaderParameters { AssemblyResolver = assemblyResolver, ReadSymbols = readWriteSymbols }); // Check if pdb was actually read readWriteSymbols = assemblyDefinition.MainModule.HasDebugHeader; } } var assemblyProcessorContext = new AssemblyProcessorContext(assemblyResolver, assemblyDefinition, Platform); foreach (var processor in processors) modified = processor.Process(assemblyProcessorContext) || modified; // Assembly might have been recreated (i.e. il-repack), so let's use it from now on assemblyDefinition = assemblyProcessorContext.Assembly; if (modified) { // In case assembly has been modified, // add AssemblyProcessedAttribute to assembly so that it doesn't get processed again var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assemblyDefinition); if (mscorlibAssembly == null) { OnErrorAction("Missing mscorlib.dll from assembly"); return false; } var attributeType = mscorlibAssembly.MainModule.GetTypeResolved(typeof (Attribute).FullName); var attributeTypeRef = assemblyDefinition.MainModule.Import(attributeType); var attributeCtorRef = assemblyDefinition.MainModule.Import(attributeType.GetConstructors().Single(x => x.Parameters.Count == 0)); var voidType = assemblyDefinition.MainModule.Import(mscorlibAssembly.MainModule.GetTypeResolved("System.Void")); // Create custom attribute var assemblyProcessedAttributeType = new TypeDefinition("SiliconStudio.Core", "AssemblyProcessedAttribute", TypeAttributes.BeforeFieldInit | TypeAttributes.AnsiClass | TypeAttributes.AutoClass | TypeAttributes.Public, attributeTypeRef); // Add constructor (call parent constructor) var assemblyProcessedAttributeConstructor = new MethodDefinition(".ctor", MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, voidType); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Call, attributeCtorRef)); assemblyProcessedAttributeConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); assemblyProcessedAttributeType.Methods.Add(assemblyProcessedAttributeConstructor); // Add AssemblyProcessedAttribute to assembly assemblyDefinition.MainModule.Types.Add(assemblyProcessedAttributeType); assemblyDefinition.CustomAttributes.Add(new CustomAttribute(assemblyProcessedAttributeConstructor)); } } catch (Exception e) { OnErrorAction(e.Message, e); return false; } return true; }
/// <summary>Saves the assembly.</summary> /// <param name="assembly">The assembly.</param> /// <param name="assemblyFileName">Name of the assembly file.</param> /// <param name="keyPair">The key pair.</param> public static void SaveAssembly( AssemblyDefinition assembly, string assemblyFileName, StrongNameKeyPair keyPair = null) { var tempFileName = String.Format("{0}.{1:N}", assemblyFileName, Guid.NewGuid()); try { if (keyPair == null) { Log.Debug("Saving '{0}'", assemblyFileName); assembly.Write(tempFileName); } else { Log.Debug("Saving and signing '{0}'", assemblyFileName); assembly.Write(tempFileName, new WriterParameters { StrongNameKeyPair = keyPair }); } File.Delete(assemblyFileName); File.Move(tempFileName, assemblyFileName); // TODO:MAK pdb may also be merged, but it's not a priority for me. // I need to deleted in though as it no longer matches assembly var pdbFileName = Path.ChangeExtension(assemblyFileName, "pdb"); if (File.Exists(pdbFileName)) DeleteFile(pdbFileName); } catch { if (File.Exists(tempFileName)) DeleteFile(tempFileName); throw; } }
void OutputAssembly(AssemblyDefinition assembly) { string directory = Context.OutputDirectory; assembly.Write(GetAssemblyFileName(assembly, directory),SaveSymbols(assembly)); //CloseSymbols (assembly); }
public static void SaveAssembly(AssemblyDefinition assembly, string destination) { bool symbols = assembly.MainModule.HasSymbols; // re-write symbols, if available, so the new tokens will match assembly.Write (destination, new WriterParameters () { WriteSymbols = symbols }); if (symbols) { // re-load symbols (cecil will dispose MdbReader and will crash later if we need to save again) var provider = new MdbReaderProvider (); assembly.MainModule.ReadSymbols (provider.GetSymbolReader (assembly.MainModule, destination)); } else { // if we're not saving the symbols then we must not leave stale/old files to be used by other tools string dest_mdb = destination + ".mdb"; if (File.Exists (dest_mdb)) File.Delete (dest_mdb); } }
static string GetExeLocation(string toolsVersion) { FilePath sourceExe = typeof(ProjectBuilder).Assembly.Location; if (toolsVersion == REFERENCED_MSBUILD_TOOLS) { return(sourceExe); } var newVersions = new Dictionary <string, string[]> (); string version; Mono.Cecil.TargetRuntime runtime; switch (toolsVersion) { case "2.0": version = "2.0.0.0"; newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version }); newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version }); newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities", version }); runtime = Mono.Cecil.TargetRuntime.Net_2_0; break; case "3.5": version = "3.5.0.0"; newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version }); newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version }); newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities.v3.5", version }); runtime = Mono.Cecil.TargetRuntime.Net_2_0; break; case "4.0": version = "4.0.0.0"; newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version }); newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version }); newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities.v4.0", version }); runtime = Mono.Cecil.TargetRuntime.Net_4_0; break; default: throw new InvalidOperationException("Unknown MSBuild ToolsVersion '" + toolsVersion + "'"); } FilePath p = FilePath.Build(PropertyService.Locations.Cache, "xbuild", toolsVersion, "MonoDevelop.Projects.Formats.MSBuild.exe"); if (!File.Exists(p) || File.GetLastWriteTime(p) < File.GetLastWriteTime(sourceExe)) { if (!Directory.Exists(p.ParentDirectory)) { Directory.CreateDirectory(p.ParentDirectory); } // Update the references to msbuild Cecil.AssemblyDefinition asm = Cecil.AssemblyDefinition.ReadAssembly(sourceExe); foreach (Cecil.AssemblyNameReference ar in asm.MainModule.AssemblyReferences) { string[] replacement; if (newVersions.TryGetValue(ar.Name, out replacement)) { ar.Name = replacement[0]; ar.Version = new Version(replacement[1]); } } asm.MainModule.Runtime = runtime; //run in 32-bit mode because usually msbuild targets are installed for 32-bit only asm.MainModule.Attributes |= Mono.Cecil.ModuleAttributes.Required32Bit; // Workaround to a bug in mcs. The ILOnly flag is not emitted when using /platform:x86 asm.MainModule.Attributes |= Mono.Cecil.ModuleAttributes.ILOnly; asm.Write(p); } FilePath configFile = p + ".config"; FilePath configSrc = typeof(ProjectBuilder).Assembly.Location + ".config"; if (!File.Exists(configFile) || File.GetLastWriteTime(configFile) < File.GetLastWriteTime(configSrc)) { var config = File.ReadAllText(configSrc); config = config.Replace(REFERENCED_MSBUILD_TOOLS + ".0.0", version); File.WriteAllText(p + ".config", config); } return(p); }
static void WriteAssembly(AssemblyDefinition assemblyDefinition) { Info("Writing assembly to {0}.", assemblyDefinition.MainModule.FullyQualifiedName); if (0 == publicKeyToken.Length) { assemblyDefinition.Name.HasPublicKey = false; assemblyDefinition.Name.PublicKey = new byte[0]; assemblyDefinition.MainModule.Attributes &= ~ModuleAttributes.StrongNameSigned; } assemblyDefinition.Write(assemblyDefinition.MainModule.FullyQualifiedName, new WriterParameters() { StrongNameKeyPair = strongNameKeyPair }); }