public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
 {
     this.methodContext = context.MethodContext;
     mappedInstructions.UnionWith(body.UnderlyingSameMethodInstructions);
     Visit(body);
     return body;
 }
        public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
        {
            HashSet<Instruction> mappedInstructions = new HashSet<Instruction>(body.UnderlyingSameMethodInstructions);
            if (context.MethodContext.IsMethodBodyChanged)
            {
                context.MethodContext.Method.RefreshBody();
                context.MethodContext.IsMethodBodyChanged = false;
            }

            List<Instruction> unmappedInstructions = new List<Instruction>();
            foreach (Instruction instruction in context.MethodContext.Method.Body.Instructions)
            {
                if (!mappedInstructions.Contains(instruction))
                {
                    unmappedInstructions.Add(instruction);
                }
            }

            if (unmappedInstructions.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder("Found unmapped instructions.\n");
                foreach (Instruction unmappedInstruction in unmappedInstructions)
                {
                    stringBuilder.AppendLine(unmappedInstruction.ToString());
                }
                throw new Exception(stringBuilder.ToString());
            }

            return body;
        }
 public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
 {
     Visit(body);
     List<Instruction> instructions = new List<Instruction>(body.UnderlyingSameMethodInstructions);
     List<Instruction> nonUniques = GetNonUniqueInstructions(instructions);
     if (nonUniques.Count > 0)
     {
         throw new Exception("Instruction duplication detected after: " + previousStep);
     }
     return body;
 }
        public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
        {
            if (!new ExpressionTreesFinder().ContainsExpressionTree(body))
            {
                return body;
            }

            this.context = context;
            this.typeSystem = context.TypeContext.CurrentType.Module.TypeSystem;
            this.failure = false;
            BlockStatement clone = (BlockStatement)Visit(body.Clone());
            if (failure || usedVariables.Count == 0 || !TryRemoveUnusedVariableAssignments(clone))
            {
                return body;
            }
            clone = (BlockStatement)new ClosureVariablesRemover(context.MethodContext).Visit(clone);
            clone = new CombinedTransformerStep(){ Method = context.MethodContext.Method }.Process(context, clone);
            return clone;
        }
예제 #5
0
 public bool OpenBinaryAs(string file, Decompiler.Core.IProcessorArchitecture arch, Decompiler.Core.Platform platform, Decompiler.Core.Address addrBase, DecompilerHost host)
 {
     throw new NotImplementedException();
 }
예제 #6
0
 public bool QueryStatus(CommandID cmdId, Decompiler.Gui.CommandStatus status, Decompiler.Gui.CommandText text)
 {
     return false;
 }
예제 #7
0
        public override Operation Process(Decompiler d)
        {
            if (m_empty)
            {
                var expr = m_r.GetExpression(Branch.SetTarget, End);
                Branch.UseExpression(expr);

                return(new RegisterSet(End - 1, Branch.SetTarget, Branch.AsExpression(m_r)));
            }
            else if (m_assign != null)
            {
                Branch.UseExpression(m_assign.GetFirstValue());

                var target = m_assign.GetFirstTarget();
                var value  = GetValue();

                return(new LambdaOperation(End - 1, (r, block) => {
                    return new Assignment(target, value);
                }));
            }
            else
            {
                return(new LambdaOperation(End - 1, (r, block) => {
                    Expression expr = null;

                    var register = 0;

                    for (; register < r.NumRegisters; register++)
                    {
                        if (r.GetUpdated(register, Branch.End - 1) == Branch.End - 1)
                        {
                            expr = r.GetValue(register, Branch.End);
                            break;
                        }
                    }

                    if (d.Code.Op(Branch.End - 2) == Op.LOADBOOL &&
                        d.Code.C(Branch.End - 2) != 0)
                    {
                        var target = d.Code.A(Branch.End - 2);

                        if (d.Code.Op(Branch.End - 3) == Op.JMP &&
                            d.Code.sBx(Branch.End - 3) == 2)
                        {
                            expr = r.GetValue(target, Branch.End - 2);
                        }
                        else
                        {
                            expr = r.GetValue(target, Branch.Begin);
                        }

                        Branch.UseExpression(expr);

                        if (r.IsLocal(target, Branch.End - 1))
                        {
                            return new Assignment(r.GetTarget(target, Branch.End - 1), Branch.AsExpression(r));
                        }

                        r.SetValue(target, Branch.End - 1, Branch.AsExpression(r));
                    }
                    else if (expr != null && Target >= 0)
                    {
                        Branch.UseExpression(expr);

                        if (r.IsLocal(Target, Branch.End - 1))
                        {
                            return new Assignment(r.GetTarget(Target, Branch.End - 1), Branch.AsExpression(r));
                        }

                        r.SetValue(Target, Branch.End - 1, Branch.AsExpression(r));
                    }
                    else
                    {
                        Console.WriteLine("-- fail " + (Branch.End - 1));
                        Console.WriteLine(expr);
                        Console.WriteLine(Target);
                    }

                    return null;
                }));
            }
        }
 public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
 {
     body = (BlockStatement)new LinqQueriesRebuilder(context.MethodContext).Visit(body);
     return body;
 }
