private static void OutputAssembly(byte[] codeBuffer, PeFile peFile) { fileCounter++; SharpDisasm.ArchitectureMode mode = SharpDisasm.ArchitectureMode.x86_32; // Configure the translator to output instruction addresses and instruction binary as hex SharpDisasm.Disassembler.Translator.IncludeAddress = true; SharpDisasm.Disassembler.Translator.IncludeBinary = true; // Create the disassembler var disasm = new SharpDisasm.Disassembler( codeBuffer, mode, 0, true); using (System.IO.StreamWriter file = new System.IO.StreamWriter("AssemblerOutput" + fileCounter.ToString() + ".txt")) { SharpDisasm.Instruction instruction = null; var instructionEnum = disasm.Disassemble().GetEnumerator(); foreach (var relocationDirectory in peFile.ImageRelocationDirectory) { foreach (var relocationOffset in relocationDirectory.TypeOffsets) { // Disassemble each instruction and output to console while (instructionEnum.MoveNext() && (instruction = instructionEnum.Current) != null && !IsOffsetInInstruction(instruction, relocationOffset)) { file.WriteLine(instruction.ToString()); } if (instruction != null) { file.WriteLine(instruction.ToString() + " Relocation Address: " + relocationOffset.Offset.ToString("X")); } } } } }
/// <summary> /// Decodes a single instruction and increments buffer position. /// </summary> /// <returns></returns> public Instruction NextInstruction() { int length = 0; if ((length = Udis86.udis86.ud_disassemble(ref _u)) > 0) { var instruction = new Instruction(ref _u, CopyBinaryToInstruction); if (!instruction.Error) { BytesDecoded += length; } return instruction; } return null; }