Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
0
        public void Fetch(bool doStrings)
        {
            if (Halted)
            {
                return;
            }

            CurrentAddr     = segments[(int)SegmentRegister.CS].GDTEntry.BaseAddress + EIP;
            disasm.CodeSize = codeSize;
            OpLen           = disasm.Disassemble(CurrentAddr, doStrings);
            opSize          = disasm.OperandSize;
            addressSize     = disasm.AddressSize;
        }
        private void DecrementCurrentAddress()
        {
            uint newaddress = currentDisassemblerAddress;

            while (true)
            {
                int bytestoadvance;
                Disassembler.Disassemble(MemoryDomains.SystemBus, newaddress, out bytestoadvance);
                if (newaddress + bytestoadvance == currentDisassemblerAddress)
                {
                    break;
                }
                newaddress--;

                if (newaddress < 0)
                {
                    newaddress = 0;
                    break;
                }

                // Just in case
                if (currentDisassemblerAddress - newaddress > 5)
                {
                    newaddress = currentDisassemblerAddress - 1;
                    break;
                }
            }

            currentDisassemblerAddress = newaddress;
        }
Ejemplo n.º 4
0
        public AssemblyInfo GetAssemblyInfo()
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title            = "Select assembly to view";
            ofd.InitialDirectory = Directory.GetCurrentDirectory();
            ofd.Filter           = ".Net assembly files (*.exe, *.dll) |*.exe;*.dll";
            Assembly asm;

            try
            {
                if (ofd.ShowDialog() == true)
                {
                    asm = Assembly.LoadFrom(ofd.FileName);
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
            Disassembler d = new Disassembler();

            return(d.Disassemble(asm));
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
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 entry = new InstructionEntry()
                    {
                        IP          = instruction.Offset,
                        Length      = instruction.Length,
                        Instruction = translator.Translate(instruction)
                    };

                    instructions.Add(entry);
                }
            }
        }
Ejemplo n.º 7
0
        private void DoDisassembly()
        {
            using (var dasm = new Disassembler(_selectedFile))
            {
                if (File.Exists(_outputFile))
                {
                    File.Delete(_outputFile);
                }

                _statusLabel.Text = "Performing Disassembly...";
                var inputFile = dasm.Disassemble(_optionMinimal);

                //Apply Selected Analysis
                if (_optionMBBSAnalysis)
                {
                    _statusLabel.Text = "Performing Additional Analysis...";
                    Analysis.MBBS.Analyze(inputFile);
                }
                _progressBar.Fraction = .25f;


                var _stringRenderer = new StringRenderer(inputFile);

                _statusLabel.Text = "Processing Segment Information...";
                File.AppendAllText(_outputFile, _stringRenderer.RenderSegmentInformation());
                _progressBar.Fraction = .50f;


                _statusLabel.Text = "Processing Entry Table...";
                File.AppendAllText(_outputFile, _stringRenderer.RenderEntryTable());
                _progressBar.Fraction = .75f;



                _statusLabel.Text = "Processing Disassembly...";
                File.AppendAllText(_outputFile, _stringRenderer.RenderDisassembly(_optionMBBSAnalysis));
                _progressBar.Fraction = .85f;


                if (_optionStrings)
                {
                    _statusLabel.Text = "Processing Strings...";
                    File.AppendAllText(_outputFile, _stringRenderer.RenderStrings());
                }

                _statusLabel.Text     = "Done!";
                _progressBar.Fraction = 1f;
            }

            var d = new Dialog($"Disassembly Complete!", 50, 12);

            d.Add(new Label(0, 0, $"Output File: {_outputFile}"),
                  new Label(0, 1, $"Bytes Written: {new FileInfo(_outputFile).Length}")
                  );
            var okBtn = new Button("OK", true);

            okBtn.Clicked += () => { Application.RequestStop(); };
            d.AddButton(okBtn);
            Application.Run(d);
        }