예제 #9
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                PrintVersion(true);
                PrintError("no input file provided");
                PrintUsage(true);

                Environment.Exit(1);
            }
            else
            {
                var       fn    = args[0];
                LFunction lMain = null;

                //Console.BufferHeight = 2500;

                /* Error Levels
                 *
                 * 0 - Successfully decompiled file
                 * 1 - An error occurred while processing the input file
                 * 2 - The specified output file could not be created
                 */

                try
                {
                    lMain = FileToFunction(fn);
                }
                catch (Exception e)
                {
                    PrintVersion(true);
                    PrintError(e.Message);

                    Environment.Exit(1);
                }

                var d = new Decompiler(lMain);

                d.Decompile();

                var writeLog = true;

                if (args.Length > 1)
                {
                    // skip first arg
                    for (int i = 1; i < args.Length; i++)
                    {
                        var arg = args[i];

                        if (arg.StartsWith("-"))
                        {
                            switch (arg.ToLower().TrimStart('-'))
                            {
                            case "nolog":
                                writeLog = false;
                                continue;

                            default:
                                // just ignore it
                                if (writeLog)
                                {
                                    Console.WriteLine("unknown argument '{0}'", arg);
                                }
                                continue;
                            }
                        }
                        else
                        {
                            /** PROGRAM MUST TERMINATE ONCE FINISHED **/
                            var filename = arg;

                            try
                            {
                                using (var writer = new StreamWriter(filename))
                                {
                                    d.Print(new Output(writer));

                                    writer.Flush();

                                    if (writeLog)
                                    {
                                        Console.WriteLine("successfully decompiled to '{0}'", filename);
                                    }

                                    Environment.Exit(0);
                                }
                            }
                            catch (Exception e)
                            {
                                PrintVersion(true);
                                PrintError(e.Message);

                                Environment.Exit(2);
                            }
                            /** PROGRAM MUST BE TERMINATED BY THIS POINT **/
                        }
                    }
                }

                // no output file was specified, spit out to console
                d.Print();

                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.ReadKey();
                }

                Environment.Exit(0);
            }
        }
        private async void DecompileCode(UndertaleCode code)
        {
            LoaderDialog dialog = new LoaderDialog("Decompiling", "Decompiling, please wait... This can take a while on complex scripts");

            dialog.Owner = Window.GetWindow(this);

            FlowDocument document = new FlowDocument();

            document.PagePadding = new Thickness(0);
            document.FontFamily  = new FontFamily("Lucida Console");
            Paragraph par = new Paragraph();

            UndertaleCode gettextCode = null;

            if (gettext == null)
            {
                gettextCode = (Application.Current.MainWindow as MainWindow).Data.Code.ByName("gml_Script_textdata_en");
            }

            string gettextJsonPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName((Application.Current.MainWindow as MainWindow).FilePath), "lang/lang_en.json");

            var  dataa = (Application.Current.MainWindow as MainWindow).Data;
            Task t     = Task.Run(() =>
            {
                string decompiled = null;
                Exception e       = null;
                try
                {
                    decompiled = Decompiler.Decompile(code, dataa).Replace("\r\n", "\n");
                }
                catch (Exception ex)
                {
                    e = ex;
                }

                if (gettextCode != null)
                {
                    UpdateGettext(gettextCode);
                }

                if (gettextJSON == null && File.Exists(gettextJsonPath))
                {
                    UpdateGettextJSON(File.ReadAllText(gettextJsonPath));
                }

                Dispatcher.Invoke(() =>
                {
                    if (e != null)
                    {
                        Brush exceptionBrush = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                        par.Inlines.Add(new Run("EXCEPTION!\n")
                        {
                            Foreground = exceptionBrush, FontWeight = FontWeights.Bold
                        });
                        par.Inlines.Add(new Run(e.ToString())
                        {
                            Foreground = exceptionBrush
                        });
                    }
                    else if (decompiled != null)
                    {
                        string[] lines = decompiled.Split('\n');
                        if (lines.Length > 5000)
                        {
                            par.Inlines.Add(new Run(decompiled));
                        }
                        else
                        {
                            Brush keywordBrush = new SolidColorBrush(Color.FromRgb(0, 0, 150));
                            Brush stringBrush  = new SolidColorBrush(Color.FromRgb(0, 0, 200));
                            Brush commentBrush = new SolidColorBrush(Color.FromRgb(0, 150, 0));
                            Brush funcBrush    = new SolidColorBrush(Color.FromRgb(100, 100, 0));
                            Brush assetBrush   = new SolidColorBrush(Color.FromRgb(0, 150, 100));

                            Dictionary <string, UndertaleFunction> funcs = new Dictionary <string, UndertaleFunction>();
                            foreach (var x in (Application.Current.MainWindow as MainWindow).Data.Functions)
                            {
                                funcs.Add(x.Name.Content, x);
                            }

                            foreach (var line in lines)
                            {
                                char[] special = { '.', ',', ')', '(', '[', ']', '>', '<', ':', ';', '=', '"' };
                                Func <char, bool> IsSpecial = (c) => Char.IsWhiteSpace(c) || special.Contains(c);
                                List <string> split         = new List <string>();
                                string tok         = "";
                                bool readingString = false;
                                for (int i = 0; i < line.Length; i++)
                                {
                                    if (tok == "//")
                                    {
                                        tok += line.Substring(i);
                                        break;
                                    }
                                    if (!readingString && tok.Length > 0 && (
                                            (Char.IsWhiteSpace(line[i]) != Char.IsWhiteSpace(tok[tok.Length - 1])) ||
                                            (special.Contains(line[i]) != special.Contains(tok[tok.Length - 1])) ||
                                            (special.Contains(line[i]) && special.Contains(tok[tok.Length - 1])) ||
                                            line[i] == '"'
                                            ))
                                    {
                                        split.Add(tok);
                                        tok = "";
                                    }
                                    tok += line[i];
                                    if (line[i] == '"')
                                    {
                                        if (readingString)
                                        {
                                            split.Add(tok);
                                            tok = "";
                                        }
                                        readingString = !readingString;
                                    }
                                }
                                if (tok != "")
                                {
                                    split.Add(tok);
                                }

                                Dictionary <string, object> usedObjects = new Dictionary <string, object>();
                                for (int i = 0; i < split.Count; i++)
                                {
                                    string token = split[i];
                                    if (token == "if" || token == "else" || token == "return" || token == "break" || token == "continue" || token == "while" || token == "with" || token == "switch" || token == "case" || token == "default")
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = keywordBrush, FontWeight = FontWeights.Bold
                                        });
                                    }
                                    else if (token == "self" || token == "global" || token == "local" || token == "other" || token == "noone" || token == "true" || token == "false")
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = keywordBrush
                                        });
                                    }
                                    else if (token.StartsWith("\""))
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = stringBrush
                                        });
                                    }
                                    else if (token.StartsWith("//"))
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = commentBrush
                                        });
                                    }
                                    else if (token.StartsWith("@") && split[i - 1][0] == '"' && split[i - 1][split[i - 1].Length - 1] == '"')
                                    {
                                        par.Inlines.LastInline.Cursor     = Cursors.Hand;
                                        par.Inlines.LastInline.MouseDown += (sender, ev) =>
                                        {
                                            MainWindow mw = Application.Current.MainWindow as MainWindow;
                                            mw.ChangeSelection(mw.Data.Strings[Int32.Parse(token.Substring(1))]);
                                        };
                                    }
                                    else if (dataa.ByName(token) != null)
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = assetBrush, Cursor = Cursors.Hand
                                        });
                                        par.Inlines.LastInline.MouseDown += (sender, ev) => (Application.Current.MainWindow as MainWindow).ChangeSelection(dataa.ByName(token));
                                        if (token == "scr_gettext" && gettext != null)
                                        {
                                            if (split[i + 1] == "(" && split[i + 2].StartsWith("\"") && split[i + 3].StartsWith("@") && split[i + 4] == ")")
                                            {
                                                string id = split[i + 2].Substring(1, split[i + 2].Length - 2);
                                                if (!usedObjects.ContainsKey(id))
                                                {
                                                    usedObjects.Add(id, (Application.Current.MainWindow as MainWindow).Data.Strings[gettext[id]]);
                                                }
                                            }
                                        }
                                        if (token == "scr_84_get_lang_string" && gettextJSON != null)
                                        {
                                            if (split[i + 1] == "(" && split[i + 2].StartsWith("\"") && split[i + 3].StartsWith("@") && split[i + 4] == ")")
                                            {
                                                string id = split[i + 2].Substring(1, split[i + 2].Length - 2);
                                                if (!usedObjects.ContainsKey(id))
                                                {
                                                    usedObjects.Add(id, gettextJSON[id]);
                                                }
                                            }
                                        }
                                    }
                                    else if (funcs.ContainsKey(token))
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Foreground = funcBrush, Cursor = Cursors.Hand
                                        });
                                        par.Inlines.LastInline.MouseDown += (sender, ev) => (Application.Current.MainWindow as MainWindow).ChangeSelection(funcs[token]);
                                    }
                                    else if (Char.IsDigit(token[0]))
                                    {
                                        par.Inlines.Add(new Run(token)
                                        {
                                            Cursor = Cursors.Hand
                                        });
                                        par.Inlines.LastInline.MouseDown += (sender, ev) =>
                                        {
                                            // TODO: Add type resolving to the decompiler so that this is handled mostly automatically

                                            UndertaleData data = (Application.Current.MainWindow as MainWindow).Data;
                                            int id             = Int32.Parse(token);
                                            List <UndertaleObject> possibleObjects = new List <UndertaleObject>();
                                            if (id < data.Sprites.Count)
                                            {
                                                possibleObjects.Add(data.Sprites[id]);
                                            }
                                            if (id < data.Rooms.Count)
                                            {
                                                possibleObjects.Add(data.Rooms[id]);
                                            }
                                            if (id < data.GameObjects.Count)
                                            {
                                                possibleObjects.Add(data.GameObjects[id]);
                                            }
                                            if (id < data.Backgrounds.Count)
                                            {
                                                possibleObjects.Add(data.Backgrounds[id]);
                                            }
                                            if (id < data.Scripts.Count)
                                            {
                                                possibleObjects.Add(data.Scripts[id]);
                                            }
                                            if (id < data.Paths.Count)
                                            {
                                                possibleObjects.Add(data.Paths[id]);
                                            }
                                            if (id < data.Fonts.Count)
                                            {
                                                possibleObjects.Add(data.Fonts[id]);
                                            }
                                            if (id < data.Sounds.Count)
                                            {
                                                possibleObjects.Add(data.Sounds[id]);
                                            }
                                            if (id < data.Shaders.Count)
                                            {
                                                possibleObjects.Add(data.Shaders[id]);
                                            }
                                            // if (id < data.Extensions.Count)
                                            //    possibleObjects.Add(data.Extensions[id]);
                                            if (id < data.Timelines.Count)
                                            {
                                                possibleObjects.Add(data.Timelines[id]);
                                            }

                                            ContextMenu contextMenu = new ContextMenu();
                                            foreach (UndertaleObject obj in possibleObjects)
                                            {
                                                MenuItem item = new MenuItem();
                                                item.Header   = obj.ToString().Replace("_", "__");
                                                item.Click   += (sender2, ev2) => (Application.Current.MainWindow as MainWindow).ChangeSelection(obj);
                                                contextMenu.Items.Add(item);
                                            }
                                            if (id > 0x00050000)
                                            {
                                                contextMenu.Items.Add(new MenuItem()
                                                {
                                                    Header = "#" + id.ToString("X6") + " (color)", IsEnabled = false
                                                });
                                            }
                                            contextMenu.Items.Add(new MenuItem()
                                            {
                                                Header = id + " (number)", IsEnabled = false
                                            });
                                            (sender as Run).ContextMenu = contextMenu;
                                            contextMenu.IsOpen          = true;
                                            ev.Handled = true;
                                        };
                                    }
                                    else
                                    {
                                        par.Inlines.Add(new Run(token));
                                    }

                                    if (token == "." && (Char.IsLetter(split[i + 1][0]) || split[i + 1][0] == '_'))
                                    {
                                        int id;
                                        if (Int32.TryParse(split[i - 1], out id))
                                        {
                                            var gos = (Application.Current.MainWindow as MainWindow).Data.GameObjects;
                                            if (!usedObjects.ContainsKey(split[i - 1]) && id >= 0 && id < gos.Count)
                                            {
                                                usedObjects.Add(split[i - 1], gos[id]);
                                            }
                                        }
                                    }
                                }
                                foreach (var gt in usedObjects)
                                {
                                    par.Inlines.Add(new Run(" // ")
                                    {
                                        Foreground = commentBrush
                                    });
                                    par.Inlines.Add(new Run(gt.Key)
                                    {
                                        Foreground = commentBrush
                                    });
                                    par.Inlines.Add(new Run(" = ")
                                    {
                                        Foreground = commentBrush
                                    });
                                    par.Inlines.Add(new Run(gt.Value is string? "\"" + (string)gt.Value + "\"" : gt.Value.ToString())
                                    {
                                        Foreground = commentBrush, Cursor = Cursors.Hand
                                    });
                                    if (gt.Value is UndertaleObject)
                                    {
                                        par.Inlines.LastInline.MouseDown += (sender, ev) => (Application.Current.MainWindow as MainWindow).ChangeSelection(gt.Value);
                                    }
                                }
                                par.Inlines.Add(new Run("\n"));
                            }
                        }
                    }

                    document.Blocks.Add(par);
                    DecompiledView.Document = document;
                    CurrentDecompiled       = code;
                    dialog.Hide();
                });
            });

            dialog.ShowDialog();
            await t;
        }
