Improved x64 encoder

This commit is contained in:
2024-07-20 12:49:26 +02:00
parent 6b5dd4c687
commit 7c2e373562
9 changed files with 214 additions and 49 deletions

View File

@ -7,40 +7,10 @@ import (
)
// StoreNumber stores a number into the memory address included in the given register.
func StoreNumber(code []byte, register cpu.Register, offset byte, byteCount byte, number int) []byte {
if byteCount == 2 {
code = append(code, 0x66)
}
func StoreNumber(code []byte, register cpu.Register, offset byte, numBytes byte, number int) []byte {
code = store(code, 0xC6, 0xC7, register, offset, numBytes, 0b000)
opCode := byte(0xC7)
if byteCount == 1 {
opCode = 0xC6
}
mod := AddressMemory
if offset != 0 || register == RBP || register == R13 {
mod = AddressMemoryOffset8
}
is64Bit := byte(0)
if byteCount == 8 {
is64Bit = 1
}
code = encode(code, is64Bit, mod, 0b000, byte(register), opCode)
if register == RSP || register == R12 {
code = append(code, SIB(0b00, 0b100, 0b100))
}
if mod == AddressMemoryOffset8 {
code = append(code, offset)
}
switch byteCount {
switch numBytes {
case 8, 4:
return binary.LittleEndian.AppendUint32(code, uint32(number))
@ -50,3 +20,39 @@ func StoreNumber(code []byte, register cpu.Register, offset byte, byteCount byte
return append(code, byte(number))
}
// StoreRegister stores the contents of the `source` register into the memory address included in the given register.
func StoreRegister(code []byte, register cpu.Register, offset byte, numBytes byte, source cpu.Register) []byte {
return store(code, 0x88, 0x89, register, offset, numBytes, source)
}
// store encodes a write to memory.
func store(code []byte, opCode8 byte, opCode32 byte, register cpu.Register, offset byte, numBytes byte, source cpu.Register) []byte {
if numBytes == 2 {
code = append(code, 0x66)
}
opCode := opCode32
if numBytes == 1 {
opCode = opCode8
}
mod := AddressMemory
if offset != 0 || register == RBP || register == R13 {
mod = AddressMemoryOffset8
}
code = encode(code, mod, source, register, numBytes, opCode)
if register == RSP || register == R12 {
code = append(code, SIB(0b00, 0b100, 0b100))
}
if mod == AddressMemoryOffset8 {
code = append(code, offset)
}
return code
}