public static async Task<string> GetSourceCode(MethodDefinition methodDefinition, ILWeaver weaver = null) { return await Task.Run(() => { try { if (weaver != null) weaver.Apply(methodDefinition.Body); var settings = new DecompilerSettings { UsingDeclarations = false }; var context = new DecompilerContext(methodDefinition.Module) { CurrentType = methodDefinition.DeclaringType, Settings = settings }; var astBuilder = new AstBuilder(context); astBuilder.AddMethod(methodDefinition); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); } catch (Exception ex) { return "Error in creating source code from IL: " + ex.Message + Environment.NewLine + ex.StackTrace; } finally { if (weaver != null) methodDefinition.Body = null; } }); }
public static string Disassemble(this MethodBody body) { var writer = new PlainTextOutput(); var dasm = new MethodBodyDisassembler(writer); dasm.Disassemble(body); return writer.ToString(); }
public static string ToSource(MethodDefinition methodDefinition) { var settings = new DecompilerSettings { UsingDeclarations = false }; var context = new DecompilerContext(methodDefinition.Module) { CurrentType = methodDefinition.DeclaringType, Settings = settings, }; var astBuilder = new AstBuilder(context); astBuilder.AddMethod(methodDefinition); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); }
private static string Decompile(string name, MethodDefinition mtd) { var decompilerSettings = new ICSharpCode.Decompiler.DecompilerSettings { ShowXmlDocumentation = false, UsingDeclarations = false, }; var output = new ICSharpCode.Decompiler.PlainTextOutput(); var method = mtd; var astBuilder = new AstBuilder(new DecompilerContext(method.DeclaringType.Module) { CancellationToken = new CancellationToken(), CurrentType = method.DeclaringType, Settings = decompilerSettings, }); astBuilder.AddMethod(method); astBuilder.GenerateCode(output); var methodCode = output.ToString(); // remove top comment line //if (methodCode.StartsWith("//")) { // methodCode = methodCode.Substring(methodCode.IndexOf('\n') + 1); //} var attrRE = new Regex(@"^(?:\[[^]]+]\s*){1,}"); methodCode = attrRE.Replace(methodCode, "", 1); // change the method name to the mod's name for the method, and replace parameter names with game names var methodName = mtd.Name; var nameLocation = methodCode.IndexOf(" " + methodName) + 1; var nameEnd = nameLocation + methodName.Length; // Prepend "void " if this was a constructor (since methodCode won't have a return type) var correctName = mtd.IsConstructor ? ("void " + name) : name; methodCode = methodCode.Substring(0, nameLocation) + correctName + methodCode.Substring(nameEnd); return(methodCode); }
public static async Task<string> GetSourceCode(TypeDefinition typeDefinition) { return await Task.Run(() => { try { var settings = new DecompilerSettings { UsingDeclarations = true }; var context = new DecompilerContext(typeDefinition.Module) { CurrentType = typeDefinition, Settings = settings }; var astBuilder = new AstBuilder(context); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); } catch (Exception ex) { return "Error in creating source code from Type: " + ex.Message + ex.Message + Environment.NewLine + ex.StackTrace; } }); }
private static string Decompile(string name, MethodDefinition mtd) { var decompilerSettings = new ICSharpCode.Decompiler.DecompilerSettings { ShowXmlDocumentation = false, UsingDeclarations = false, }; var output = new ICSharpCode.Decompiler.PlainTextOutput(); var method = mtd; var astBuilder = new AstBuilder(new DecompilerContext(method.DeclaringType.Module) { CancellationToken = new CancellationToken(), CurrentType = method.DeclaringType, Settings = decompilerSettings, }); astBuilder.AddMethod(method); astBuilder.GenerateCode(output); var methodCode = output.ToString(); // remove top comment line //if (methodCode.StartsWith("//")) { // methodCode = methodCode.Substring(methodCode.IndexOf('\n') + 1); //} var attrRE = new Regex(@"^(?:\[[^]]+]\s*){1,}"); methodCode = attrRE.Replace(methodCode, "", 1); // change the method name to the mod's name for the method, and replace parameter names with game names var methodName = mtd.Name; var nameLocation = methodCode.IndexOf(" " + methodName) + 1; var nameEnd = nameLocation + methodName.Length; // Prepend "void " if this was a constructor (since methodCode won't have a return type) var correctName = mtd.IsConstructor ? ("void " + name) : name; methodCode = methodCode.Substring(0, nameLocation) + correctName + methodCode.Substring(nameEnd); return methodCode; }
private string GetCSharpCode(IMemberDefinition member, bool debug) { PlainTextOutput output = new PlainTextOutput(); CSharpLanguage csharp = new CSharpLanguage(); DecompilationOptions options = new DecompilationOptions(); options.DecompilerSettings = LoadDecompilerSettings(); if (member is TypeDefinition) { DecomplieType(csharp, (TypeDefinition)member, output, options); return output.ToString(); } else { MessageBox.Show("Not TypeDefinition"); } return null; }
public string getSourceCode(MethodDefinition methodDefinition) { try { var csharpLanguage = new CSharpLanguage(); var textOutput = new PlainTextOutput(); var decompilationOptions = new DecompilationOptions(); decompilationOptions.FullDecompilation = true; csharpLanguage.DecompileMethod(methodDefinition, textOutput, decompilationOptions); return textOutput.ToString(); /* ILanguage language = CSharp.GetLanguage(CSharpVersion.V1); language.GetWriter(new PlainTextFormatter(writer)).Write(method); MemoryStream stream = new MemoryStream(); StreamWriter writer3 = new StreamWriter(stream); language.GetWriter(new PlainTextFormatter(writer3)).Write(method); stream.Flush();*/ } catch (Exception exception) { PublicDI.log.error("in getSourceCode: {0}", new object[] { exception.Message }); return ("Error in creating source code from IL: " + exception.Message); } }
private void SetupDecompilerAndOriginalSource(MethodDefinition method) { _cSharpDecompiler = new CSharpLanguage(); var decompilationOutput = new PlainTextOutput(); _decompilationOptions = new DecompilationOptions(); _cSharpDecompiler.DecompileMethod(method, decompilationOutput, _decompilationOptions); _oldText = decompilationOutput.ToString(); _differ = new SideBySideDiffBuilder(new Differ()); }
public string ToString(Language language) { var output = new PlainTextOutput(); Write(output, language); return output.ToString(); }
public static void Main (string[] args) { string appPath = null; string slnName = null; string libPath = null; string expOpt = null; string outLanguageType = LAN_TYPE_CSHARP; DecompilerSettings ds = new DecompilerSettings (); ds.AnonymousMethods = true; ds.AsyncAwait = true; ds.YieldReturn = true; string onlyDecomileClassName = null; List<string> onlyDecompilingFileNameList = new List<string> (); //parsing args foreach (string x in args) { if (x.StartsWith ("-")) { switch (x) { case "-n": case "-l": case "-t": case "-C": case "-D": expOpt = x; continue; default: if (x.StartsWith ("-")) { if (x.Length < 2) { Console.WriteLine (" Unexpected options " + x); showUsage (); return; } for (int i = 0; i < x.Length; i++) { if (!praseDecompileSetting (x [i], ds)) { Console.WriteLine (" Unexpected options " + x); showUsage (); return; } } continue; } break; } } else if (expOpt != null) { switch (expOpt) { case "-n": slnName = x; expOpt = null; break; case "-l": libPath = x; expOpt = null; break; case "-t": if (x != LAN_TYPE_CSHARP && x != LAN_TYPE_IL) { Console.WriteLine (" Unexpected Output language type: " + x); showUsage (); return; } outLanguageType = x; expOpt = null; break; case "-C": onlyDecomileClassName = x; expOpt = null; break; case "-D": onlyDecompilingFileNameList.Add (x); break; default: showUsage (); expOpt = null; return; } } else { if (appPath == null) { appPath = x; continue; } else { Console.WriteLine (" Unexpected options " + x); showUsage (); return; } } } if (appPath == null) { Console.WriteLine ("directory/to/all/your/dll missing"); showUsage (); return; } if (slnName == null && outLanguageType==LAN_TYPE_CSHARP) { Console.WriteLine ("Solution Name missing"); showUsage (); return; } Console.WriteLine ("Decompiling all dll in " + appPath); Console.WriteLine ("Please wait..."); DirectoryInfo di = new DirectoryInfo(appPath); appPath = di.FullName; FileInfo[] dllFileInfoList = di.GetFiles("*.dll"); FileInfo[] exeFileInfoList = di.GetFiles ("*.exe"); AssemblyList asmlist = new AssemblyList ("mylistname"); foreach (var dllfile in dllFileInfoList) { bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList); asmlist.OpenAssembly (dllfile.FullName,!bDecompile); } foreach (var dllfile in exeFileInfoList) { bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList); asmlist.OpenAssembly (dllfile.FullName,!bDecompile); } if (libPath != null) { di = new DirectoryInfo(libPath); libPath = di.FullName; dllFileInfoList = di.GetFiles("*.dll"); foreach (var dllfile in dllFileInfoList) { asmlist.OpenAssembly (dllfile.FullName,true); } } StringBuilder projSln = new StringBuilder (); projSln.Append ("Microsoft Visual Studio Solution File, Format Version 11.00\n# Visual Studio 2010\n"); StringBuilder globSec = new StringBuilder (); Guid slnProjGuid = Guid.NewGuid(); int num = 0; LoadedAssembly [] ls = asmlist.GetAssemblies (); var decompilationOptions = new DecompilationOptions (); decompilationOptions.FullDecompilation = true; decompilationOptions.assenmlyList = asmlist; decompilationOptions.DecompilerSettings = ds; decompilationOptions.IncludedClassName = onlyDecomileClassName; if(outLanguageType==LAN_TYPE_CSHARP) { foreach (LoadedAssembly asm in ls) { if (asm.IsAutoLoaded) continue; string projectPath = appPath + "/"+ asm.ShortName; if(!Directory.Exists(projectPath)) { Directory.CreateDirectory (projectPath); } string projectFileName = projectPath + "/" + asm.ShortName + ".csproj"; asm.ProjectGuid = Guid.NewGuid(); asm.ProjectFileName = projectFileName; } } foreach (LoadedAssembly asm in ls) { num++; Console.WriteLine(asm.FileName + " " + num+"/"+ls.Length); if (asm.IsAutoLoaded) continue; if(outLanguageType==LAN_TYPE_CSHARP) { var csharpLanguage = new CSharpLanguage (); var textOutput = new PlainTextOutput (); decompilationOptions.SaveAsProjectDirectory = appPath + "/"+ asm.ShortName; csharpLanguage.DecompileAssembly (asm, textOutput, decompilationOptions); File.WriteAllText (asm.ProjectFileName, textOutput.ToString ()); Guid createdProjGuid = asm.ProjectGuid; projSln.Append(" Project(\"{"); projSln.Append (slnProjGuid.ToString()); projSln.Append ("}\") = \""); projSln.Append (asm.ShortName); projSln.Append ("\", \""); projSln.Append (asm.ShortName+"/"+ asm.ShortName + ".csproj"); projSln.Append ("\", \"{"); projSln.Append (createdProjGuid.ToString()); projSln.Append ("}\"\n"); projSln.Append("EndProject\n"); globSec.Append (" {"+createdProjGuid.ToString()+"}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n"); globSec.Append (" {"+createdProjGuid.ToString()+"}.Debug|Any CPU.Build.0 = Debug|Any CPU\n"); globSec.Append (" {"+createdProjGuid.ToString()+"}.Release|Any CPU.ActiveCfg = Release|Any CPU\n"); globSec.Append (" {"+createdProjGuid.ToString()+"}.Release|Any CPU.Build.0 = Release|Any CPU\n"); } else { var ilLanguage = new ILLanguage(true); var textOutput = new PlainTextOutput (); ilLanguage.DecompileAssembly (asm, textOutput, decompilationOptions); string ilFileName = appPath + "/"+ asm.ShortName+".il"; File.WriteAllText(ilFileName,textOutput.ToString()); } } if (outLanguageType == LAN_TYPE_CSHARP) { projSln.Append ("Global\n"); projSln.Append ("GlobalSection(SolutionConfigurationPlatforms) = preSolution\n"); projSln.Append ("\t\t\t\tDebug|Any CPU = Debug|Any CPU\n"); projSln.Append ("\t\t\t\tRelease|Any CPU = Release|Any CPU\n"); projSln.Append ("EndGlobalSection\n"); projSln.Append ("GlobalSection(ProjectConfigurationPlatforms) = postSolution\n"); projSln.Append (globSec.ToString ()); projSln.Append ("EndGlobalSection\n"); projSln.Append ("GlobalSection(MonoDevelopProperties) = preSolution\n"); projSln.Append ("\nEndGlobalSection\n"); projSln.Append ("EndGlobal\n\t\t"); string slnFileName = appPath + "/" + slnName + ".sln"; File.WriteAllText (slnFileName, projSln.ToString ()); } }
public override string TypeToString(TypeReference t) { PlainTextOutput output = new PlainTextOutput(); t.WriteTo(output, true, true); return output.ToString(); }
public override string TypeToString(TypeReference t, bool includeNamespace, ICustomAttributeProvider attributeProvider) { PlainTextOutput output = new PlainTextOutput(); t.WriteTo(output, true, shortName: !includeNamespace); return output.ToString(); }
public string getSourceCode(TypeDefinition typeDefinition) { try { var csharpLanguage = new CSharpLanguage(); var textOutput = new PlainTextOutput(); var decompilationOptions = new DecompilationOptions(); decompilationOptions.FullDecompilation = true; csharpLanguage.DecompileType(typeDefinition, textOutput, decompilationOptions); return textOutput.ToString(); } catch (Exception exception) { PublicDI.log.error("in getSourceCode: {0}", new object[] { exception.Message }); return ("Error in creating source code from Type: " + exception.Message); } }
public override string TypeToString(TypeReference t, bool includeNamespace, ICustomAttributeProvider attributeProvider = null) { PlainTextOutput output = new PlainTextOutput(); t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName); return output.ToString(); }
private string ConstructEstimateCodeDiff(MethodDefinition method) { var decompilationOutput = new PlainTextOutput(); try { _cSharpDecompiler.DecompileMethod(method, decompilationOutput, _decompilationOptions); } catch { return "\t\tNo decompilation available for mutated version.\n"; } string newText = decompilationOutput.ToString(); var model = _differ.BuildDiffModel(_oldText, newText); string diffOutput = "\t\tApproximate source code difference from IL decompilation:\n"; var lines = new SortedSet<int>(); for (int i = 0; i < Math.Max(model.OldText.Lines.Count, model.NewText.Lines.Count); i++) { if ((i < model.OldText.Lines.Count && model.OldText.Lines[i].Type != ChangeType.Unchanged) || (i < model.NewText.Lines.Count && model.NewText.Lines[i].Type != ChangeType.Unchanged)) { lines.Add(i - 2); lines.Add(i - 1); lines.Add(i); lines.Add(i + 1); lines.Add(i + 2); } } int lastLine = -1; string adds = ""; string takes = ""; foreach (var line in lines) { if (line < 0) continue; if (line > lastLine + 1) { diffOutput += string.Format("{1}{2}\t\t@@ {0} @@\n", line, takes, adds); takes = ""; adds = ""; } if (line < model.OldText.Lines.Count) { takes += string.Format("\t\t- {0}\n", (model.OldText.Lines[line].Text ?? "").Replace("\t", " ")); } if (line < model.NewText.Lines.Count) { adds += string.Format("\t\t+ {0}\n", (model.NewText.Lines[line].Text ?? "").Replace("\t", " ")); } lastLine = line; } if (!string.IsNullOrEmpty(adds) || !string.IsNullOrEmpty(takes)) { diffOutput += takes + adds; } return diffOutput; }
public string GetClass(TypeIdentity identity) { // Before we attempt to fetch it just try a decompilation. GetAssembly(identity.AssemblyPath); ModuleDefinition moduleDef; if (!this.loadedModules.TryGetValue(identity.AssemblyPath, out moduleDef)) { // Can't find the assembly, just return nothing. return string.Empty; } TypeDefinition typeDef = moduleDef.GetType(identity.FullyQualifiedName); if (typeDef == null) { // If we can't find our type just return as well. return string.Empty; } DecompilerContext context = new DecompilerContext(moduleDef); AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(typeDef); PlainTextOutput textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); }