예제 #11
0
        /// <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();
        }
예제 #12
0
 protected override string GetNameInternal()
 {
     return(Decompiler.GetModuleName(AssemblyPath, TokenId));
 }
예제 #13
0
 public void Indexers()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "Indexers"));
 }
예제 #14
0
 public void InterfaceBadAttributes()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "InterfaceBadAttributes"));
 }
예제 #15
0
 public void GenericClass()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "GenericClass`1"));
 }
예제 #16
0
 public void ClassWithPrivateMethodNoAssert()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "ClassWithPrivateMethod"));
 }
예제 #17
0
 public void ClassWithBadAttributes()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "ClassWithBadAttributes"));
 }
        /// <summary>
        /// Extracts files from a merge module and creates corresponding ComponentGroup WiX authoring.
        /// </summary>
        private void MeltModule()
        {
            Decompiler decompiler = null;
            Unbinder   unbinder   = null;
            Melter     melter     = null;

            try
            {
                // create the decompiler, unbinder, and melter
                decompiler = new Decompiler();
                unbinder   = new Unbinder();
                melter     = new Melter(decompiler, id);

                // read the configuration file (melt.exe.config)
                AppCommon.ReadConfiguration(this.extensionList);

                // load all extensions
                ExtensionManager extensionManager = new ExtensionManager();
                foreach (string extension in this.extensionList)
                {
                    extensionManager.Load(extension);
                }

                foreach (IDecompilerExtension extension in extensionManager.Create <IDecompilerExtension>())
                {
                    decompiler.AddExtension(extension);
                }

                foreach (IUnbinderExtension extension in extensionManager.Create <IUnbinderExtension>())
                {
                    unbinder.AddExtension(extension);
                }

                // set options
                decompiler.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP");

                unbinder.TempFilesLocation        = Environment.GetEnvironmentVariable("WIX_TEMP");
                unbinder.SuppressDemodularization = true;

                // print friendly message saying what file is being decompiled
                Console.WriteLine(Path.GetFileName(this.inputFile));

                // unbind
                Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath);

                if (null != output)
                {
                    Wix.Wix wix = melter.Melt(output);
                    if (null != wix)
                    {
                        XmlTextWriter writer = null;

                        try
                        {
                            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();
                        }
                        finally
                        {
                            if (null != writer)
                            {
                                writer.Close();
                            }
                        }
                    }
                }
            }
            finally
            {
                if (null != decompiler)
                {
                    if (this.tidy)
                    {
                        if (!decompiler.DeleteTempFiles())
                        {
                            Console.Error.WriteLine(MeltStrings.WAR_FailedToDeleteTempDir, decompiler.TempFilesLocation);
                        }
                    }
                    else
                    {
                        Console.WriteLine(MeltStrings.INF_TempDirLocatedAt, decompiler.TempFilesLocation);
                    }
                }

                if (null != unbinder)
                {
                    if (this.tidy)
                    {
                        if (!unbinder.DeleteTempFiles())
                        {
                            Console.Error.WriteLine(MeltStrings.WAR_FailedToDeleteTempDir, unbinder.TempFilesLocation);
                        }
                    }
                    else
                    {
                        Console.WriteLine(MeltStrings.INF_TempDirLocatedAt, unbinder.TempFilesLocation);
                    }
                }
            }
        }
예제 #19
0
 protected override AccessModifier GetAccessModifier()
 {
     return(Decompiler.GetTypeAccessModifier(AssemblyPath, Module.TokenId, TokenId));
 }
예제 #20
0
 public void SimpleClassNoAssert()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "SimpleClass"));
 }
