/// <summary> /// Converts a Module wixout into a ComponentGroup. /// </summary> /// <param name="wixout">The output object representing the unbound merge module to melt.</param> /// <returns>The converted Module as a ComponentGroup.</returns> public Wix.Wix Melt(Output wixout) { string moduleId = GetModuleId(wixout); // Assign the default componentGroupId if none was specified if (null == this.id) { this.id = moduleId; } this.componentGroup.Id = this.id; this.primaryDirectoryRef.Id = this.id; PreDecompile(wixout); Wix.Wix wix = decompiler.Decompile(wixout); if (null == wix) { return(wix); } ConvertModule(wix); return(wix); }
public string GetBytesCode() { StringBuilder code = new StringBuilder(); SwfReader Reader = new SwfReader(this.File); Swf swf = null; try { swf = Reader.ReadSwf(); } catch (Exception Ex) { throw new Exception(Ex.ToString()); } IEnumerator enumerator = swf.Tags.GetEnumerator(); while (enumerator.MoveNext()) { BaseTag current = (BaseTag)enumerator.Current; if (current.ActionRecCount != 0) { IEnumerator currentenumerator = current.GetEnumerator(); while (currentenumerator.MoveNext()) { Decompiler decompiler = new Decompiler(swf.Version); foreach (BaseAction action in decompiler.Decompile((byte[])currentenumerator.Current)) { code.AppendLine(action.ToString()); } } } } return(code.ToString()); }
public void TemplateHasCorrectSymbols() { using (ApprovalResults.ForScenario(Suffix)) { Approvals.Verify(Decompiler.Decompile(afterAssemblyPath, "Costura.AssemblyLoader")); } }
private void PrintMain(Output output, Decompiler d, bool includeFirst) { output.Print("("); var start = includeFirst ? 0 : 1; if (m_function.NumParams > start) { new VariableTarget(d.DeclList[start]).Print(output); for (int i = start + 1; i < m_function.NumParams; i++) { output.Print(", "); new VariableTarget(d.DeclList[i]).Print(output); } } if ((m_function.VarArg & 1) == 1) { output.Print((m_function.NumParams > start) ? ", ..." : "..."); } output.Print(")"); output.PrintLine(); output.IncreaseIndent(); d.Decompile(); d.Print(output); output.DecreaseIndent(); output.Print("end"); //output.PrintLine(); //This is an extra space for formatting }
private async Task BatchDecompile(string outdir) { LoaderDialog dialog = new LoaderDialog("Decompiling", "Decompiling, please wait..."); dialog.Owner = this; Task t = Task.Run(() => { foreach (var code in Data.Code) { Debug.WriteLine(code.Name.Content); string path = System.IO.Path.Combine(outdir, code.Name.Content + ".gml"); try { string decomp = Decompiler.Decompile(code); File.WriteAllText(path, decomp); } catch (Exception e) { File.WriteAllText(path, "/*\nDECOMPILER FAILED!\n\n" + e.ToString() + "\n*/"); } } Dispatcher.Invoke(() => { dialog.Hide(); }); }); dialog.ShowDialog(); await t; }
public void TestDecompileTjs() { var path = "..\\..\\..\\Res\\Initialize.tjs.comp"; Decompiler decompiler = new Decompiler(path); //var result = decompiler.Decompile(); var result = decompiler.Decompile("global"); //var result = decompiler.Decompile("countLayerMetrics"); //var result = decompiler.Decompile("Test"); //there is a bug at [var b3 = b2 || b;] to be solved only by data flow analysis // B1 -> B2 -> B3, B1 -> B3, B3.From = B1 & B2, B3.Input = flag, B1.Output & B1.Def = flag, B2.Output & B2.Def = flag => flag = φ //var result = decompiler.Decompile("TestLoop"); //bug: the generated expression is wrong at [v4 ++ += 2] //TODO: v4++ shouldn't be kept in registers, just pend to expList and leave v4 in register //Maybe block hiding is a bad idea //For Condition: if first Block can be merged (Propagation) into 1 statement, then it can be the condition, otherwise no condition. //Should be able to determine whether a slot is not used anymore using data flow (Dead) so can perform propagation //Add Block.LastRead LastWrite ? return; var KAGLoadScript = decompiler.Script.Objects.Find(c => c.Name == "KAGLoadScript"); var argC = KAGLoadScript.FuncDeclArgCount; var argD = KAGLoadScript.FuncDeclCollapseBase; var argU = KAGLoadScript.FuncDeclUnnamedArgArrayBase; var vR = KAGLoadScript.VariableReserveCount; var vM = KAGLoadScript.MaxVariableCount; foreach (var tjsVariant in KAGLoadScript.Variants) { var v = tjsVariant; } var s = KAGLoadScript.SourcePosArray; }
static void RecursionDetector() { // First decompile all methods in the assembly: Dictionary<MethodBase, MethodBase[]> calling = new Dictionary<MethodBase, MethodBase[]>(); var assembly = typeof(StackOverflowDetector).Assembly; foreach (var type in assembly.GetTypes()) { foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).OfType<MethodBase>()) { var body = member.GetMethodBody(); if (body!=null) { var bytes = body.GetILAsByteArray(); if (bytes != null) { // Store all the calls of this method: var calls = Decompiler.Decompile(member, bytes); calling[member] = calls; } } } } // Check every method: foreach (var method in calling.Keys) { // If method A -> ... -> method A, we have a possible infinite recursion CheckRecursion(method, calling, new HashSet<MethodBase>()); } }
public static SwfDecompiledMap ReadSwfMap(string id, string mapid) { string path = (Constants.MapsPath + $"{id}" + "_" + $"{mapid}X.swf"); SwfReader Reader = new SwfReader(path); Swf swf = Reader.ReadSwf(); SwfDecompiledMap mapDatas = null; IEnumerator enumerator = swf.Tags.GetEnumerator(); while (enumerator.MoveNext()) { BaseTag current = (BaseTag)enumerator.Current; if (current.ActionRecCount != 0) { string sb = ""; IEnumerator currentenumerator = current.GetEnumerator(); while (currentenumerator.MoveNext()) { Decompiler decompiler = new Decompiler(swf.Version); ArrayList actions = decompiler.Decompile((byte[])currentenumerator.Current); foreach (BaseAction obj in actions) { sb += obj.ToString(); } } mapDatas = ParseSwfMapDatas(sb); } } Reader.Close(); return(mapDatas); }
public void ReplaceTextInGML(string codeName, string keyword, string replacement, bool case_sensitive = false, bool isRegex = false) { UndertaleCode code; string passBack = ""; EnsureDataLoaded(); if (Data.Code.ByName(codeName) != null) { code = Data.Code.ByName(codeName); } else { ScriptError("No code named " + codeName + " was found!"); return; } if (Data.ToolInfo.ProfileMode == false || Data.GMS2_3) { ThreadLocal <DecompileContext> DECOMPILE_CONTEXT = new ThreadLocal <DecompileContext>(() => new DecompileContext(Data, false)); try { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, DECOMPILE_CONTEXT.Value) : ""), keyword, replacement, case_sensitive, isRegex); code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } else if (Data.ToolInfo.ProfileMode && !Data.GMS2_3) { try { string path = Path.Combine(ProfilesFolder, Data.ToolInfo.CurrentMD5, "Temp", codeName + ".gml"); if (File.Exists(path)) { passBack = GetPassBack(File.ReadAllText(path), keyword, replacement, case_sensitive, isRegex); File.WriteAllText(path, passBack); code.ReplaceGML(passBack, Data); } else { ThreadLocal <DecompileContext> DECOMPILE_CONTEXT = new ThreadLocal <DecompileContext>(() => new DecompileContext(Data, false)); try { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, DECOMPILE_CONTEXT.Value) : ""), keyword, replacement, case_sensitive, isRegex); code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } } catch (Exception exc) { throw new Exception("Error during writing of GML code to profile:\n" + exc.ToString() + "\n\nCode:\n\n" + passBack); } } }
public MeleeDataNode(string fname) { fileName = fname; DatFile = Decompiler.Decompile(File.ReadAllBytes(fname)); if (Path.GetFileNameWithoutExtension(fname).StartsWith("Pl") && File.Exists(fname.Substring(0, fname.Length - 6) + ".dat")) { DialogResult dialogResult = MessageBox.Show("Mark LOD Models?\nUseful for easier importing", "Import LOD Information", MessageBoxButtons.YesNo); if (dialogResult != DialogResult.Yes) { return; } // Read it FileData d = new FileData(fname.Substring(0, fname.Length - 6) + ".dat"); d.endian = Endianness.Big; d.Seek(0x24); d.Seek(d.ReadInt() + 0x20); int off; while ((off = d.ReadInt()) != 0) { int temp = d.Pos(); d.Seek(off + 0x20); int Count = d.ReadInt(); int Offset = d.ReadInt() + 0x20; for (int i = 0; i < Count; i++) { d.Seek(Offset + i * 8); int c = d.ReadInt(); int o = d.ReadInt() + 0x20; LodModels.AddRange(d.GetSection(o, c)); } d.Seek(temp); break; } } ImageKey = "dat"; SelectedImageKey = "dat"; ContextMenu = new ContextMenu(); MenuItem Save = new MenuItem(); MenuItem Export = new MenuItem("Save As"); Export.Click += SaveAs; ContextMenu.MenuItems.Add(Export); MenuItem Recompile = new MenuItem("Update Vertices"); Recompile.Click += RecompileVertices; ContextMenu.MenuItems.Add(Recompile); /*if(LodModels.Count > 0) * { * MenuItem Import = new MenuItem("Import High Poly From File"); * Import.Click += SaveAs; * ContextMenu.MenuItems.Add(Import); * }*/ }
public static void ReplaceInGML(string str1, string str2, UndertaleCode code, UndertaleData data) { string decomp = Decompiler.Decompile(code, new DecompileContext(data, false)); decomp = decomp.Replace(str1, str2); code.ReplaceGML(decomp, data); code.UpdateAddresses(); }
public void TemplateHasCorrectSymbols() { using (ApprovalResults.ForScenario(Suffix)) { var text = Decompiler.Decompile(afterAssemblyPath, "Costura.AssemblyLoader"); Approvals.Verify(WriterFactory.CreateTextWriter(text), new CustomNamer(), Approvals.GetReporter()); } }
public void ReplaceTextInGML(UndertaleCode code, string keyword, string replacement, bool caseSensitive = false, bool isRegex = false, GlobalDecompileContext context = null) { EnsureDataLoaded(); string passBack = ""; string codeName = code.Name.Content; GlobalDecompileContext DECOMPILE_CONTEXT = context is null ? new(Data, false) : context; if (!Data.ToolInfo.ProfileMode) { try { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, DECOMPILE_CONTEXT) : ""), keyword, replacement, caseSensitive, isRegex); code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } else { try { string path = Path.Combine(ProfilesFolder, Data.ToolInfo.CurrentMD5, "Temp", codeName + ".gml"); if (File.Exists(path)) { passBack = GetPassBack(File.ReadAllText(path), keyword, replacement, caseSensitive, isRegex); File.WriteAllText(path, passBack); code.ReplaceGML(passBack, Data); } else { try { if (context is null) { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, new GlobalDecompileContext(Data, false)) : ""), keyword, replacement, caseSensitive, isRegex); } else { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, context) : ""), keyword, replacement, caseSensitive, isRegex); } code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } } catch (Exception exc) { throw new Exception("Error during writing of GML code to profile:\n" + exc.ToString() + "\n\nCode:\n\n" + passBack); } } }
public static List <MapDatas> ReadListSwfMap(string id) { List <MapDatas> MapList = new List <MapDatas>(); List <string> Files = Directory.GetFiles(Constants.MapsPath, "*.swf").ToList(); Files = Files.Where(x => x.Contains("\\" + id)).ToList(); SwfReader Reader; foreach (var mapFile in Files) { string path = mapFile; Reader = new SwfReader(path); Swf swf = Reader.ReadSwf(); IEnumerator enumerator = swf.Tags.GetEnumerator(); while (enumerator.MoveNext()) { BaseTag current = (BaseTag)enumerator.Current; if (current.ActionRecCount != 0) { string sb = ""; IEnumerator currentenumerator = current.GetEnumerator(); while (currentenumerator.MoveNext()) { Decompiler decompiler = new Decompiler(swf.Version); ArrayList actions = decompiler.Decompile((byte[])currentenumerator.Current); foreach (BaseAction obj in actions) { sb += obj.ToString(); } } SwfDecompiledMap content = ParseSwfMapDatas(sb); content.DecypheredMapData = Hash.DecypherData(content.CypheredMapData, MapKeyCracker.MapCrackKey(content.CypheredMapData)); GlobalMapsInfos.First(x => x.Id == content.Id).SwfDatas.MapId = path.Substring(path.IndexOf(id) + id.Length + 1, path.IndexOf(".swf") - (path.IndexOf(id) + id.Length + 1)); GlobalMapsInfos.First(x => x.Id == content.Id).SwfDatas = content; MapList.Add(GlobalMapsInfos.First(x => x.SwfDatas == content)); sb = ""; } } Reader.Close(); swf = null; } string firstValue = MapList.First().SwfDatas.DecypheredMapData; if (MapList.All(x => x.SwfDatas.DecypheredMapData == firstValue)) { return new List <MapDatas>() { MapList.First() } } ; return(MapList); }
public static void ReadSwfLang(string path) { //This part is dirty but there arent so much ressources about how to decompile langs, decompilation & reading takes more than12 secondes.. StringHelper.WriteLine($"[DataManager] Reading maps lang ..", ConsoleColor.Cyan); SwfReader Reader = new SwfReader(path); Swf swf = Reader.ReadSwf(); IEnumerator enumerator = swf.Tags.GetEnumerator(); while (enumerator.MoveNext()) { BaseTag current = (BaseTag)enumerator.Current; if (current.ActionRecCount != 0) { string sb = ""; IEnumerator currentenumerator = current.GetEnumerator(); while (currentenumerator.MoveNext()) { Decompiler decompiler = new Decompiler(swf.Version); ArrayList actions = decompiler.Decompile((byte[])currentenumerator.Current); foreach (BaseAction obj in actions) { sb += obj.ToString(); } //maps coords & subarea id string regex = @"getMemberpush ([0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int"; MatchCollection matches = Regex.Matches(sb, regex); foreach (Match match in matches) { GlobalMapsInfos.Add(new MapDatas(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[5].Value), int.Parse(match.Groups[7].Value))); } //area id foreach (var map in GlobalMapsInfos.Where(x => x.AreaId == -1)) { var regex2 = @"getMemberpush " + map.SubAreaId + " as int push (-?[0-9]*?) as var push (-?[0-9]*?) as var push (-?[0-9]*?) as var push (-?[0-9]*?) "; var matches2 = Regex.Matches(sb, regex2); foreach (Match match2 in matches2) { map.AreaId = int.Parse(match2.Groups[4].Value); } } GC.Collect(); GC.WaitForPendingFinalizers(); sb = ""; Console.Write($"\r{DateTime.Now:[HH:mm:ss:fff]} [DataManager] {GlobalMapsInfos.Count()} maps loaded.."); } } } Reader.Close(); swf = null; Console.Write("\n"); StringHelper.WriteLine($"[DataManager] {GlobalMapsInfos.Count()} maps added to list !", ConsoleColor.Cyan); StringHelper.WriteLine("[DataManager] Map with undefinied AreaId : " + GlobalMapsInfos.Count(x => x.AreaId == -1), ConsoleColor.Blue); }
public IDecompileResult Execute() { var result = this.Context.ServiceProvider.GetService <IDecompileResult>(); try { using (var database = new Database(this.Context.DecompilePath, OpenDatabase.ReadOnly)) { // Delete the directory and its files to prevent cab extraction failure due to an existing file. if (Directory.Exists(this.Context.ExtractFolder)) { Directory.Delete(this.Context.ExtractFolder, true); } var backendHelper = this.Context.ServiceProvider.GetService <IBackendHelper>(); var unbindCommand = new UnbindDatabaseCommand(this.Messaging, backendHelper, database, this.Context.DecompilePath, this.Context.DecompileType, this.Context.ExtractFolder, this.Context.IntermediateFolder, this.Context.IsAdminImage, suppressDemodularization: false, skipSummaryInfo: false); var output = unbindCommand.Execute(); var extractedFilePaths = new List <string>(unbindCommand.ExportedFiles); var decompiler = new Decompiler(this.Messaging, backendHelper, this.Extensions, this.Context.BaseSourcePath, this.Context.SuppressCustomTables, this.Context.SuppressDroppingEmptyTables, this.Context.SuppressUI, this.Context.TreatProductAsModule); result.Document = decompiler.Decompile(output); result.Platform = GetPlatformFromOutput(output); // extract the files from the cabinets if (!String.IsNullOrEmpty(this.Context.ExtractFolder) && !this.Context.SuppressExtractCabinets) { var fileDirectory = String.IsNullOrEmpty(this.Context.CabinetExtractFolder) ? Path.Combine(this.Context.ExtractFolder, "File") : this.Context.CabinetExtractFolder; var extractCommand = new ExtractCabinetsCommand(output, database, this.Context.DecompilePath, fileDirectory, this.Context.IntermediateFolder, this.Context.TreatProductAsModule); extractCommand.Execute(); extractedFilePaths.AddRange(extractCommand.ExtractedFiles); result.ExtractedFilePaths = extractedFilePaths; } else { result.ExtractedFilePaths = new string[0]; } } } catch (Win32Exception e) { if (0x6E == e.NativeErrorCode) // ERROR_OPEN_FAILED { throw new WixException(ErrorMessages.OpenDatabaseFailed(this.Context.DecompilePath)); } throw; } return(result); }
public override void HandleOpenFile() { if (GlobalUtils.GlobalConfig.DecompileWhole) { Decompiler.Decompile(BaseDirectory + "\\raw.jar", (str) => { StatusMessage = str; }); } else { FirePluginNotification(IPlugin.NotifyOptions.ArchiveOpened); } }
private void UpdateGettext(UndertaleCode gettextCode) { gettext = new Dictionary <string, int>(); foreach (var line in Decompiler.Decompile(gettextCode, new DecompileContext(null, true)).Replace("\r\n", "\n").Split('\n')) { Match m = Regex.Match(line, "^ds_map_add\\(global.text_data_en, \"(.*)\"@([0-9]+), \"(.*)\"@([0-9]+)\\)"); if (m.Success) { gettext.Add(m.Groups[1].Value, Int32.Parse(m.Groups[4].Value)); } } }
public string GetDecompiledText(UndertaleCode code, GlobalDecompileContext context = null) { GlobalDecompileContext DECOMPILE_CONTEXT = context is null ? new(Data, false) : context; try { return(code != null?Decompiler.Decompile(code, DECOMPILE_CONTEXT) : ""); } catch (Exception e) { return("/*\nDECOMPILER FAILED!\n\n" + e.ToString() + "\n*/"); } }
static void Main(string[] args) { Config config = new Config("scripty.xml"); Rom rom = new Rom("rom.gba"); Decompiler decomp = new Decompiler(rom, config); foreach (string line in decomp.Decompile(0x008015c0)) { Console.WriteLine(line); } Console.WriteLine("done"); Console.ReadLine(); }
/// <inheritdoc/> public void ReplaceTextInGML(UndertaleCode code, string keyword, string replacement, bool caseSensitive = false, bool isRegex = false, GlobalDecompileContext context = null) { if (code == null) { throw new ArgumentNullException(nameof(code)); } EnsureDataLoaded(); string passBack = ""; GlobalDecompileContext decompileContext = context is null ? new(Data, false) : context; if (!Data.ToolInfo.ProfileMode) { try { passBack = GetPassBack(Decompiler.Decompile(code, decompileContext), keyword, replacement, caseSensitive, isRegex); code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc); } } else if (Data.ToolInfo.ProfileMode) { try { try { if (context is null) { passBack = GetPassBack(Decompiler.Decompile(code, new GlobalDecompileContext(Data, false)), keyword, replacement, caseSensitive, isRegex); } else { passBack = GetPassBack(Decompiler.Decompile(code, context), keyword, replacement, caseSensitive, isRegex); } code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc); } } catch (Exception exc) { throw new Exception("Error during writing of GML code to profile:\n" + exc + "\n\nCode:\n\n" + passBack); } } }
public string GetDecompiledText(string codeName) { UndertaleCode code = Data.Code.ByName(codeName); ThreadLocal <GlobalDecompileContext> DECOMPILE_CONTEXT = new ThreadLocal <GlobalDecompileContext>(() => new GlobalDecompileContext(Data, false)); try { return(code != null?Decompiler.Decompile(code, DECOMPILE_CONTEXT.Value) : ""); } catch (Exception e) { return("/*\nDECOMPILER FAILED!\n\n" + e.ToString() + "\n*/"); } }
/// <param name="indent">How much to indent the decompiled result /// /// </param> /// <param name="flags">Flags specifying format of decompilation output /// </param> internal override string Decompile(int indent, int flags) { string encodedSource = EncodedSource; if (encodedSource == null) { return(base.Decompile(indent, flags)); } else { UintMap properties = new UintMap(1); properties.put(Decompiler.INITIAL_INDENT_PROP, indent); return(Decompiler.Decompile(encodedSource, flags, properties)); } }
public void DecompileAllScripts() { Parallel.ForEach(data.Code, (code) => { //Console.WriteLine(code.Name.Content); try { Decompiler.Decompile(code, data); } catch (Exception e) { throw new Exception("Failed to decompile script " + code.Name.Content, e); } }); }
private void UpdateGettext(UndertaleCode gettextCode) { gettext = new Dictionary <string, int>(); string[] DecompilationOutput; if (!SettingsWindow.ProfileModeEnabled) { DecompilationOutput = Decompiler.Decompile(gettextCode, new DecompileContext(null, true)).Replace("\r\n", "\n").Split('\n'); } else { try { string path = Path.Combine(TempPath, gettextCode.Name.Content + ".gml"); if (File.Exists(path)) { DecompilationOutput = File.ReadAllText(path).Replace("\r\n", "\n").Split('\n'); } else { DecompilationOutput = Decompiler.Decompile(gettextCode, new DecompileContext(null, true)).Replace("\r\n", "\n").Split('\n'); } } catch { DecompilationOutput = Decompiler.Decompile(gettextCode, new DecompileContext(null, true)).Replace("\r\n", "\n").Split('\n'); } } foreach (var line in DecompilationOutput) { Match m = Regex.Match(line, "^ds_map_add\\(global.text_data_en, \"(.*)\"@([0-9]+), \"(.*)\"@([0-9]+)\\)"); if (m.Success) { try { gettext.Add(m.Groups[1].Value, Int32.Parse(m.Groups[4].Value)); } catch (ArgumentException) { MessageBox.Show("There is a duplicate key in textdata_en. This may cause errors in the comment display of text.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch { MessageBox.Show("Unknown error in textdata_en. This may cause errors in the comment display of text.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } } }
public void ReplaceTextInGML(UndertaleCode code, string keyword, string replacement, bool case_sensitive = false, bool isRegex = false, GlobalDecompileContext context = null) { EnsureDataLoaded(); string passBack = ""; string codeName = code.Name.Content; GlobalDecompileContext DECOMPILE_CONTEXT = context is null ? new(Data, false) : context; if (Data.ToolInfo.ProfileMode == false || Data.GMS2_3) { try { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, DECOMPILE_CONTEXT) : ""), keyword, replacement, case_sensitive, isRegex); code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } else if (Data.ToolInfo.ProfileMode && !Data.GMS2_3) { try { try { if (context is null) { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, new GlobalDecompileContext(Data, false)) : ""), keyword, replacement, case_sensitive, isRegex); } else { passBack = GetPassBack((code != null ? Decompiler.Decompile(code, context) : ""), keyword, replacement, case_sensitive, isRegex); } code.ReplaceGML(passBack, Data); } catch (Exception exc) { throw new Exception("Error during GML code replacement:\n" + exc.ToString()); } } catch (Exception exc) { throw new Exception("Error during writing of GML code to profile:\n" + exc.ToString() + "\n\nCode:\n\n" + passBack); } } }
private static void Decompile(string path, bool print = false) { Decompiler decompiler = new Decompiler(path); var result = decompiler.Decompile(); if (print) { Console.WriteLine("// File: " + path); Console.WriteLine(result); Console.WriteLine(); } else { path = Path.ChangeExtension(path, Path.GetExtension(path) == ".tjs" ? ".dec.tjs" : ".tjs"); File.WriteAllText(path, result); } }
/// <summary> /// Arguments to Run /// /a:Path to assembly file to decompile /// /o:Path to JSON file to create /// </summary> /// <param name="args"></param> static void Main(string[] args) { ArgsHelper oArgsHelp = new ArgsHelper(args); System.ApplicationException ex = new System.ApplicationException(ERROR_MSG); if (args.Count() == 0) { throw ex; } string AssemblyFileAndPath = oArgsHelp["a"]; string OutPutPath = oArgsHelp["o"]; Decompiler decompiler = new Decompiler(AssemblyFileAndPath, OutPutPath); decompiler.Decompile(); }
public void LoadMsi(WixSettings settings) { decompiler.ContinueOnError = !settings.QuitOnError; decompiler.SkipUI = settings.SkipUI; decompiler.SkipVSI = settings.SkipVSI; decompiler.ProcessUIOnly = settings.ProcessUIOnly; decompiler.SkipSequenceTables = settings.SkipSequenceTables; decompiler.SkipSummaryInfo = settings.SkipSummaryInfo; decompiler.Unicode = settings.Unicode; decompiler.ExportBinaries = settings.ExportBinaries; decompiler.IsMergeModule = settings.IsMergeModule; decompiler.KeepEmptyTables = settings.KeepEmptyTables; string temporary = Path.GetFileNameWithoutExtension(settings.FileName) + ".wix"; decompiler.Decompile(settings.FileName, temporary); LoadWix(temporary); }
public void LoadPlayerAJ(string fname) { DialogResult dialogResult = MessageBox.Show("Import Animations?", "Animation Import", MessageBoxButtons.YesNo); if (dialogResult != DialogResult.Yes) { return; } FileData d = new FileData(fname); //Extract All Animations from the AJ file DATRoot r = new DATRoot(); r.Text = Path.GetFileNameWithoutExtension(fname); DatFile.AddRoot(r); FileData f = new FileData(fname); while (f.Pos() < f.Eof()) { int size = f.ReadInt(); byte[] data = f.GetSection(f.Pos() - 4, size); f.Skip(size - 4); f.Align(0x20); DATFile datfile = Decompiler.Decompile(data); datfile.Roots[0].Animations[0].Text = datfile.Roots[0].Text; r.Animations.Add(datfile.Roots[0].Animations[0]); } /*foreach (DATRoot root in DatFile.Roots) * { * if(root.FighterData.Count > 0) * foreach (DatFighterScript script in root.FighterData[0].Scripts) * { * if(script.AnimationOffset != 0) * { * DATFile datfile = Decompiler.Decompile(d.getSection(script.AnimationOffset, script.AnimationSize)); * datfile.Roots[0].Animations[0].Text = script.Text; * r.Animations.Add(datfile.Roots[0].Animations[0]); * } * } * }*/ }
public void Test() { Decompiler dc = new Decompiler(); dc.Decompile(); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Decompiler decompiler = null; Mutator mutator = null; Unbinder unbinder = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } if (null == this.inputFile) { this.showHelp = true; } else if (null == this.outputFile) { if (null == this.outputDirectory) { this.outputFile = Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs"); } else { this.outputFile = Path.Combine(this.outputDirectory, Path.ChangeExtension(Path.GetFileName(this.inputFile), ".wxs")); } } if (this.showLogo) { AppCommon.DisplayToolHeader(); } if (this.showHelp) { Console.WriteLine(DarkStrings.HelpMessage); AppCommon.DisplayToolFooter(); return this.messageHandler.LastErrorNumber; } foreach (string parameter in this.invalidArgs) { this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter)); } this.invalidArgs = null; // create the decompiler and mutator decompiler = new Decompiler(); mutator = new Mutator(); mutator.Core = new HarvesterCore(new MessageEventHandler(this.messageHandler.Display)); unbinder = new Unbinder(); // read the configuration file (dark.exe.config) AppCommon.ReadConfiguration(this.extensionList); // load any extensions foreach (string extension in this.extensionList) { WixExtension wixExtension = WixExtension.Load(extension); decompiler.AddExtension(wixExtension); unbinder.AddExtension(wixExtension); } // set options decompiler.SuppressCustomTables = this.suppressCustomTables; decompiler.SuppressDroppingEmptyTables = this.suppressDroppingEmptyTables; decompiler.SuppressRelativeActionSequencing = this.suppressRelativeActionSequencing; decompiler.SuppressUI = this.suppressUI; decompiler.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); if (!String.IsNullOrEmpty(this.exportBasePath)) { decompiler.ExportFilePath = this.exportBasePath; } unbinder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); decompiler.Message += new MessageEventHandler(this.messageHandler.Display); unbinder.Message += new MessageEventHandler(this.messageHandler.Display); // print friendly message saying what file is being decompiled Console.WriteLine(Path.GetFileName(this.inputFile)); // unbind // TODO: passing a bundle to the decompiler without the /x parameter specified stumbles here // as the exportBasePath will be null. Need a design decision whether to throw an // message below or throw a message here Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath); if (null != output) { if (OutputType.Patch == this.outputType || OutputType.Transform == this.outputType || this.outputXml) { output.Save(this.outputFile, null, new WixVariableResolver(), null); } else // decompile { Wix.Wix wix = decompiler.Decompile(output); // output if (null != wix) { XmlTextWriter writer = null; // mutate the Wix document if (!mutator.Mutate(wix)) { return this.messageHandler.LastErrorNumber; } try { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(this.outputFile))); writer = new XmlTextWriter(this.outputFile, System.Text.Encoding.UTF8); writer.Indentation = 4; writer.IndentChar = ' '; writer.QuoteChar = '"'; writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); wix.OutputXml(writer); writer.WriteEndDocument(); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.FileWriteError(this.outputFile, e.Message)); return this.messageHandler.LastErrorNumber; } finally { if (null != writer) { writer.Close(); } } } } } } catch (WixException we) { this.messageHandler.Display(this, we.Error); } catch (Exception e) { this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != decompiler) { if (this.tidy) { if (!decompiler.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, decompiler.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, decompiler.TempFilesLocation); } } if (null != unbinder) { if (this.tidy) { if (!unbinder.DeleteTempFiles()) { Console.WriteLine(DarkStrings.WAR_FailedToDeleteTempDir, unbinder.TempFilesLocation); } } else { Console.WriteLine(DarkStrings.INF_TempDirLocatedAt, unbinder.TempFilesLocation); } } } return this.messageHandler.LastErrorNumber; }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> public int Run(string[] args) { try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.FoundError) { return this.messageHandler.PostProcess(); } if (null == this.inputFile) { this.showHelp = true; } if (this.showLogo) { Assembly darkAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Decompiler Version {0}", darkAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved.\n"); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: dark [-?] [-x basePath] msiFileName xmlFileName"); Console.WriteLine(); Console.WriteLine(" --Convert a Windows Installer database to an XML installation manifest --"); Console.WriteLine(" 1st argument is path to the MSI database to query"); Console.WriteLine(" 2nd argument is path to the XML manifest to create"); Console.WriteLine(); Console.WriteLine(" case-insensitive option arguments may be specified in any order:"); Console.WriteLine(" /s or -s exclude standard sequence actions, process Custom and dialogs"); Console.WriteLine(" /p or -p exclude Package element generation from summary information"); Console.WriteLine(" /n or -n no UI elements processed"); Console.WriteLine(" /ui or -ui only UI elements processed"); Console.WriteLine(" /ext extension (class, assembly), should extend CompilerExtension"); Console.WriteLine(" /x <path> or -x <path> export binary streams from Binary and Icon tables to path"); Console.WriteLine(" /m or -m merge module"); Console.WriteLine(" /notidy or -notidy Do not delete temporary files (for checking results)"); Console.WriteLine(" /e or -e include empty tables"); Console.WriteLine(" /f or -f generate many fragment files via internal heuristic"); Console.WriteLine(" /g or -g generate single monolithic fragment"); Console.WriteLine(" /wx or -wx treat warnings as errors"); Console.WriteLine(" /w<N> or -w<N> set the warning level (0: show all, 3: show none)"); Console.WriteLine(" /sw or -sw suppress all warnings (same as -w3)"); Console.WriteLine(" /sw<N> or -sw<N> suppress warning with specific message ID"); Console.WriteLine(" /v or -v verbose output (same as -v2)"); Console.WriteLine(" /v<N> or -v<N> sets the level of verbose output (0: most output, 3: none)"); Console.WriteLine(" /vsi or -vsi filter out problematic Visual Studio Installer constructs"); Console.WriteLine(" /is or -is filter out problematic InstallShield constructs"); Console.WriteLine(" /nologo or -nologo skip printing dark logo information"); Console.WriteLine(" /z or -z write explicit sequence numbers (no relative references)"); Console.WriteLine(" /? or -? show this help info, same as if no arguments supplied"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(" CONVERTING FROM MSI to WiX"); Console.WriteLine(); Console.WriteLine(" In general, WiX does a good job of validating your Xml source code."); Console.WriteLine(" Therefore, you will encounter logical errors -- invalid attributes, for"); Console.WriteLine(" example -- that were ignored by MSI but will need to be fixed for WiX. "); Console.WriteLine(); return this.messageHandler.PostProcess(); } // print friendly message saying what file is being compiled Console.WriteLine(this.inputFile); // create the decompiler Decompiler decompiler = new Decompiler(); // load any extensions foreach (string extension in this.extensionList) { Type extensionType = Type.GetType(extension); if (null == extensionType) { throw new WixInvalidExtensionException(extension); } if (extensionType.IsSubclassOf(typeof(DecompilerExtension))) { DecompilerExtension decompilerExtensionObject = Activator.CreateInstance(extensionType) as DecompilerExtension; decompiler.AddExtension(decompilerExtensionObject); } if (!extensionType.IsSubclassOf(typeof(DecompilerExtension))) { throw new WixInvalidExtensionException(extension); } } // Set the Properties decompiler.SkipUI = this.skipUI; decompiler.SkipVSI = this.skipVSI; decompiler.SkipInstallShield = this.skipInstallShield; decompiler.ProcessUIOnly = this.processUIOnly; decompiler.SkipSequenceTables = this.skipSequenceTables; decompiler.ExplicitSequenceTables = this.explicitSequenceTables; decompiler.SkipSummaryInfo = this.skipSummaryInfo; decompiler.ExportBinaries = this.exportBinaries; decompiler.IsMergeModule = this.processingModule; decompiler.IsFragmentContainer = this.processingFragment; decompiler.GenerateFragments = this.generateFragments; decompiler.KeepEmptyTables = this.keepEmptyTables; decompiler.AddComments = this.addComments; decompiler.ExportBasePath = this.basePath; decompiler.Tidy = this.tidy; decompiler.Message += new MessageEventHandler(this.messageHandler.Display); // and now we do what we came here to do... decompiler.Decompile(this.inputFile, this.outputFile); } catch (WixException we) { // TODO: once all WixExceptions are converted to errors, this clause // should be a no-op that just catches WixFatalErrorException's this.messageHandler.Display("dark.exe", "DARK", we); return 1; } catch (Exception e) { this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } return this.messageHandler.PostProcess(); }