Ejemplo n.º 8
0
        public static DreyProgram FromJson(JObject json)
        {
            var strings =

                json["strings"]
                .Cast <JProperty>()
                .ToDictionary(x => Int32.Parse(x.Name), x => x.Value.Value <string>());


            var bytes = json["program"].Values <byte>().ToArray();

            var opcodes =
                json["opcodes"]
                .Cast <JProperty>()
                .ToDictionary(
                    x => x.Value["code"].Value <int>(),
                    x => new OpcodeData()
            {
                Opcode = x.Name, Extended = x.Value["extended"].Value <int>() == 1
            });

            var diss = new Disassembler(bytes, opcodes, strings);

            var instructions = diss.Disassemble();

            var prog = new DreyProgram()
            {
                ByteCode    = instructions,
                StringTable = strings
            };

            return(prog);
        }
Ejemplo n.º 9
0
        private bool isDecryptMethod(MethodBase method)
        {
            if (method.GetParameters().Length != 0 || !(method is MethodInfo) || (method as MethodInfo).ReturnType != typeof(void))
            {
                return(false);
            }
            InstructionCollection insts = Disassembler.Disassemble(method.GetMethodBody().GetILAsByteArray());

            foreach (Instruction inst in from instr in insts where instr.OpCode == OpCodes.Call select instr)
            {
                uint destToken = (inst.Operand.Value as MetadataToken).Value;
                {
                    try
                    {
                        MethodBase destMethod = method.Module.ResolveMethod((int)destToken);
                        if (destMethod == typeof(Marshal).GetMethod("GetHINSTANCE", BindingFlags.Public | BindingFlags.Static))
                        {
                            return(true);
                        }
                    }
                    catch { }
                }
            }
            return(false);
        }
Ejemplo n.º 10
0
            protected override void TraceFromCallback(uint addr, uint value, uint flags)
            {
                var  regs   = DebuggableCore.GetCpuFlagsAndRegisters();
                uint pc     = (uint)regs["M68K PC"].Value;
                var  disasm = Disassembler.Disassemble(MemoryDomains.SystemBus, pc & 0xFFFFFF, out _);

                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($"{r.Key.Replace("M68K", "").Trim()}:{r.Value.Value.ToHexString(r.Value.BitSize / 4)} ");
                        }
                    }
                }
                var sr = regs["M68K SR"].Value;

                sb.Append(string.Concat(
                              (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"));

                this.Put(new(disassembly: $"{pc:X6}:  {disasm}".PadRight(50), registerInfo: sb.ToString().Trim()));
            }
Ejemplo n.º 11
0
        private void DisassembleAndWrite(ClrMethod method, string message, ArchitectureMode architecture, Translator translator, Reference <ulong> methodAddressRef, TextWriter writer)
        {
            writer.WriteLine(method.GetFullSignature());
            if (message != null)
            {
                writer.Write("    ; ");
                writer.WriteLine(message);
                return;
            }

            var info = FindNonEmptyHotColdInfo(method);

            if (info == null)
            {
                writer.WriteLine("    ; Failed to find HotColdInfo — please report at https://github.com/ashmind/TryRoslyn/issues.");
                return;
            }

            var methodAddress = info.HotStart;

            methodAddressRef.Value = methodAddress;
            using (var disasm = new Disassembler(new IntPtr(unchecked ((long)methodAddress)), (int)info.HotSize, architecture, methodAddress)) {
                foreach (var instruction in disasm.Disassemble())
                {
                    writer.Write("    L");
                    writer.Write((instruction.Offset - methodAddress).ToString("x4"));
                    writer.Write(": ");
                    writer.WriteLine(translator.Translate(instruction));
                }
            }
        }
 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);
                 }
             }
         }
     }
 }
    void Start()
    {
        Type       type       = Type.GetType("Program,Assembly-CSharp");
        MethodInfo methodInfo = type.GetMethod("AngleVectorPlane", BindingFlags.Instance | BindingFlags.NonPublic);

        Debug.Log(Disassembler.Disassemble(methodInfo));
    }