예제 #21
0
        private async void DecompileCode(UndertaleCode code)
        {
            DecompiledEditor.IsReadOnly = true;
            if (code.DuplicateEntry)
            {
                DecompiledEditor.Text = "// Duplicate code entry; cannot edit here.";
                CurrentDecompiled     = code;
            }
            else
            {
                LoaderDialog dialog = new LoaderDialog("Decompiling", "Decompiling, please wait... This can take a while on complex scripts");
                dialog.Owner = Window.GetWindow(this);
                _            = Dispatcher.BeginInvoke(new Action(() => { if (!dialog.IsClosed)
                                                                         {
                                                                             dialog.ShowDialog();
                                                                         }
                                                                 }));

                UndertaleCode gettextCode = null;
                if (gettext == null)
                {
                    gettextCode = (Application.Current.MainWindow as MainWindow).Data.Code.ByName("gml_Script_textdata_en");
                }

                string dataPath        = Path.GetDirectoryName((Application.Current.MainWindow as MainWindow).FilePath);
                string gettextJsonPath = (dataPath != null) ? Path.Combine(dataPath, "lang", "lang_en.json") : null;

                var  dataa = (Application.Current.MainWindow as MainWindow).Data;
                Task t     = Task.Run(() =>
                {
                    DecompileContext context = new DecompileContext(dataa, false);
                    string decompiled        = null;
                    Exception e = null;
                    try
                    {
                        string path = Path.Combine(TempPath, code.Name.Content + ".gml");
                        if (!SettingsWindow.ProfileModeEnabled || !File.Exists(path))
                        {
                            decompiled = Decompiler.Decompile(code, context).Replace("\r\n", "\n");
                        }
                        else
                        {
                            decompiled = File.ReadAllText(path).Replace("\r\n", "\n");
                        }
                    }
                    catch (Exception ex)
                    {
                        e = ex;
                    }

                    if (gettextCode != null)
                    {
                        UpdateGettext(gettextCode);
                    }

                    try
                    {
                        if (gettextJSON == null && gettextJsonPath != null && File.Exists(gettextJsonPath))
                        {
                            string err = UpdateGettextJSON(File.ReadAllText(gettextJsonPath));
                            if (err != null)
                            {
                                e = new Exception(err);
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.ToString());
                    }

                    if (gettextJSON == null && gettextJsonPath != null && File.Exists(gettextJsonPath))
                    {
                        string err = UpdateGettextJSON(File.ReadAllText(gettextJsonPath));
                        if (err != null)
                        {
                            e = new Exception(err);
                        }
                    }

                    Dispatcher.Invoke(() =>
                    {
                        if (e != null)
                        {
                            DecompiledEditor.Text = "/* EXCEPTION!\n   " + e.ToString() + "\n*/";
                        }
                        else if (decompiled != null)
                        {
                            DecompiledEditor.Text   = decompiled;
                            CurrentDecompiledLocals = new List <string>();

                            var locals = dataa.CodeLocals.ByName(code.Name.Content);
                            if (locals != null)
                            {
                                foreach (var local in locals.Locals)
                                {
                                    CurrentDecompiledLocals.Add(local.Name.Content);
                                }
                            }
                        }
                        DecompiledEditor.IsReadOnly = false;
                        DecompiledChanged           = false;

                        CurrentDecompiled = code;
                        dialog.Hide();
                    });
                });
                await t;
                dialog.Close();
            }
        }
예제 #22
0
                /// <summary>
                /// FORMATION ISSUESSES:
                ///     1:(-> Logic remains the same)   Continue's are decompiled as Else's statements e.g.
                ///         -> Original
                ///         if( continueCondition )
                ///         {
                ///             continue;
                ///         }
                ///
                ///         // Actual code
                ///
                ///         -> Decompiled
                ///         if( continueCodition )
                ///         {
                ///         }
                ///         else
                ///         {
                ///             // Actual code
                ///         }
                ///
                ///
                ///     2:(-> ...)  ...
                ///         -> Original
                ///             ...
                ///         -> Decompiled
                ///             ...
                ///
                /// </summary>
                public override string Decompile()
                {
                    // Break offset!
                    if (CodeOffset >= Position)
                    {
                        //==================We're inside a Case and at the end of it!
                        if (Decompiler.IsInNest(NestManager.Nest.NestType.Case) != null)
                        {
                            //Decompiler._Nester.AddNestEnd( NestManager.Nest.NestType.Case, Position );
                            NoJumpLabel();
                            Commentize();
                            Decompiler._CanAddSemicolon = true;
                            return("break");
                        }

                        //==================We're inside a Default and at the end of it!
                        if (Decompiler.IsInNest(NestManager.Nest.NestType.Default) != null)
                        {
                            NoJumpLabel();
                            Commentize();
                            Decompiler._Nester.AddNestEnd(NestManager.Nest.NestType.Default, Position);
                            Decompiler._Nester.AddNestEnd(NestManager.Nest.NestType.Switch, Position);
                            Decompiler._CanAddSemicolon = true;
                            return("break");
                        }

                        var nest = Decompiler.IsWithinNest(NestManager.Nest.NestType.ForEach);
                        if (nest != null)
                        {
                            var dest = Decompiler.TokenAt(CodeOffset);
                            if (dest != null)
                            {
                                if (dest is IteratorPopToken)
                                {
                                    if (Decompiler.PreviousToken is IteratorNextToken)
                                    {
                                        NoJumpLabel();
                                        return(String.Empty);
                                    }

                                    NoJumpLabel();
                                    Commentize();
                                    Decompiler._CanAddSemicolon = true;
                                    return("break");
                                }

                                if (dest is IteratorNextToken)
                                {
                                    NoJumpLabel();
                                    Commentize();
                                    Decompiler._CanAddSemicolon = true;
                                    return("continue");
                                }
                            }
                        }

                        nest = Decompiler.IsWithinNest(NestManager.Nest.NestType.Loop);
                        if (nest != null)
                        {
                            var dest = nest.Creator as JumpToken;
                            if (dest != null)
                            {
                                if (CodeOffset + 10 == dest.CodeOffset)
                                {
                                    CommentStatement("Explicit Continue");
                                    goto gotoJump;
                                }

                                if (CodeOffset == dest.CodeOffset)
                                {
                                    CommentStatement("Explicit Break");
                                    goto gotoJump;
                                }
                            }
                        }

                        nest = Decompiler.IsInNest(NestManager.Nest.NestType.If);
                        //==================We're inside a If and at the end of it!
                        if (nest != null)
                        {
                            // We're inside a If however the kind of jump could range from: continue; break; goto; else
                            var nestEnd = Decompiler.CurNestEnd();
                            if (nestEnd != null)
                            {
                                // Else, Req:In If nest, nestends > 0, curendnest position == Position
                                if (nestEnd.Position - Size == Position)
                                {
                                    // HACK: This should be handled by UByteCodeDecompiler.Decompile()
                                    UDecompilingState.RemoveTabs(1);
                                    Decompiler._NestChain.RemoveAt(Decompiler._NestChain.Count - 1);
                                    Decompiler._Nester.Nests.Remove(nestEnd);

                                    Decompiler._Nester.AddNest(NestManager.Nest.NestType.Else, Position, CodeOffset);

                                    NoJumpLabel();

                                    // HACK: This should be handled by UByteCodeDecompiler.Decompile()
                                    return("}" + "\r\n" +
                                           (UnrealConfig.SuppressComments
                                        ? UDecompilingState.Tabs + "else"
                                        : UDecompilingState.Tabs + String.Format("// End:0x{0:X2}", CodeOffset) + "\r\n" +
                                            UDecompilingState.Tabs + "else"));
                                }
                            }
                        }
                    }

                    if (CodeOffset < Position)
                    {
                        CommentStatement("Loop Continue");
                    }
gotoJump:
                    // This is an implicit GoToToken.
                    Decompiler._CanAddSemicolon = true;
                    return(String.Format("goto J0x{0:X2}", CodeOffset));
                }
예제 #23
0
 public void SkipIXamlMetadataProvider()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "XamlMetadataProvider"));
 }
예제 #24
0
        private static void Main2(string[] args)
        {
            var tree = SyntaxTree.ParseText(@"using System;
namespace HelloWorld
{
    public class Program
    {
        public static void Tain(int x)
        {
            Console.ReadKey();
        }
    }
}");

            var mscorlib = new MetadataFileReference(
                typeof(object).Assembly.Location);

            var comp = Compilation.Create("MyCompilation", new CompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                       .AddSyntaxTrees(tree).AddReferences(mscorlib);

            var outputFileName = Path.Combine(Path.GetTempPath(), "MyCompilation.lib");
            var ilStream       = new FileStream(outputFileName, FileMode.OpenOrCreate);

            var result = comp.Emit(ilStream);

            ilStream.Close();

            using (var host = new PeReader.DefaultHost())
            {
                //Read the Metadata Model from the PE file
                var module = host.LoadUnitFrom(outputFileName) as IModule;
                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    Console.WriteLine(outputFileName + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                //Construct a Code Model from the Metadata model via decompilation
                Module decompiledModule = Decompiler.GetCodeModelFromMetadataModel(host, module, null);
                //    decompiledModule.UnitNamespaceRoot.GetMembersNamed(host.NameTable.GetNameFor("Tain"), true);
                var type = decompiledModule.AllTypes.Single(t => t.Name.Value == "Program");
                //type.Methods.Single(m=>m.)
            }

            if (result.Success)
            {
                // Run the compiled program.
                Process.Start(outputFileName);
            }
            else
            {
                foreach (var diag in result.Diagnostics)
                {
                    Console.WriteLine(diag.ToString());
                }
            }

            /*
             * var   sourceText =     @"using System;
             * using System.Collections;
             * using System.Linq;
             * using System.Text;
             *
             * namespace HelloWorld
             * {
             * class Program
             * {
             * static void Main(string[] args)
             * {
             * Console.WriteLine(""Hello, World!"");
             * }
             * }
             * }";
             *
             * SyntaxTree tree = SyntaxTree.ParseText(sourceText);
             *
             * MetadataReference mscorlib = MetadataReference.CreateAssemblyReference(
             *                               "mscorlib");
             *
             * Compilation compilation = Compilation.Create("HelloWorld", new CompilationOptions(OutputKind.ConsoleApplication))
             *              .AddReferences(mscorlib)
             *              .AddSyntaxTrees(tree);
             *
             * //Directory.CreateDirectory(@"C:\Ttemp")
             * compilation.Emit(@"C:\VisualMutatorTemp\Test.exe");*/
        }
예제 #25
0
 public void SpecialClass()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "SpecialClass"));
 }
예제 #26
0
 public Assembly Decompile(ModuleInfo module)
 {
     return(Decompiler.GetCodeModelFromMetadataModel(_host, module.Module, module.PdbReader, DecompilerOptions.None));
 }
