示例#1
0
        public void Setup()
        {
            PatchEngine.Init(config =>
            {
                config.EnableAttributes();
                config.SetCustomAttributesConfigurator(new CustomAttributesConfigurator());
                config
                .SetPrePatchProcessingFunction(context =>
                {
                    if (context.PropertyConfiguration.ExtraSettings.ContainsKey(RoundValueAttribute.PARAMETER_NAME))
                    {
                        if (!(context.NewValue is double))
                        {
                            return(context.NewValue);
                        }

                        var precision = (int)(context.PropertyConfiguration.ExtraSettings[RoundValueAttribute.PARAMETER_NAME]);

                        return(Math.Round((double)(context.NewValue), precision));
                    }

                    return(context.NewValue);
                });
            });
        }
示例#2
0
 /// <summary>
 ///     パッチを当てたファイルを保存する
 /// </summary>
 /// <param name="fileName">保存先のファイル名</param>
 /// <returns>保存に成功すればtrueを返す</returns>
 private static bool SavePatchedFile(string fileName)
 {
     // ファイル名が空ならば何もしない
     if (string.IsNullOrEmpty(fileName))
     {
         return(false);
     }
     // 自動処理モードで保存先にファイルがあれば上書き確認する
     if (File.Exists(fileName) && AutoMode)
     {
         if (MessageBox.Show(
                 "パッチを当てたファイルの保存先に他のファイルがあります。\n" +
                 "上書きしてもよろしいですか?",
                 "パッチを当てたファイルを保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
         {
             return(false);
         }
     }
     // パッチを当てたファイルを保存する
     PatchEngine.SavePatchedFile(fileName);
     // 16bitカラー設定を付加する
     if (Color16Bit)
     {
         Set16BitColor(fileName);
     }
     return(true);
 }
示例#3
0
        public PatchEngine()
        {
            runMode    = RunMode.Macro;
            protossl   = new SSLCode("VOODOO");
            updateFile = new UpdateFile(new Regex(@"^[\t ]*/[/]+[\t ]+sfall-asm:([A-Za-z0-9_]+)-(begin|end)[\t ]+/[/]+[\t ]*$"), "begin", "end");

            singleton = this;

            Error.GetErrorContext = () => GetErrorContext();
        }
示例#4
0
        public void SimpleInitEntityCreationTest()
        {
            PatchEngineCore.Cleanup();
            PatchEngine.Init();

            var request = GetPatchRequestWithFields("Login", "LastSeenFrom");
            var entity  = request.CreateNewEntity();

            Assert.NotNull(entity);
            Assert.AreEqual(request["Login"].ToString(), entity.Login);
        }
示例#5
0
        private void LoadPatchDefinitions()
        {
            if (LoadingPatchDefinitions)
            {
                return;
            }
            LoadingPatchDefinitions = true;

            string PatchDefinitionName = cmbPatchDefinitionName.Text;
            string TargetVersion       = cmbTargetVersion.Text;
            string TargetPath          = cmbTargetPath.Text;

            cmbPatchDefinitionName.SelectedIndex = -1;
            cmbTargetVersion.SelectedIndex       = -1;
            cmbTargetPath.SelectedIndex          = -1;

            cmbPatchDefinitionName.Items.Clear();
            cmbTargetVersion.Items.Clear();
            cmbTargetPath.Items.Clear();

            cmbPatchDefinitionName.Text = PatchDefinitionName;
            cmbTargetVersion.Text       = TargetVersion;
            cmbTargetPath.Text          = TargetPath;

            try
            {
                string      Definitions = File.ReadAllText(txtPatchDefinitionsFile.Text);
                PatchEngine Engine      = new PatchEngine(Definitions);
                Engine.PatchDefinitions.Where(d => !string.IsNullOrEmpty(d.Name)).Select(d => d.Name).Distinct().ToList().ForEach(n => cmbPatchDefinitionName.Items.Add(n));
                PatchDefinition Definition = null;
                if (cmbPatchDefinitionName.Text.Trim().Length > 0)
                {
                    Definition = Engine.PatchDefinitions.Where(d => string.Compare(d.Name, cmbPatchDefinitionName.Text.Trim(), true) == 0).FirstOrDefault();
                }
                if (Definition != null)
                {
                    Definition.TargetVersions.Where(v => !string.IsNullOrEmpty(v.Description)).Select(v => v.Description).Distinct().ToList().ForEach(d => cmbTargetVersion.Items.Add(d));
                    TargetVersion Version = null;
                    if (cmbTargetVersion.Text.Trim().Length > 0)
                    {
                        Version = Definition.TargetVersions.Where(v => string.Compare(v.Description, cmbTargetVersion.Text.Trim(), true) == 0).FirstOrDefault();
                    }
                    if (Version != null)
                    {
                        Version.TargetFiles.Where(f => !string.IsNullOrEmpty(f.Path)).Select(f => Path.GetDirectoryName(f.Path)).Distinct().ToList().ForEach(f => cmbTargetPath.Items.Add(f));
                    }
                }
            }
            catch { }

            LoadingPatchDefinitions = false;
        }
示例#6
0
        private void LoadPatchDefinitions()
        {
            if (LoadingPatchDefinitions)
            {
                return;
            }
            LoadingPatchDefinitions = true;

            try
            {
                string Definitions = File.ReadAllText(txtPatchDefinitionsFile.Text);
                PatchEngine = new PatchEngine(Definitions);
            }
            catch
            {
                PatchEngine = new PatchEngine();
            }

            LoadingPatchDefinitions = false;
        }
示例#7
0
        private void cmdApplyDBScript_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=" + txtServer.Text + ";User ID=" + txtUserID.Text + ";Password="******";Initial Catalog=" + txtDatabase.Text;

            DatabaseConnection dbConn = new DatabaseConnection(connectionString, DatabaseConnection.DatabaseType.MSSQL);

            txtResult.Text = txtResult.Text + "DB Connection established" + "\r\n";
            Application.DoEvents();

            PatchEngine patchEngine = new PatchEngine(dbConn, "./", txtTargetDBVersion.Text);

            txtResult.Text = txtResult.Text + "Applying database upgrade scripts" + "\r\n";
            Application.DoEvents();

            patchEngine.UpdateDatabaseVersion(false);

            txtResult.Text = txtResult.Text + "Database upgraded.  Current DB Version is : " + patchEngine.RunningDatabaseVersion() + "\r\n";
            Application.DoEvents();
            ESystemParameter.setParameter(dbConn, "DBVersion", "1.0.0");
            txtResult.Text = txtResult.Text + "Database upgraded.  Database version is reset to : " + patchEngine.RunningDatabaseVersion() + "\r\n";
        }
示例#8
0
        /// <summary>
        ///     パッチ処理
        /// </summary>
        /// <returns>パッチ処理が成功すればtrueを返す</returns>
        public static bool Patch()
        {
            if (!File.Exists(TargetFileName))
            {
                MessageBox.Show("パッチ対象のファイルがありません。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (GameType == GameType.Unknown)
            {
                DetectGameType(TargetFileName);
                if (GameType == GameType.Unknown)
                {
                    MessageBox.Show("パッチの種類が判別できません。\nゲーム本体の実行ファイルを指定して下さい。", "エラー", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    return(false);
                }
            }

            return(PatchEngine.Patch(TargetFileName, GameType));
        }
示例#9
0
        public void RFC7396PatchingEnabledTest()
        {
            PatchEngineCore.Cleanup();
            PatchEngine.Init(cfg =>
            {
                cfg.EnableNestedPatching();
            });

            var model = new Post
            {
                Title  = "Hello!",
                Author = new Author
                {
                    GivenName  = "John",
                    FamilyName = "Doe"
                },
                Tags    = new[] { "example", "sample" },
                Content = "This will be unchanged"
            };

            var jsonPatch = @"{
                                 ""title"": ""Hello!"",
                                 ""phoneNumber"": ""+01-123-456-7890"",
                                 ""author"": {
                                            ""familyName"": null
                                 },
                                 ""tags"": [ ""example"" ]
                               }";

            var patchObject = JObject.Parse(jsonPatch).ToObject <PatchObject <Post> >();

            patchObject.ApplyTo(model);

            Assert.AreEqual("+01-123-456-7890", model.PhoneNumber);
            Assert.IsNull(model.Author.FamilyName);
            Assert.AreEqual("John", model.Author.GivenName);
            Assert.AreEqual(1, model.Tags.Length);
            Assert.AreEqual("example", model.Tags.First());
        }
示例#10
0
        static void Main(string[] args)
        {
            // Force english language, for exceptions
            System.Threading.Thread.CurrentThread.CurrentCulture   = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;

            if (args.Length == 0)
            {
                Console.WriteLine(AppDomain.CurrentDomain.FriendlyName + " [asm_patch] <options...>");
                Console.WriteLine();
                Console.WriteLine("RUN MODE");
                Console.WriteLine("\t--macro           Generate patch file as preprocessor macro (default)");
                Console.WriteLine("\t--procedure       Generate patch file as inline procedure");
                Console.WriteLine("\t--memory          Write the code directly into Fallout2.exe");
                Console.WriteLine();
                Console.WriteLine("SSL GENERATION");
                Console.WriteLine("\t--no-lower        Hex values won't be lowercased");
                Console.WriteLine("\t--no-macro-guard  Macros won't be guarded with begin/end");
                Console.WriteLine("\t--no-pack         Force using write_byte() function only");
                Console.WriteLine("\t--update-file     Apply changes to given file");
                Console.WriteLine("\t--malloc          Use dynamically allocated memory in patches where requested");
                Console.WriteLine();
                Console.WriteLine("GENERATORS");
                Console.WriteLine("\t--sfall-assert    Generate a patch to assert that code is correct");
                Console.WriteLine();
                Console.WriteLine("PATCH VARIABLES");
                Console.WriteLine("\t--memory-args     Set memory variables");
                Console.WriteLine();
                Console.WriteLine("DEBUGGING");
                Console.WriteLine("\t-r                Console.ReadKey() on exit");
                Console.WriteLine();
                Console.WriteLine("ERROR HANDLING");
                Console.WriteLine("\t-strict           Use strict error handling");

                return;
            }

            bool malloc    = false;
            bool readKey   = false;
            bool runEngine = true;
            var  engine    = new PatchEngine();

            foreach (var a in args)
            {
                // run mode
                if (a == "--macro")
                {
                    engine.runMode = RunMode.Macro;
                }
                else if (a == "--procedure")
                {
                    engine.runMode = RunMode.Procedure;
                }
                else if (a == "--memory")
                {
                    engine.runMode = RunMode.Memory;
                }
                // ssl generation
                else if (a == "--no-pack")
                {
                    engine.protossl.Pack = false;
                }
                else if (a == "--no-lower")
                {
                    engine.protossl.Lower = false;
                }
                else if (a == "--no-macro-guard")
                {
                    engine.protossl.MacroGuard = false;
                }
                else if (a == "--malloc")
                {
                    engine.protossl.Malloc = true;
                }
                else if (a == "-r")
                {
                    readKey = true;
                }
                else if (a == "-strict")
                {
                    Error.Strict = true;
                }
                else if (a.StartsWith("--memory-args="))
                {
                    engine.ParseMemoryArgs(a);
                }
                else if (a.StartsWith("--sfall-assert=")) // --sfall-assert=name,hook_address,bytes
                {
                    Asserts.Sfall.ParseAndRunAssertArgs(a);
                    runEngine = false;
                }
                else if (a.StartsWith("--update-file="))
                {
                    string filename = a.Replace("--update-file=", "");
                    engine.currentFilename = filename;
                    engine.updateFile.SetData(filename, engine.SafeReadAllLines(filename));
                }
                else
                {
                    if (Directory.Exists(a))
                    {
                        Directory.GetFiles(a, "*.asm").OrderBy(x => x).ToList().ForEach(x => engine.AddPatch(x));
                    }
                    else
                    {
                        engine.AddPatch(a);
                    }
                }
            }

            if (runEngine)
            {
                engine.Run();
            }

            if (readKey)
            {
                Console.ReadKey();
            }
        }
示例#11
0
        private void btnImport_Click(object sender, EventArgs e)
        {
            if (!EmulationState.instance.AssertWrite(segmentedAddress, 1))
            {
                return;
            }

            EmulationState.instance.RefreshROM();
            int numObjects = 0;

            foreach (TabPage page in tabImports.TabPages)
            {
                foreach (Control c in page.Controls[0].Controls)
                {
                    Importable import = c as Importable;
                    if (import != null)
                    {
                        if (import.PrepareForImport() == -1)
                        {
                            EmulationState.messages.AppendMessage("Import failed.", "Error");
                            return;
                        }
                        numObjects++;
                    }
                }
            }

            StringBuilder log    = new StringBuilder();
            int           cursor = segmentedAddress;

            cursor = globalsControl.Import(cursor);

            foreach (KeyValuePair <string, TextureImage> texture in textureLibrary.textures)
            {
                texture.Value.segmentOffset = cursor;
                texture.Value.WriteBytes(ref cursor);
                cursor = (cursor + 7) / 8 * 8;
            }
            int offsetInBank = segmentedAddress & 0xFFFFFF;

            EmulationState.RAMBank bank = EmulationState.instance.banks[segmentedAddress >> 0x18];
            Array.Copy(bank.value, offsetInBank, EmulationState.instance.ROM, bank.ROMStart + offsetInBank, cursor - segmentedAddress);

            foreach (TabPage page in tabImports.TabPages)
            {
                foreach (Control c in page.Controls[0].Controls)
                {
                    Importable import = c as Importable;
                    if (import != null)
                    {
                        int newCursor = import.Import(cursor);
                        if (newCursor == -1)
                        {
                            EmulationState.messages.AppendMessage("Import failed.", "Error");
                            return;
                        }
                        else if (newCursor != 0)
                        {
                            cursor = newCursor;
                        }
                    }
                }
            }
            File.WriteAllBytes(EmulationState.instance.ROMName, EmulationState.instance.ROM);
            PatchEngine.RecalculateChecksum();
            EmulationState.messages.AppendMessage("Imported " + numObjects + " objects.", "Info");
        }
示例#12
0
        public void LoadSettings(FileParser.Block block)
        {
            string fileName = block.GetString("ROM");

            if (!System.IO.File.Exists(fileName))
            {
                string prompt = "File " + fileName + " does not exist anymore. Do you want to load another ROM?";
                if (fileName != "" && MessageBox.Show(prompt, "ROM not found.", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                {
                    return;
                }
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "z64 ROMs|*.z64";
                if (SM64RAM.EmulationState.instance.ROMName != "")
                {
                    fileName = SM64RAM.EmulationState.instance.ROMName;
                }
                else
                {
                    if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        return;
                    }
                    fileName = dlg.FileName;
                }
            }
            RAMControl.LoadROM(fileName);
            runLevelScripts.Clear();
            if (SM64RAM.EmulationState.instance.ROM == null)
            {
                EmulationState.messages.AppendMessage("An error occured while loading the ROM. Make sure no other programs are using the ROM file right now and try again.", "Error");
                return;
            }

            segmentedAddress     = block.GetInt("Base Offset", false);
            txtBaseOffset.Text   = segmentedAddress.ToString("X8");
            Settings.importScale = block.GetInt("Import Scale", false);
            if (Settings.importScale == 0)
            {
                Settings.importScale = 1000;
            }
            numScale.Value = Math.Max((int)numScale.Minimum, Math.Min((int)numScale.Maximum, (int)Settings.importScale));

            FileParser.Block globalBlock = block.GetBlock("Globals", false);
            if (globalBlock != null)
            {
                globalsControl.LoadSettings(globalBlock);
            }

            //Apply patches if necessary / desired
            string patchString = block.GetString("Patches", false);

            if (patchString != "" && MessageBox.Show("Apply level patches?", "Patch ROM", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                PatchEngine.Run(patchString, Path.GetDirectoryName(block.fileName));
            }

            runLevelScripts.AddRange(block.GetIntArray("Run level scripts"));
            RunLevelScripts();

            textureLibrary.textures.Clear();
            displayLists.Clear();
            collisionMaps.Clear();
            SuspendLayout();
            tabImports.TabPages.Clear();
            tabImports.TabPages.Add(tabPagePlus);

            //Load Display List Data
            int numDls = block.GetInt("NumDisplayLists");

            for (int i = 0; i < numDls; i++)
            {
                DisplayListControl newControl = new DisplayListControl();
                newControl.PerformLayout();
                newControl.LoadSettings(block.GetBlock("DisplayList" + i));
                AddDisplayList(newControl);
            }

            textureLibrary.LoadSettings(block.GetBlock("Textures", false));

            //Load Collision Map Data
            int numCMaps = block.GetInt("NumCollisionMaps");

            for (int i = 0; i < numCMaps; i++)
            {
                CollisionControl newControl = new CollisionControl();
                newControl.PerformLayout();
                newControl.LoadSettings(block.GetBlock("CollisionMap" + i));
                AddCollision(newControl);
            }
            ResumeLayout();
        }
示例#13
0
 protected override void Setup()
 {
     PatchEngine.Init(Configure);
 }
示例#14
0
 public MallocVar(string name)
 {
     this.Name = "VOODOO_ID_" + name;
     this.Id   = PatchEngine.Get().DeclareMallocVar(name);
 }
示例#15
0
        // TargetFilePath is relative to the root of the PatchDefinition
        // OutputFilePath can be null
        public static void AddPatch(string InputFilePath, string OutputFilePath, string PatchDefinitionName, string TargetVersionDescription, string TargetFilePath, string PathToVisualStudioWithWP8SDK, UInt32 VirtualAddress, CodeType CodeType, string ArmCodeFragment, string PatchDefintionsXmlPath)
        {
            SHA1Managed SHA = new SHA1Managed();

            // Compile ARM code
            byte[] CompiledCode = null;
            if (VirtualAddress != 0)
            {
                CompiledCode = ArmCompiler.Compile(PathToVisualStudioWithWP8SDK, VirtualAddress, CodeType, ArmCodeFragment);
            }

            // Read original binary
            byte[] Binary = File.ReadAllBytes(InputFilePath);

            // Backup original checksum
            UInt32 ChecksumOffset   = GetChecksumOffset(Binary);
            UInt32 OriginalChecksum = ByteOperations.ReadUInt32(Binary, ChecksumOffset);

            // Determine Raw Offset
            PeFile PeFile    = new PeFile(Binary);
            UInt32 RawOffset = 0;

            if (VirtualAddress != 0)
            {
                RawOffset = PeFile.ConvertVirtualAddressToRawOffset(VirtualAddress);
            }

            // Add or replace patch
            string          PatchDefintionsXml = File.ReadAllText(PatchDefintionsXmlPath);
            PatchEngine     PatchEngine        = new PatchEngine(PatchDefintionsXml);
            PatchDefinition PatchDefinition    = PatchEngine.PatchDefinitions.Where(d => (string.Compare(d.Name, PatchDefinitionName, true) == 0)).FirstOrDefault();

            if (PatchDefinition == null)
            {
                PatchDefinition      = new PatchDefinition();
                PatchDefinition.Name = PatchDefinitionName;
                PatchEngine.PatchDefinitions.Add(PatchDefinition);
            }
            TargetVersion TargetVersion = PatchDefinition.TargetVersions.Where(v => (string.Compare(v.Description, TargetVersionDescription, true) == 0)).FirstOrDefault();

            if (TargetVersion == null)
            {
                TargetVersion             = new TargetVersion();
                TargetVersion.Description = TargetVersionDescription;
                PatchDefinition.TargetVersions.Add(TargetVersion);
            }
            TargetFile TargetFile = TargetVersion.TargetFiles.Where(f => ((f.Path != null) && (string.Compare(f.Path.TrimStart(new char[] { '\\' }), TargetFilePath.TrimStart(new char[] { '\\' }), true) == 0))).FirstOrDefault();

            if (TargetFile == null)
            {
                TargetFile = new TargetFile();
                TargetVersion.TargetFiles.Add(TargetFile);
            }
            TargetFile.Path         = TargetFilePath;
            TargetFile.HashOriginal = SHA.ComputeHash(Binary);
            Patch Patch;

            if (VirtualAddress != 0)
            {
                Patch = TargetFile.Patches.Where(p => p.Address == RawOffset).FirstOrDefault();
                if (Patch == null)
                {
                    Patch         = new Patch();
                    Patch.Address = RawOffset;
                    TargetFile.Patches.Add(Patch);
                }
                Patch.OriginalBytes = new byte[CompiledCode.Length];
                Buffer.BlockCopy(Binary, (int)RawOffset, Patch.OriginalBytes, 0, CompiledCode.Length);
                Patch.PatchedBytes = CompiledCode;
            }

            // Apply all patches
            foreach (Patch CurrentPatch in TargetFile.Patches)
            {
                Buffer.BlockCopy(CurrentPatch.PatchedBytes, 0, Binary, (int)CurrentPatch.Address, CurrentPatch.PatchedBytes.Length);
            }

            // Calculate checksum
            // This also modifies the binary
            // Original checksum is already backed up
            UInt32 Checksum = CalculateChecksum(Binary);

            // Add or replace checksum patch
            Patch = TargetFile.Patches.Where(p => p.Address == ChecksumOffset).FirstOrDefault();
            if (Patch == null)
            {
                Patch         = new Patch();
                Patch.Address = ChecksumOffset;
                TargetFile.Patches.Add(Patch);
            }
            Patch.OriginalBytes = new byte[4];
            ByteOperations.WriteUInt32(Patch.OriginalBytes, 0, OriginalChecksum);
            Patch.PatchedBytes = new byte[4];
            ByteOperations.WriteUInt32(Patch.PatchedBytes, 0, Checksum);

            // Calculate hash for patched target file
            TargetFile.HashPatched = SHA.ComputeHash(Binary);

            // Write patched file
            if (OutputFilePath != null)
            {
                File.WriteAllBytes(OutputFilePath, Binary);
            }

            // Write PatchDefintions
            PatchEngine.WriteDefinitions(PatchDefintionsXmlPath);
        }