Ejemplo n.º 14
0
        private void DisassembleAndWrite(ClrMethod method, ArchitectureMode architecture, Translator translator, ref ulong methodAddressRef, TextWriter writer)
        {
            writer.WriteLine(method.GetFullSignature());
            var info = FindNonEmptyHotColdInfo(method);

            if (info == null)
            {
                writer.WriteLine("    ; Unable to load method data (not JITted?)");
                return;
            }
            var methodAddress = info.HotStart;

            methodAddressRef = methodAddress;
            using (var disasm = new Disassembler(new IntPtr(unchecked ((long)methodAddress)), (int)info.HotSize, architecture, methodAddress))
            {
                foreach (var instruction in disasm.Disassemble())
                {
                    writer.Write(String.Format("0x{0:X8}`{1:X8}:", (instruction.Offset >> 32) & 0xFFFFFFFF, instruction.Offset & 0xFFFFFFFF));
                    writer.Write("    L");
                    writer.Write((instruction.Offset - methodAddress).ToString("x4"));
                    writer.Write(": ");
                    writer.WriteLine(translator.Translate(instruction));
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Patches all jumps pointing to originalJmpTarget to point to newJmpTarget.
        /// </summary>
        /// <param name="searchRange">Range of addresses where to patch jumps.</param>
        /// <param name="originalJmpTarget">Address range of JMP targets to patch with newJmpTarget.</param>
        /// <param name="newJmpTarget">The new address instructions should jmp to.</param>
        private List <Patch> PatchJumpTargets_Internal(AddressRange searchRange, AddressRange originalJmpTarget, long newJmpTarget)
        {
            var patches = new List <Patch>();
            int length  = (int)(searchRange.EndPointer - searchRange.StartPointer);
            var memory  = TryReadFromMemory((IntPtr)searchRange.StartPointer, length);

            Disassembler disassembler = new Disassembler(memory, _architecture, (ulong)searchRange.StartPointer, true);

            Instruction[] instructions = disassembler.Disassemble().ToArray();

            for (int x = 0; x < instructions.Length; x++)
            {
                Instruction instruction     = instructions[x];
                Instruction nextInstruction = (x + 1 < instructions.Length) ? instructions[x + 1] : null;

                if (IsRelativeJump(instruction))
                {
                    PatchRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
                else if (IsRIPRelativeJump(instruction))
                {
                    PatchRIPRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
                else if (nextInstruction != null && IsPushReturn(instruction, nextInstruction))
                {
                    PatchPushReturn(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
            }

            // Return all the addresses to patch!.
            return(patches);
        }
        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);
        }
Ejemplo n.º 17
0
        public bool FirmwareFromAppFolder()
        {
            if (!SourceExists)
            {
                return(false);
            }

            // delete old firmware before making new one
            if (File.Exists(FirmwareFile))
            {
                File.Delete(FirmwareFile);
            }

            if (File.Exists(MainFile))
            {
                FirmwareFromMainFile();
            }
            else
            {
                FirmwareFromCS();
            }

            if (File.Exists(FirmwareFile))
            {
                var disassembler = new Disassembler();
                FileTools.WriteAllText(FirmwareAsmFile, disassembler.Disassemble(Instructions()));
            }
            else
            {
                Console.WriteLine($"Firmware file was not found: {FirmwareFile}");
            }

            return(File.Exists(FirmwareFile));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Retrieves the length of the hook for trampoline, mid-function hooks etc.
        /// This works by reading a short fixed array of bytes from memory then disassembling the bytes
        /// and iterating over each individual instruction up to the point where the total length of the
        /// disassembled exceeds the user set length of instructions to be assembled.
        /// </summary>
        /// <param name="hookAddress">The address that is to be hooked.</param>
        /// <param name="hookLength">The minimum length of the hook, the length of our assembled bytes for the hook.</param>
        /// <returns>The necessary length of bytes to hook the individual game function.</returns>
        public static int GetHookLength(IntPtr hookAddress, int hookLength)
        {
            // Retrieve the function header, arbitrary length of 32 bytes is used for this operation.
            // While you can technically build infinite length X86 instructions, anything greater than 16 to compare seems reasonable.
            byte[] functionHeader = Bindings.TargetProcess.ReadMemoryExternal(hookAddress, 64);

            // Define the disassembler.
            Disassembler disassembler = new Disassembler(functionHeader, ArchitectureMode.x86_32);

            // Disassemble function header and find shortest amount of bytes.
            Instruction[] x86Instructions = disassembler.Disassemble().ToArray();

            int completeHookLength = 0;

            foreach (Instruction x86Instruction in x86Instructions)
            {
                completeHookLength += x86Instruction.Length;
                if (completeHookLength > hookLength)
                {
                    break;
                }
            }

            return(completeHookLength);
        }
Ejemplo n.º 19
0
        private void UpdateDisplay(ulong address, byte[] memory)
        {
            if (address != Platform.InstructionPointer.Value)
            {
                return;
            }

            var mode = ArchitectureMode.x86_32;             // todo:

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

                    foreach (var instruction in disasm.Disassemble())
                    {
                        var asm = translator.Translate(instruction);
                        tbInstruction.Text = asm;
                        break;
                    }
                }
            }
            catch
            {
                tbInstruction.Text = "Unable to decode!";
            }
        }
Ejemplo n.º 20
0
        private void AddressUpDown_ValueChanged(object sender, EventArgs e)
        {
            if (extend)
            {
                ReadProcessMemory(hProcess, (uint)AddressUpDown.Value, wmInfo.ByteArray, wmInfo.ByteArray.Length, 0);
            }
            var disasm = new Disassembler(wmInfo.ByteArray, ArchitectureMode.x86_32, (uint)AddressUpDown.Value, true);

            DisAsmListView.Items.Clear();
            int index = -1;

            foreach (var item in disasm.Disassemble())
            {
                ListViewItem listViewItem = new ListViewItem("0x" + item.Offset.ToString("X8"));
                listViewItem.SubItems.Add(Disassembler.Translator.TranslateBytes(item).ToUpper());
                listViewItem.SubItems.Add(Disassembler.Translator.TranslateMnemonic(item));
                DisAsmListView.Items.Add(listViewItem);
                if (extend && item.Offset == wmInfo.Address)
                {
                    index = DisAsmListView.Items.Count - 1;
                }
            }
            if (extend && index >= 0)
            {
                DisAsmListView.SelectedIndices.Add(index);
                DisAsmListView.EnsureVisible(index);
            }
        }
Ejemplo n.º 21
0
        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);
                        }

                    }
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Patches all jumps pointing to originalJmpTarget to point to newJmpTarget.
        /// </summary>
        /// <param name="searchRange">Range of addresses where to patch jumps.</param>
        /// <param name="originalJmpTarget">Address range of JMP targets to patch with newJmpTarget.</param>
        /// <param name="newJmpTarget">The new address instructions should jmp to.</param>
        internal List <Patch> PatchJumpTargets(AddressRange searchRange, AddressRange originalJmpTarget, long newJmpTarget)
        {
            var patches = new List <Patch>();

            int length = (int)(searchRange.EndPointer - searchRange.StartPointer);

            CurrentProcess.SafeReadRaw((IntPtr)searchRange.StartPointer, out byte[] memory, length);

            Disassembler disassembler = new Disassembler(memory, _architecture, (ulong)searchRange.StartPointer, true);

            Instruction[] instructions = disassembler.Disassemble().ToArray();

            for (int x = 0; x < instructions.Length; x++)
            {
                Instruction instruction     = instructions[x];
                Instruction nextInstruction = (x + 1 < instructions.Length) ? instructions[x + 1] : null;

                if (IsRelativeJump(instruction))
                {
                    PatchRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
                if (IsRIPRelativeJump(instruction))
                {
                    PatchRIPRelativeJump(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
                if (IsPushReturn(instruction, nextInstruction))
                {
                    PatchPushReturn(instruction, ref originalJmpTarget, newJmpTarget, patches);
                }
            }

            // Return all the addresses to patch!.
            return(patches);
        }
Ejemplo n.º 23
0
        public async Task Disasamx86x64x16(ArchitectureMode mode, [Remainder] string hex = null)
        {
            Disassembler.Translator.IncludeBinary = true;
            var disasm = new Disassembler(Utilities.HexStringToByteArray(hex.ToString().Replace("\\x", "").Replace("0x", "").Replace(" ", "")), mode, 0, true);

            await ReplyAsync($"```x86asm\n{string.Join("\n", disasm.Disassemble())}```");
        }
        public void ArraysDisasm()
        {
            var firmwareTools = new FirmwareTools(AppPath("Arrays"));
            var disassembler  = new Disassembler();

            File.WriteAllText(firmwareTools.FirmwareAsmFile, disassembler.Disassemble(firmwareTools.Instructions()));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Retrieves the length of the hook for trampoline, mid-function hooks etc.
        /// </summary>
        /// <param name="hookAddress">The address that is to be hooked.</param>
        /// <param name="hookLength">The minimum length of the hook, the length of our assembled bytes for the hook.</param>
        /// <param name="architectureMode">X86 or X64 to use for disassembly.</param>
        public static int GetHookLength(IntPtr hookAddress, int hookLength, ArchitectureMode architectureMode)
        {
            /*
             *  This works by reading a short fixed array of bytes from memory then disassembling the bytes
             *  and iterating over each individual instruction up to the point where the total length of the
             *  disassembled exceeds the user set length of instructions to be assembled.
             */

            // Retrieve the function header, arbitrary length of <see below> bytes is used for this operation.
            // While you can technically build infinite length X86 instructions, anything greater than 16 to compare seems reasonable.
            Memory.Sources.Memory.CurrentProcess.ReadRaw(hookAddress, out byte[] functionHeader, 64);

            Disassembler disassembler = new Disassembler(functionHeader, architectureMode);

            Instruction[] instructions = disassembler.Disassemble().ToArray();

            int completeHookLength = 0;

            foreach (Instruction instruction in instructions)
            {
                completeHookLength += instruction.Length;
                if (completeHookLength >= hookLength)
                {
                    break;
                }
            }

            return(completeHookLength);
        }
Ejemplo n.º 26
0
        private static bool RunCode(SourceCodeFile file)
        {
            var tokens = Lexer.ScanTokens(file);

            if (Context.Instance.ErrorsReported > 0)
            {
                return(true);
            }

            var ast = Parser.Parse(tokens);

            if (Context.Instance.ErrorsReported > 0)
            {
                return(true);
            }

            // TODO: Scanning on demand.
            tokens.Clear();

            var byteCode = Compiler.Compile(ast);

            if (Context.Instance.ErrorsReported > 0)
            {
                return(true);
            }

#if DEBUG
            Disassembler.Disassemble(byteCode.ToArray());
            Console.WriteLine("----------------------------------------");
#endif

            VirtualMachine.Execute(byteCode);
            return(false);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// profile the closure to extract a list of the cells referenced
        /// </summary>
        /// <param name="func"></param>
        private static ICell[] ProfileObject(object func)
        {
            var l      = new LinkedList <ICell>();
            var fields = func.GetType().GetFields();
            var fd     = new Dictionary <string, object>();

            foreach (var f in fields)
            {
                var o = f.GetValue(func);
                fd.Add(f.Name, o);
                if (o is ICell c && !(c is Model))
                {
                    l.AddLast(c);
                }
            }

            var method      = func.GetType().GetMethod("Invoke");
            var disasembler = new Disassembler(method, SequencePointEnumerator.Empty);
            var code        = disasembler.Disassemble();

            foreach (var il in code.Instructions)
            {
                if (il.InstructionType == ILInstructionType.Ldfld)
                {
                    var fi = il.Argument as FieldInfo;
                    if (!fd.ContainsKey(fi.Name))
                    {
                        foreach (var o in fd)
                        {
                            try
                            {
                                var p = fi.GetValue(o.Value);
                                if (p != null)
                                {
                                    fd.Add(fi.Name, p);
                                    if (p is ICell c)
                                    {
                                        if (p is ITrivial t)
                                        {
                                            foreach (var x in ProfileObject(t.GetFunction()))
                                            {
                                                l.AddLast(x);
                                            }
                                        }
                                        else
                                        {
                                            l.AddLast(c);
                                        }
                                    }
                                }
                                break;
                            }
                            catch { }
                        }
                    }
                }
            }
            return(l.Distinct().ToArray());
        }
Ejemplo n.º 28
0
        private void SaveProgram(Program program)
        {
            string       programText = Disassembler.Disassemble(program);
            StreamWriter programFile = File.CreateText(ProgramDirectory.ProgramPath(program.name));

            programFile.Write(programText);
            programFile.Close();
        }
        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;
            }
        }
Ejemplo n.º 30
0
        private void mnuLoadBIN_Click(object sender, EventArgs e)
        {
            pauseEmulation = true;
            try
            {
                string fname;
                if (string.IsNullOrEmpty(fname = OpenFile("BIN files|*.bin|RBN files|*.rbn|All files|*.*")))
                {
                    return;
                }
                try
                {
                    MemAddressInputForm.ShowDialog(this);
                    if (MemAddressInputForm.cancel)
                    {
                        MessageBox.Show("Bin Not Loaded!");
                        return;
                    }

                    string memVal  = settings.MemoryLoadAddress.ToLower();
                    int    memAddr = 0;
                    if (memVal.Contains('x') || memVal.Contains('$'))
                    {
                        memVal  = memVal.Replace("x", string.Empty).Replace("$", string.Empty);
                        memAddr = int.Parse(memVal, NumberStyles.HexNumber);
                    }
                    else
                    {
                        memAddr = int.Parse(memVal);
                    }

                    // even address
                    memAddr &= -2;

                    byte[] bin = File.ReadAllBytes(fname);
                    Buffer.BlockCopy(bin, 0, Memory.Data, memAddr, bin.Length + memAddr > Memory.MEMORY_TOP ? Memory.MEMORY_TOP - memAddr : bin.Length);

                    UpdateDasmSymbols(fname, Path.GetExtension(fname) == ".rbn" ? memAddr : 0);

                    List <string> dasmtext = Disassembler.Disassemble();
                    File.WriteAllLines("disassembly.lst", dasmtext, Encoding.ASCII);

                    MessageBox.Show(this, string.Format("Bin Loaded at {0}", memAddr));
                }
                catch (Exception ex)
                {
                    string msg = @"Exception: {0}
{1}

PC: {2}";
                    MessageBox.Show(string.Format(msg, ex.Message, ex.StackTrace, Convert.ToString(State.PC, 16).PadLeft(4, '0')), "Λάθος", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                pauseEmulation = false;
            }
        }
Ejemplo n.º 31
0
 public void Disassemble(byte[] code, int address, bool x64)
 {
     Disassembler.Translator.IncludeAddress = true;
     Disassembler.Translator.IncludeBinary  = true;
     using (var disassem = new Disassembler(code, x64 ? ArchitectureMode.x86_64 : ArchitectureMode.x86_32, (ulong)address, true)) {
         Instructions = disassem.Disassemble().TakeWhileIncluding(i => i.Mnemonic != SharpDisasm.Udis86.ud_mnemonic_code.UD_Iret).
                        Select(i => new InstructionViewModel(i)).ToArray();
     }
 }
Ejemplo n.º 32
0
        static void DisassembleThings()
        {
            string dasm = Disassembler.Disassemble(File.ReadAllBytes("C:\\Users\\adam\\Downloads\\XUBR580\\pcxtbios.bin"), 0);

            StreamWriter sw = new StreamWriter("C:\\Users\\adam\\Downloads\\XUBR580\\pcxtbios.txt");

            sw.Write(dasm);
            sw.Close();
        }
Ejemplo n.º 33
0
        private Instruction GetCurrentInstruction()
        {
            if (buffer == null || buffer.Length == 0)
            {
                return(null);
            }

            return(disassembler.Disassemble(buffer, ProgramCounter));
        }
Ejemplo n.º 34
0
        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);
        }
Ejemplo n.º 35
0
 private static void ReAssembleMethod(MethodBase method)
 {
     var disassembler = new Disassembler();
     if (disassembler.CanDisassemble(method))
     {
         var result = disassembler.Disassemble(method);
         result.Assemble(new AssembleContext());
     }
 }