public void DisassembleSystemAll()
        {
            foreach (var type in typeof( Uri).Assembly.GetTypes() )
            {
                foreach (var member in type.GetAllMembers())
                {
                    if (member is MethodInfo)
                    {
                        var method = member as MethodInfo;
                        var disassembler = new Disassembler();
                        if (disassembler.CanDisassemble(method))
                        {
                            disassembler.Disassemble(method);
                        }
                    }
                    if (member is ConstructorInfo)
                    {
                        var ctor = member as ConstructorInfo;
                        var disassembler = new Disassembler();
                        if (disassembler.CanDisassemble(ctor))
                        {
                            disassembler.Disassemble(ctor);
                        }

                    }
                }
            }
        }
        public void DisassembleVendorTest()
        {
            var bytes = new byte[] {
                0x0F, 0x01, 0xDD,            // clgi (AMD)
                0x66, 0x0F, 0x38, 0x80, 0x00 // invept eax,[eax] (intel)
            };

            // Any vendor
            var disam = new Disassembler(bytes, ArchitectureMode.x86_64, 0x0, false, Vendor.Any);
            foreach (var ins in disam.Disassemble())
            {
                Assert.IsFalse(ins.Error);
                Assert.AreNotEqual(Udis86.ud_mnemonic_code.UD_Iinvalid, ins.Mnemonic);
            }

            // AMD only
            disam = new Disassembler(bytes, ArchitectureMode.x86_64, 0x0, false, Vendor.AMD);
            var results = disam.Disassemble().ToArray();
            Assert.IsFalse(results.First().Error);
            Assert.IsTrue(results.Last().Error);

            // Intel only
            disam = new Disassembler(bytes, ArchitectureMode.x86_64, 0x0, false, Vendor.Intel);
            results = disam.Disassemble().ToArray();
            Assert.IsTrue(results.First().Error);
            Assert.IsFalse(results.Last().Error);
        }
Beispiel #3
0
 private MachineInstruction RunTest(params byte[] bytes)
 {
     var image = new MemoryArea(Address.Ptr32(0x200), bytes);
     var rdr = new LeImageReader(image, 0);
     var dasm = new Disassembler(rdr);
     return dasm.First();
 }
Beispiel #4
0
 protected override void DoDispose()
 {
     if (disassembler != null) {
         disassembler.Dispose ();
         disassembler = null;
     }
 }
 public IEnumerable<Instruction> Disassemble(Disassembler disassembler)
 {
     disassembler.Reset();
     Instruction instruction;
     while ((instruction = disassembler.NextInstruction()) != null)
         yield return instruction;
 }
        public static List<Tuple<string, string, int>> Find()
        {
            var candidates = new List<Tuple<string, string, int>>();

            var process = Process.GetProcessesByName("tera").SingleOrDefault();
            if (process == null)
                throw new ApplicationException("Tera doesn't run");
            using (var memoryScanner = new MemoryScanner(process))
            {
                var memoryRegions = memoryScanner.MemoryRegions();
                var relevantRegions = memoryRegions.Where(x => x.State == MemoryScanner.PageState.Commit && x.Protect == MemoryScanner.PageFlags.ExecuteReadWrite);
                foreach (var memoryRegion in relevantRegions)
                {
                    var data = memoryScanner.ReadMemory(memoryRegion.BaseAddress, memoryRegion.RegionSize);
                    //data = data.Skip(0x012F6F46 - 0x00401000).ToArray();
                    var dataSlice = new byte[300];
                    var s = Stringify(data);
                    var index = 0;// 0x016F6EFC - 0x00401000;
                    while ((index = s.IndexOf("\x00CC\x00CC\x00CC\x00CC\x00CC", index, StringComparison.Ordinal)) >= 0)
                    {
                        index++;
                        while (data[index] == 0xCC)
                            index++;
                        Array.Copy(data, index, dataSlice, 0, Math.Min(data.Length - index, dataSlice.Length));
                        var disasm = new Disassembler(dataSlice, ArchitectureMode.x86_32, (ulong)memoryRegion.BaseAddress + (uint)index, true);
                        try
                        {
                            var instructions = disasm.Disassemble().TakeWhile(x => x.Mnemonic != ud_mnemonic_code.UD_Iint3);

                            var movs = new List<Instruction>();
                            foreach (var instruction in instructions)
                            {
                                if (instruction.Mnemonic == ud_mnemonic_code.UD_Imov)
                                    movs.Add(instruction);
                                else
                                {
                                    var matches = movs.Where(x => regex.IsMatch(x.ToString())).ToList();
                                    if (matches.Count == 8)
                                    {
                                        var keyIv = string.Join(" ", matches.Select(x => x.Operands[1].Value).Select(x => BitConverter.ToString(GetBytes((uint)x)).Replace("-", "")));
                                        var interestingChars = keyIv.Count(c => !"0F ".Contains(c));
                                        var key = keyIv.Substring(0, 32 + 3);
                                        var iv = keyIv.Substring(32 + 4, 32 + 3);

                                        candidates.Add(Tuple.Create(key, iv, interestingChars));
                                    }
                                    movs.Clear();
                                }
                            }
                        }
                        catch (IndexOutOfRangeException)
                        {
                        }
                    }
                }
            }
            var candidatesByQuality = candidates.OrderByDescending(t => t.Item3).Where(t => t.Item3 >= 32).ToList();
            return candidatesByQuality;
        }
Beispiel #7
0
        protected X86_Opcodes(Process process)
        {
            this.process = process;

            target_info = Inferior.GetTargetMemoryInfo (AddressDomain.Global);
            if (!Inferior.IsRunningOnWindows)
                disassembler = new BfdDisassembler (null, Is64BitMode);
        }
        public void InvalidSeg32Test()
        {
            var disasm = new Disassembler(new byte[] {
                0x8c, 0x38
            }, ArchitectureMode.x86_32);

            var insn = disasm.NextInstruction();
            Assert.AreEqual("invalid", insn.ToString());
        }
Beispiel #9
0
        protected Architecture(Process process, TargetInfo info)
        {
            this.process = process;
            this.TargetInfo = info;

            if (!Inferior.IsRunningOnWindows)
                disassembler = new BfdDisassembler (process, info.TargetAddressSize == 8);
            if (info.TargetAddressSize == 8)
                opcodes = new Opcodes_X86_64 (process);
            else
                opcodes = new Opcodes_I386 (process);
        }