예제 #27
0
 public void PublicNestedInsideNonPublic()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "NonPublicWithNested"));
 }
예제 #28
0
 public SetBlockOperationOther(int line, Branch _branch, Decompiler _d, int _target) : base(line)
 {
     branch = _branch;
     d      = _d;
     target = _target;
 }
예제 #29
0
 public void UnsafeClass()
 {
     Approvals.Verify(Decompiler.Decompile(AssemblyWeaver.AfterAssemblyPath, "UnsafeClass"));
 }
예제 #30
0
 public void Error(Decompiler.Core.ICodeLocation location, Exception ex, string message)
 {
 }
예제 #31
0
 public override void PerformWork(IWorkerDialogService workerDlgSvc)
 {
     workerDlgSvc.SetCaption("Generating intermediate code");
     Decompiler.AnalyzeDataFlow();
 }
 public Ast.Statements.BlockStatement Process(Decompiler.DecompilationContext context, Ast.Statements.BlockStatement body)
 {
     this.context = context;
     this.typeSystem = context.TypeContext.CurrentType.Module.TypeSystem;
     return (Telerik.JustDecompiler.Ast.Statements.BlockStatement)Visit(body);
 }
예제 #33
0
        static void Export(ExportOptions eo)
        {
            var file = Path.GetFullPath(String.IsNullOrEmpty(eo.File) ? DATA_WIN : eo.File);

            try // see #17
            {
                int i = Console.CursorLeft;
                i = i-- + 1;
            }
            catch
            {
                eo.NoPrecProg = true;
            }

            if (Directory.Exists(file) && !File.Exists(file))
            {
                file += Path.DirectorySeparatorChar + DATA_WIN;
            }
            if (!File.Exists(file))
            {
                throw new ParserException("File \"" + file + "\" not found.");
            }

            var od = (String.IsNullOrEmpty(eo.OutputDirectory) ? Path.GetDirectoryName(file) : eo.OutputDirectory) + Path.DirectorySeparatorChar;

            if (!Directory.Exists(od))
            {
                Directory.CreateDirectory(od);
            }

            using (var f = GMFile.GetFile(file))
            {
                #region defaults
                if (!(eo.Disassemble || eo.String || eo.Variables || eo.Functions ||
                      eo.Audio || eo.Background || eo.Decompile || eo.Font || eo.General ||
                      eo.Object || eo.Options || eo.Path || eo.Room || eo.Script ||
                      eo.Sound || eo.Sprite || eo.Texture || eo.TPag || eo.AudioGroups ||
                      eo.Shader || eo.ExportToProject || eo.Any || eo.DumpUnknownChunks ||
                      eo.DumpEmptyChunks || eo.DumpAllChunks))
                {
                    eo.Any = true;
                }

                if (eo.ExportToProject)
                {
                    eo.Disassemble = eo.String = eo.Variables = eo.Functions
                                                                    = eo.Audio = eo.Background = eo.Font = eo.General
                                                                                                               = eo.Object = eo.Options = eo.Path = eo.Room = eo.Script
                                                                                                                                                                  = eo.Sound = eo.Sprite = eo.Texture = eo.TPag = eo.AudioGroups
                                                                                                                                                                                                                      = eo.Shader = eo.DumpUnknownChunks = true;
                }
                if (eo.Any)
                {
                    eo.Disassemble = false;

                    eo.Audio = eo.Background = eo.Decompile = eo.Font = eo.General
                                                                            = eo.Object = eo.Options = eo.Path = eo.Room = eo.Script
                                                                                                                               = eo.Sound = eo.Sprite = eo.Texture = eo.TPag
                                                                                                                                                                         = eo.String = eo.Variables = eo.Functions = eo.DumpUnknownChunks
                                                                                                                                                                                                                         = eo.AudioGroups = eo.Shader = true;
                }
                #endregion

                eos   = eo;
                quiet = eo.Quiet;
                nopp  = eo.NoPrecProg;

                // ---
                #region GEN8
                if (eo.General && f.Content.General != null)
                {
                    WriteLine("Exporting manifest file...");

                    File.WriteAllText(od + "general.json", JsonMapper.ToJson(Serialize.SerializeGeneral(f.General)));
                }
                #endregion
                #region OPTN
                if (eo.Options && f.Content.Options != null)
                {
                    WriteLine("Exporting options...");

                    File.WriteAllText(od + "options.json", JsonMapper.ToJson(Serialize.SerializeOptions(f.Options)));
                }
                #endregion

                #region STRG
                if (eo.String && f.Strings != null)
                {
                    WriteLine("Dumping strings...");

                    File.WriteAllText(od + "strings.json", JsonMapper.ToJson(Serialize.SerializeStrings(f)));
                }
                #endregion
                #region VARI
                if (eo.Variables && f.RefData.Variables != null)
                {
                    WriteLine("Dumping variables...");

                    File.WriteAllText(od + "variables.json", JsonMapper.ToJson(Serialize.SerializeVars(f)));
                }
                #endregion
                #region FUNC
                if (eo.Functions && f.RefData.Functions != null)
                {
                    WriteLine("Dumping functions...");

                    File.WriteAllText(od + "functions.json", JsonMapper.ToJson(Serialize.SerializeFuncs(f)));
                }
                #endregion
                int cl = 0, ct = 0;
                #region AGRP
                if (eo.AudioGroups && f.AudioGroups != null)
                {
                    WriteLine("Dumping audio groups...");

                    File.WriteAllText(od + "audiogroups.json", JsonMapper.ToJson(Serialize.SerializeAudioGroups(f)));
                }
                if (eo.DetachedAgrp && f.AudioGroups != null)
                {
                    WriteLine("Dumping audio from detached audio groups...");

                    for (int i = 1; i < f.AudioGroups.Length; ++i)
                    {
                        WrAndGetC(DASH_ + f.AudioGroups[i] + O_PAREN + i +
                                  SLASH + f.AudioGroups.Length + C_PAREN + SPACE_S,
                                  out cl, out ct);

                        var agrpfn = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar
                                     + AGRPF + i + D_DAT;
                        if (!File.Exists(agrpfn))
                        {
                            Console.Error.WriteLine("Eep: file '" + agrpfn + "' doesn't exist, skipping...");
                            continue;
                        }

                        var infoTable = new Dictionary <int, SoundInfo>();

                        for (uint iii = 0; iii < f.Sound.Length; ++iii)
                        {
                            var s = f.Sound[iii];
                            if ((s.IsEmbedded || s.IsCompressed) && s.AudioID != -1 &&
                                s.GroupID == i)
                            {
                                infoTable[s.AudioID] = s;
                            }
                        }

                        var odgrp = od + DIR_AGRP + f.AudioGroups[i];
                        if (!Directory.Exists(odgrp))
                        {
                            Directory.CreateDirectory(odgrp);
                        }

                        using (var af = GMFile.GetFile(agrpfn))
                        {
                            for (int j = 0; j < af.Audio.Length; ++j)
                            {
                                SetCAndWr(cl, ct, O_PAREN + (j + 1) + SLASH +
                                          (af.Audio.Length - 1) + C_PAREN);
                                File.WriteAllBytes(odgrp + Path.DirectorySeparatorChar
                                                   + infoTable[j].Name + SR.EXT_WAV, af.Audio[j].Wave);
                            }
                        }
                        Console.WriteLine();
                    }
                    f.AudioGroups.Clear();
                }
                #endregion

                #region TXTR
                MemoryStream[] txtrStreams = null;
                Bitmap      [] txtrBitmaps = null;
                if (eo.Texture && f.Textures != null)
                {
                    txtrStreams = new MemoryStream[f.Textures.Length];
                    txtrBitmaps = new Bitmap      [f.Textures.Length];
                    WrAndGetC("Exporting texture sheets... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_TEX))
                    {
                        Directory.CreateDirectory(od + DIR_TEX);
                    }

                    for (int i = 0; i < f.Textures.Length; i++)
                    {
                        if (f.Textures[i].PngData == null)
                        {
                            continue;
                        }

                        using (var ms = new MemoryStream(f.Textures[i].PngData))
                        {
                            txtrBitmaps[i] = new Bitmap(txtrStreams[i] = ms);
                        }

                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Textures.Length + C_PAREN);

                        File.WriteAllBytes(od + DIR_TEX + i + EXT_PNG, f.Textures[i].PngData);
                    }
                    Console.WriteLine();
                    f.Textures.Clear();
                }
                #endregion
                #region AUDO
                if (eo.Audio && f.Audio != null)
                {
                    WrAndGetC("Exporting audio files... ", out cl, out ct);

                    var infoTable = new Dictionary <int, SoundInfo>();

                    foreach (var s in f.Sound)
                    {
                        if ((s.IsEmbedded || s.IsCompressed) && s.AudioID != -1 &&
                            s.GroupID == 0)        // not from audiogroup$n.dat
                        {
                            infoTable[s.AudioID] = s;
                        }
                    }

                    if (!Directory.Exists(od + DIR_WAV))
                    {
                        Directory.CreateDirectory(od + DIR_WAV);
                    }

                    for (int i = 0; i < f.Audio.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Audio.Length + C_PAREN);

                        File.WriteAllBytes(od + DIR_WAV + infoTable[i].Name + SR.EXT_WAV, f.Audio[i].Wave);
                    }
                    Console.WriteLine();
                    f.Audio.Clear();
                }
                #endregion
                #region CODE
                if (eo.Decompile && f.Code != null)
                {
                    WrAndGetC("Decompiling code... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_CODE))
                    {
                        Directory.CreateDirectory(od + DIR_CODE);
                    }

                    for (int i = 0; i < f.Code.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Code.Length + C_PAREN);

                        try
                        {
                            File.WriteAllText(od + DIR_CODE + f.Code[i].Name + EXT_GML_LSP, Decompiler.DecompileCode(f, i, eo.AbsoluteAddresses));
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine($"Error: Failed to decompile {f.Code[i].Name}, ignoring...");
#if DEBUG
                            Console.Error.WriteLine(e);
#endif
                        }
                    }
                    Console.WriteLine();
                }
                if (eo.Disassemble && f.Code != null)
                {
                    WrAndGetC("Disassembling bytecode... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_CODE))
                    {
                        Directory.CreateDirectory(od + DIR_CODE);
                    }

                    for (int i = 0; i < f.Code.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Code.Length + C_PAREN);

                        File.WriteAllText(od + DIR_CODE + f.Code[i].Name + EXT_GML_ASM, Disassembler.DisplayInstructions(f, i, eo.AbsoluteAddresses));

                        /*
                         * // Dump binary code to separate files. Useful for debugging de-/re-assembly/de-/re-compilation.
                         * BinBuffer bb = new BinBuffer();
                         * for (uint j = 0; j < f.Code[i].Instructions.Length; j++)
                         * {
                         *  var instr = f.Code[i].Instructions[j];
                         *  var isize = DisasmExt.Size(instr, f.General.BytecodeVersion)*4;
                         *
                         *  bb.Write((IntPtr)instr, (int)isize);
                         * }
                         * bb.Position = 0;
                         * File.WriteAllBytes(od + DIR_CODE + f.Code[i].Name + EXT_BIN, bb.ReadBytes(bb.Size));
                         */
                    }
                    Console.WriteLine();
                }
                if (f.Code != null)
                {
                    f.Code.Clear();
                }
                #endregion

                #region SCPT
                if (eo.Script && f.Scripts != null && f.Code != null)
                {
                    WrAndGetC("Exporting scripts... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_SCR))
                    {
                        Directory.CreateDirectory(od + DIR_SCR);
                    }

                    for (int i = 0; i < f.Scripts.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Scripts.Length + C_PAREN);

                        File.WriteAllText(od + DIR_SCR + f.Scripts[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeScript(f.Scripts[i], f.Code)));
                    }
                    Console.WriteLine();
                    f.Scripts.Clear();
                }
                #endregion
                #region TPAG
                Bitmap[] tpagBitmaps = null;
                if (eo.TPag && f.TexturePages != null)
                {
                    tpagBitmaps = new Bitmap[f.TexturePages.Length];
                    WrAndGetC("Exporting texture maps... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_TXP))
                    {
                        Directory.CreateDirectory(od + DIR_TXP);
                    }

                    for (int i = 0; i < f.TexturePages.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.TexturePages.Length + C_PAREN);

                        var tpag = f.TexturePages[i];
                        File.WriteAllText(od + DIR_TXP + i + EXT_JSON,
                                          JsonMapper.ToJson(Serialize.SerializeTPag(tpag)));

                        var bc = txtrBitmaps[tpag.SpritesheetId]
                                 .Clone(new GDIRectangle(tpag.Source.X, tpag.Source.Y,
                                                         tpag.Source.Width, tpag.Source.Height),
                                        PixelFormat.DontCare);
                        tpagBitmaps[i] = bc;

                        if (eo.DumpTPagPNGs)
                        {
                            bc.Save(od + DIR_TXP + i + EXT_PNG);
                        }
                    }
                    Console.WriteLine();
                    f.TexturePages.Clear();
                }
                #endregion
                #region SPRT
                if (eo.Sprite && f.Sprites != null)
                {
                    WrAndGetC("Exporting sprites... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_SPR))
                    {
                        Directory.CreateDirectory(od + DIR_SPR);
                    }

                    for (int i = 0; i < f.Sprites.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Sprites.Length + C_PAREN);

                        File.WriteAllText(od + DIR_SPR + f.Sprites[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeSprite(f.Sprites[i])));

                        if (eo.DumpSpritePNGs)
                        {
                            for (int j = 0; j < f.Sprites[i].TextureIndices.Length; ++j)
                            {
                                uint id = f.Sprites[i].TextureIndices[j];
                                tpagBitmaps[id].Save(od + DIR_SPR + f.Sprites[i].Name + UNDERSCORE + j + EXT_PNG);
                            }
                        }
                    }
                    Console.WriteLine();
                    f.Sprites.Clear();
                }
                #endregion
                #region SOND
                if (eo.Sound && f.Sound != null)
                {
                    WrAndGetC("Exporting sounds... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_SND))
                    {
                        Directory.CreateDirectory(od + DIR_SND);
                    }

                    for (int i = 0; i < f.Sound.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Sound.Length + C_PAREN);

                        File.WriteAllText(od + DIR_SND + f.Sound[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeSound(f.Sound[i])));
                    }
                    Console.WriteLine();
                    f.Sound.Clear();
                }
                #endregion

                #region OBJT
                if (eo.Object && f.Objects != null && f.Sprites != null)
                {
                    WrAndGetC("Exporting objects... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_OBJ))
                    {
                        Directory.CreateDirectory(od + DIR_OBJ);
                    }

                    for (int i = 0; i < f.Objects.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Objects.Length + C_PAREN);

                        File.WriteAllText(od + DIR_OBJ + f.Objects[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeObj(f.Objects[i], f.Sprites, f.Objects)));
                    }
                    Console.WriteLine();
                }
                #endregion
                #region BGND
                if (eo.Background && f.Backgrounds != null)
                {
                    WrAndGetC("Exporting backgrounds... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_BG))
                    {
                        Directory.CreateDirectory(od + DIR_BG);
                    }

                    for (int i = 0; i < f.Backgrounds.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Backgrounds.Length + C_PAREN);

                        File.WriteAllText(od + DIR_BG + f.Backgrounds[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeBg(f.Backgrounds[i])));
                    }
                    Console.WriteLine();
                }
                #endregion
                #region ROOM
                if (eo.Room && f.Rooms != null)
                {
                    WrAndGetC("Exporting rooms... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_ROOM))
                    {
                        Directory.CreateDirectory(od + DIR_ROOM);
                    }

                    for (int i = 0; i < f.Rooms.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Rooms.Length + C_PAREN);

                        File.WriteAllText(od + DIR_ROOM + f.Rooms[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeRoom(f.Rooms[i], f.Backgrounds, f.Objects)));
                    }
                    Console.WriteLine();
                }
                if (f.Backgrounds != null)
                {
                    f.Backgrounds.Clear();
                }
                if (f.Objects != null)
                {
                    f.Objects.Clear();
                }
                if (f.Rooms != null)
                {
                    f.Rooms.Clear();
                }
                #endregion

                #region FONT
                if (eo.Font && f.Fonts != null)
                {
                    WrAndGetC("Exporting fonts... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_FNT))
                    {
                        Directory.CreateDirectory(od + DIR_FNT);
                    }

                    for (int i = 0; i < f.Fonts.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Fonts.Length + C_PAREN);

                        File.WriteAllText(od + DIR_FNT + f.Fonts[i].CodeName + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeFont(f.Fonts[i])));
                    }
                    Console.WriteLine();
                    f.Fonts.Clear();
                }
                #endregion
                #region PATH
                if (eo.Path && f.Paths != null)
                {
                    WrAndGetC("Exporting paths... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_PATH))
                    {
                        Directory.CreateDirectory(od + DIR_PATH);
                    }

                    for (int i = 0; i < f.Paths.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Paths.Length + C_PAREN);

                        File.WriteAllText(od + DIR_PATH + f.Paths[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializePath(f.Paths[i])));
                    }
                    Console.WriteLine();
                    f.Paths.Clear();
                }
                #endregion
                #region SHDR
                if (eo.Shader && f.Shaders != null)
                {
                    WrAndGetC("Exporting shaders... ", out cl, out ct);

                    if (!Directory.Exists(od + DIR_SHDR))
                    {
                        Directory.CreateDirectory(od + DIR_SHDR);
                    }

                    for (int i = 0; i < f.Shaders.Length; i++)
                    {
                        SetCAndWr(cl, ct, O_PAREN + (i + 1) + SLASH + f.Shaders.Length + C_PAREN);

                        File.WriteAllText(od + DIR_SHDR + f.Shaders[i].Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeShader(f.Shaders[i])));
                    }
                    Console.WriteLine();
                }
                #endregion
                List <IntPtr> chunks = null;

                if (eo.DumpUnknownChunks || eo.DumpAllChunks)
                {
                    chunks = new List <IntPtr>(6);
                    Action <IntPtr> DumpUnk = _unk =>
                    {
                        var unk = (SectionUnknown *)_unk;

                        if (unk == null || (unk->IsEmpty() && !eo.DumpEmptyChunks))
                        {
                            return;
                        }

                        WriteLine($"Dumping {unk->Header.MagicString()} chunk...");

                        var    len = unk->Header.Size;
                        byte[] buf = new byte[len];
                        uint * src = &unk->Unknown;

                        if (len != 0)
                        {
                            ILHacks.Cpblk <byte>((void *)src, buf, 0, (int)len);
                        }

                        File.WriteAllBytes(od + unk->Header.MagicString() + EXT_BIN, buf);
                    };

                    var c = f.Content;

                    if (eo.DumpAllChunks)
                    {
                        chunks.AddRange(c.Chunks.Values);
                    }

                    // TODO: how to filter out unknowns?

                    for (int i = 0; i < chunks.Count; i++)
                    {
                        DumpUnk(chunks[i]);
                    }
                }

                if (eo.ExportToProject)
                {
                    WriteLine("Emitting project file...");

                    File.WriteAllText(od + f.General.Name + EXT_JSON, JsonMapper.ToJson(Serialize.SerializeProject(f, eo, chunks)));
                }

                if (tpagBitmaps != null)
                {
                    for (int i = 0; i < tpagBitmaps.Length; ++i)
                    {
                        tpagBitmaps[i].Dispose();
                    }
                }
                if (txtrStreams != null)
                {
                    for (int i = 0; i < txtrStreams.Length; ++i)
                    {
                        txtrBitmaps[i].Dispose();
                        txtrStreams[i].Dispose();
                    }
                }
            }
        }
