2025-04-12 18:41:40 +03:00
|
|
|
using System.Text;
|
2025-04-12 19:57:42 +03:00
|
|
|
using System.Collections.Generic;
|
2025-04-12 18:41:40 +03:00
|
|
|
|
|
|
|
namespace X86Disassembler.X86;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Core x86 instruction disassembler
|
|
|
|
/// </summary>
|
|
|
|
public class Disassembler
|
|
|
|
{
|
2025-04-12 19:57:42 +03:00
|
|
|
// The buffer containing the code to disassemble
|
2025-04-12 18:41:40 +03:00
|
|
|
private readonly byte[] _codeBuffer;
|
|
|
|
|
2025-04-12 19:57:42 +03:00
|
|
|
// The length of the buffer
|
|
|
|
private readonly int _length;
|
2025-04-12 18:41:40 +03:00
|
|
|
|
2025-04-12 19:57:42 +03:00
|
|
|
// The base address of the code
|
|
|
|
private readonly uint _baseAddress;
|
2025-04-12 18:41:40 +03:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Initializes a new instance of the Disassembler class
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="codeBuffer">The buffer containing the code to disassemble</param>
|
2025-04-12 19:57:42 +03:00
|
|
|
/// <param name="baseAddress">The base address of the code</param>
|
|
|
|
public Disassembler(byte[] codeBuffer, uint baseAddress)
|
2025-04-12 18:41:40 +03:00
|
|
|
{
|
|
|
|
_codeBuffer = codeBuffer;
|
2025-04-12 19:57:42 +03:00
|
|
|
_length = codeBuffer.Length;
|
2025-04-12 18:41:40 +03:00
|
|
|
_baseAddress = baseAddress;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2025-04-12 19:57:42 +03:00
|
|
|
/// Disassembles the code buffer and returns the disassembled instructions
|
2025-04-12 18:41:40 +03:00
|
|
|
/// </summary>
|
|
|
|
/// <returns>A list of disassembled instructions</returns>
|
2025-04-12 19:57:42 +03:00
|
|
|
public List<Instruction> Disassemble()
|
2025-04-12 18:41:40 +03:00
|
|
|
{
|
|
|
|
List<Instruction> instructions = new List<Instruction>();
|
|
|
|
|
2025-04-12 19:57:42 +03:00
|
|
|
// Create an instruction decoder
|
|
|
|
InstructionDecoder decoder = new InstructionDecoder(_codeBuffer, _length);
|
2025-04-12 18:41:40 +03:00
|
|
|
|
2025-04-12 19:57:42 +03:00
|
|
|
// Decode instructions until the end of the buffer is reached
|
|
|
|
while (true)
|
2025-04-12 18:41:40 +03:00
|
|
|
{
|
2025-04-12 19:57:42 +03:00
|
|
|
int position = decoder.GetPosition();
|
|
|
|
|
|
|
|
// Check if we've reached the end of the buffer
|
|
|
|
if (position >= _length)
|
|
|
|
{
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode the next instruction
|
|
|
|
Instruction? instruction = decoder.DecodeInstruction();
|
|
|
|
|
|
|
|
// Check if decoding failed
|
|
|
|
if (instruction == null)
|
|
|
|
{
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Adjust the instruction address to include the base address
|
|
|
|
instruction.Address += _baseAddress;
|
|
|
|
|
|
|
|
// Add the instruction to the list
|
2025-04-12 18:41:40 +03:00
|
|
|
instructions.Add(instruction);
|
|
|
|
}
|
|
|
|
|
|
|
|
return instructions;
|
|
|
|
}
|
|
|
|
}
|