Beispiel #10
0
        private static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: Chip8Disassembler program [initial address in hex].");
                return;
            }

            string program = args[0];
            int startAddress = -1;

            if (!File.Exists(program))
            {
                Console.WriteLine("Couldn't find program: {0}.", program);
                return;
            }

            if (args.Length == 2)
            {
                if (!int.TryParse(args[1], NumberStyles.HexNumber, CultureInfo.CurrentCulture, out startAddress))
                {
                    Console.WriteLine("Invalid initial address.");
                    return;
                }
            }

            Disassembler disassembler = new Disassembler();

            List<string> instructions;

            if (startAddress != -1)
            {
                try
                {
                    instructions = disassembler.Disassemble(program, (ushort)startAddress).ToList();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            else
            {
                instructions = disassembler.Disassemble(program).ToList();
            }

            foreach (string instruction in instructions)
            {
                Console.WriteLine(instruction);
            }
        }
        public void NegativeRIPAddress()
        {
            var disasm = new Disassembler(new byte[] {
                0x48, 0x8B, 0x05, 0xF7, 0xFF, 0xFF, 0xFF, // mov rax, [rip-0x9]
                0xFF, 0x15, 0xF7, 0xFF, 0xFF, 0xFF,       // call qword [rip-0x9]
            }, ArchitectureMode.x86_64);

            Instruction insn = null;

            insn = disasm.NextInstruction();
            Assert.AreEqual("mov rax, [rip-0x9]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("call qword [rip-0x9]", insn.ToString());
        }
        /// <summary>
        /// Disassemble and reassemble the given ROM and assert the reassembled copy
        /// is bitwise identical to the original.
        /// </summary>
        private static void TestRom(string romToTest)
        {
            //arrange: files and disassembler
            var rom            = new RomFile(romToTest);
            var asmFile        = Path.ChangeExtension(romToTest, ".asm");
            var objectFile     = Path.ChangeExtension(romToTest, ".o");
            var reassembledRom = Path.GetFileNameWithoutExtension(romToTest) + "_Reassembled" + Path.GetExtension(romToTest);
            var dasm           = new Disassembler(rom, new Decoder());

            //act: disassemble, reassemble, hash and compare
            try
            {
                dasm.Disassemble(asmFile);
                if (!Process.Start(new ProcessStartInfo()
                {
                    FileName = Assembler, Arguments = $"{AssemblerFlags} -o \"{objectFile}\" \"{asmFile}\""
                }).WaitForExit(WaitMilliseconds))
                {
                    Assert.Fail($"Assembling \"{asmFile}\" failed or took longer than the allowed {WaitMilliseconds} milliseconds.");
                }

                if (!Process.Start(new ProcessStartInfo()
                {
                    FileName = Linker, Arguments = $"-o \"{reassembledRom}\" \"{objectFile}\""
                }).WaitForExit(WaitMilliseconds))
                {
                    Assert.Fail($"Linking \"{reassembledRom}\" failed or took longer than the allowed {WaitMilliseconds} milliseconds.");
                }

                //assert: re-assembled ROMs are identical to originals
                Assert.AreEqual(ComputeHash(romToTest), ComputeHash(reassembledRom), $"Reassembled ROM differs from original ({romToTest})!");

                //Process.Start(new ProcessStartInfo() { FileName = "bgb", Arguments = $"\"{reassembledRom}\"" });
            }
            catch (Win32Exception ex)
            {
                if (ex.Message.Contains("cannot find the file specified") ||
                    ex.Message.Contains("No such file or directory"))
                {
                    Assert.Fail("Unable to find RGBDS (is it installed and in your PATH?)");
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #13
0
        public override int?Run(AugmentrexContext context, string[] args)
        {
            var opts = Parse <DisassembleOptions>(context, args);

            if (opts == null)
            {
                return(null);
            }

            var parsed  = (int)TypeDescriptor.GetConverter(typeof(int)).ConvertFromString(opts.Offset);
            var address = opts.Absolute ? (MemoryAddress)parsed : context.Memory.ToAddress((MemoryOffset)parsed);

            using var disasm = new Disassembler(address, (int)opts.Length, ArchitectureMode.x86_32, (uint)address, true);
            var         insns = new List <Instruction>();
            Instruction insn;
            string      error = null;

            while ((insn = disasm.NextInstruction()) != null)
            {
                if (insn.Error)
                {
                    error = insn.ErrorMessage;
                    break;
                }

                insns.Add(insn);
            }

            var length = insns.Max(x => x.Bytes.Length);

            foreach (var i in insns)
            {
                i.PrintColored(context, length);
            }

            if (error != null)
            {
                if (insns.Count != 0)
                {
                    context.Line();
                }

                context.WarningLine("Could not disassemble further: {0}", error);
            }

            return(null);
        }
Beispiel #14
0
        public OptionsForm(Disassembler op, Assembler ap, LabelContainer lc, MainFormOptions mf)
        {
            InitializeComponent();
            disassembler = op;
            assembler    = ap;
            lcs          = lc;
            mfo          = mf;
            printOffsetsCheckBox.Checked     = op.PrintOffsets;
            hideDataSectionsCheckBox.Checked = op.HideDefinedData;
            printBitPatternCheckBox.Checked  = op.PrintBitPattern;
            printCommentsCheckBox.Checked    = op.PrintComments;
            wordWrapCheckBox.Checked         = mf.isWordWrap;
            switch (op.PrintedOffsetFormat)
            {
            case OffsetFormat.BankOffset:
                offsetNumberFormatBox.SelectedIndex = 0;
                break;

            case OffsetFormat.Hex:
                offsetNumberFormatBox.SelectedIndex = 1;
                break;

            case OffsetFormat.Decimal:
                offsetNumberFormatBox.SelectedIndex = 2;
                break;
            }
            switch (op.InstructionNumberFormat)
            {
            case OffsetFormat.Hex:
                instructionNumberFormatBox.SelectedIndex = 0;
                break;

            case OffsetFormat.Decimal:
                instructionNumberFormatBox.SelectedIndex = 1;
                break;
            }
            dsmColor00Box.Text = op.GameboyFormatChars.Length > 0 ? op.GameboyFormatChars[0].ToString() : "0";
            dsmColor01Box.Text = op.GameboyFormatChars.Length > 1 ? op.GameboyFormatChars[1].ToString() : "1";
            dsmColor10Box.Text = op.GameboyFormatChars.Length > 2 ? op.GameboyFormatChars[2].ToString() : "2";
            dsmColor11Box.Text = op.GameboyFormatChars.Length > 3 ? op.GameboyFormatChars[3].ToString() : "3";

            asmColor00Box.Text = ap.GameboyFormatChars.Length > 0 ? ap.GameboyFormatChars[0].ToString() : "0";
            asmColor01Box.Text = ap.GameboyFormatChars.Length > 1 ? ap.GameboyFormatChars[1].ToString() : "1";
            asmColor10Box.Text = ap.GameboyFormatChars.Length > 2 ? ap.GameboyFormatChars[2].ToString() : "2";
            asmColor11Box.Text = ap.GameboyFormatChars.Length > 3 ? ap.GameboyFormatChars[3].ToString() : "3";
        }
Beispiel #15
0
        static void DisplayDebug()
        {
            Console.WriteLine(string.Format("AX: {0:X4}\tBX: {1:X4}\tCX: {2:X4}\tDX: {3:X4}",
                                            cpu.EU.Registers.AX, cpu.EU.Registers.BX, cpu.EU.Registers.CX, cpu.EU.Registers.DX));

            Console.WriteLine(string.Format("SP: {0:X4}\tBP: {1:X4}\tSI: {2:X4}\tDI: {3:X4}",
                                            cpu.EU.Registers.SP, cpu.EU.Registers.BP, cpu.EU.Registers.SI, cpu.EU.Registers.DI));

            Console.WriteLine(string.Format("CS: {0:X4}\tDS: {1:X4}\tSS: {2:X4}\tES: {3:X4}",
                                            cpu.Bus.CS, cpu.Bus.DS, cpu.Bus.SS, cpu.Bus.ES));

            Console.WriteLine("\t\tTF DF IF OF SF ZF AF PF CF");

            Console.WriteLine(string.Format("\t\t{0}  {1}  {2}  {3}  {4}  {5}  {6}  {7}  {8}",
                                            FlagToInt(cpu.EU.CondReg.TrapFlag),
                                            FlagToInt(cpu.EU.CondReg.DirectionFlag),
                                            FlagToInt(cpu.EU.CondReg.InterruptEnable),
                                            FlagToInt(cpu.EU.CondReg.OverflowFlag),
                                            FlagToInt(cpu.EU.CondReg.SignFlag),
                                            FlagToInt(cpu.EU.CondReg.ZeroFlag),
                                            FlagToInt(cpu.EU.CondReg.AuxCarryFlag),
                                            FlagToInt(cpu.EU.CondReg.ParityFlag),
                                            FlagToInt(cpu.EU.CondReg.CarryFlag)));

            Console.WriteLine();
            string dasm;
            int    bytes = (int)Disassembler.DisassembleNext(cpu.Bus.GetNext6Bytes(), 0, 0, out dasm);

            Console.WriteLine("IP {0:X4}:{1:X4}: {2}", cpu.Bus.CS, cpu.Bus.IP, dasm);

            byte[] data     = cpu.Bus.GetNextIPBytes(bytes);
            string opstring = "";

            for (int ii = 0; ii < bytes; ii++)
            {
                opstring += string.Format("{0:X2}", data[ii]);
                opstring += " ";
            }
            Console.WriteLine("Op Code: " + opstring);

            if (cpu.EU.Halted)
            {
                Console.WriteLine("Halted! Executed " + count.ToString() + " instructions");
                Console.WriteLine("Execution Time: " + sw.ElapsedMilliseconds.ToString());
            }
        }
Beispiel #16
0
        public static void SearchAssembly()
        {
            //  Disassemble the assembly.
            DisassembledAssembly disassembledAssembly = Disassembler.DisassembleAssembly(@"SomeAssembly.dll");

            //  Create a disassembly target that targets the interface named 'ISomeInterface'.
            DisassemblyTarget target = new DisassemblyTarget(DisassemblyTargetType.Interface, @"SimeAssembly.ISomeInterface");

            //  Search for the interface.
            DisassembledEntity entity = disassembledAssembly.FindDisassembledEntity(target);

            //  If we found it, show the IL.
            if (entity != null)
            {
                Console.WriteLine(entity.RawIL);
            }
        }
        public void Disassemble64BitResolveRIPAddress()
        {
            var defaultTranslator = SharpDisasm.Disassembler.Translator;

            SharpDisasm.Disassembler.Translator = new SharpDisasm.Translators.IntelTranslator()
            {
                ResolveRip = true
            };
            try
            {
                var disasm = new Disassembler(new byte[] {
                    0x48, 0x8B, 0x05, 0xF7, 0xFF, 0xFF, 0xFF, // mov rax, [rip-0x9] -> mov rax, [0x7ff71bfffffe]
                    0xFF, 0x15, 0xF7, 0xFF, 0xFF, 0xFF,       // call qword [rip-0x9] -> call qword [0x7ff71c000004]
                }, ArchitectureMode.x86_64, 0x7ff71c000000);

                var dis = disasm.Disassemble();
                Assert.AreEqual("mov rax, [0x7ff71bfffffe]", dis.First().ToString());
                Assert.AreEqual("call qword [0x7ff71c000004]", dis.Last().ToString());

                Disassembler.Translator.IncludeAddress = true;
                Disassembler.Translator.IncludeBinary  = true;
                foreach (var ins in dis)
                {
                    Debug.WriteLine(ins.ToString());
                }

                SharpDisasm.Disassembler.Translator = new SharpDisasm.Translators.ATTTranslator()
                {
                    ResolveRip = true
                };

                Assert.AreEqual("movq 0x7ff71bfffffe, %rax", dis.First().ToString());
                Assert.AreEqual("callq 0x7ff71c000004", dis.Last().ToString());

                Disassembler.Translator.IncludeAddress = true;
                Disassembler.Translator.IncludeBinary  = true;
                foreach (var ins in disasm.Disassemble())
                {
                    Debug.WriteLine(ins.ToString());
                }
            }
            finally
            {
                SharpDisasm.Disassembler.Translator = defaultTranslator;
            }
        }
        public void DisassembleFile(string outputfile)
        {
            bool _skipDisassembly = false;

            if (File.Exists(outputfile))
            {
                if (MessageBox.Show("Assemblerfile already exists, do you want to redo the disassembly?", "Question", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    _skipDisassembly = true;
                }
            }
            if (!_skipDisassembly)
            {
                Disassembler disasm = new Disassembler();
                disasm.onProgress += new Disassembler.Progress(disasm_onProgress);
                logger.Debug("Starting disassembly");
                disasm.DisassembleFile(filename, m_symbols);
                logger.Debug("Done disassembling: " + disasm.Mnemonics.Count.ToString());
                using (StreamWriter sw = new StreamWriter(outputfile))
                {
                    foreach (MNemonicHelper helper in disasm.Mnemonics)
                    {
                        if (helper.Mnemonic.Contains(":"))
                        {
                            //listBox1.Items.Add(helper.Mnemonic);
                            if (!helper.Mnemonic.Contains("LBL_"))
                            {
                                sw.WriteLine();
                            }
                            sw.WriteLine(helper.Mnemonic);
                        }
                        else
                        {
                            //listBox1.Items.Add(helper.Address.ToString("X8") + " " + helper.Mnemonic);
                            sw.WriteLine("0x" + helper.Address.ToString("X8") + "\t" + helper.Mnemonic);
                        }
                    }
                }
                // start the external viewer with the file
            }
            LoadFile(outputfile);
            string copyFile = filename + DateTime.Now.Ticks.ToString();

            File.Copy(filename, copyFile);
            LoadBinaryFile(copyFile, m_symbols);
        }
Beispiel #19
0
        /// <summary>
        /// Disassemble the specified bytes.
        /// </summary>
        /// <param name="bytes">The bytes to be disassembled.</param>
        /// <param name="isProcess32Bit">Whether or not the assembly is in the context of a 32 bit program.</param>
        /// <param name="baseAddress">The address where the code is rebased.</param>
        /// <returns>An array of bytes containing the assembly code.</returns>
        public IEnumerable <NormalizedInstruction> Disassemble(Byte[] bytes, Boolean isProcess32Bit, IntPtr baseAddress)
        {
            this.disassembler = new Disassembler(
                code: bytes,
                architecture: isProcess32Bit ? ArchitectureMode.x86_32 : ArchitectureMode.x86_64,
                address: baseAddress.ToUInt64(),
                copyBinaryToInstruction: true);

            IEnumerable <Instruction> instructions = this.disassembler.Disassemble();

            return(instructions.Select(instruction =>
                                       new NormalizedInstruction(
                                           instruction.Offset,
                                           instruction.ToString(),
                                           instruction.Bytes,
                                           instruction.Bytes.Length)).ToArray());
        }
        private void AutoPatchButton_Click(object sender, EventArgs e)
        {
            ArchitectureMode architecture = ArchitectureMode.x86_64;

            Disassembler.Translator.IncludeAddress = true;
            Disassembler.Translator.IncludeBinary  = true;
            ulong uint64 = Convert.ToUInt64(this.AddressTextBox.Text.Trim().Replace("0x", ""), 16);

            Instruction[] array =
                new Disassembler(this.ps4.ReadMemory(this.attachpid, uint64, 50), architecture, uint64, true,
                                 Vendor.Any, 0UL).Disassemble().ToArray <Instruction>();
            for (int index = 0; index < array[0].Length; ++index)
            {
                this.ps4.WriteMemory(this.attachpid, array[0].Offset + (ulong)index, (byte)144);
            }
            this.PeekButton_Click((object)null, (EventArgs)null);
        }
Beispiel #21
0
        private void CPU_ExecutedInstruction(object sender, System.EventArgs e)
        {
            var pc = this.CPU.PC.Word;

            if (this.oldPC != pc)
            {
                this.oldPC = pc;
            }
            else
            {
                this.LowerPOWER();
                var test = this.Peek(0x0200);
                System.Console.Out.WriteLine();
                System.Console.Out.Write("** Test=");
                System.Console.Out.WriteLine(Disassembler.DumpByteValue(test));
            }
        }
Beispiel #22
0
        private void CountStepsToRunBeforeCallingAfterScenario()
        {
            int        i = -1;
            StackFrame stackFrame;

            do
            {
                i++;
                stackFrame = new StackFrame(i);
            } while (stackFrame.GetMethod().DeclaringType.Assembly == typeof(ScenarioBuilder).Assembly);

            var instructions = Disassembler.GetInstructions(stackFrame.GetMethod())
                               .Where(CallsNBehave)
                               .ToList();

            stepsToRunBeforeAfterScenario = instructions.Count;
        }
Beispiel #23
0
        private long PerformanceTest_SimulatedRewriter(byte[] buf, Decoder root)
        {
#if NYI
            var       rdr      = new BeImageReader(buf);
            var       dasm     = new Disassembler(rdr, root);
            var       rewriter = new Rewriter(dasm);
            Stopwatch sw       = new Stopwatch();
            sw.Start();
            foreach (var instr in rewriter)
            {
            }
            sw.Stop();
            var time = sw.ElapsedMilliseconds;
            return(time);
#endif
            return(1);
        }
Beispiel #24
0
        public void Disassemble_Test_Program()
        {
            var program = new byte[] { 0x00, 0x01, 0xAD, 0xDE, 0x00, 0x03 };
            var dasm    = new Disassembler(new RomFile(program)
            {
                HasHeader = false
            }, decoder, targetLineWidth: 20);

            string expectedDisassembly =
                $"SECTION \"rom0\", ROM0{Environment.NewLine}" +
                $"nop           ;$0000{Environment.NewLine}" +
                $"ld bc, $dead  ;$0001{Environment.NewLine}" +
                $"nop           ;$0004{Environment.NewLine}" +
                $"inc bc        ;$0005";

            Assert.AreEqual(expectedDisassembly, dasm.Disassemble());
        }
Beispiel #25
0
        protected override void Disassemble(Disassembler disasm, bool publicOnly)
        {
            disasm.AppendHeader(Type);
            disasm.BeginNamespace(Type.FirstNamespace);
            disasm.AppendType(Type, publicOnly);

            foreach (var c in Overloads.Children)
            {
                var t = c as TypeItem;
                if (t != null)
                {
                    disasm.AppendType(t.Type, publicOnly);
                }
            }

            disasm.EndNamespace();
        }
Beispiel #26
0
        //string _code = String.Empty;

        /// <summary>
        /// For a given methodDefinition, create a CFG and run basic analyses such as
        /// stack removal, SSA transformation, live-variables analysis, and copy-propagation.
        /// </summary>
        /// <param name="methodDefinition"></param>
        /// <returns></returns>
        private ControlFlowGraph PrepareMethod(IMethodDefinition methodDefinition)
        {
            var disassembler = new Disassembler(mhost, methodDefinition, sourceLocationProvider);
            var methodBody   = disassembler.Execute();

            var cfg = ControlFlowGraph.GenerateNormalControlFlow(methodBody);

            ControlFlowGraph.ComputeDominators(cfg);
            ControlFlowGraph.IdentifyLoops(cfg);

            ControlFlowGraph.ComputeDominatorTree(cfg);
            ControlFlowGraph.ComputeDominanceFrontiers(cfg);

            // Uniquely rename stack variables.
            var splitter = new WebAnalysis(cfg);

            splitter.Analyze();
            splitter.Transform();

            methodBody.UpdateVariables();

            // Infer types for stack variables.
            var typeAnalysis = new TypeInferenceAnalysis(cfg);

            typeAnalysis.Analyze();

            var backwardCopyAnalysis = new BackwardCopyPropagationAnalysis(cfg);

            backwardCopyAnalysis.Analyze();
            backwardCopyAnalysis.Transform(methodBody);

            var lva = new LiveVariablesAnalysis(cfg);

            lva.Analyze();

            var ssa = new StaticSingleAssignmentAnalysis(methodBody, cfg);

            ssa.Transform();
            ssa.Prune(lva);

            methodBody.UpdateVariables();

            //_code = methodBody.ToString();
            return(cfg);
        }
Beispiel #27
0
            public void Run(string programpath)
            {
                var display  = new ConsoleDisplay();
                var keyboard = new ConsoleKeyboard();

                memory       = new Memory();
                cpu          = new CPU(memory, display, keyboard);
                disassembler = new Disassembler();

                // Load ROM
                var romfile = File.OpenRead("ROM.bin");
                var rom     = new byte[512];

                romfile.Read(rom, 0, 512);
                romfile.Close();
                memory.InitializeROM(rom);

                // Load Program
                var programfile = File.OpenRead(programpath);
                var program     = new byte[3584];

                programfile.Read(program, 0, 3584);
                memory.LoadProgram(program);

                // Start clock
                Stopwatch sw       = new Stopwatch();
                var       cpuspeed = 6 * Stopwatch.Frequency / 1000;

                while (true)
                {
                    var debug = keyboard.CheckKeys();
                    if (debug)
                    {
                        StartDebugging();
                        debug = false;
                        continue;
                    }

                    if (!sw.IsRunning || sw.ElapsedTicks > cpuspeed)
                    {
                        cpu.Clock();
                        sw.Restart();
                    }
                }
            }
        public void DisassembleLargeBuffer()
        {
            var b = new byte[] {
                0x67, 0x66, 0x8b, 0x40, 0xf0                                    // mov ax, [eax-0x10]
                , 0x67, 0x66, 0x03, 0x5e, 0x10                                  // add bx, [esi+0x10]
                , 0x48, 0x03, 0x04, 0x25, 0xff, 0xff, 0x00, 0x00                // add rax, [0xffff]
                , 0x67, 0x66, 0x03, 0x44, 0xbe, 0xf0                            // add ax, [esi+edi*4-0x10]
                , 0x4c, 0x03, 0x84, 0x98, 0x00, 0x00, 0x00, 0x80                // add r8, [rax+rbx*4-0x80000000]
                , 0x48, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00    // mov rax, [0x800000000000]
            };

            int         iterations = 1000000;
            List <byte> bytes      = new List <byte>(b.Length * iterations);

            for (var i = 0; i < iterations; i++)
            {
                bytes.AddRange(b);
            }

            var disasm = new Disassembler(bytes.ToArray(), ArchitectureMode.x86_64, 0, false);

            Stopwatch sw = new Stopwatch();
            int       instructionCount = 0;
            int       totalBytes       = 0;

            sw.Start();
            foreach (var ins in disasm.Disassemble())
            {
                instructionCount++;
                totalBytes += ins.Length;
                //var s = ins.ToString();
            }

            sw.Stop();
            Debug.WriteLine(sw.Elapsed);

            // Should be completed in less than 1 seconds even in debug (usually completes 600k instructions within 200-600ms)
            //Assert.IsTrue(sw.Elapsed < new TimeSpan(0, 0, 1));

            // Ensure correct number of instructions were disassembled
            Assert.AreEqual(6 * iterations, instructionCount);

            // Ensure correct number of bytes in total
            Assert.AreEqual(b.Length * iterations, totalBytes);
        }
Beispiel #29
0
        /**
         * Prints last n instructions that were executed up to MAX_ADDRESS_HISTORY.
         * Useful when a debugger is attached. Only works when Debug is true.
         */
        private static List <string> FormatRecentInstructions(List <UInt16> history, IMemory memory, int count = 10)
        {
            var output = new List <string>();

            if (count > history.Count)
            {
                count = history.Count;
            }

            var startIndex = history.Count - count;

            for (var i = startIndex; i < history.Count; i++)
            {
                var address = history[i];

                try
                {
                    var disassemblyLine = Disassembler.Disassemble(memory, address, out _, true, true);

                    // Double tabs followed by a semi-colon indicate a split between the address/instruction disassembly
                    // and the generated psuedocode or annotations.
                    var disassemblyLineParts   = disassemblyLine.Split("\t\t; ".ToCharArray());
                    var disassemblyInstruction = disassemblyLineParts[0];
                    var disassemblyComments    = disassemblyLineParts.Length > 1 ? disassemblyLineParts[1] : "";

                    // Convert tabs to spaces (there is no tab character in the font set, only 8x8 glyphs).
                    disassemblyInstruction = disassemblyInstruction.Replace("\t", "     ");

                    disassemblyInstruction = disassemblyInstruction.PadRight(30);
                    var line = $"{COLOR_WHITE}{disassemblyInstruction} {COLOR_BLUE};{disassemblyComments}";

                    output.Add(line);
                }
                catch (IndexOutOfRangeException)
                {
                    // Edge case for being able to print instruction history when we've jumped outside
                    // of the allowable memory locations.
                    var addressDisplay = String.Format("0x{0:X4}", address);
                    output.Add($"[IndexOutOfRange: {addressDisplay}]");
                    continue;
                }
            }

            return(output);
        }
Beispiel #30
0
        public void ControlFlowLabelsSample()
        {
            Action method       = ControlFlowLabels;
            var    disassembler = new Disassembler();
            var    result       = disassembler.Disassemble(method);

            result.IsNotNull();

            // enumerate label with Labels result count is 2
            //
            // because for (int i = 0; i < 100; i++) { WriteLine()} is compiled as
            // i=0; goto Label1;
            // Label0: Console.WriteLine(i);
            // i++;
            // Label1: if( (i<100 ) ) goto Label0;
            //
            result.Labels.Count().Is(2);
        }
Beispiel #31
0
        protected Architecture(Process process, TargetInfo info)
        {
            this.process    = process;
            this.TargetInfo = info;

            if (!Inferior.IsRunningOnWindows)
            {
                disassembler = new BfdDisassembler(process, info.TargetAddressSize == 8);
            }
            if (info.TargetAddressSize == 8)
            {
                opcodes = new Opcodes_X86_64(process);
            }
            else
            {
                opcodes = new Opcodes_I386(process);
            }
        }
Beispiel #32
0
        private void Disassemble()
        {
            int lineCount = DisassemblerView.RowCount + 2;

            _disassemblyLines.Clear();
            uint a = _currentDisassemblerAddress;

            for (int i = 0; i <= lineCount; ++i)
            {
                string line = Disassembler.Disassemble(MemoryDomains.SystemBus, a, out var advance);
                _disassemblyLines.Add(new DisasmOp(a, advance, line));
                a += (uint)advance;
                if (a > BusMaxValue)
                {
                    break;
                }
            }
        }
Beispiel #33
0
        public void Basics()
        {
            var parsed = Parser.Parse(@"
                #ip 0
                seti 5 0 1
                seti 6 0 2
                addi 0 1 0
                addr 1 2 3
                setr 1 0 0
                seti 8 0 4
                seti 9 0 5");

            var text = Disassembler
                       .Disassemble(parsed.boundIP, parsed.instrs)
                       .StringJoin('\n');

            Debug.WriteLine(text);
        }
Beispiel #34
0
        private void UpdateDisplay(ulong address, byte[] memory)
        {
            instructions.Clear();

            var mode = ArchitectureMode.x86_32;             // todo:

            using (var disasm = new Disassembler(memory, mode, address, true, Vendor.Any))
            {
                var translator = new SharpDisasm.Translators.IntelTranslator()
                {
                    IncludeAddress = false,
                    IncludeBinary  = false
                };

                foreach (var instruction in disasm.Disassemble())
                {
                    var text = translator.Translate(instruction);

                    var info = string.Empty;

                    var value = ParseAddress(text);

                    if (value != 0)
                    {
                        var symbol = DebugSource.GetFirstSymbolsStartingAt(value);

                        if (symbol != null)
                        {
                            info = symbol.Name;
                        }
                    }

                    var entry = new MethodInstructionEntry()
                    {
                        IP          = instruction.Offset,
                        Length      = instruction.Length,
                        Instruction = text,
                        Info        = info
                    };

                    instructions.Add(entry);
                }
            }
        }
Beispiel #35
0
        internal GMFile(GMFileContent f)
        {
            Content = f;

            General = SectionReader.GetGeneralInfo(f);
            Options = SectionReader.GetOptionInfo(f);

            Sound        = Utils.UintRange(0, f.Sounds->Count).Select(i => SectionReader.GetSoundInfo(f, i)).ToArray();
            Sprites      = Utils.UintRange(0, f.Sprites->Count).Select(i => SectionReader.GetSpriteInfo(f, i)).ToArray();
            Backgrounds  = Utils.UintRange(0, f.Backgrounds->Count).Select(i => SectionReader.GetBgInfo(f, i)).ToArray();
            Paths        = Utils.UintRange(0, f.Paths->Count).Select(i => SectionReader.GetPathInfo(f, i)).ToArray();
            Scripts      = Utils.UintRange(0, f.Scripts->Count).Select(i => SectionReader.GetScriptInfo(f, i)).ToArray();
            Fonts        = Utils.UintRange(0, f.Fonts->Count).Select(i => SectionReader.GetFontInfo(f, i)).ToArray();
            Objects      = Utils.UintRange(0, f.Objects->Count).Select(i => SectionReader.GetObjectInfo(f, i)).ToArray();
            Rooms        = Utils.UintRange(0, f.Rooms->Count).Select(i => SectionReader.GetRoomInfo(f, i)).ToArray();
            TexturePages = Utils.UintRange(0, f.TexturePages->Count).Select(i => SectionReader.GetTexPageInfo(f, i)).ToArray();
            Code         = Utils.UintRange(0, f.Code->Count).Select(i => Disassembler.DisassembleCode(f, i)).ToArray();
            Strings      = Utils.UintRange(0, f.Strings->Count).Select(i => SectionReader.GetStringInfo(f, i)).ToArray();
            Textures     = Utils.UintRange(0, f.Textures->Count).Select(i => SectionReader.GetTextureInfo(f, i)).ToArray();
            Audio        = Utils.UintRange(0, f.Audio->Count).Select(i => SectionReader.GetAudioInfo(f, i)).ToArray();

            AudioSoundMap = new Dictionary <uint, uint>();
            for (uint i = 0; i < Sound.Length; i++)
            {
                var s = Sound[i];

                if ((s.IsEmbedded || s.IsCompressed) && s.AudioId != -1)
                {
                    AudioSoundMap[(uint)s.AudioId] = i;
                }
            }

            var vars = General.IsOldBCVersion ? SectionReader.GetRefDefs(f, f.Variables) : SectionReader.GetRefDefsWithOthers(f, f.Variables);
            var fns  = General.IsOldBCVersion ? SectionReader.GetRefDefs(f, f.Functions) : SectionReader.GetRefDefsWithLength(f, f.Functions);

            RefData = new RefData
            {
                Variables = vars,
                Functions = fns,

                VarAccessors  = Disassembler.GetReferenceTable(f, vars),
                FuncAccessors = Disassembler.GetReferenceTable(f, fns)
            };
        }
Beispiel #36
0
        public Mini8086Emulator()
        {
            var components = new List <BaseComponent>();

            _memMapper  = new MemoryMapper(512);
            _portMapper = new PortMapper();

            _cpu          = new Cpu8086(_memMapper, _portMapper);
            _disassembler = new Disassembler(_cpu, _memMapper);

            components.Add(_bios = new Rom(Config.BiosMemAddress));
            _memMapper.Register(Config.BiosMemAddress, Config.BiosMemAddress + Config.BiosMemSize - 1, _bios);

            components.Add(_pic = new InterruptController(Config.PicBasePort));
            _portMapper.Register(Config.PicBasePort, Config.PicBasePort + 0x07, _pic);

            components.Add(_timer = new Timer(Config.TimerBasePort, _pic));
            _portMapper.Register(Config.TimerBasePort, Config.TimerBasePort + 0x07, _timer);

            components.Add(_graphicsAdapter = new GraphicsAdapter(Config.VgaBasePort, Config.VgaMemAddress, _pic, @"..\..\..\ROMs\charrom.bin"));
            _portMapper.Register(Config.VgaBasePort, Config.VgaBasePort + 0x07, _graphicsAdapter);
            _memMapper.Register(Config.VgaMemAddress, Config.VgaMemAddress + Config.VgaMemSize - 1, _graphicsAdapter);

            components.Add(_lcd = new Lcd44780(Config.LcdBasePort));
            _portMapper.Register(Config.LcdBasePort, Config.LcdBasePort + 0x07, _lcd);

            //components.Add(_ppi = new Ppi(Config.PpiBasePort));
            //_portMapper.Register(Config.PpiBasePort, Config.PpiBasePort + 0x07, _ppi);

            components.Add(_keybController = new KeybController(Config.KeybControllerBasePort, _pic));
            _portMapper.Register(Config.KeybControllerBasePort, Config.KeybControllerBasePort + 0x07, _keybController);

            components.Add(_sdController = new SdController(Config.SdControllerBasePort, Config.SdImagePath));
            _portMapper.Register(Config.SdControllerBasePort, Config.SdControllerBasePort + 0x07, _sdController);

            _memMapper.FinishRegistration();

            components.ForEach(_ =>
            {
                _.EventTimer     = _cpu;
                _.DoCpuInterrupt = _cpu.DoInterrupt;
            });
        }
Beispiel #37
0
 private void frmMain_Shown(object sender, EventArgs e)
 {
     if (InstructionSet.OperationsList == null)
     {
         MessageBox.Show("No Intruction Set!", "Fatal", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         Application.Exit();
         return;
     }
     DiskOperations.VHDPath = settings.VHDImagePath;
     CheckDiskImageWritable();
     Disassembler.GenerateInstructionsText();
     Display.InitScreen();
     Sound.Init();
     Clipboard.Clear();
     if (OpenBin("system.bin"))
     {
         btnRun_Click(null, null);
     }
 }
Beispiel #38
0
        /// <summary>
        /// Runs the disassembler with the provided set of arguments.
        /// </summary>
        /// <param name="options">The options provided by the user.</param>
        private static int RunDisassembler(DisassemblerOptions options)
        {
            ILogger logger      = null;
            string  logFileName = options.LogFile;

            if (!string.IsNullOrEmpty(logFileName) && !string.IsNullOrWhiteSpace(logFileName))
            {
                logger = new HybridLogger(logFileName.Trim());
            }
            else
            {
                logger = new ConsoleLogger();
            }

            var disassembler = new Disassembler();

            disassembler.Disassemble(options, logger);
            return(0);
        }
Beispiel #39
0
            protected override void TraceFromCallback()
            {
                var  regs   = DebuggableCore.GetCpuFlagsAndRegisters();
                uint pc     = (uint)regs["M68K PC"].Value;
                var  length = 0;
                var  disasm = Disassembler.Disassemble(MemoryDomains.SystemBus, pc, out length);

                var traceInfo = new TraceInfo
                {
                    Disassembly = string.Format("{0:X6}:  {1}", pc, disasm)
                };

                var sb = new StringBuilder();

                foreach (var r in regs)
                {
                    if (r.Key.StartsWith("M68K"))                        // drop Z80 regs until it has its own debugger/tracer
                    {
                        if (r.Key != "M68K SP" && r.Key != "M68K ISP" && // copies of a7
                            r.Key != "M68K PC" &&                        // already present in every line start
                            r.Key != "M68K IR")                          // copy of last opcode, already shown in raw bytes
                        {
                            sb.Append(
                                string.Format("{0}:{1} ",
                                              r.Key.Replace("M68K", "").Trim(),
                                              r.Value.Value.ToHexString(r.Value.BitSize / 4)));
                        }
                    }
                }
                var sr = regs["M68K SR"].Value;

                sb.Append(
                    string.Format("{0}{1}{2}{3}{4}",
                                  (sr & 16) > 0 ? "X" : "x",
                                  (sr & 8) > 0 ? "N" : "n",
                                  (sr & 4) > 0 ? "Z" : "z",
                                  (sr & 2) > 0 ? "V" : "v",
                                  (sr & 1) > 0 ? "C" : "c"));

                traceInfo.RegisterInfo = sb.ToString().Trim();

                Put(traceInfo);
            }
        private void Disassemble()
        {
            int line_count = DisassemblerView.NumberOfVisibleRows;

            DisassemblyLines.Clear();
            uint a = currentDisassemblerAddress;

            for (int i = 0; i <= line_count; ++i)
            {
                int    advance;
                string line = Disassembler.Disassemble(MemoryDomains.SystemBus, a, out advance);
                DisassemblyLines.Add(new DisasmOp(a, advance, line));
                a += (uint)advance;
                if (a > BusMaxValue)
                {
                    break;
                }
            }
        }
Beispiel #41
0
        private void UpdateDisplay(ulong address, byte[] memory)
        {
            if (address != InstructionPointer)
            {
                return;
            }

            var disassembler = new Disassembler("x86");

            disassembler.SetMemory(memory, address);

            tbInstruction.Text = "Unable to decode!";

            foreach (var instruction in disassembler.Decode())
            {
                tbInstruction.Text = instruction.Instruction;
                break;
            }
        }
Beispiel #42
0
        public Gameboy(Rom rom, bool useBios = true)
        {
            MemoryRouter = new MemoryRouter(rom.Memory);
            Cpu = new Cpu(MemoryRouter);
            timer = new GameboyTimer();
            Video = new Video();
            Joypad = new Joypad();
            Audio = new Audio();
            Disassembler = new Disassembler(MemoryRouter);

            Video.MemoryRouter = MemoryRouter;
            MemoryRouter.Video = Video;
            Joypad.MemoryRouter = MemoryRouter;
            MemoryRouter.Joypad = Joypad;
            timer.MemoryRouter = MemoryRouter;
            MemoryRouter.Timer = timer;
            MemoryRouter.Audio = Audio;

            if (!useBios) InitDevice();
        }
        public void Disp64Test()
        {
            var disasm = new Disassembler(new byte[] {
                0x67, 0x66, 0x8b, 0x40, 0xf0      
                , 0x67, 0x66, 0x03, 0x5e, 0x10      
                , 0x48, 0x03, 0x04, 0x25, 0xff, 0xff, 0x00, 0x00
                , 0x67, 0x66, 0x03, 0x44, 0xbe, 0xf0    
                , 0x4c, 0x03, 0x84, 0x98, 0x00, 0x00, 0x00, 0x80
                , 0x48, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00
            }, ArchitectureMode.x86_64);
//0000000000000000 67668b40f0       mov ax, [eax-0x10]      
//0000000000000005 6766035e10       add bx, [esi+0x10]      
//000000000000000a 48030425ffff0000 add rax, [0xffff]       
//0000000000000012 67660344bef0     add ax, [esi+edi*4-0x10]
//0000000000000018 4c03849800000080 add r8, [rax+rbx*4-0x80000000]
//0000000000000020 48a1000000000080 mov rax, [0x800000000000]

            Instruction insn = null;

            insn = disasm.NextInstruction();
            Assert.AreEqual("mov ax, [eax-0x10]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("add bx, [esi+0x10]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("add rax, [0xffff]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("add ax, [esi+edi*4-0x10]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("add r8, [rax+rbx*4-0x80000000]", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("mov rax, [0x800000000000]", insn.ToString());

        }
        public void Corner32Test()
        {
            var disasm = new Disassembler(new byte[] {
                0x67, 0x0f, 0x02, 0x00,
                0x90,
                0xf3, 0x90
            }, ArchitectureMode.x86_32);
//0000000000000000 670f0200         lar eax, word [bx+si]   
//0000000000000004 90               nop                     
//0000000000000005 f390             pause                   

            var insn = disasm.NextInstruction();
            Assert.AreEqual("lar eax, word [bx+si]", insn.ToString());
            Assert.AreEqual(4, insn.Length);

            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            Assert.AreEqual(1, insn.Length);

            insn = disasm.NextInstruction();
            Assert.AreEqual("pause", insn.ToString());
            Assert.AreEqual(2, insn.Length);
        }
        public void Decode32Test()
        {
            var disasm = new Disassembler(new byte[] {
                0xb8, 0x34, 0x12, 0x00, 0x00,   // mov eax, 0x1234
                0xa1, 0x34, 0x12, 0x00, 0x00,   // mov eax, [0x1234]
                0x89, 0x45, 0xEC,               // mov [ebp-0x14], eax
                0x83, 0xe2, 0xdf,               // and edx, 0xffffffdf
            }, ArchitectureMode.x86_32);

            var insn = disasm.NextInstruction();
            Assert.AreEqual("mov eax, 0x1234", insn.ToString());
            Assert.AreEqual(5, insn.Length);

            insn = disasm.NextInstruction();
            Assert.AreEqual("mov eax, [0x1234]", insn.ToString());
            Assert.AreEqual(5, insn.Length);

            insn = disasm.NextInstruction();
            Assert.AreEqual("mov [ebp-0x14], eax", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("and edx, 0xffffffdf", insn.ToString());
        }
Beispiel #46
0
 private void showFullDisassemblyToolStripMenuItem_Click(object sender, EventArgs e)
 {
     string outputfile = Path.GetDirectoryName(m_currentfile);
     outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(m_currentfile) + "_full.asm");
     if (!AssemblerViewerActive(true, outputfile))
     {
         frmProgress progress = new frmProgress();
         progress.Show();
         progress.SetProgress("Start disassembler");
         if (!File.Exists(outputfile))
         {
             progress.SetProgress("Disassembler running...");
             Disassembler dis = new Disassembler();
             dis.DisassembleFileRtf(m_currentfile, outputfile, m_currentfile_size, m_symbols);
             progress.SetProgress("Disassembler done...");
         }
         progress.SetProgress("Loading assembler file");
         StartAssemblerViewer(outputfile, progress);
         progress.Close();
     }
 }
	private void btSave_Click(System.Object sender, System.EventArgs e)
	{
		SaveFileDialog dialog = new SaveFileDialog();
		if (dialog.ShowDialog() == DialogResult.OK) {
			Disassembler disasm = new Disassembler();
			disasm.DisassembleBinaryLoadFile(_file, dialog.FileName);
		}
	}
        public void RelativeJump32Test()
        {
            // set program counter offset
            var disasm = new Disassembler(new byte[] {
                0x90,
                0x90,
                0x90,
                0x90,
                0x90,
                0xeb, 0xf9,
                0x90,
                0x66, 0xe9, 0x0a, 0x00,
                0x90,
                0x90,
                0xe9, 0x03, 0x00, 0x00, 0x00,
                0x90,
                0x90,
                0x90,
                0x90,
                0x90,
                0xeb, 0xe6,
                0x89, 0x45, 0xEC,
            }, ArchitectureMode.x86_32, 0x80000000);
/*
0000000080000000 90               nop                     
0000000080000001 90               nop                     
0000000080000002 90               nop                     
0000000080000003 90               nop                     
0000000080000004 90               nop                     
0000000080000005 ebf9             jmp 0x80000000          
0000000080000007 90               nop                     
0000000080000008 66e90a00         jmp 0x16                
000000008000000c 90               nop                     
000000008000000d 90               nop                     
000000008000000e e903000000       jmp 0x80000016          
0000000080000013 90               nop                     
0000000080000014 90               nop                     
0000000080000015 90               nop                     
0000000080000016 90               nop                     
0000000080000017 90               nop                     
0000000080000018 ebe6             jmp 0x80000000  
    * */

            var insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("jmp 0x80000000", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("jmp 0x16", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("jmp 0x80000016", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());
            insn = disasm.NextInstruction();
            Assert.AreEqual("nop", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("jmp 0x80000000", insn.ToString());
        }
Beispiel #49
0
		private void  printActions(ActionList list)
		{
			if (decompile)
			{
				/*
				AsNode node;
				try
				{
				node = new Decompiler(defunc).decompile(list);
				new PrettyPrinter(out, indent).list(node);
				return;
				}
				catch (Exception e)
				{
				indent();
				out.println("// error while decompiling.  falling back to disassembler");
				}
				*/
			}
			
			Disassembler disassembler = new Disassembler(out_Renamed, showOffset, indent_Renamed_Field);
			if (showDebugSource)
			{
				disassembler.ShowDebugSource = showDebugSource;
				disassembler.Comment = "// ";
			}
			list.visitAll(disassembler);
		}
        public void DisassembleLargeMemory()
        {
            var b = new byte[] {
                0x67, 0x66, 0x8b, 0x40, 0xf0                                    // mov ax, [eax-0x10]
                , 0x67, 0x66, 0x03, 0x5e, 0x10                                  // add bx, [esi+0x10]
                , 0x48, 0x03, 0x04, 0x25, 0xff, 0xff, 0x00, 0x00                // add rax, [0xffff]
                , 0x67, 0x66, 0x03, 0x44, 0xbe, 0xf0                            // add ax, [esi+edi*4-0x10]
                , 0x4c, 0x03, 0x84, 0x98, 0x00, 0x00, 0x00, 0x80                // add r8, [rax+rbx*4-0x80000000]
                , 0x48, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00    // mov rax, [0x800000000000]
            };

            int iterations = 1000000;

            IntPtr mem = Marshal.AllocHGlobal(b.Length * iterations);

            int len = 0;
            for (var i = 0; i < iterations; i++)
            {
                foreach (var v in b)
                {
                    Marshal.WriteByte(mem, len++, v);
                }
            }

            var disasm = new Disassembler(mem, len, ArchitectureMode.x86_64, 0, false);

            Stopwatch sw = new Stopwatch();
            int instructionCount = 0;
            int totalBytes = 0;
            sw.Start();
            foreach (var ins in disasm.Disassemble())
            {
                instructionCount++;
                totalBytes += ins.Length;
                //var s = ins.ToString();
            }

            sw.Stop();
            Debug.WriteLine(sw.Elapsed);

            // Should be completed in less than 1 seconds even in debug (usually completes 600k instructions within 200-600ms)
            //Assert.IsTrue(sw.Elapsed < new TimeSpan(0, 0, 1));

            // Ensure correct number of instructions were disassembled
            Assert.AreEqual(6 * iterations, instructionCount);

            // Ensure correct number of bytes in total
            Assert.AreEqual(b.Length * iterations, totalBytes);
        }
 private static void ReAssembleMethod(MethodBase method)
 {
     var disassembler = new Disassembler();
     if (disassembler.CanDisassemble(method))
     {
         var result = disassembler.Disassemble(method);
         result.Assemble(new AssembleContext());
     }
 }
Beispiel #52
0
 protected virtual void DoDispose()
 {
     if (disassembler != null) {
         disassembler.Dispose ();
         disassembler = null;
     }
 }
        public void Obscure32Test()
        {
            var disasm = new Disassembler(new byte[] {
                0xd1, 0xf6,
                0xd0, 0xf6,
                0xd9, 0xd9,
                0xdc, 0xd0, 
                0xdc, 0xd8,
                0xdd, 0xc8,
                0xde, 0xd1,
                0xdf, 0xc3,
                0xdf, 0xd0,
                0xdf, 0xd8,
            }, ArchitectureMode.x86_32);
//0000000000000000 d1f6             shl esi, 1              
//0000000000000002 d0f6             shl dh, 1               
//0000000000000004 d9d9             fstp1 st1               
//0000000000000006 dcd0             fcom2 st0               
//0000000000000008 dcd8             fcomp3 st0              
//000000000000000a ddc8             fxch4 st0               
//000000000000000c ded1             fcomp5 st1              
//000000000000000e dfc3             ffreep st3              
//0000000000000010 dfd0             fstp8 st0               
//0000000000000012 dfd8             fstp9 st0               
//0000000000000014 83e2df           and edx, 0xffffffdf     

            var insn = disasm.NextInstruction();
            Assert.AreEqual("shl esi, 1", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("shl dh, 1", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fstp1 st1", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fcom2 st0", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fcomp3 st0", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fxch4 st0", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fcomp5 st1", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("ffreep st3", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fstp8 st0", insn.ToString());

            insn = disasm.NextInstruction();
            Assert.AreEqual("fstp9 st0", insn.ToString());
        }