예제 #34
0
 public bool Assemble(string file, Decompiler.Core.Assemblers.Assembler asm, DecompilerHost host)
 {
     throw new NotImplementedException();
 }
예제 #35
0
        /// <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;
        }
예제 #36
0
        protected override IDocumentViewModel _InnerOpenDocument(IJPath path)
        {
            DecompileDocumentViewModel viewModel;

            viewModel        = Container.Resolve <DecompileDocumentViewModel>();
            viewModel.Parent = this;
            viewModel.Title  = Path.GetFileName(path.Path);
            Documents.Add(viewModel);

            /*viewModel.TokenSource = new CancellationTokenSource();
             * viewModel.DecompileTask = new Task(() =>
             * {
             *    if (MapSourceToMd5.ContainsKey(path.Path))
             *    {
             *        if (APIHelper.GetMd5Of(path.Path) == MapSourceToMd5[path.Path])
             *        {
             *            //TODO
             *        }
             *    }
             *    var basedir = Path.GetDirectoryName(path.Path);
             *    var tempPath = Path.GetTempFileName();
             *    File.Delete(tempPath);
             *    Directory.CreateDirectory(tempPath);
             *    File.Copy(path.Path, Path.Combine(tempPath, Path.GetFileName(path.Path)));
             *    foreach(var p in path.InnerClassPaths)
             *    {
             *        File.Copy(p, Path.Combine(tempPath, Path.GetFileName(p)));
             *    }
             *    var result = Decompiler.Decompile(tempPath, r => MessageWhole = r, viewModel.TokenSource.Token, BaseDirectory + "\\raw.jar");
             *
             *    if (result.ResultCode == CommonDecompiler.DecompileResultEnum.DecompileSuccess)
             *    {
             *        viewModel.Load(result.Output);
             *    }
             * });
             * viewModel.DecompileTask.Start();*/
            viewModel.DecompTaskTokenSource = new CancellationTokenSource();
            IBackgroundTask backgroundTask = null;

            backgroundTask = Container.Resolve <IBackgroundTaskBuilder>()
                             .WithTask(async obj =>
            {
                var token = obj as CancellationToken?;
                if (MapSourceToMd5.ContainsKey(path.Path))
                {
                    if (APIHelper.GetMd5Of(path.Path) == MapSourceToMd5[path.Path])
                    {
                        //TODO
                    }
                }
                var basedir  = Path.GetDirectoryName(path.Path);
                var tempPath = Path.GetTempFileName();
                File.Delete(tempPath);
                Directory.CreateDirectory(tempPath);
                File.Copy(path.Path, Path.Combine(tempPath, Path.GetFileName(path.Path)));
                if (path.InnerClassPaths != null)
                {
                    foreach (var p in path.InnerClassPaths)
                    {
                        File.Copy(p, Path.Combine(tempPath, Path.GetFileName(p)));
                    }
                }
                IDecompileResult result = null;
                try
                {
                    result = Decompiler.Decompile(tempPath,
                                                  r => { if (backgroundTask != null)
                                                         {
                                                             backgroundTask.TaskDescription = r;
                                                         }
                                                  },
                                                  token, BaseDirectory + "\\raw.jar");
                    if (result.ResultCode == DecompileResultEnum.Success)
                    {
                        var files = Directory.GetFiles(result.OutputDir);
#if DEBUG
                        Debug.Assert(files.Length == 1);
#endif
                        string newFileName = files[0];
                        if (EnableDecompiledFileCache)
                        {
                            newFileName = Path.Combine(basedir + '\\', Path.GetFileNameWithoutExtension(files[0]) + ".java");
                            File.Copy(files[0], newFileName, true);
                            MapSourceToMd5.Add(newFileName, APIHelper.GetMd5Of(newFileName));
                        }
                        StatusMessage = backgroundTask.TaskDescription = "Processing " + path.ClassPath;
                        await viewModel.LoadAsync(newFileName, path);

                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            if (!(Manager.ActiveContent is IDocumentViewModel))
                            {
                                ActivateDocument(viewModel);
                            }
                        });
                    }
                    else
                    {
                        Container.Resolve <IDialogService>().ReportError(result.ResultCode.ToString(), _ => { });
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Documents.Remove(viewModel);
                        });
                    }
                }
                catch (Exception e)
                {
                    if (e is OperationCanceledException)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Documents.Remove(viewModel);
                        });
                    }
                    else
                    {
                        string message = null;
                        if (e is Win32Exception win32Exception)
                        {
                            message = $"Unexpected exception:\n{win32Exception.Message}\nHRESULT is {System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error().ToString("x")}";
                        }
                        else
                        {
                            message = $"Unexpected exception:\n{e.Message}\n";
                        }
                        Container.Resolve <IDialogService>().ReportError(message, r => { }, e.StackTrace);
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Documents.Remove(viewModel);
                        });
                    }
                }
                if (token.HasValue)
                {
                    token.Value.ThrowIfCancellationRequested();
                }
                Directory.Delete(tempPath, true);
                StatusMessage = "Ready";
            }, viewModel.DecompTaskTokenSource.Token)
                             .WithName($"{Decompiler.GetDecompilerInfo().FriendlyName}:{Path.GetFileName(path.Path)}")
                             .WithDescription($"Decompiler started")
                             .Build();
            viewModel.AttachDecompileTask(backgroundTask);
            viewModel.BackgroundTask.Start();
            return(viewModel);
        }
