static void Main(string[] args) { string path = Assembly.GetEntryAssembly().Location; path = Path.GetDirectoryName(path); Console.WriteLine(path); string input = Console.ReadLine(); DirectoryInfo d = new DirectoryInfo(path); var decompiler = new CSharpDecompiler(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\" + "ClassLibrary.dll", new DecompilerSettings()); string value = decompiler.DecompileWholeModuleAsString(); string s = value.Substring(value.IndexOf("namespace ")); Console.WriteLine(s); CompileCSharpCode(s, "testcompile.dll"); foreach (var file in d.GetFiles("*.dll")) { Console.WriteLine(file.FullName); } Assembly DLL = Assembly.LoadFile(d.GetFiles("*.dll")[9].FullName); foreach (Type type in DLL.GetExportedTypes()) { var c = Activator.CreateInstance(type); type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] { input }); } Console.ReadLine(); }
private void cseditopen_Click(object sender, EventArgs e) { if (csOpenFileDialog.ShowDialog() != DialogResult.OK) { return; } try { if (csOpenFileDialog.FilterIndex == 1) { Stream s = File.OpenRead(csOpenFileDialog.FileName); string[][] tmp = (string[][])new BinaryFormatter().Deserialize(s); s.Dispose(); _cseditcodel = tmp[0]; _cseditrefl = tmp[1]; cseditCode.Text = string.Join("\r\n", cseditref.Text == "References" ? _cseditcodel : _cseditrefl); } else { CSharpDecompiler decompiler = new CSharpDecompiler(csOpenFileDialog.FileName, new DecompilerSettings()); _cseditcodel = decompiler.DecompileWholeModuleAsString() .Split(new[] { "\r\n" }, StringSplitOptions.None); _cseditrefl = Assembly.LoadFrom(csOpenFileDialog.FileName).GetReferencedAssemblies() .Where(s => !new[] { "mscorlib" }.Contains(s.Name)) .Select(s => string.IsNullOrWhiteSpace(s.CodeBase) ? s.Name + ".dll" : s.CodeBase).ToArray(); cseditCode.Text = string.Join("\r\n", cseditref.Text == "References" ? _cseditcodel : _cseditrefl); } } catch (Exception e1) { Console.WriteLine(e1.ToString()); MetroMessageBox.Show(this, e1.ToString(), "Failed to Load", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: ILSpyConvert.exe <langversion> <file>"); return; } var versionInt = int.Parse(args[0]); if (!Enum.IsDefined(typeof(LanguageVersion), versionInt)) { Console.WriteLine("Invalid version"); return; } var decompiler = new CSharpDecompiler(args[1], new DecompilerSettings((LanguageVersion)versionInt)); decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); decompiler.AstTransforms.Add(new RemoveCLSCompliantAttribute()); var str = decompiler.DecompileWholeModuleAsString(); var version = typeof(CSharpDecompiler).Assembly.GetName().Version.ToString(); Console.Error.WriteLine("/* ICSharpCode.Decompiler v" + version + " */"); Console.WriteLine(str); }
/// <summary> /// Decompiles. /// </summary> /// /// <param name="parm"> The parameter. </param> public String Decompile(String parm) { Version runtimeVersion = Utils.RuntimeVersion(parm); //! Asset Compiled with: .Net v2.0.50727 //! Asset Compiled with: .Net v4.0.30319 // Debug.WriteLine($"Asset Compiled with: .Net {runtimeVersion}"); Boolean isAsset = Utils.IsAsset(parm); Boolean isPortableAsset = Utils.IsPortableAsset(parm); #warning Also check runtime version/.net profile here. Debug.WriteLine($"Is Asset: {isAsset}"); Debug.WriteLine($"Is Portable Asset: {isPortableAsset}"); //{ CSharpDecompiler decompilerA = new CSharpDecompiler(parm, new DecompilerSettings() { ShowXmlDocumentation = false, AlwaysUseBraces = true, LoadInMemory = true, RemoveDeadCode = true, }); return(decompilerA.DecompileWholeModuleAsString()); }
public static string DecompileCode(string applicationName) { CSharpDecompiler decompiler = new CSharpDecompiler(applicationName, new DecompilerSettings() { ThrowOnAssemblyResolveErrors = false, RemoveDeadCode = true }); return(decompiler.DecompileWholeModuleAsString()); }
private void DecopmileDllToCs(string dllFile, string csPath) { var dec = new CSharpDecompiler(dllFile, new DecompilerSettings { AsyncAwait = true }); var rs = dec.DecompileWholeModuleAsString(); File.WriteAllText(csPath, rs); }
public MainWindow() { InitializeComponent(); var fileName = @"C:\Temp\BinarDataGenerator.dll"; var decompiler = new CSharpDecompiler(fileName, new DecompilerSettings()); string code = decompiler.DecompileWholeModuleAsString(); Debug.WriteLine(code); }
static void Decompile(string assemblyFileName, TextWriter output, string typeName = null) { CSharpDecompiler decompiler = GetDecompiler(assemblyFileName); if (typeName == null) { output.Write(decompiler.DecompileWholeModuleAsString()); } else { var name = new FullTypeName(typeName); output.Write(decompiler.DecompileTypeAsString(name)); } }
public Task HandleAsync(WorkspaceFile file, HandleFileOptions options, CancellationToken cancellationToken) { try { var decompiler = new CSharpDecompiler( file.Path, new DecompilerSettings()); file.Content = decompiler.DecompileWholeModuleAsString(); file.Meta.Language = "csharp"; } catch (Exception ex) { Log.Warning(ex, "Could not decompile: {File}", file.Path); } return(Task.CompletedTask); }
public Result <string> GetSource(byte[] bytecode) { if (bytecode == null) { return(Result.Fail <string>("Bytecode cannot be null")); } using (var memStream = new MemoryStream(bytecode)) { try { var modDefinition = ModuleDefinition.ReadModule(memStream); var decompiler = new CSharpDecompiler(modDefinition, new DecompilerSettings { }); string cSharp = decompiler.DecompileWholeModuleAsString(); return(Result.Ok(cSharp)); } catch (BadImageFormatException e) { return(Result.Fail <string>(e.Message)); } } }
private string NormalizeFileContent(string filename, byte[] buffer) { Logger.Trace("NormalizeFileContent({0}, {1}", filename, buffer?.Length); if (buffer == null || buffer.Length == 0) { return(string.Empty); } // Check if we have a binary file - meaning more than 10% control characters // TODO: Is this the right metric? var bufferString = Encoding.ASCII.GetString(buffer); var countControlChars = bufferString.Count(ch => char.IsControl(ch) && ch != '\r' && ch != '\n' && ch != '\t'); var isBinaryFile = (((double)countControlChars / (double)bufferString.Length) > 0.10); if (isBinaryFile) { // First, is it a PE file? if (PeFile.IsPeFile(buffer)) { try { var decompiler = new CSharpDecompiler(filename, new DecompilerSettings()); return(decompiler.DecompileWholeModuleAsString()); } catch (Exception ex) { Logger.Warn("Unable to decompile {0}: {1}", filename, ex.Message); } } var resultStrings = new HashSet <string>(); try { // Do a full disassembly, but only show unique lines. Disassembler.Translator.IncludeAddress = false; Disassembler.Translator.IncludeBinary = false; var architecture = buffer.Length > 5 && buffer[5] == 0x02 ? ArchitectureMode.x86_64 : ArchitectureMode.x86_32; using var disassembler = new Disassembler(buffer, architecture); foreach (var instruction in disassembler.Disassemble()) { resultStrings.Add(instruction.ToString()); } } catch (Exception ex) { Logger.Warn("Unable to decompile {0}: {1}", filename, ex.Message); } try { // Maybe it's WebAseembly -- @TODO Make this less random. using var webAssemblyByteStream = new MemoryStream(buffer); var m = WebAssembly.Module.ReadFromBinary(webAssemblyByteStream); foreach (var data in m.Data) { resultStrings.Add(Encoding.ASCII.GetString(data.RawData.ToArray())); } foreach (var functionBody in m.Codes) { foreach (var instruction in functionBody.Code) { switch (instruction.OpCode) { case OpCode.Int32Constant: resultStrings.Add(((Int32Constant)instruction).Value.ToString()); break; case OpCode.Int64Constant: resultStrings.Add(((Int64Constant)instruction).Value.ToString()); break; default: break; } } } return(string.Join('\n', resultStrings)); } catch (WebAssembly.ModuleLoadException) { // OK to ignore } catch (Exception ex) { Logger.Warn("Unable to analyze WebAssembly {0}: {1}", filename, ex.Message); } if (resultStrings.Any()) { return(string.Join('\n', resultStrings)); } return(string.Join('\n', UniqueStringsFromBinary(buffer))); } // Fallback, just return the string iteself return(bufferString); }
/// <summary> /// Decompiles. /// </summary> /// /// <param name="parm"> The parameter. </param> public void Decompile(String parm) { //Dictionary<String, String> code = new Dictionary<String, String>(); host.AddResult(Severity.Info, true, $"[Decompiling '{Path.GetFileNameWithoutExtension(parm)}' Assembly to Check for Dead Code]"); Version runtimeVersion = Utils.RuntimeVersion(parm); //! Asset Compiled with: .Net v2.0.50727 //! Asset Compiled with: .Net v4.0.30319 // Debug.WriteLine($"Asset Compiled with: .Net {runtimeVersion}"); Boolean isAsset = Utils.IsAsset(parm); Boolean isPortableAsset = Utils.IsPortableAsset(parm); #warning Also check runtime version/.net profile here. Debug.WriteLine($"Is Asset: {isAsset}"); Debug.WriteLine($"Is Portable Asset: {isPortableAsset}"); //{ CSharpDecompiler decompilerA = new CSharpDecompiler(parm, new DecompilerSettings() { AlwaysUseBraces = true, LoadInMemory = true, AutomaticProperties = false, RemoveDeadCode = false, }); String decompA = decompilerA.DecompileWholeModuleAsString(); CSharpDecompiler decompilerB = new CSharpDecompiler(parm, new DecompilerSettings() { AlwaysUseBraces = true, LoadInMemory = true, AutomaticProperties = false, RemoveDeadCode = true, }); String decompB = decompilerB.DecompileWholeModuleAsString(); //! Examples of failures that are NOT dead code (so we always will have some false alerts). // //!A: // NodePath nodePath = new NodePath(); // nodePath = root.ToNodeStructure(); // string text = serializer.Serialize(nodePath, format); //!B: // new NodePath(); // NodePath obj = root.ToNodeStructure(); // string text = serializer.Serialize(obj, format); //!A: string empty = string.Empty; // ... // empty = serializer.Serialize(nodeValue, format); // if (jsonValue.IsMatch(empty)) // //!B: string empty = string.Empty; // ... // string text = serializer.Serialize(nodeValue, format); // if (jsonValue.IsMatch(text)) if (decompA != decompB) { host.AddResult(Severity.Warning, true, $"Possible Dead Code Detected in '{decompilerB.TypeSystem.MainModule.AssemblyName}'."); Debug.WriteLine(Utils.Diff(decompA, decompB)); } else { host.AddResult(Severity.Info, true, $"No Dead Code Detected in '{decompilerB.TypeSystem.MainModule.AssemblyName}'."); } }
static void Main(string[] args) { if (args.Length > 1) { Parallel.ForEach(args, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (arg) => ShellUtils.RunShellAsync( "dotnet", $"\"{Assembly.GetExecutingAssembly().Location}\" \"{arg}\"") .GetAwaiter().GetResult() ); } else if (args.Length == 1) { string arg = args[0]; if (File.Exists(arg)) { using (var rizin = new Rizin()) { rizin.Command($"o \"{arg}\""); string fileName = Path.GetFileName(arg); using (DataTable dt = rizin.CommandDataTable("itj")) { if (dt.Columns.Contains(".md5")) { fileName = (string)dt.Rows[0][".md5"]; } } string path = $"rz_report/{fileName}"; Directory.CreateDirectory(path); Report report = new Report(rizin, path); rizin.CommandAnalyzeBinary(); Yara yara = new Yara(rizin, path); yara.TryYaraCheck(); report.Hashes(); report.Info(); if (CheckIsNotExecutable(rizin)) { return; } if (CheckIsCilExecutable(rizin)) { try { var decompiler = new CSharpDecompiler(arg, new DecompilerSettings()); string code = decompiler.DecompileWholeModuleAsString(); string cilFileName = string.Concat(path, Path.DirectorySeparatorChar, "cil.txt"); File.WriteAllText(cilFileName, code); } catch (Exception) { } return; } report.Headers(); report.Sections(); report.Resources(); report.Libraries(); report.Signature(); report.Entrypoints(); report.Imports(); report.Exports(); report.Strings(); report.StackStrings(); report.Functions(); rizin.Command($"Ps \"{path}/project.rzdb\""); // Opcodes opcodes = new Opcodes(rizin, path); // opcodes.Disassemble(); Data data = new Data(rizin, path); data.Export(); } } } else { Console.WriteLine(@"usage: rz_report [FILE]..."); Console.WriteLine(@"creates a folder ""./rz_report"" and writes the analysis " + @"results inside subfolders named after their MD5 sums."); } }