예제 #37
0
 public override void Deserialize(IUnrealStream stream)
 {
     CodeOffset = stream.ReadUInt16();
     Decompiler.AlignSize(sizeof(ushort));
 }
예제 #38
0
파일: melt.cs 프로젝트: DavidFlamme/wix3
        /// <summary>
        /// Extracts files from a merge module and creates corresponding ComponentGroup WiX authoring.
        /// </summary>
        private void MeltModule()
        {
            Decompiler decompiler = null;
            Unbinder unbinder = null;
            Melter melter = null;

            try
            {
                // create the decompiler, unbinder, and melter
                decompiler = new Decompiler();
                unbinder = new Unbinder();
                melter = new Melter(decompiler, id);

                // read the configuration file (melt.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.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP");

                unbinder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP");
                unbinder.SuppressDemodularization = true;

                decompiler.Message += new MessageEventHandler(this.messageHandler.Display);
                unbinder.Message += new MessageEventHandler(this.messageHandler.Display);
                melter.Message += new MessageEventHandler(this.messageHandler.Display);

                // print friendly message saying what file is being decompiled
                Console.WriteLine(Path.GetFileName(this.inputFile));

                // unbind
                Output output = unbinder.Unbind(this.inputFile, this.outputType, this.exportBasePath);

                if (null != output)
                {
                    Wix.Wix wix = melter.Melt(output);
                    if (null != wix)
                    {
                        XmlTextWriter writer = null;

                        try
                        {
                            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();
                        }
                        finally
                        {
                            if (null != writer)
                            {
                                writer.Close();
                            }
                        }
                    }
                }
            }
            finally
            {
                if (null != decompiler)
                {
                    if (this.tidy)
                    {
                        if (!decompiler.DeleteTempFiles())
                        {
                            Console.WriteLine(MeltStrings.WAR_FailedToDeleteTempDir, decompiler.TempFilesLocation);
                        }
                    }
                    else
                    {
                        Console.WriteLine(MeltStrings.INF_TempDirLocatedAt, decompiler.TempFilesLocation);
                    }
                }

                if (null != unbinder)
                {
                    if (this.tidy)
                    {
                        if (!unbinder.DeleteTempFiles())
                        {
                            Console.WriteLine(MeltStrings.WAR_FailedToDeleteTempDir, unbinder.TempFilesLocation);
                        }
                    }
                    else
                    {
                        Console.WriteLine(MeltStrings.INF_TempDirLocatedAt, unbinder.TempFilesLocation);
                    }
                }
            }
        }
예제 #39
0
        protected override async void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            methoddef = MainForm.GetMethod(Hook.AssemblyName, Hook.TypeName, Hook.Signature);

            hooktypes = new List <Type>();
            int selindex = 0;
            int i        = 0;

            foreach (var hooktype in Hook.GetHookTypes())
            {
                string typename = hooktype.GetCustomAttribute <HookType>().Name;
                hooktypedropdown.Items.Add(typename);
                hooktypes.Add(hooktype);
                if (typename == Hook.HookTypeName)
                {
                    selindex = i;
                }
                i++;
            }

            var hooks     = MainForm.CurrentProject.GetManifest(Hook.AssemblyName).Hooks;
            var baseHooks = (from hook in hooks where hook.BaseHook != null select hook.BaseHook).ToList();

            basehookdropdown.Items.Add("");
            int selindex2 = 0;

            i = 1;
            foreach (var hook in hooks)
            {
                if (hook.BaseHook == Hook)
                {
                    clonebutton.Enabled = false;
                }
                if (hook != Hook.BaseHook && baseHooks.Contains(hook))
                {
                    continue;
                }
                basehookdropdown.Items.Add(hook.Name);
                if (hook == Hook.BaseHook)
                {
                    selindex2 = i;
                }
                i++;
            }

            assemblytextbox.Text = Hook.AssemblyName;
            typenametextbox.Text = Hook.TypeName;

            if (methoddef != null)
            {
                methodnametextbox.Text = Hook.Signature.ToString();
            }
            else
            {
                methodnametextbox.Text = Hook.Signature + " (METHOD MISSING)";
            }
            nametextbox.Text               = Hook.Name;
            hooknametextbox.Text           = Hook.HookName;
            ignoretypechange               = true;
            hooktypedropdown.SelectedIndex = selindex;
            basehookdropdown.SelectedIndex = selindex2;
            ignoretypechange               = false;

            applybutton.Enabled = false;

            if (Hook.Flagged)
            {
                flagbutton.Enabled   = false;
                unflagbutton.Enabled = true;
                unflagbutton.Focus();
            }
            else
            {
                flagbutton.Enabled   = true;
                unflagbutton.Enabled = false;
                flagbutton.Focus();
            }

            HookSettingsControl settingsview = Hook.CreateSettingsView();

            if (settingsview == null)
            {
                Label tmp = new Label();
                tmp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                tmp.AutoSize  = false;
                tmp.Text      = "No settings.";
                tmp.Dock      = DockStyle.Fill;
                hooksettingstab.Controls.Add(tmp);
            }
            else
            {
                settingsview.Dock = DockStyle.Fill;
                settingsview.OnSettingsChanged += settingsview_OnSettingsChanged;
                hooksettingstab.Controls.Add(settingsview);
            }

            if (methoddef == null)
            {
                Label missinglabel1 = new Label();
                missinglabel1.Dock      = DockStyle.Fill;
                missinglabel1.AutoSize  = false;
                missinglabel1.Text      = "METHOD MISSING";
                missinglabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                beforetab.Controls.Add(missinglabel1);

                Label missinglabel2 = new Label();
                missinglabel2.Dock      = DockStyle.Fill;
                missinglabel2.AutoSize  = false;
                missinglabel2.Text      = "METHOD MISSING";
                missinglabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
                aftertab.Controls.Add(missinglabel2);

                return;
            }

            var weaver = new ILWeaver(methoddef.Body)
            {
                Module = methoddef.Module
            };

            Hook.PreparePatch(methoddef, weaver, MainForm.OxideAssembly);
            msilbefore = new TextEditorControl {
                Dock = DockStyle.Fill, Text = weaver.ToString(), IsReadOnly = true
            };
            codebefore = new TextEditorControl
            {
                Dock     = DockStyle.Fill,
                Text     = await Decompiler.GetSourceCode(methoddef, weaver),
                Document =
                {
                    HighlightingStrategy = HighlightingManager.Manager.FindHighlighter("C#")
                },
                IsReadOnly = true
            };

            Hook.ApplyPatch(methoddef, weaver, MainForm.OxideAssembly);
            msilafter = new TextEditorControl {
                Dock = DockStyle.Fill, Text = weaver.ToString(), IsReadOnly = true
            };
            codeafter = new TextEditorControl
            {
                Dock     = DockStyle.Fill,
                Text     = await Decompiler.GetSourceCode(methoddef, weaver),
                Document =
                {
                    HighlightingStrategy = HighlightingManager.Manager.FindHighlighter("C#")
                },
                IsReadOnly = true
            };

            beforetab.Controls.Add(msilbefore);
            aftertab.Controls.Add(msilafter);
            codebeforetab.Controls.Add(codebefore);
            codeaftertab.Controls.Add(codeafter);
        }
예제 #40
0
        /// <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);
        }
예제 #41
0
 protected override string GetNameInternal()
 {
     return(Decompiler.GetTypeName(AssemblyPath, Module.TokenId, TokenId, SupportedLanguage.CSharp));
 }
예제 #42
0
 public override void Decompile(Language language, Decompiler.ITextOutput output, DecompilationOptions options)
 {
     language.DecompileModule(module, output, options);
 }
예제 #43
0
 public string GetNamespace()
 {
     return(Decompiler.GetTypeNamespace(AssemblyPath, Module.TokenId, TokenId));
 }
 public void Test()
 {
     Decompiler dc = new Decompiler();
     dc.Decompile();
 }
예제 #45
0
 public override void PerformWork(IWorkerDialogService workerDialogSvc)
 {
     workerDialogSvc.SetCaption("Scanning source program.");
     Decompiler.ScanPrograms();
 }