17 Commits

Author SHA1 Message Date
36d71a4ee2 thumb: add execution of instructions
also arm: fix some instructions

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-30 01:31:09 +05:30
03dbb7052f nix: bump
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-30 01:30:44 +05:30
0f09874929 cpu: get rid of the test workaround
now can we remove the pimpl?

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 22:43:50 +05:30
03ebc6378a clang: make linter happy
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 17:36:25 +05:30
5ec5e6dddc thumb: add disassembler
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 17:31:00 +05:30
208527b7f8 thumb: initialise instruction formats
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 01:36:05 +05:30
6822e1255a meson: make disassembler feature true by default
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 01:33:51 +05:30
bd91112509 refactor: make disassembler optional
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 01:31:32 +05:30
1baebd72f6 refactor: make cpu-impl private when not testing
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 01:25:47 +05:30
b55f6ee16b refactor: replace fmt ostreams with stringify
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-27 01:24:32 +05:30
ed01ed80cd tests: add tests for memory
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-24 18:04:28 +05:30
8e26cadc9a chore: revert util/crypto
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-24 17:45:19 +05:30
6e56828dfd tests/arm/exec: test conditions
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-24 17:38:11 +05:30
5fcc75bc9a tests: add tests for internal utilities
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-24 17:36:38 +05:30
560bd5bfa1 tests: add tests for bus
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-23 23:20:05 +05:30
9cdfa90acc memory: remove unused functions
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-23 21:58:41 +05:30
91a82eec7c log: encapsulate logger
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-09-23 21:09:44 +05:30
53 changed files with 4050 additions and 969 deletions

View File

@@ -6,4 +6,5 @@ Checks: '
, -cppcoreguidelines-macro-usage
, -cppcoreguidelines-avoid-const-or-ref-data-members
, -cppcoreguidelines-non-private-member-variables-in-classes
, -cppcoreguidelines-avoid-non-const-global-variables
'

2
.envrc
View File

@@ -1 +1 @@
use flake .#matar-clang
use flake

View File

@@ -1,6 +1,7 @@
#include "bus.hh"
#include "cpu/cpu.hh"
#include "memory.hh"
#include "util/loglevel.hh"
#include <array>
#include <cstdlib>
#include <fstream>
@@ -84,6 +85,8 @@ main(int argc, const char* argv[]) {
std::flush(std::cout);
std::flush(std::cout);
matar::set_log_level(matar::LogLevel::Debug);
try {
matar::Memory memory(std::move(bios), std::move(rom));
matar::Bus bus(memory);

6
flake.lock generated
View File

@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1695318763,
"narHash": "sha256-FHVPDRP2AfvsxAdc+AsgFJevMz5VBmnZglFUMlxBkcY=",
"lastModified": 1695806987,
"narHash": "sha256-fX5kGs66NZIxCMcpAGIpxuftajHL8Hil1vjHmjjl118=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "e12483116b3b51a185a33a272bf351e357ba9a99",
"rev": "f3dab3509afca932f3f4fd0908957709bb1c1f57",
"type": "github"
},
"original": {

View File

@@ -26,7 +26,7 @@
".hh"
".cc"
".build"
"meson_options.txt"
".options"
];
in
rec {

View File

@@ -17,12 +17,6 @@ class Memory {
uint8_t read(size_t address) const;
void write(size_t address, uint8_t byte);
uint16_t read_halfword(size_t address) const;
void write_halfword(size_t address, uint16_t halfword);
uint32_t read_word(size_t address) const;
void write_word(size_t address, uint32_t word);
private:
#define MEMORY_REGION(name, start, end) \
static constexpr size_t name##_START = start; \

View File

@@ -7,5 +7,6 @@ headers = files(
inc = include_directories('.')
subdir('cpu')
subdir('util')
install_headers(headers, subdir: meson.project_name(), preserve_path: true)

14
include/util/loglevel.hh Normal file
View File

@@ -0,0 +1,14 @@
#pragma once
namespace matar {
enum class LogLevel {
Off = 1 << 0,
Error = 1 << 1,
Warn = 1 << 2,
Info = 1 << 3,
Debug = 1 << 4
};
void
set_log_level(LogLevel level);
}

3
include/util/meson.build Normal file
View File

@@ -0,0 +1,3 @@
headers += files(
'loglevel.hh'
)

View File

@@ -4,7 +4,8 @@ project('matar', 'cpp',
default_options : ['warning_level=3',
'werror=true',
'optimization=3',
'cpp_std=c++20'])
'cpp_std=c++20',
'default_library=static'])
compiler = meson.get_compiler('cpp')
@@ -23,11 +24,6 @@ else
error(compiler.get_id() + ' ' + compiler.version() + 'does not meet the compiler requirements')
endif
if compiler.has_argument('-fexperimental-library')
add_global_arguments('-fexperimental-library', language: 'cpp')
else
error(compiler.get_id() + ' ' + compiler.version() + 'does not support -fexperimental-library')
endif
'''
subdir('include')

2
meson.options Normal file
View File

@@ -0,0 +1,2 @@
option('tests', type : 'boolean', value : true, description: 'enable tests')
option('disassembler', type: 'boolean', value: true, description: 'enable disassembler')

View File

@@ -1 +0,0 @@
option('tests', type : 'boolean', value : true, description: 'enable tests')

View File

@@ -19,7 +19,7 @@
packages.matar-clang = pkgs.callPackage ./build.nix { inherit src libraries stdenv; };
devShells.matar-clang = pkgs.callPackage ./shell.nix {
inherit libraries stdenv;
tools = with pkgs; [ clang-tools_16 ];
tools = with pkgs; [ (clang-tools_16.override { enableLibcxx = true; }) ];
};
};
}

View File

@@ -1,4 +1,5 @@
#include "bus.hh"
#include "util/log.hh"
#include <memory>
namespace matar {
@@ -17,21 +18,38 @@ Bus::write_byte(size_t address, uint8_t byte) {
uint16_t
Bus::read_halfword(size_t address) {
return memory->read_halfword(address);
if (address & 0b01)
glogger.warn("Reading a non aligned halfword address");
return memory->read(address) | memory->read(address + 1) << 8;
}
void
Bus::write_halfword(size_t address, uint16_t halfword) {
memory->write_halfword(address, halfword);
if (address & 0b01)
glogger.warn("Writing to a non aligned halfword address");
memory->write(address, halfword & 0xFF);
memory->write(address + 1, halfword >> 8 & 0xFF);
}
uint32_t
Bus::read_word(size_t address) {
return memory->read_word(address);
if (address & 0b11)
glogger.warn("Reading a non aligned word address");
return memory->read(address) | memory->read(address + 1) << 8 |
memory->read(address + 2) << 16 | memory->read(address + 3) << 24;
}
void
Bus::write_word(size_t address, uint32_t word) {
memory->write_word(address, word);
if (address & 0b11)
glogger.warn("Writing to a non aligned word address");
memory->write(address, word & 0xFF);
memory->write(address + 1, word >> 8 & 0xFF);
memory->write(address + 2, word >> 16 & 0xFF);
memory->write(address + 3, word >> 24 & 0xFF);
}
}

View File

@@ -3,7 +3,7 @@
namespace matar {
uint32_t
eval_shift(ShiftType shift_type, uint32_t value, uint8_t amount, bool& carry) {
eval_shift(ShiftType shift_type, uint32_t value, uint32_t amount, bool& carry) {
uint32_t eval = 0;
switch (shift_type) {
@@ -49,23 +49,42 @@ eval_shift(ShiftType shift_type, uint32_t value, uint8_t amount, bool& carry) {
return eval;
}
std::ostream&
operator<<(std::ostream& os, const ShiftType shift_type) {
uint32_t
sub(uint32_t a, uint32_t b, bool& carry, bool& overflow) {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
#define CASE(type) \
case ShiftType::type: \
os << #type; \
break;
uint32_t result = a - b;
switch (shift_type) {
CASE(LSL)
CASE(LSR)
CASE(ASR)
CASE(ROR)
}
carry = b <= a;
overflow = s1 != s2 && s2 == get_bit(result, 31);
#undef CASE
return result;
}
return os;
uint32_t
add(uint32_t a, uint32_t b, bool& carry, bool& overflow, bool c) {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
uint64_t result = a + b + c;
carry = get_bit(result, 32);
overflow = s1 == s2 && s2 != get_bit(result, 31);
return result & 0xFFFFFFFF;
}
uint32_t
sbc(uint32_t a, uint32_t b, bool& carry, bool& overflow, bool c) {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
uint64_t result = a - b - !c;
carry = get_bit(result, 32);
overflow = s1 != s2 && s2 == get_bit(result, 31);
return result & 0xFFFFFFFF;
}
}

View File

@@ -10,6 +10,24 @@ enum class ShiftType {
ROR = 0b11
};
constexpr auto
stringify(ShiftType shift_type) {
#define CASE(type) \
case ShiftType::type: \
return #type;
switch (shift_type) {
CASE(LSL)
CASE(LSR)
CASE(ASR)
CASE(ROR)
}
#undef CASE
return "";
}
struct ShiftData {
ShiftType type;
bool immediate;
@@ -22,14 +40,14 @@ struct Shift {
};
uint32_t
eval_shift(ShiftType shift_type, uint32_t value, uint8_t amount, bool& carry);
eval_shift(ShiftType shift_type, uint32_t value, uint32_t amount, bool& carry);
// https://fmt.dev/dev/api.html#std-ostream-support
std::ostream&
operator<<(std::ostream& os, const ShiftType cond);
}
uint32_t
sub(uint32_t a, uint32_t b, bool& carry, bool& overflow);
namespace fmt {
template<>
struct formatter<matar::ShiftType> : ostream_formatter {};
uint32_t
add(uint32_t a, uint32_t b, bool& carry, bool& overflow, bool c = 0);
uint32_t
sbc(uint32_t a, uint32_t b, bool& carry, bool& overflow, bool c);
}

233
src/cpu/arm/disassembler.cc Normal file
View File

@@ -0,0 +1,233 @@
#include "instruction.hh"
#include "util/bits.hh"
namespace matar::arm {
std::string
Instruction::disassemble() {
auto condition = stringify(this->condition);
return std::visit(
overloaded{
[condition](BranchAndExchange& data) {
return fmt::format("BX{} R{:d}", condition, data.rn);
},
[condition](Branch& data) {
return fmt::format(
"B{}{} 0x{:06X}", (data.link ? "L" : ""), condition, data.offset);
},
[condition](Multiply& data) {
if (data.acc) {
return fmt::format("MLA{}{} R{:d},R{:d},R{:d},R{:d}",
condition,
(data.set ? "S" : ""),
data.rd,
data.rm,
data.rs,
data.rn);
} else {
return fmt::format("MUL{}{} R{:d},R{:d},R{:d}",
condition,
(data.set ? "S" : ""),
data.rd,
data.rm,
data.rs);
}
},
[condition](MultiplyLong& data) {
return fmt::format("{}{}{}{} R{:d},R{:d},R{:d},R{:d}",
(data.uns ? 'U' : 'S'),
(data.acc ? "MLAL" : "MULL"),
condition,
(data.set ? "S" : ""),
data.rdlo,
data.rdhi,
data.rm,
data.rs);
},
[](Undefined) { return std::string("UND"); },
[condition](SingleDataSwap& data) {
return fmt::format("SWP{}{} R{:d},R{:d},[R{:d}]",
condition,
(data.byte ? "B" : ""),
data.rd,
data.rm,
data.rn);
},
[condition](SingleDataTransfer& data) {
std::string expression;
std::string address;
if (const uint16_t* offset = std::get_if<uint16_t>(&data.offset)) {
if (*offset == 0) {
expression = "";
} else {
expression =
fmt::format(",{}#{:d}", (data.up ? '+' : '-'), *offset);
}
} else if (const Shift* shift = std::get_if<Shift>(&data.offset)) {
// Shifts are always immediate in single data transfer
expression = fmt::format(",{}R{:d},{} #{:d}",
(data.up ? '+' : '-'),
shift->rm,
stringify(shift->data.type),
shift->data.operand);
}
return fmt::format(
"{}{}{}{} R{:d},[R{:d}{}]{}",
(data.load ? "LDR" : "STR"),
condition,
(data.byte ? "B" : ""),
(!data.pre && data.write ? "T" : ""),
data.rd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[condition](HalfwordTransfer& data) {
std::string expression;
if (data.imm) {
if (data.offset == 0) {
expression = "";
} else {
expression = fmt::format(
",{}#{:d}", (data.up ? '+' : '-'), data.offset);
}
} else {
expression =
fmt::format(",{}R{:d}", (data.up ? '+' : '-'), data.offset);
}
return fmt::format(
"{}{}{}{} R{:d},[R{:d}{}]{}",
(data.load ? "LDR" : "STR"),
condition,
(data.sign ? "S" : ""),
(data.half ? 'H' : 'B'),
data.rd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[condition](BlockDataTransfer& data) {
std::string regs;
for (uint8_t i = 0; i < 16; i++) {
if (get_bit(data.regs, i))
fmt::format_to(std::back_inserter(regs), "R{:d},", i);
};
regs.pop_back();
return fmt::format("{}{}{}{} R{:d}{},{{{}}}{}",
(data.load ? "LDM" : "STM"),
condition,
(data.up ? 'I' : 'D'),
(data.pre ? 'B' : 'A'),
data.rn,
(data.write ? "!" : ""),
regs,
(data.s ? "^" : ""));
},
[condition](PsrTransfer& data) {
if (data.type == PsrTransfer::Type::Mrs) {
return fmt::format("MRS{} R{:d},{}",
condition,
data.operand,
(data.spsr ? "SPSR_all" : "CPSR_all"));
} else {
return fmt::format(
"MSR{} {}_{},{}{}",
condition,
(data.spsr ? "SPSR" : "CPSR"),
(data.type == PsrTransfer::Type::Msr_flg ? "flg" : "all"),
(data.imm ? '#' : 'R'),
data.operand);
}
},
[condition](DataProcessing& data) {
using OpCode = DataProcessing::OpCode;
std::string op_2;
if (const uint32_t* operand =
std::get_if<uint32_t>(&data.operand)) {
op_2 = fmt::format("#{:d}", *operand);
} else if (const Shift* shift = std::get_if<Shift>(&data.operand)) {
op_2 = fmt::format("R{:d},{} {}{:d}",
shift->rm,
stringify(shift->data.type),
(shift->data.immediate ? '#' : 'R'),
shift->data.operand);
}
switch (data.opcode) {
case OpCode::MOV:
case OpCode::MVN:
return fmt::format("{}{}{} R{:d},{}",
stringify(data.opcode),
condition,
(data.set ? "S" : ""),
data.rd,
op_2);
case OpCode::TST:
case OpCode::TEQ:
case OpCode::CMP:
case OpCode::CMN:
return fmt::format("{}{} R{:d},{}",
stringify(data.opcode),
condition,
data.rn,
op_2);
default:
return fmt::format("{}{}{} R{:d},R{:d},{}",
stringify(data.opcode),
condition,
(data.set ? "S" : ""),
data.rd,
data.rn,
op_2);
}
},
[condition](SoftwareInterrupt) {
return fmt::format("SWI{}", condition);
},
[condition](CoprocessorDataTransfer& data) {
std::string expression = fmt::format(",#{:d}", data.offset);
return fmt::format(
"{}{}{} p{:d},c{:d},[R{:d}{}]{}",
(data.load ? "LDC" : "STC"),
condition,
(data.len ? "L" : ""),
data.cpn,
data.crd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[condition](CoprocessorDataOperation& data) {
return fmt::format("CDP{} p{},{},c{},c{},c{},{}",
condition,
data.cpn,
data.cp_opc,
data.crd,
data.crn,
data.crm,
data.cp);
},
[condition](CoprocessorRegisterTransfer& data) {
return fmt::format("{}{} p{},{},R{},c{},c{},{}",
(data.load ? "MRC" : "MCR"),
condition,
data.cpn,
data.cp_opc,
data.rd,
data.crn,
data.crm,
data.cp);
},
[](auto) { return std::string("unknown instruction"); } },
data);
}
}

View File

@@ -2,87 +2,82 @@
#include "util/bits.hh"
#include "util/log.hh"
using namespace logger;
namespace matar {
namespace matar::arm {
void
CpuImpl::exec_arm(const arm::Instruction instruction) {
Condition cond = instruction.condition;
arm::InstructionData data = instruction.data;
debug(cpsr.condition(cond));
if (!cpsr.condition(cond)) {
Instruction::exec(CpuImpl& cpu) {
if (!cpu.cpsr.condition(condition)) {
return;
}
auto pc_error = [](uint8_t r) {
if (r == PC_INDEX)
log_error("Using PC (R15) as operand register");
auto pc_error = [cpu](uint8_t r) {
if (r == cpu.PC_INDEX)
glogger.error("Using PC (R15) as operand register");
};
auto pc_warn = [](uint8_t r) {
if (r == PC_INDEX)
log_warn("Using PC (R15) as operand register");
auto pc_warn = [cpu](uint8_t r) {
if (r == cpu.PC_INDEX)
glogger.warn("Using PC (R15) as operand register");
};
using namespace arm;
std::visit(
overloaded{
[this, pc_warn](BranchAndExchange& data) {
[&cpu, pc_warn](BranchAndExchange& data) {
State state = static_cast<State>(data.rn & 1);
pc_warn(data.rn);
// set state
cpsr.set_state(state);
cpu.cpsr.set_state(state);
// copy to PC
pc = gpr[data.rn];
cpu.pc = cpu.gpr[data.rn];
// ignore [1:0] bits for arm and 0 bit for thumb
rst_bit(pc, 0);
rst_bit(cpu.pc, 0);
if (state == State::Arm)
rst_bit(pc, 1);
rst_bit(cpu.pc, 1);
// pc is affected so flush the pipeline
is_flushed = true;
cpu.is_flushed = true;
},
[this](Branch& data) {
[&cpu](Branch& data) {
if (data.link)
gpr[14] = pc - INSTRUCTION_SIZE;
cpu.gpr[14] = cpu.pc - INSTRUCTION_SIZE;
// data.offset accounts for two instructions ahead when
// disassembling, so need to adjust
pc = static_cast<int32_t>(pc) - 2 * INSTRUCTION_SIZE + data.offset;
cpu.pc =
static_cast<int32_t>(cpu.pc) - 2 * INSTRUCTION_SIZE + data.offset;
// pc is affected so flush the pipeline
is_flushed = true;
cpu.is_flushed = true;
},
[this, pc_error](Multiply& data) {
[&cpu, pc_error](Multiply& data) {
if (data.rd == data.rm)
log_error("rd and rm are not distinct in {}",
typeid(data).name());
glogger.error("rd and rm are not distinct in {}",
typeid(data).name());
pc_error(data.rd);
pc_error(data.rd);
pc_error(data.rd);
gpr[data.rd] =
gpr[data.rm] * gpr[data.rs] + (data.acc ? gpr[data.rn] : 0);
cpu.gpr[data.rd] = cpu.gpr[data.rm] * cpu.gpr[data.rs] +
(data.acc ? cpu.gpr[data.rn] : 0);
if (data.set) {
cpsr.set_z(gpr[data.rd] == 0);
cpsr.set_n(get_bit(gpr[data.rd], 31));
cpsr.set_c(0);
cpu.cpsr.set_z(cpu.gpr[data.rd] == 0);
cpu.cpsr.set_n(get_bit(cpu.gpr[data.rd], 31));
cpu.cpsr.set_c(0);
}
},
[this, pc_error](MultiplyLong& data) {
[&cpu, pc_error](MultiplyLong& data) {
if (data.rdhi == data.rdlo || data.rdhi == data.rm ||
data.rdlo == data.rm)
log_error("rdhi, rdlo and rm are not distinct in {}",
typeid(data).name());
glogger.error("rdhi, rdlo and rm are not distinct in {}",
typeid(data).name());
pc_error(data.rdhi);
pc_error(data.rdlo);
@@ -94,60 +89,62 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
return static_cast<uint64_t>(x);
};
uint64_t eval = cast(gpr[data.rm]) * cast(gpr[data.rs]) +
(data.acc ? (cast(gpr[data.rdhi]) << 32) |
cast(gpr[data.rdlo])
: 0);
uint64_t eval =
cast(cpu.gpr[data.rm]) * cast(cpu.gpr[data.rs]) +
(data.acc ? (cast(cpu.gpr[data.rdhi]) << 32) |
cast(cpu.gpr[data.rdlo])
: 0);
gpr[data.rdlo] = bit_range(eval, 0, 31);
gpr[data.rdhi] = bit_range(eval, 32, 63);
cpu.gpr[data.rdlo] = bit_range(eval, 0, 31);
cpu.gpr[data.rdhi] = bit_range(eval, 32, 63);
} else {
auto cast = [](uint32_t x) -> int64_t {
return static_cast<int64_t>(static_cast<int32_t>(x));
};
int64_t eval = cast(gpr[data.rm]) * cast(gpr[data.rs]) +
(data.acc ? (cast(gpr[data.rdhi]) << 32) |
cast(gpr[data.rdlo])
int64_t eval = cast(cpu.gpr[data.rm]) * cast(cpu.gpr[data.rs]) +
(data.acc ? (cast(cpu.gpr[data.rdhi]) << 32) |
cast(cpu.gpr[data.rdlo])
: 0);
gpr[data.rdlo] = bit_range(eval, 0, 31);
gpr[data.rdhi] = bit_range(eval, 32, 63);
cpu.gpr[data.rdlo] = bit_range(eval, 0, 31);
cpu.gpr[data.rdhi] = bit_range(eval, 32, 63);
}
if (data.set) {
cpsr.set_z(gpr[data.rdhi] == 0 && gpr[data.rdlo] == 0);
cpsr.set_n(get_bit(gpr[data.rdhi], 31));
cpsr.set_c(0);
cpsr.set_v(0);
cpu.cpsr.set_z(cpu.gpr[data.rdhi] == 0 &&
cpu.gpr[data.rdlo] == 0);
cpu.cpsr.set_n(get_bit(cpu.gpr[data.rdhi], 31));
cpu.cpsr.set_c(0);
cpu.cpsr.set_v(0);
}
},
[](Undefined) { log_warn("Undefined instruction"); },
[this, pc_error](SingleDataSwap& data) {
[](Undefined) { glogger.warn("Undefined instruction"); },
[&cpu, pc_error](SingleDataSwap& data) {
pc_error(data.rm);
pc_error(data.rn);
pc_error(data.rd);
if (data.byte) {
gpr[data.rd] = bus->read_byte(gpr[data.rn]);
bus->write_byte(gpr[data.rn], gpr[data.rm] & 0xFF);
cpu.gpr[data.rd] = cpu.bus->read_byte(cpu.gpr[data.rn]);
cpu.bus->write_byte(cpu.gpr[data.rn], cpu.gpr[data.rm] & 0xFF);
} else {
gpr[data.rd] = bus->read_word(gpr[data.rn]);
bus->write_word(gpr[data.rn], gpr[data.rm]);
cpu.gpr[data.rd] = cpu.bus->read_word(cpu.gpr[data.rn]);
cpu.bus->write_word(cpu.gpr[data.rn], cpu.gpr[data.rm]);
}
},
[this, pc_warn, pc_error](SingleDataTransfer& data) {
[&cpu, pc_warn, pc_error](SingleDataTransfer& data) {
uint32_t offset = 0;
uint32_t address = gpr[data.rn];
uint32_t address = cpu.gpr[data.rn];
if (!data.pre && data.write)
log_warn("Write-back enabled with post-indexing in {}",
typeid(data).name());
glogger.warn("Write-back enabled with post-indexing in {}",
typeid(data).name());
if (data.rn == PC_INDEX && data.write)
log_warn("Write-back enabled with base register as PC {}",
typeid(data).name());
if (data.rn == cpu.PC_INDEX && data.write)
glogger.warn("Write-back enabled with base register as PC {}",
typeid(data).name());
if (data.write)
pc_warn(data.rn);
@@ -159,22 +156,22 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
} else if (const Shift* shift = std::get_if<Shift>(&data.offset)) {
uint8_t amount =
(shift->data.immediate ? shift->data.operand
: gpr[shift->data.operand] & 0xFF);
: cpu.gpr[shift->data.operand] & 0xFF);
bool carry = cpsr.c();
bool carry = cpu.cpsr.c();
if (!shift->data.immediate)
pc_error(shift->data.operand);
pc_error(shift->rm);
offset =
eval_shift(shift->data.type, gpr[shift->rm], amount, carry);
offset = eval_shift(
shift->data.type, cpu.gpr[shift->rm], amount, carry);
cpsr.set_c(carry);
cpu.cpsr.set_c(carry);
}
// PC is always two instructions ahead
if (data.rn == PC_INDEX)
if (data.rn == cpu.PC_INDEX)
address -= 2 * INSTRUCTION_SIZE;
if (data.pre)
@@ -184,43 +181,43 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
if (data.load) {
// byte
if (data.byte)
gpr[data.rd] = bus->read_byte(address);
cpu.gpr[data.rd] = cpu.bus->read_byte(address);
// word
else
gpr[data.rd] = bus->read_word(address);
cpu.gpr[data.rd] = cpu.bus->read_word(address);
// store
} else {
// take PC into consideration
if (data.rd == PC_INDEX)
if (data.rd == cpu.PC_INDEX)
address += INSTRUCTION_SIZE;
// byte
if (data.byte)
bus->write_byte(address, gpr[data.rd] & 0xFF);
cpu.bus->write_byte(address, cpu.gpr[data.rd] & 0xFF);
// word
else
bus->write_word(address, gpr[data.rd]);
cpu.bus->write_word(address, cpu.gpr[data.rd]);
}
if (!data.pre)
address += (data.up ? offset : -offset);
if (!data.pre || data.write)
gpr[data.rn] = address;
cpu.gpr[data.rn] = address;
if (data.rd == PC_INDEX && data.load)
is_flushed = true;
if (data.rd == cpu.PC_INDEX && data.load)
cpu.is_flushed = true;
},
[this, pc_warn, pc_error](HalfwordTransfer& data) {
uint32_t address = gpr[data.rn];
[&cpu, pc_warn, pc_error](HalfwordTransfer& data) {
uint32_t address = cpu.gpr[data.rn];
uint32_t offset = 0;
if (!data.pre && data.write)
log_error("Write-back enabled with post-indexing in {}",
typeid(data).name());
glogger.error("Write-back enabled with post-indexing in {}",
typeid(data).name());
if (data.sign && !data.load)
log_error("Signed data found in {}", typeid(data).name());
glogger.error("Signed data found in {}", typeid(data).name());
if (data.write)
pc_warn(data.rn);
@@ -228,13 +225,13 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
// offset is register number (4 bits) when not an immediate
if (!data.imm) {
pc_error(data.offset);
offset = gpr[data.offset];
offset = cpu.gpr[data.offset];
} else {
offset = data.offset;
}
// PC is always two instructions ahead
if (data.rn == PC_INDEX)
if (data.rn == cpu.PC_INDEX)
address -= 2 * INSTRUCTION_SIZE;
if (data.pre)
@@ -246,69 +243,71 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
if (data.sign) {
// halfword
if (data.half) {
gpr[data.rd] = bus->read_halfword(address);
cpu.gpr[data.rd] = cpu.bus->read_halfword(address);
// sign extend the halfword
gpr[data.rd] =
(static_cast<int32_t>(gpr[data.rd]) << 16) >> 16;
cpu.gpr[data.rd] =
(static_cast<int32_t>(cpu.gpr[data.rd]) << 16) >> 16;
// byte
} else {
gpr[data.rd] = bus->read_byte(address);
cpu.gpr[data.rd] = cpu.bus->read_byte(address);
// sign extend the byte
gpr[data.rd] =
(static_cast<int32_t>(gpr[data.rd]) << 24) >> 24;
cpu.gpr[data.rd] =
(static_cast<int32_t>(cpu.gpr[data.rd]) << 24) >> 24;
}
// unsigned halfword
} else if (data.half) {
gpr[data.rd] = bus->read_halfword(address);
cpu.gpr[data.rd] = cpu.bus->read_halfword(address);
}
// store
} else {
// take PC into consideration
if (data.rd == PC_INDEX)
if (data.rd == cpu.PC_INDEX)
address += INSTRUCTION_SIZE;
// halfword
if (data.half)
bus->write_halfword(address, gpr[data.rd]);
cpu.bus->write_halfword(address, cpu.gpr[data.rd]);
}
if (!data.pre)
address += (data.up ? offset : -offset);
if (!data.pre || data.write)
gpr[data.rn] = address;
cpu.gpr[data.rn] = address;
if (data.rd == PC_INDEX && data.load)
is_flushed = true;
if (data.rd == cpu.PC_INDEX && data.load)
cpu.is_flushed = true;
},
[this, pc_error](BlockDataTransfer& data) {
uint32_t address = gpr[data.rn];
Mode mode = cpsr.mode();
[&cpu, pc_error](BlockDataTransfer& data) {
uint32_t address = cpu.gpr[data.rn];
Mode mode = cpu.cpsr.mode();
uint8_t alignment = 4; // word
uint8_t i = 0;
uint8_t n_regs = std::popcount(data.regs);
pc_error(data.rn);
if (cpsr.mode() == Mode::User && data.s) {
log_error("Bit S is set outside priviliged modes in {}",
typeid(data).name());
if (cpu.cpsr.mode() == Mode::User && data.s) {
glogger.error("Bit S is set outside priviliged modes in {}",
typeid(data).name());
}
// we just change modes to load user registers
if ((!get_bit(data.regs, PC_INDEX) && data.s) ||
if ((!get_bit(data.regs, cpu.PC_INDEX) && data.s) ||
(!data.load && data.s)) {
chg_mode(Mode::User);
cpu.chg_mode(Mode::User);
if (data.write) {
log_error("Write-back enable for user bank registers in {}",
typeid(data).name());
glogger.error(
"Write-back enable for user bank registers in {}",
typeid(data).name());
}
}
// TODO: clean this shit
// account for decrement
if (!data.up)
address -= (n_regs - 1) * alignment;
@@ -317,22 +316,22 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
address += (data.up ? alignment : -alignment);
if (data.load) {
if (get_bit(data.regs, PC_INDEX) && data.s && data.load) {
// current mode's spsr is already loaded when it was
if (get_bit(data.regs, cpu.PC_INDEX) && data.s && data.load) {
// current mode's cpu.spsr is already loaded when it was
// switched
spsr = cpsr;
cpu.spsr = cpu.cpsr;
}
for (i = 0; i < GPR_COUNT; i++) {
for (i = 0; i < cpu.GPR_COUNT; i++) {
if (get_bit(data.regs, i)) {
gpr[i] = bus->read_word(address);
cpu.gpr[i] = cpu.bus->read_word(address);
address += alignment;
}
}
} else {
for (i = 0; i < GPR_COUNT; i++) {
for (i = 0; i < cpu.GPR_COUNT; i++) {
if (get_bit(data.regs, i)) {
bus->write_word(address, gpr[i]);
cpu.bus->write_word(address, cpu.gpr[i]);
address += alignment;
}
}
@@ -348,37 +347,37 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
address -= alignment;
if (!data.pre || data.write)
gpr[data.rn] = address;
cpu.gpr[data.rn] = address;
if (data.load && get_bit(data.regs, PC_INDEX))
is_flushed = true;
if (data.load && get_bit(data.regs, cpu.PC_INDEX))
cpu.is_flushed = true;
// load back the original mode registers
chg_mode(mode);
cpu.chg_mode(mode);
},
[this, pc_error](PsrTransfer& data) {
if (data.spsr && cpsr.mode() == Mode::User) {
log_error("Accessing SPSR in User mode in {}",
typeid(data).name());
[&cpu, pc_error](PsrTransfer& data) {
if (data.spsr && cpu.cpsr.mode() == Mode::User) {
glogger.error("Accessing CPU.SPSR in User mode in {}",
typeid(data).name());
}
Psr& psr = data.spsr ? spsr : cpsr;
Psr& psr = data.spsr ? cpu.spsr : cpu.cpsr;
switch (data.type) {
case PsrTransfer::Type::Mrs:
pc_error(data.operand);
gpr[data.operand] = psr.raw();
cpu.gpr[data.operand] = psr.raw();
break;
case PsrTransfer::Type::Msr:
pc_error(data.operand);
if (cpsr.mode() != Mode::User) {
psr.set_all(gpr[data.operand]);
if (cpu.cpsr.mode() != Mode::User) {
psr.set_all(cpu.gpr[data.operand]);
}
break;
case PsrTransfer::Type::Msr_flg:
uint32_t operand =
(data.imm ? data.operand : gpr[data.operand]);
(data.imm ? data.operand : cpu.gpr[data.operand]);
psr.set_n(get_bit(operand, 31));
psr.set_z(get_bit(operand, 30));
psr.set_c(get_bit(operand, 29));
@@ -386,10 +385,10 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
break;
}
},
[this, pc_error](DataProcessing& data) {
[&cpu, pc_error](DataProcessing& data) {
using OpCode = DataProcessing::OpCode;
uint32_t op_1 = gpr[data.rn];
uint32_t op_1 = cpu.gpr[data.rn];
uint32_t op_2 = 0;
uint32_t result = 0;
@@ -400,64 +399,26 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
} else if (const Shift* shift = std::get_if<Shift>(&data.operand)) {
uint8_t amount =
(shift->data.immediate ? shift->data.operand
: gpr[shift->data.operand] & 0xFF);
: cpu.gpr[shift->data.operand] & 0xFF);
bool carry = cpsr.c();
bool carry = cpu.cpsr.c();
if (!shift->data.immediate)
pc_error(shift->data.operand);
pc_error(shift->rm);
op_2 =
eval_shift(shift->data.type, gpr[shift->rm], amount, carry);
op_2 = eval_shift(
shift->data.type, cpu.gpr[shift->rm], amount, carry);
cpsr.set_c(carry);
cpu.cpsr.set_c(carry);
// PC is 12 bytes ahead when shifting
if (data.rn == PC_INDEX)
if (data.rn == cpu.PC_INDEX)
op_1 += INSTRUCTION_SIZE;
}
bool overflow = cpsr.v();
bool carry = cpsr.c();
auto sub = [&carry, &overflow](uint32_t a, uint32_t b) -> uint32_t {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
uint32_t result = a - b;
carry = b <= a;
overflow = s1 != s2 && s2 == get_bit(result, 31);
return result;
};
auto add = [&carry, &overflow](
uint32_t a, uint32_t b, bool c = 0) -> uint32_t {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
// 33 bits
uint64_t result_ = a + b + c;
uint32_t result = result_ & 0xFFFFFFFF;
carry = get_bit(result_, 32);
overflow = s1 == s2 && s2 != get_bit(result, 31);
return result;
};
auto sbc = [&carry,
&overflow](uint32_t a, uint32_t b, bool c) -> uint32_t {
bool s1 = get_bit(a, 31);
bool s2 = get_bit(b, 31);
uint64_t result_ = a - b + c - 1;
uint32_t result = result_ & 0xFFFFFFFF;
carry = get_bit(result_, 32);
overflow = s1 != s2 && s2 == get_bit(result, 31);
return result;
};
bool overflow = cpu.cpsr.v();
bool carry = cpu.cpsr.c();
switch (data.opcode) {
case OpCode::AND:
@@ -471,23 +432,23 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
break;
case OpCode::SUB:
case OpCode::CMP:
result = sub(op_1, op_2);
result = sub(op_1, op_2, carry, overflow);
break;
case OpCode::RSB:
result = sub(op_2, op_1);
result = sub(op_2, op_1, carry, overflow);
break;
case OpCode::ADD:
case OpCode::CMN:
result = add(op_1, op_2);
result = add(op_1, op_2, carry, overflow);
break;
case OpCode::ADC:
result = add(op_1, op_2, carry);
result = add(op_1, op_2, carry, overflow, carry);
break;
case OpCode::SBC:
result = sbc(op_1, op_2, carry);
result = sbc(op_1, op_2, carry, overflow, carry);
break;
case OpCode::RSC:
result = sbc(op_2, op_1, carry);
result = sbc(op_2, op_1, carry, overflow, carry);
break;
case OpCode::ORR:
result = op_1 | op_2;
@@ -503,19 +464,19 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
break;
}
auto set_conditions = [this, carry, overflow, result]() {
cpsr.set_c(carry);
cpsr.set_v(overflow);
cpsr.set_n(get_bit(result, 31));
cpsr.set_z(result == 0);
auto set_conditions = [&cpu, carry, overflow, result]() {
cpu.cpsr.set_c(carry);
cpu.cpsr.set_v(overflow);
cpu.cpsr.set_n(get_bit(result, 31));
cpu.cpsr.set_z(result == 0);
};
if (data.set) {
if (data.rd == PC_INDEX) {
if (cpsr.mode() == Mode::User)
log_error("Running {} in User mode",
typeid(data).name());
spsr = cpsr;
if (data.rd == cpu.PC_INDEX) {
if (cpu.cpsr.mode() == Mode::User)
glogger.error("Running {} in User mode",
typeid(data).name());
cpu.spsr = cpu.cpsr;
} else {
set_conditions();
}
@@ -525,18 +486,18 @@ CpuImpl::exec_arm(const arm::Instruction instruction) {
data.opcode == OpCode::CMP || data.opcode == OpCode::CMN) {
set_conditions();
} else {
gpr[data.rd] = result;
if (data.rd == PC_INDEX || data.opcode == OpCode::MVN)
is_flushed = true;
cpu.gpr[data.rd] = result;
if (data.rd == cpu.PC_INDEX || data.opcode == OpCode::MVN)
cpu.is_flushed = true;
}
},
[this](SoftwareInterrupt) {
chg_mode(Mode::Supervisor);
pc = 0x08;
spsr = cpsr;
[&cpu](SoftwareInterrupt) {
cpu.chg_mode(Mode::Supervisor);
cpu.pc = 0x08;
cpu.spsr = cpu.cpsr;
},
[](auto& data) {
log_error("Unimplemented {} instruction", typeid(data).name());
glogger.error("Unimplemented {} instruction", typeid(data).name());
} },
data);
}

View File

@@ -2,9 +2,7 @@
#include "util/bits.hh"
#include <iterator>
namespace matar {
namespace arm {
namespace matar::arm {
Instruction::Instruction(uint32_t insn)
: condition(static_cast<Condition>(bit_range(insn, 28, 31))) {
// Branch and exhcange
@@ -275,261 +273,4 @@ Instruction::Instruction(uint32_t insn)
data = Undefined{};
}
}
std::string
Instruction::disassemble() {
// goddamn this is gore
// TODO: make this less ugly
return std::visit(
overloaded{
[this](BranchAndExchange& data) {
return fmt::format("BX{} R{:d}", condition, data.rn);
},
[this](Branch& data) {
return fmt::format(
"B{}{} 0x{:06X}", (data.link ? "L" : ""), condition, data.offset);
},
[this](Multiply& data) {
if (data.acc) {
return fmt::format("MLA{}{} R{:d},R{:d},R{:d},R{:d}",
condition,
(data.set ? "S" : ""),
data.rd,
data.rm,
data.rs,
data.rn);
} else {
return fmt::format("MUL{}{} R{:d},R{:d},R{:d}",
condition,
(data.set ? "S" : ""),
data.rd,
data.rm,
data.rs);
}
},
[this](MultiplyLong& data) {
return fmt::format("{}{}{}{} R{:d},R{:d},R{:d},R{:d}",
(data.uns ? 'U' : 'S'),
(data.acc ? "MLAL" : "MULL"),
condition,
(data.set ? "S" : ""),
data.rdlo,
data.rdhi,
data.rm,
data.rs);
},
[](Undefined) { return std::string("UND"); },
[this](SingleDataSwap& data) {
return fmt::format("SWP{}{} R{:d},R{:d},[R{:d}]",
condition,
(data.byte ? "B" : ""),
data.rd,
data.rm,
data.rn);
},
[this](SingleDataTransfer& data) {
std::string expression;
std::string address;
if (const uint16_t* offset = std::get_if<uint16_t>(&data.offset)) {
if (*offset == 0) {
expression = "";
} else {
expression =
fmt::format(",{}#{:d}", (data.up ? '+' : '-'), *offset);
}
} else if (const Shift* shift = std::get_if<Shift>(&data.offset)) {
// Shifts are always immediate in single data transfer
expression = fmt::format(",{}R{:d},{} #{:d}",
(data.up ? '+' : '-'),
shift->rm,
shift->data.type,
shift->data.operand);
}
return fmt::format(
"{}{}{}{} R{:d},[R{:d}{}]{}",
(data.load ? "LDR" : "STR"),
condition,
(data.byte ? "B" : ""),
(!data.pre && data.write ? "T" : ""),
data.rd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[this](HalfwordTransfer& data) {
std::string expression;
if (data.imm) {
if (data.offset == 0) {
expression = "";
} else {
expression = fmt::format(
",{}#{:d}", (data.up ? '+' : '-'), data.offset);
}
} else {
expression =
fmt::format(",{}R{:d}", (data.up ? '+' : '-'), data.offset);
}
return fmt::format(
"{}{}{}{} R{:d},[R{:d}{}]{}",
(data.load ? "LDR" : "STR"),
condition,
(data.sign ? "S" : ""),
(data.half ? 'H' : 'B'),
data.rd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[this](BlockDataTransfer& data) {
std::string regs;
for (uint8_t i = 0; i < 16; i++) {
if (get_bit(data.regs, i))
fmt::format_to(std::back_inserter(regs), "R{:d},", i);
};
regs.pop_back();
return fmt::format("{}{}{}{} R{:d}{},{{{}}}{}",
(data.load ? "LDM" : "STM"),
condition,
(data.up ? 'I' : 'D'),
(data.pre ? 'B' : 'A'),
data.rn,
(data.write ? "!" : ""),
regs,
(data.s ? "^" : ""));
},
[this](PsrTransfer& data) {
if (data.type == PsrTransfer::Type::Mrs) {
return fmt::format("MRS{} R{:d},{}",
condition,
data.operand,
(data.spsr ? "SPSR_all" : "CPSR_all"));
} else {
return fmt::format(
"MSR{} {}_{},{}{}",
condition,
(data.spsr ? "SPSR" : "CPSR"),
(data.type == PsrTransfer::Type::Msr_flg ? "flg" : "all"),
(data.imm ? '#' : 'R'),
data.operand);
}
},
[this](DataProcessing& data) {
using OpCode = DataProcessing::OpCode;
std::string op_2;
if (const uint32_t* operand =
std::get_if<uint32_t>(&data.operand)) {
op_2 = fmt::format("#{:d}", *operand);
} else if (const Shift* shift = std::get_if<Shift>(&data.operand)) {
op_2 = fmt::format("R{:d},{} {}{:d}",
shift->rm,
shift->data.type,
(shift->data.immediate ? '#' : 'R'),
shift->data.operand);
}
switch (data.opcode) {
case OpCode::MOV:
case OpCode::MVN:
return fmt::format("{}{}{} R{:d},{}",
data.opcode,
condition,
(data.set ? "S" : ""),
data.rd,
op_2);
case OpCode::TST:
case OpCode::TEQ:
case OpCode::CMP:
case OpCode::CMN:
return fmt::format(
"{}{} R{:d},{}", data.opcode, condition, data.rn, op_2);
default:
return fmt::format("{}{}{} R{:d},R{:d},{}",
data.opcode,
condition,
(data.set ? "S" : ""),
data.rd,
data.rn,
op_2);
}
},
[this](SoftwareInterrupt) { return fmt::format("SWI{}", condition); },
[this](CoprocessorDataTransfer& data) {
std::string expression = fmt::format(",#{:d}", data.offset);
return fmt::format(
"{}{}{} p{:d},c{:d},[R{:d}{}]{}",
(data.load ? "LDC" : "STC"),
condition,
(data.len ? "L" : ""),
data.cpn,
data.crd,
data.rn,
(data.pre ? expression : ""),
(data.pre ? (data.write ? "!" : "") : expression));
},
[this](CoprocessorDataOperation& data) {
return fmt::format("CDP{} p{},{},c{},c{},c{},{}",
condition,
data.cpn,
data.cp_opc,
data.crd,
data.crn,
data.crm,
data.cp);
},
[this](CoprocessorRegisterTransfer& data) {
return fmt::format("{}{} p{},{},R{},c{},c{},{}",
(data.load ? "MRC" : "MCR"),
condition,
data.cpn,
data.cp_opc,
data.rd,
data.crn,
data.crm,
data.cp);
},
[](auto) { return std::string("unknown instruction"); } },
data);
}
std::ostream&
operator<<(std::ostream& os, const DataProcessing::OpCode opcode) {
#define CASE(opcode) \
case DataProcessing::OpCode::opcode: \
os << #opcode; \
break;
switch (opcode) {
CASE(AND)
CASE(EOR)
CASE(SUB)
CASE(RSB)
CASE(ADD)
CASE(ADC)
CASE(SBC)
CASE(RSC)
CASE(TST)
CASE(TEQ)
CASE(CMP)
CASE(CMN)
CASE(ORR)
CASE(MOV)
CASE(BIC)
CASE(MVN)
}
#undef CASE
return os;
}
}
}

View File

@@ -6,8 +6,11 @@
#include <variant>
namespace matar {
class CpuImpl;
namespace arm {
// https://en.cppreference.com/w/cpp/utility/variant/visit
template<class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
@@ -113,6 +116,37 @@ struct DataProcessing {
OpCode opcode;
};
constexpr auto
stringify(DataProcessing::OpCode opcode) {
#define CASE(opcode) \
case DataProcessing::OpCode::opcode: \
return #opcode;
switch (opcode) {
CASE(AND)
CASE(EOR)
CASE(SUB)
CASE(RSB)
CASE(ADD)
CASE(ADC)
CASE(SBC)
CASE(RSC)
CASE(TST)
CASE(TEQ)
CASE(CMP)
CASE(CMN)
CASE(ORR)
CASE(MOV)
CASE(BIC)
CASE(MVN)
}
#undef CASE
return "";
}
struct PsrTransfer {
enum class Type {
Mrs,
@@ -178,23 +212,19 @@ using InstructionData = std::variant<BranchAndExchange,
SoftwareInterrupt>;
struct Instruction {
Condition condition;
InstructionData data;
Instruction(uint32_t insn);
Instruction(Condition condition, InstructionData data) noexcept
Instruction(Condition condition, InstructionData data)
: condition(condition)
, data(data){};
void exec(CpuImpl& cpu);
#ifdef DISASSEMBLER
std::string disassemble();
#endif
Condition condition;
InstructionData data;
};
std::ostream&
operator<<(std::ostream& os, const DataProcessing::OpCode cond);
}
}
namespace fmt {
template<>
struct formatter<matar::arm::DataProcessing::OpCode> : ostream_formatter {};
}

View File

@@ -1,4 +1,8 @@
lib_sources += files(
'instruction.cc',
'exec.cc'
)
)
if get_option('disassembler')
lib_sources += files('disassembler.cc')
endif

View File

@@ -1,10 +1,11 @@
#include "cpu-impl.hh"
#include "cpu/arm/instruction.hh"
#include "cpu/thumb/instruction.hh"
#include "util/bits.hh"
#include "util/log.hh"
#include <algorithm>
#include <cstdio>
using namespace logger;
#include <type_traits>
namespace matar {
CpuImpl::CpuImpl(const Bus& bus) noexcept
@@ -12,14 +13,14 @@ CpuImpl::CpuImpl(const Bus& bus) noexcept
, gpr({ 0 })
, cpsr(0)
, spsr(0)
, is_flushed(false)
, gpr_banked({ { 0 }, { 0 }, { 0 }, { 0 }, { 0 }, { 0 } })
, spsr_banked({ 0, 0, 0, 0, 0 }) {
, spsr_banked({ 0, 0, 0, 0, 0 })
, is_flushed(false) {
cpsr.set_mode(Mode::Supervisor);
cpsr.set_irq_disabled(true);
cpsr.set_fiq_disabled(true);
cpsr.set_state(State::Arm);
log_info("CPU successfully initialised");
glogger.info("CPU successfully initialised");
// PC always points to two instructions ahead
// PC - 2 is the instruction being executed
@@ -121,24 +122,38 @@ CpuImpl::step() {
uint32_t cur_pc = pc - 2 * arm::INSTRUCTION_SIZE;
if (cpsr.state() == State::Arm) {
debug(cur_pc);
uint32_t x = bus->read_word(cur_pc);
arm::Instruction instruction(x);
log_info("{:#034b}", x);
arm::Instruction instruction(bus->read_word(cur_pc));
exec_arm(instruction);
#ifdef DISASSEMBLER
glogger.info("0x{:08X} : {}", cur_pc, instruction.disassemble());
#endif
log_info("0x{:08X} : {}", cur_pc, instruction.disassemble());
instruction.exec(*this);
} else {
thumb::Instruction instruction(bus->read_halfword(cur_pc));
#ifdef DISASSEMBLER
glogger.info("0x{:08X} : {}", cur_pc, instruction.disassemble(cur_pc));
#endif
instruction.exec(*this);
}
// advance PC
{
size_t size = cpsr.state() == State::Arm ? arm::INSTRUCTION_SIZE
: thumb::INSTRUCTION_SIZE;
if (is_flushed) {
// if flushed, do not increment the PC, instead set it to two
// instructions ahead to account for flushed "fetch" and "decode"
// instructions
pc += 2 * arm::INSTRUCTION_SIZE;
pc += 2 * size;
is_flushed = false;
} else {
// if not flushed continue like normal
pc += arm::INSTRUCTION_SIZE;
pc += size;
}
}
}

View File

@@ -1,8 +1,9 @@
#pragma once
#include "arm/instruction.hh"
#include "bus.hh"
#include "cpu/arm/instruction.hh"
#include "cpu/psr.hh"
#include "thumb/instruction.hh"
#include <cstdint>
@@ -13,7 +14,10 @@ class CpuImpl {
void step();
void chg_mode(const Mode to);
void exec_arm(const arm::Instruction instruction);
private:
friend void arm::Instruction::exec(CpuImpl& cpu);
friend void thumb::Instruction::exec(CpuImpl& cpu);
static constexpr uint8_t GPR_COUNT = 16;
@@ -30,13 +34,18 @@ class CpuImpl {
Psr cpsr; // current program status register
Psr spsr; // status program status register
static constexpr uint8_t SP_INDEX = 13;
static_assert(SP_INDEX < GPR_COUNT);
uint32_t& sp = gpr[SP_INDEX];
static constexpr uint8_t LR_INDEX = 14;
static_assert(LR_INDEX < GPR_COUNT);
uint32_t& lr = gpr[LR_INDEX];
static constexpr uint8_t PC_INDEX = 15;
static_assert(PC_INDEX < GPR_COUNT);
uint32_t& pc = gpr[PC_INDEX];
bool is_flushed;
struct {
std::array<uint32_t, GPR_COUNT - GPR_FIQ_FIRST - 1> fiq;
std::array<uint32_t, GPR_COUNT - GPR_SVC_FIRST - 1> svc;
@@ -55,5 +64,7 @@ class CpuImpl {
Psr irq;
Psr und;
} spsr_banked; // banked saved program status registers
bool is_flushed;
};
}

View File

@@ -5,4 +5,5 @@ lib_sources += files(
'alu.cc'
)
subdir('arm')
subdir('arm')
subdir('thumb')

View File

@@ -13,7 +13,7 @@ Psr::raw() const {
void
Psr::set_all(uint32_t raw) {
psr = raw & ~PSR_CLEAR_RESERVED;
psr = raw;
}
Mode
@@ -91,42 +91,9 @@ Psr::condition(Condition cond) const {
case Condition::LE:
return z() || (n() != v());
case Condition::AL:
return true && state() == State::Arm;
return true;
}
return false;
}
std::ostream&
operator<<(std::ostream& os, const Condition cond) {
#define CASE(cond) \
case Condition::cond: \
os << #cond; \
break;
switch (cond) {
CASE(EQ)
CASE(NE)
CASE(CS)
CASE(CC)
CASE(MI)
CASE(PL)
CASE(VS)
CASE(VC)
CASE(HI)
CASE(LS)
CASE(GE)
CASE(LT)
CASE(GT)
CASE(LE)
case Condition::AL: {
// empty
}
}
#undef CASE
return os;
}
}

View File

@@ -38,6 +38,38 @@ enum class Condition {
AL = 0b1110
};
constexpr auto
stringify(Condition cond) {
#define CASE(cond) \
case Condition::cond: \
return #cond;
switch (cond) {
CASE(EQ)
CASE(NE)
CASE(CS)
CASE(CC)
CASE(MI)
CASE(PL)
CASE(VS)
CASE(VC)
CASE(HI)
CASE(LS)
CASE(GE)
CASE(LT)
CASE(GT)
CASE(LE)
case Condition::AL: {
return "";
}
}
#undef CASE
return "";
}
class Psr {
public:
// clear the reserved bits i.e, [8:27]
@@ -88,13 +120,4 @@ class Psr {
uint32_t psr;
};
// https://fmt.dev/dev/api.html#std-ostream-support
std::ostream&
operator<<(std::ostream& os, const Condition cond);
}
namespace fmt {
template<>
struct formatter<matar::Condition> : ostream_formatter {};
}

View File

@@ -0,0 +1,154 @@
#include "instruction.hh"
#include "util/bits.hh"
namespace matar::thumb {
std::string
Instruction::disassemble(uint32_t pc) {
return std::visit(
overloaded{
[](MoveShiftedRegister& data) {
return fmt::format("{} R{:d},R{:d},#{:d}",
stringify(data.opcode),
data.rd,
data.rs,
data.offset);
},
[](AddSubtract& data) {
return fmt::format("{} R{:d},R{:d},{}{:d}",
stringify(data.opcode),
data.rd,
data.rs,
(data.imm ? '#' : 'R'),
data.offset);
},
[](MovCmpAddSubImmediate& data) {
return fmt::format(
"{} R{:d},#{:d}", stringify(data.opcode), data.rd, data.offset);
},
[](AluOperations& data) {
return fmt::format(
"{} R{:d},R{:d}", stringify(data.opcode), data.rd, data.rs);
},
[](HiRegisterOperations& data) {
if (data.opcode == HiRegisterOperations::OpCode::BX) {
return fmt::format("{} R{:d}", stringify(data.opcode), data.rs);
}
return fmt::format(
"{} R{:d},R{:d}", stringify(data.opcode), data.rd, data.rs);
},
[](PcRelativeLoad& data) {
return fmt::format("LDR R{:d},[PC,#{:d}]", data.rd, data.word);
},
[](LoadStoreRegisterOffset& data) {
return fmt::format("{}{} R{:d},[R{:d},R{:d}]",
(data.load ? "LDR" : "STR"),
(data.byte ? "B" : ""),
data.rd,
data.rb,
data.ro);
},
[](LoadStoreSignExtendedHalfword& data) {
if (!data.s && !data.h) {
return fmt::format(
"STRH R{:d},[R{:d},R{:d}]", data.rd, data.rb, data.ro);
}
return fmt::format("{}{} R{:d},[R{:d},R{:d}]",
(data.s ? "LDS" : "LDR"),
(data.h ? 'H' : 'B'),
data.rd,
data.rb,
data.ro);
},
[](LoadStoreImmediateOffset& data) {
return fmt::format("{}{} R{:d},[R{:d},#{:d}]",
(data.load ? "LDR" : "STR"),
(data.byte ? "B" : ""),
data.rd,
data.rb,
data.offset);
},
[](LoadStoreHalfword& data) {
return fmt::format("{} R{:d},[R{:d},#{:d}]",
(data.load ? "LDRH" : "STRH"),
data.rd,
data.rb,
data.offset);
},
[](SpRelativeLoad& data) {
return fmt::format("{} R{:d},[SP,#{:d}]",
(data.load ? "LDR" : "STR"),
data.rd,
data.word);
},
[](LoadAddress& data) {
return fmt::format("ADD R{:d},{},#{:d}",
data.rd,
(data.sp ? "SP" : "PC"),
data.word);
},
[](AddOffsetStackPointer& data) {
return fmt::format("ADD SP,#{:d}", data.word);
},
[](PushPopRegister& data) {
std::string regs;
for (uint8_t i = 0; i < 16; i++) {
if (get_bit(data.regs, i))
fmt::format_to(std::back_inserter(regs), "R{:d},", i);
};
if (data.load) {
if (data.pclr)
regs += "PC";
else
regs.pop_back();
return fmt::format("POP {{{}}}", regs);
} else {
if (data.pclr)
regs += "LR";
else
regs.pop_back();
return fmt::format("PUSH {{{}}}", regs);
}
},
[](MultipleLoad& data) {
std::string regs;
for (uint8_t i = 0; i < 16; i++) {
if (get_bit(data.regs, i))
fmt::format_to(std::back_inserter(regs), "R{:d},", i);
};
regs.pop_back();
return fmt::format(
"{} R{}!,{{{}}}", (data.load ? "LDMIA" : "STMIA"), data.rb, regs);
},
[](SoftwareInterrupt& data) {
return fmt::format("SWI {:d}", data.vector);
},
[pc](ConditionalBranch& data) {
return fmt::format(
"B{} #{:d}",
stringify(data.condition),
static_cast<int32_t>(data.offset + pc + 2 * INSTRUCTION_SIZE));
},
[pc](UnconditionalBranch& data) {
return fmt::format(
"B #{:d}",
static_cast<int32_t>(data.offset + pc + 2 * INSTRUCTION_SIZE));
},
[](LongBranchWithLink& data) {
// duh this manual be empty for H = 0
return fmt::format(
"BL{} #{:d}", (data.high ? "H" : ""), data.offset);
},
[](auto) { return std::string("unknown instruction"); } },
data);
}
}

384
src/cpu/thumb/exec.cc Normal file
View File

@@ -0,0 +1,384 @@
#include "cpu/cpu-impl.hh"
#include "instruction.hh"
#include "util/bits.hh"
#include "util/log.hh"
namespace matar::thumb {
void
Instruction::exec(CpuImpl& cpu) {
auto set_cc = [&cpu](bool c, bool v, bool n, bool z) {
cpu.cpsr.set_c(c);
cpu.cpsr.set_v(v);
cpu.cpsr.set_n(n);
cpu.cpsr.set_z(z);
};
std::visit(
overloaded{
[&cpu, set_cc](MoveShiftedRegister& data) {
if (data.opcode == ShiftType::ROR)
glogger.error("Invalid opcode in {}", typeid(data).name());
bool carry = cpu.cpsr.c();
uint32_t shifted =
eval_shift(data.opcode, cpu.gpr[data.rs], data.offset, carry);
cpu.gpr[data.rd] = shifted;
set_cc(carry, cpu.cpsr.v(), get_bit(shifted, 31), shifted == 0);
},
[&cpu, set_cc](AddSubtract& data) {
uint32_t offset =
data.imm ? static_cast<uint32_t>(static_cast<int8_t>(data.offset))
: cpu.gpr[data.offset];
uint32_t result = 0;
bool carry = cpu.cpsr.c();
bool overflow = cpu.cpsr.v();
switch (data.opcode) {
case AddSubtract::OpCode::ADD:
result = add(cpu.gpr[data.rs], offset, carry, overflow);
break;
case AddSubtract::OpCode::SUB:
result = sub(cpu.gpr[data.rs], offset, carry, overflow);
break;
}
cpu.gpr[data.rd] = result;
set_cc(carry, overflow, get_bit(result, 31), result == 0);
},
[&cpu, set_cc](MovCmpAddSubImmediate& data) {
uint32_t result = 0;
bool carry = cpu.cpsr.c();
bool overflow = cpu.cpsr.v();
switch (data.opcode) {
case MovCmpAddSubImmediate::OpCode::MOV:
result = data.offset;
carry = 0;
break;
case MovCmpAddSubImmediate::OpCode::ADD:
result =
add(cpu.gpr[data.rd], data.offset, carry, overflow);
break;
case MovCmpAddSubImmediate::OpCode::SUB:
case MovCmpAddSubImmediate::OpCode::CMP:
result =
sub(cpu.gpr[data.rd], data.offset, carry, overflow);
break;
}
set_cc(carry, overflow, get_bit(result, 31), result == 0);
if (data.opcode != MovCmpAddSubImmediate::OpCode::CMP)
cpu.gpr[data.rd] = result;
},
[&cpu, set_cc](AluOperations& data) {
uint32_t op_1 = cpu.gpr[data.rd];
uint32_t op_2 = cpu.gpr[data.rs];
uint32_t result = 0;
bool carry = cpu.cpsr.c();
bool overflow = cpu.cpsr.v();
switch (data.opcode) {
case AluOperations::OpCode::AND:
case AluOperations::OpCode::TST:
result = op_1 & op_2;
break;
case AluOperations::OpCode::EOR:
result = op_1 ^ op_2;
break;
case AluOperations::OpCode::LSL:
result = eval_shift(ShiftType::LSL, op_1, op_2, carry);
break;
case AluOperations::OpCode::LSR:
result = eval_shift(ShiftType::LSR, op_1, op_2, carry);
break;
case AluOperations::OpCode::ASR:
result = eval_shift(ShiftType::ASR, op_1, op_2, carry);
break;
case AluOperations::OpCode::ADC:
result = add(op_1, op_2, carry, overflow, carry);
break;
case AluOperations::OpCode::SBC:
result = sbc(op_1, op_2, carry, overflow, carry);
break;
case AluOperations::OpCode::ROR:
result = eval_shift(ShiftType::ROR, op_1, op_2, carry);
break;
case AluOperations::OpCode::NEG:
result = -op_2;
break;
case AluOperations::OpCode::CMP:
result = sub(op_1, op_2, carry, overflow);
break;
case AluOperations::OpCode::CMN:
result = add(op_1, op_2, carry, overflow);
break;
case AluOperations::OpCode::ORR:
result = op_1 | op_2;
break;
case AluOperations::OpCode::MUL:
result = op_1 * op_2;
break;
case AluOperations::OpCode::BIC:
result = op_1 & ~op_2;
break;
case AluOperations::OpCode::MVN:
result = ~op_2;
break;
}
if (data.opcode != AluOperations::OpCode::TST &&
data.opcode != AluOperations::OpCode::CMP &&
data.opcode != AluOperations::OpCode::CMN)
cpu.gpr[data.rd] = result;
set_cc(carry, overflow, get_bit(result, 31), result == 0);
},
[&cpu, set_cc](HiRegisterOperations& data) {
uint32_t op_1 = cpu.gpr[data.rd];
uint32_t op_2 = cpu.gpr[data.rs];
bool carry = cpu.cpsr.c();
bool overflow = cpu.cpsr.v();
// PC is already current + 4, so dont need to do that
if (data.rd == cpu.PC_INDEX)
rst_bit(op_1, 0);
if (data.rs == cpu.PC_INDEX)
rst_bit(op_2, 0);
switch (data.opcode) {
case HiRegisterOperations::OpCode::ADD: {
cpu.gpr[data.rd] = add(op_1, op_2, carry, overflow);
if (data.rd == cpu.PC_INDEX)
cpu.is_flushed = true;
} break;
case HiRegisterOperations::OpCode::CMP: {
uint32_t result = sub(op_1, op_2, carry, overflow);
set_cc(carry, overflow, get_bit(result, 31), result == 0);
} break;
case HiRegisterOperations::OpCode::MOV: {
cpu.gpr[data.rd] = op_2;
if (data.rd == cpu.PC_INDEX)
cpu.is_flushed = true;
} break;
case HiRegisterOperations::OpCode::BX: {
State state = static_cast<State>(op_2 & 1);
// set state
cpu.cpsr.set_state(state);
// copy to PC
cpu.pc = op_2;
// ignore [1:0] bits for arm and 0 bit for thumb
rst_bit(cpu.pc, 0);
if (state == State::Arm)
rst_bit(cpu.pc, 1);
// pc is affected so flush the pipeline
cpu.is_flushed = true;
} break;
}
},
[&cpu](PcRelativeLoad& data) {
uint32_t pc = cpu.pc;
rst_bit(pc, 1);
cpu.gpr[data.rd] = cpu.bus->read_word(pc + data.word);
},
[&cpu](LoadStoreRegisterOffset& data) {
uint32_t address = cpu.gpr[data.rb] + cpu.gpr[data.ro];
if (data.load) {
if (data.byte) {
cpu.gpr[data.rd] = cpu.bus->read_byte(address);
} else {
cpu.gpr[data.rd] = cpu.bus->read_word(address);
}
} else {
if (data.byte) {
cpu.bus->write_byte(address, cpu.gpr[data.rd] & 0xFF);
} else {
cpu.bus->write_word(address, cpu.gpr[data.rd]);
}
}
},
[&cpu](LoadStoreSignExtendedHalfword& data) {
uint32_t address = cpu.gpr[data.rb] + cpu.gpr[data.ro];
switch (data.s << 1 | data.h) {
case 0b00:
cpu.bus->write_halfword(address, cpu.gpr[data.rd] & 0xFFFF);
break;
case 0b01:
cpu.gpr[data.rd] = cpu.bus->read_halfword(address);
break;
case 0b10:
// sign extend and load the byte
cpu.gpr[data.rd] =
(static_cast<int32_t>(cpu.bus->read_byte(address))
<< 24) >>
24;
break;
case 0b11:
// sign extend the halfword
cpu.gpr[data.rd] =
(static_cast<int32_t>(cpu.bus->read_halfword(address))
<< 16) >>
16;
break;
// unreachable
default: {
}
}
},
[&cpu](LoadStoreImmediateOffset& data) {
uint32_t address = cpu.gpr[data.rb] + data.offset;
if (data.load) {
if (data.byte) {
cpu.gpr[data.rd] = cpu.bus->read_byte(address);
} else {
cpu.gpr[data.rd] = cpu.bus->read_word(address);
}
} else {
if (data.byte) {
cpu.bus->write_byte(address, cpu.gpr[data.rd] & 0xFF);
} else {
cpu.bus->write_word(address, cpu.gpr[data.rd]);
}
}
},
[&cpu](LoadStoreHalfword& data) {
uint32_t address = cpu.gpr[data.rb] + data.offset;
if (data.load) {
cpu.gpr[data.rd] = cpu.bus->read_halfword(address);
} else {
cpu.bus->write_halfword(address, cpu.gpr[data.rd] & 0xFFFF);
}
},
[&cpu](SpRelativeLoad& data) {
uint32_t address = cpu.sp + data.word;
if (data.load) {
cpu.gpr[data.rd] = cpu.bus->read_word(address);
} else {
cpu.bus->write_word(address, cpu.gpr[data.rd]);
}
},
[&cpu](LoadAddress& data) {
if (data.sp) {
cpu.gpr[data.rd] = cpu.sp + data.word;
} else {
// PC is already current + 4, so dont need to do that
// force bit 1 to 0
cpu.gpr[data.rd] = (cpu.pc & ~(1 << 1)) + data.word;
}
},
[&cpu](AddOffsetStackPointer& data) { cpu.sp += data.word; },
[&cpu](PushPopRegister& data) {
if (data.load) {
for (uint8_t i = 0; i < 8; i++) {
if (get_bit(data.regs, i)) {
cpu.gpr[i] = cpu.bus->read_word(cpu.sp);
cpu.sp += 4;
}
}
if (data.pclr) {
cpu.pc = cpu.bus->read_word(cpu.sp);
cpu.sp += 4;
cpu.is_flushed = true;
}
} else {
if (data.pclr) {
cpu.sp -= 4;
cpu.bus->write_word(cpu.sp, cpu.lr);
}
for (int8_t i = 7; i >= 0; i--) {
if (get_bit(data.regs, i)) {
cpu.sp -= 4;
cpu.bus->write_word(cpu.sp, cpu.gpr[i]);
}
}
}
},
[&cpu](MultipleLoad& data) {
uint32_t rb = cpu.gpr[data.rb];
if (data.load) {
for (uint8_t i = 0; i < 8; i++) {
if (get_bit(data.regs, i)) {
cpu.gpr[i] = cpu.bus->read_word(rb);
rb += 4;
}
}
} else {
for (int8_t i = 7; i >= 0; i--) {
if (get_bit(data.regs, i)) {
rb -= 4;
cpu.bus->write_word(rb, cpu.gpr[i]);
}
}
}
cpu.gpr[data.rb] = rb;
},
[&cpu](ConditionalBranch& data) {
if (data.condition == Condition::AL)
glogger.warn("Condition 1110 (AL) is undefined");
if (!cpu.cpsr.condition(data.condition))
return;
cpu.pc += data.offset;
cpu.is_flushed = true;
},
[&cpu](SoftwareInterrupt& data) {
// next instruction is one instruction behind PC
cpu.lr = cpu.pc - INSTRUCTION_SIZE;
cpu.spsr = cpu.cpsr;
cpu.pc = data.vector;
cpu.cpsr.set_state(State::Arm);
cpu.chg_mode(Mode::Supervisor);
cpu.is_flushed = true;
},
[&cpu](UnconditionalBranch& data) {
cpu.pc += data.offset;
cpu.is_flushed = true;
},
[&cpu](LongBranchWithLink& data) {
// 12 bit integer
int32_t offset = data.offset;
if (data.high) {
uint32_t old_pc = cpu.pc;
cpu.pc = cpu.lr + offset;
cpu.lr = (old_pc - INSTRUCTION_SIZE) | 1;
cpu.is_flushed = true;
} else {
// 12 + 11 = 23 bit
offset <<= 11;
// sign extend
offset = (offset << 9) >> 9;
cpu.lr = cpu.pc + offset;
}
},
[](auto& data) {
glogger.error("Unknown thumb format : {}", typeid(data).name());
} },
data);
}
}

View File

@@ -0,0 +1,213 @@
#include "instruction.hh"
#include "util/bits.hh"
#include "util/log.hh"
namespace matar::thumb {
Instruction::Instruction(uint16_t insn) {
// Format 2: Add/Subtract
if ((insn & 0xF800) == 0x1800) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rs = bit_range(insn, 3, 5);
uint8_t offset = bit_range(insn, 6, 8);
AddSubtract::OpCode opcode =
static_cast<AddSubtract::OpCode>(get_bit(insn, 9));
bool imm = get_bit(insn, 10);
data = AddSubtract{
.rd = rd, .rs = rs, .offset = offset, .opcode = opcode, .imm = imm
};
// Format 1: Move Shifted Register
} else if ((insn & 0xE000) == 0x0000) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rs = bit_range(insn, 3, 5);
uint8_t offset = bit_range(insn, 6, 10);
ShiftType opcode = static_cast<ShiftType>(bit_range(insn, 11, 12));
data = MoveShiftedRegister{
.rd = rd, .rs = rs, .offset = offset, .opcode = opcode
};
// Format 3: Move/compare/add/subtract immediate
} else if ((insn & 0xE000) == 0x2000) {
uint8_t offset = bit_range(insn, 0, 7);
uint8_t rd = bit_range(insn, 8, 10);
MovCmpAddSubImmediate::OpCode opcode =
static_cast<MovCmpAddSubImmediate::OpCode>(bit_range(insn, 11, 12));
data =
MovCmpAddSubImmediate{ .offset = offset, .rd = rd, .opcode = opcode };
// Format 4: ALU operations
} else if ((insn & 0xFC00) == 0x4000) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rs = bit_range(insn, 3, 5);
AluOperations::OpCode opcode =
static_cast<AluOperations::OpCode>(bit_range(insn, 6, 9));
data = AluOperations{ .rd = rd, .rs = rs, .opcode = opcode };
// Format 5: Hi register operations/branch exchange
} else if ((insn & 0xFC00) == 0x4400) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rs = bit_range(insn, 3, 5);
bool hi_2 = get_bit(insn, 6);
bool hi_1 = get_bit(insn, 7);
HiRegisterOperations::OpCode opcode =
static_cast<HiRegisterOperations::OpCode>(bit_range(insn, 8, 9));
if (opcode == HiRegisterOperations::OpCode::BX && hi_1)
glogger.warn("H1 set with BX");
rd += (hi_1 ? LO_GPR_COUNT : 0);
rs += (hi_2 ? LO_GPR_COUNT : 0);
data = HiRegisterOperations{ .rd = rd, .rs = rs, .opcode = opcode };
// Format 6: PC-relative load
} else if ((insn & 0xF800) == 0x4800) {
uint16_t word = bit_range(insn, 0, 7);
uint8_t rd = bit_range(insn, 8, 10);
data =
PcRelativeLoad{ .word = static_cast<uint16_t>(word << 2), .rd = rd };
// Format 7: Load/store with register offset
} else if ((insn & 0xF200) == 0x5000) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rb = bit_range(insn, 3, 5);
uint8_t ro = bit_range(insn, 6, 8);
bool byte = get_bit(insn, 10);
bool load = get_bit(insn, 11);
data = LoadStoreRegisterOffset{
.rd = rd, .rb = rb, .ro = ro, .byte = byte, .load = load
};
// Format 8: Load/store sign-extended byte/halfword
} else if ((insn & 0xF200) == 0x5200) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rb = bit_range(insn, 3, 5);
uint8_t ro = bit_range(insn, 6, 8);
bool s = get_bit(insn, 10);
bool h = get_bit(insn, 11);
data = LoadStoreSignExtendedHalfword{
.rd = rd, .rb = rb, .ro = ro, .s = s, .h = h
};
// Format 9: Load/store with immediate offset
} else if ((insn & 0xE000) == 0x6000) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rb = bit_range(insn, 3, 5);
uint8_t offset = bit_range(insn, 6, 10);
bool load = get_bit(insn, 11);
bool byte = get_bit(insn, 12);
if (!byte)
offset <<= 2;
data = LoadStoreImmediateOffset{
.rd = rd, .rb = rb, .offset = offset, .load = load, .byte = byte
};
// Format 10: Load/store halfword
} else if ((insn & 0xF000) == 0x8000) {
uint8_t rd = bit_range(insn, 0, 2);
uint8_t rb = bit_range(insn, 3, 5);
uint8_t offset = bit_range(insn, 6, 10);
bool load = get_bit(insn, 11);
offset <<= 1;
data = LoadStoreHalfword{
.rd = rd, .rb = rb, .offset = offset, .load = load
};
// Format 11: SP-relative load/store
} else if ((insn & 0xF000) == 0x9000) {
uint16_t word = bit_range(insn, 0, 7);
uint8_t rd = bit_range(insn, 8, 10);
bool load = get_bit(insn, 11);
word <<= 2;
data = SpRelativeLoad{ .word = word, .rd = rd, .load = load };
// Format 12: Load address
} else if ((insn & 0xF000) == 0xA000) {
uint16_t word = bit_range(insn, 0, 7);
uint8_t rd = bit_range(insn, 8, 10);
bool sp = get_bit(insn, 11);
word <<= 2;
data = LoadAddress{ .word = word, .rd = rd, .sp = sp };
// Format 13: Add offset to stack pointer
} else if ((insn & 0xFF00) == 0xB000) {
int16_t word = static_cast<int16_t>(bit_range(insn, 0, 6));
bool sign = get_bit(insn, 7);
word <<= 2;
word = static_cast<int16_t>(word * (sign ? -1 : 1));
data = AddOffsetStackPointer{
.word = word,
};
// Format 14: Push/pop registers
} else if ((insn & 0xF600) == 0xB400) {
uint8_t regs = bit_range(insn, 0, 7);
bool pclr = get_bit(insn, 8);
bool load = get_bit(insn, 11);
data = PushPopRegister{ .regs = regs, .pclr = pclr, .load = load };
// Format 15: Multiple load/store
} else if ((insn & 0xF000) == 0xC000) {
uint8_t regs = bit_range(insn, 0, 7);
uint8_t rb = bit_range(insn, 8, 10);
bool load = get_bit(insn, 11);
data = MultipleLoad{ .regs = regs, .rb = rb, .load = load };
// Format 17: Software interrupt
} else if ((insn & 0xFF00) == 0xDF00) {
uint8_t vector = bit_range(insn, 0, 7);
data = SoftwareInterrupt{ .vector = vector };
// Format 16: Conditional branch
} else if ((insn & 0xF000) == 0xD000) {
int32_t offset = bit_range(insn, 0, 7);
Condition condition = static_cast<Condition>(bit_range(insn, 8, 11));
offset <<= 1;
// sign extend the 9 bit integer
offset = (offset << 23) >> 23;
data = ConditionalBranch{ .offset = offset, .condition = condition };
// Format 18: Unconditional branch
} else if ((insn & 0xF800) == 0xE000) {
int32_t offset = bit_range(insn, 0, 10);
offset <<= 1;
// sign extend the 12 bit integer
offset = (offset << 20) >> 20;
data = UnconditionalBranch{ .offset = offset };
// Format 19: Long branch with link
} else if ((insn & 0xF000) == 0xF000) {
uint16_t offset = bit_range(insn, 0, 10);
bool high = get_bit(insn, 11);
offset <<= 1;
data = LongBranchWithLink{ .offset = offset, .high = high };
}
}
}

View File

@@ -0,0 +1,291 @@
#pragma once
#include "cpu/alu.hh"
#include "cpu/psr.hh"
#include <cstdint>
#include <fmt/ostream.h>
#include <variant>
namespace matar {
class CpuImpl;
namespace thumb {
// https://en.cppreference.com/w/cpp/utility/variant/visit
template<class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
static constexpr size_t INSTRUCTION_SIZE = 2;
static constexpr uint8_t LO_GPR_COUNT = 8;
struct MoveShiftedRegister {
uint8_t rd;
uint8_t rs;
uint8_t offset;
ShiftType opcode;
};
struct AddSubtract {
enum class OpCode {
ADD = 0,
SUB = 1
};
uint8_t rd;
uint8_t rs;
uint8_t offset;
OpCode opcode;
bool imm;
};
constexpr auto
stringify(AddSubtract::OpCode opcode) {
#define CASE(opcode) \
case AddSubtract::OpCode::opcode: \
return #opcode;
switch (opcode) {
CASE(ADD)
CASE(SUB)
}
#undef CASE
return "";
}
struct MovCmpAddSubImmediate {
enum class OpCode {
MOV = 0b00,
CMP = 0b01,
ADD = 0b10,
SUB = 0b11
};
uint8_t offset;
uint8_t rd;
OpCode opcode;
};
constexpr auto
stringify(MovCmpAddSubImmediate::OpCode opcode) {
#define CASE(opcode) \
case MovCmpAddSubImmediate::OpCode::opcode: \
return #opcode;
switch (opcode) {
CASE(MOV)
CASE(CMP)
CASE(ADD)
CASE(SUB)
}
#undef CASE
return "";
}
struct AluOperations {
enum class OpCode {
AND = 0b0000,
EOR = 0b0001,
LSL = 0b0010,
LSR = 0b0011,
ASR = 0b0100,
ADC = 0b0101,
SBC = 0b0110,
ROR = 0b0111,
TST = 0b1000,
NEG = 0b1001,
CMP = 0b1010,
CMN = 0b1011,
ORR = 0b1100,
MUL = 0b1101,
BIC = 0b1110,
MVN = 0b1111
};
uint8_t rd;
uint8_t rs;
OpCode opcode;
};
constexpr auto
stringify(AluOperations::OpCode opcode) {
#define CASE(opcode) \
case AluOperations::OpCode::opcode: \
return #opcode;
switch (opcode) {
CASE(AND)
CASE(EOR)
CASE(LSL)
CASE(LSR)
CASE(ASR)
CASE(ADC)
CASE(SBC)
CASE(ROR)
CASE(TST)
CASE(NEG)
CASE(CMP)
CASE(CMN)
CASE(ORR)
CASE(MUL)
CASE(BIC)
CASE(MVN)
}
#undef CASE
return "";
}
struct HiRegisterOperations {
enum class OpCode {
ADD = 0b00,
CMP = 0b01,
MOV = 0b10,
BX = 0b11
};
uint8_t rd;
uint8_t rs;
OpCode opcode;
};
constexpr auto
stringify(HiRegisterOperations::OpCode opcode) {
#define CASE(opcode) \
case HiRegisterOperations::OpCode::opcode: \
return #opcode;
switch (opcode) {
CASE(ADD)
CASE(CMP)
CASE(MOV)
CASE(BX)
}
#undef CASE
return "";
}
struct PcRelativeLoad {
uint16_t word;
uint8_t rd;
};
struct LoadStoreRegisterOffset {
uint8_t rd;
uint8_t rb;
uint8_t ro;
bool byte;
bool load;
};
struct LoadStoreSignExtendedHalfword {
uint8_t rd;
uint8_t rb;
uint8_t ro;
bool s;
bool h;
};
struct LoadStoreImmediateOffset {
uint8_t rd;
uint8_t rb;
uint8_t offset;
bool load;
bool byte;
};
struct LoadStoreHalfword {
uint8_t rd;
uint8_t rb;
uint8_t offset;
bool load;
};
struct SpRelativeLoad {
uint16_t word;
uint8_t rd;
bool load;
};
struct LoadAddress {
uint16_t word;
uint8_t rd;
bool sp;
};
struct AddOffsetStackPointer {
int16_t word;
};
struct PushPopRegister {
uint8_t regs;
bool pclr;
bool load;
};
struct MultipleLoad {
uint8_t regs;
uint8_t rb;
bool load;
};
struct ConditionalBranch {
int32_t offset;
Condition condition;
};
struct SoftwareInterrupt {
uint8_t vector;
};
struct UnconditionalBranch {
int32_t offset;
};
struct LongBranchWithLink {
uint16_t offset;
bool high;
};
using InstructionData = std::variant<MoveShiftedRegister,
AddSubtract,
MovCmpAddSubImmediate,
AluOperations,
HiRegisterOperations,
PcRelativeLoad,
LoadStoreRegisterOffset,
LoadStoreSignExtendedHalfword,
LoadStoreImmediateOffset,
LoadStoreHalfword,
SpRelativeLoad,
LoadAddress,
AddOffsetStackPointer,
PushPopRegister,
MultipleLoad,
ConditionalBranch,
SoftwareInterrupt,
UnconditionalBranch,
LongBranchWithLink>;
struct Instruction {
Instruction(uint16_t insn);
Instruction(InstructionData data)
: data(data) {}
void exec(CpuImpl& cpu);
#ifdef DISASSEMBLER
std::string disassemble(uint32_t pc = 0);
#endif
InstructionData data;
};
}
}

View File

@@ -0,0 +1,8 @@
lib_sources += files(
'instruction.cc',
'exec.cc'
)
if get_option('disassembler')
lib_sources += files('disassembler.cc')
endif

View File

@@ -1,13 +1,11 @@
#include "memory.hh"
#include "header.hh"
#include "util/bits.hh"
#include "util/crypto.hh"
#include "util/log.hh"
#include "util/utils.hh"
#include <bitset>
#include <stdexcept>
using namespace logger;
namespace matar {
Memory::Memory(std::array<uint8_t, BIOS_SIZE>&& bios,
std::vector<uint8_t>&& rom)
@@ -23,17 +21,17 @@ Memory::Memory(std::array<uint8_t, BIOS_SIZE>&& bios,
"fd2547724b505f487e6dcb29ec2ecff3af35a841a77ab2e85fd87350abd36570";
if (bios_hash != expected_hash) {
log_warn("BIOS hash failed to match, run at your own risk"
"\nExpected : {} "
"\nGot : {}",
expected_hash,
bios_hash);
glogger.warn("BIOS hash failed to match, run at your own risk"
"\nExpected : {} "
"\nGot : {}",
expected_hash,
bios_hash);
}
parse_header();
log_info("Memory successfully initialised");
log_info("Cartridge Title: {}", header.title);
glogger.info("Memory successfully initialised");
glogger.info("Cartridge Title: {}", header.title);
};
#define MATCHES(area) address >= area##_START&& address <= area##_END
@@ -59,7 +57,7 @@ Memory::read(size_t address) const {
} else if (MATCHES(ROM_2)) {
return rom[address - ROM_2_START];
} else {
log_error("Invalid memory region accessed");
glogger.error("Invalid memory region accessed");
return 0xFF;
}
}
@@ -85,49 +83,12 @@ Memory::write(size_t address, uint8_t byte) {
} else if (MATCHES(ROM_2)) {
rom[address - ROM_2_START] = byte;
} else {
log_error("Invalid memory region accessed");
glogger.error("Invalid memory region accessed");
}
}
#undef MATCHES
uint16_t
Memory::read_halfword(size_t address) const {
if (address & 0b01)
log_warn("Reading a non aligned halfword address");
return read(address) | read(address + 1) << 8;
}
void
Memory::write_halfword(size_t address, uint16_t halfword) {
if (address & 0b01)
log_warn("Writing to a non aligned halfword address");
write(address, halfword & 0xFF);
write(address + 1, halfword >> 8 & 0xFF);
}
uint32_t
Memory::read_word(size_t address) const {
if (address & 0b11)
log_warn("Reading a non aligned word address");
return read(address) | read(address + 1) << 8 | read(address + 2) << 16 |
read(address + 3) << 24;
}
void
Memory::write_word(size_t address, uint32_t word) {
if (address & 0b11)
log_warn("Writing to a non aligned word address");
write(address, word & 0xFF);
write(address + 1, word >> 8 & 0xFF);
write(address + 2, word >> 16 & 0xFF);
write(address + 3, word >> 24 & 0xFF);
}
void
Memory::parse_header() {
@@ -142,7 +103,7 @@ Memory::parse_header() {
// nintendo logo
if (rom[0x9C] != 0x21)
log_info("HEADER: BIOS debugger bits not set to 0");
glogger.info("HEADER: BIOS debugger bits not set to 0");
// game info
header.title = std::string(&rom[0xA0], &rom[0xA0 + 12]);
@@ -177,7 +138,7 @@ Memory::parse_header() {
break;
default:
log_error("HEADER: invalid unique code: {}", rom[0xAC]);
glogger.error("HEADER: invalid unique code: {}", rom[0xAC]);
}
header.title_code = std::string(&rom[0xAD], &rom[0xAE]);
@@ -206,15 +167,16 @@ Memory::parse_header() {
break;
default:
log_error("HEADER: invalid destination/language: {}", rom[0xAF]);
glogger.error("HEADER: invalid destination/language: {}",
rom[0xAF]);
}
if (rom[0xB2] != 0x96)
log_error("HEADER: invalid fixed byte at 0xB2");
glogger.error("HEADER: invalid fixed byte at 0xB2");
for (size_t i = 0xB5; i < 0xBC; i++) {
if (rom[i] != 0x00)
log_error("HEADER: invalid fixed bytes at 0xB5");
glogger.error("HEADER: invalid fixed bytes at 0xB5");
}
header.version = rom[0xBC];
@@ -228,7 +190,7 @@ Memory::parse_header() {
chk &= 0xFF;
if (chk != rom[0xBD])
log_error("HEADER: checksum does not match");
glogger.error("HEADER: checksum does not match");
}
// multiboot not required right now

View File

@@ -3,15 +3,19 @@ lib_sources = files(
'bus.cc'
)
subdir('util')
subdir('cpu')
lib_cpp_args = [ ]
lib_cpp_args = []
fmt = dependency('fmt', version : '>=10.1.0', static: true)
if not fmt.found()
fmt = dependency('fmt', version : '>=10.1.0', static: false)
lib_cpp_args += 'DFMT_HEADER_ONLY'
lib_cpp_args += '-DFMT_HEADER_ONLY'
endif
if get_option('disassembler')
lib_cpp_args += '-DDISASSEMBLER'
endif
lib = library(

View File

@@ -14,19 +14,19 @@ get_bit(Int num, size_t n) {
template<std::integral Int>
inline void
set_bit(Int& num, size_t n) {
num |= (1 << n);
num |= (static_cast<Int>(1) << n);
}
template<std::integral Int>
inline void
rst_bit(Int& num, size_t n) {
num &= ~(1 << n);
num &= ~(static_cast<Int>(1) << n);
}
template<std::integral Int>
inline void
chg_bit(Int& num, size_t n, bool x) {
num = (num & ~(1 << n)) | (x << n);
num = (num & ~(static_cast<Int>(1) << n)) | (static_cast<Int>(x) << n);
}
/// read range of bits from start to end inclusive
@@ -36,5 +36,5 @@ bit_range(Int num, size_t start, size_t end) {
// NOTE: we do not require -1 if it is a signed integral
Int left =
std::numeric_limits<Int>::digits - (std::is_unsigned<Int>::value) - end;
return num << left >> (left + start);
return static_cast<Int>(num << left) >> (left + start);
}

8
src/util/log.cc Normal file
View File

@@ -0,0 +1,8 @@
#include "log.hh"
logging::Logger glogger = logging::Logger();
void
matar::set_log_level(LogLevel level) {
glogger.set_level(level);
}

View File

@@ -1,58 +1,83 @@
#pragma once
#include "util/loglevel.hh"
#include <fmt/ostream.h>
#include <iostream>
using fmt::print;
using std::clog;
namespace logger {
namespace logging {
namespace ansi {
static constexpr std::string_view RED = "\033[31m";
static constexpr std::string_view YELLOW = "\033[33m";
static constexpr std::string_view MAGENTA = "\033[35m";
static constexpr std::string_view WHITE = "\033[37m";
static constexpr std::string_view BOLD = "\033[1m";
static constexpr std::string_view RESET = "\033[0m";
static constexpr auto RED = "\033[31m";
static constexpr auto YELLOW = "\033[33m";
static constexpr auto MAGENTA = "\033[35m";
static constexpr auto WHITE = "\033[37m";
static constexpr auto BOLD = "\033[1m";
static constexpr auto RESET = "\033[0m";
}
template<typename... Args>
inline void
log_raw(const fmt::format_string<Args...>& fmt, Args&&... args) {
fmt::println(clog, fmt, std::forward<Args>(args)...);
using fmt::print;
class Logger {
using LogLevel = matar::LogLevel;
public:
Logger(LogLevel level = LogLevel::Debug, FILE* stream = stderr)
: level(0)
, stream(stream) {
set_level(level);
}
template<typename... Args>
void log(const fmt::format_string<Args...>& fmt, Args&&... args) {
fmt::println(stream, fmt, std::forward<Args>(args)...);
}
template<typename... Args>
void debug(const fmt::format_string<Args...>& fmt, Args&&... args) {
if (level & static_cast<uint8_t>(LogLevel::Debug)) {
print(stream, "{}{}[DEBUG] ", ansi::MAGENTA, ansi::BOLD);
log(fmt, std::forward<Args>(args)...);
print(stream, ansi::RESET);
}
}
template<typename... Args>
void info(const fmt::format_string<Args...>& fmt, Args&&... args) {
if (level & static_cast<uint8_t>(LogLevel::Info)) {
print(stream, "{}[INFO] ", ansi::WHITE);
log(fmt, std::forward<Args>(args)...);
print(stream, ansi::RESET);
}
}
template<typename... Args>
void warn(const fmt::format_string<Args...>& fmt, Args&&... args) {
if (level & static_cast<uint8_t>(LogLevel::Warn)) {
print(stream, "{}[WARN] ", ansi::YELLOW);
log(fmt, std::forward<Args>(args)...);
print(stream, ansi::RESET);
}
}
template<typename... Args>
void error(const fmt::format_string<Args...>& fmt, Args&&... args) {
if (level & static_cast<uint8_t>(LogLevel::Error)) {
print(stream, "{}{}[ERROR] ", ansi::RED, ansi::BOLD);
log(fmt, std::forward<Args>(args)...);
print(stream, ansi::RESET);
}
}
void set_level(LogLevel level) {
this->level = (static_cast<uint8_t>(level) << 1) - 1;
}
void set_stream(FILE* stream) { this->stream = stream; }
private:
uint8_t level;
FILE* stream;
};
}
template<typename... Args>
inline void
log_debug(const fmt::format_string<Args...>& fmt, Args&&... args) {
print(clog, "{}{}[DEBUG] ", ansi::MAGENTA, ansi::BOLD);
log_raw(fmt, std::forward<Args>(args)...);
print(clog, ansi::RESET);
}
extern logging::Logger glogger;
template<typename... Args>
inline void
log_info(const fmt::format_string<Args...>& fmt, Args&&... args) {
print(clog, "{}[INFO] ", ansi::WHITE);
log_raw(fmt, std::forward<Args>(args)...);
print(clog, ansi::RESET);
}
template<typename... Args>
inline void
log_warn(const fmt::format_string<Args...>& fmt, Args&&... args) {
print(clog, "{}[WARN] ", ansi::YELLOW);
log_raw(fmt, std::forward<Args>(args)...);
print(clog, ansi::RESET);
}
template<typename... Args>
inline void
log_error(const fmt::format_string<Args...>& fmt, Args&&... args) {
print(clog, "{}{}[ERROR] ", ansi::RED, ansi::BOLD);
log_raw(fmt, std::forward<Args>(args)...);
print(clog, ansi::RESET);
}
}
#define debug(value) logger::log_debug("{} = {}", #value, value)
#define dbg(x) glogger.debug("{} = {}", #x, x);

3
src/util/meson.build Normal file
View File

@@ -0,0 +1,3 @@
lib_sources += files(
'log.cc'
)

45
tests/bus.cc Normal file
View File

@@ -0,0 +1,45 @@
#include "bus.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "[bus]"
using namespace matar;
class BusFixture {
public:
BusFixture()
: bus(Memory(std::array<uint8_t, Memory::BIOS_SIZE>(),
std::vector<uint8_t>(Header::HEADER_SIZE))) {}
protected:
Bus bus;
};
TEST_CASE_METHOD(BusFixture, "Byte", TAG) {
CHECK(bus.read_byte(3349) == 0);
bus.write_byte(3349, 0xEC);
CHECK(bus.read_byte(3349) == 0xEC);
CHECK(bus.read_word(3349) == 0xEC);
CHECK(bus.read_halfword(3349) == 0xEC);
}
TEST_CASE_METHOD(BusFixture, "Halfword", TAG) {
CHECK(bus.read_halfword(33750745) == 0);
bus.write_halfword(33750745, 0x1A4A);
CHECK(bus.read_halfword(33750745) == 0x1A4A);
CHECK(bus.read_word(33750745) == 0x1A4A);
CHECK(bus.read_byte(33750745) == 0x4A);
}
TEST_CASE_METHOD(BusFixture, "Word", TAG) {
CHECK(bus.read_word(100724276) == 0);
bus.write_word(100724276, 0x3ACC491D);
CHECK(bus.read_word(100724276) == 0x3ACC491D);
CHECK(bus.read_halfword(100724276) == 0x491D);
CHECK(bus.read_byte(100724276) == 0x1D);
}
#undef TAG

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
#include "cpu/arm/instruction.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "disassembler"
#define TAG "[arm][disassembly]"
using namespace matar;
using namespace arm;
@@ -16,7 +16,9 @@ TEST_CASE("Branch and Exchange", TAG) {
CHECK(bx->rn == 10);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "BXGT R10");
#endif
}
TEST_CASE("Branch", TAG) {
@@ -33,10 +35,12 @@ TEST_CASE("Branch", TAG) {
CHECK(b->offset == 0xFE15FF14);
CHECK(b->link == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "BL 0xFE15FF14");
b->link = false;
CHECK(instruction.disassemble() == "B 0xFE15FF14");
#endif
}
TEST_CASE("Multiply", TAG) {
@@ -54,11 +58,13 @@ TEST_CASE("Multiply", TAG) {
CHECK(mul->acc == true);
CHECK(mul->set == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MLAEQS R10,R0,R15,R14");
mul->acc = false;
mul->set = false;
CHECK(instruction.disassemble() == "MULEQ R10,R0,R15");
#endif
}
TEST_CASE("Multiply Long", TAG) {
@@ -77,6 +83,7 @@ TEST_CASE("Multiply Long", TAG) {
CHECK(mull->set == true);
CHECK(mull->uns == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "UMULLNES R7,R14,R2,R6");
mull->acc = true;
@@ -85,6 +92,7 @@ TEST_CASE("Multiply Long", TAG) {
mull->uns = false;
mull->set = false;
CHECK(instruction.disassemble() == "SMLALNE R7,R14,R2,R6");
#endif
}
TEST_CASE("Undefined", TAG) {
@@ -94,7 +102,10 @@ TEST_CASE("Undefined", TAG) {
Instruction instruction(raw);
CHECK(instruction.condition == Condition::AL);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "UND");
#endif
}
TEST_CASE("Single Data Swap", TAG) {
@@ -110,10 +121,12 @@ TEST_CASE("Single Data Swap", TAG) {
CHECK(swp->rn == 9);
CHECK(swp->byte == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "SWPGE R5,R6,[R9]");
swp->byte = true;
CHECK(instruction.disassemble() == "SWPGEB R5,R6,[R9]");
#endif
}
TEST_CASE("Single Data Transfer", TAG) {
@@ -138,6 +151,7 @@ TEST_CASE("Single Data Transfer", TAG) {
CHECK(ldr->up == true);
CHECK(ldr->pre == true);
#ifdef DISASSEMBLER
ldr->load = true;
ldr->byte = true;
ldr->write = false;
@@ -153,6 +167,7 @@ TEST_CASE("Single Data Transfer", TAG) {
ldr->pre = true;
CHECK(instruction.disassemble() == "LDRB R10,[R2,-#9023]");
#endif
}
TEST_CASE("Halfword Transfer", TAG) {
@@ -176,6 +191,7 @@ TEST_CASE("Halfword Transfer", TAG) {
CHECK(ldr->up == true);
CHECK(ldr->pre == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STRCCH R2,[R15,+R6]!");
ldr->pre = false;
@@ -193,6 +209,7 @@ TEST_CASE("Halfword Transfer", TAG) {
ldr->imm = 1;
ldr->offset = 90;
CHECK(instruction.disassemble() == "STRCCSB R2,[R15],-#90");
#endif
}
TEST_CASE("Block Data Transfer", TAG) {
@@ -223,6 +240,7 @@ TEST_CASE("Block Data Transfer", TAG) {
CHECK(ldm->up == false);
CHECK(ldm->pre == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "LDMLSDB R7,{R0,R2,R3,R5,R6,R8,R14}^");
ldm->write = true;
@@ -238,6 +256,7 @@ TEST_CASE("Block Data Transfer", TAG) {
ldm->pre = false;
CHECK(instruction.disassemble() == "STMLSIA R7!,{R0,R2,R5,R14}");
#endif
}
TEST_CASE("PSR Transfer", TAG) {
@@ -256,7 +275,9 @@ TEST_CASE("PSR Transfer", TAG) {
CHECK(mrs->operand == 10);
CHECK(mrs->spsr == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MRSMI R10,SPSR_all");
#endif
}
SECTION("MSR") {
@@ -272,7 +293,9 @@ TEST_CASE("PSR Transfer", TAG) {
CHECK(msr->operand == 8);
CHECK(msr->spsr == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MSR CPSR_all,R8");
#endif
}
SECTION("MSR_flg with register operand") {
@@ -287,7 +310,9 @@ TEST_CASE("PSR Transfer", TAG) {
CHECK(msr->operand == 8);
CHECK(msr->spsr == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MSRVS CPSR_flg,R8");
#endif
}
SECTION("MSR_flg with immediate operand") {
@@ -304,7 +329,9 @@ TEST_CASE("PSR Transfer", TAG) {
CHECK(msr->operand == 27262976);
CHECK(msr->spsr == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MSR SPSR_flg,#27262976");
#endif
}
}
@@ -331,6 +358,7 @@ TEST_CASE("Data Processing", TAG) {
CHECK(alu->set == true);
CHECK(alu->opcode == OpCode::AND);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "ANDS R7,R14,R1,ROR #22");
shift->data.immediate = false;
@@ -392,6 +420,7 @@ TEST_CASE("Data Processing", TAG) {
alu->opcode = OpCode::MVN;
CHECK(instruction.disassemble() == "MVN R7,#3300012");
}
#endif
}
TEST_CASE("Coprocessor Data Transfer", TAG) {
@@ -412,6 +441,7 @@ TEST_CASE("Coprocessor Data Transfer", TAG) {
CHECK(ldc->up == true);
CHECK(ldc->pre == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STCGE p1,c15,[R5,#70]!");
ldc->load = true;
@@ -420,6 +450,7 @@ TEST_CASE("Coprocessor Data Transfer", TAG) {
ldc->len = true;
CHECK(instruction.disassemble() == "LDCGEL p1,c15,[R5],#70");
#endif
}
TEST_CASE("Coprocessor Operand Operation", TAG) {
@@ -437,7 +468,9 @@ TEST_CASE("Coprocessor Operand Operation", TAG) {
CHECK(cdp->crn == 5);
CHECK(cdp->cp_opc == 10);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "CDP p1,10,c15,c5,c6,2");
#endif
}
TEST_CASE("Coprocessor Register Transfer", TAG) {
@@ -457,7 +490,9 @@ TEST_CASE("Coprocessor Register Transfer", TAG) {
CHECK(mrc->load == false);
CHECK(mrc->cp_opc == 5);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MCR p1,5,R15,c5,c6,2");
#endif
}
TEST_CASE("Software Interrupt", TAG) {
@@ -465,7 +500,10 @@ TEST_CASE("Software Interrupt", TAG) {
Instruction instruction(raw);
CHECK(instruction.condition == Condition::EQ);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "SWIEQ");
#endif
}
#undef TAG

96
tests/cpu/cpu-fixture.cc Normal file
View File

@@ -0,0 +1,96 @@
#include "cpu-fixture.hh"
Psr
CpuFixture::psr(bool spsr) {
Psr psr(0);
CpuImpl tmp = cpu;
arm::Instruction instruction(
Condition::AL,
arm::PsrTransfer{ .operand = 0,
.spsr = spsr,
.type = arm::PsrTransfer::Type::Mrs,
.imm = false });
instruction.exec(tmp);
psr.set_all(getr_(0, tmp));
return psr;
}
void
CpuFixture::set_psr(Psr psr, bool spsr) {
// R0
uint32_t old = getr(0);
setr(0, psr.raw());
arm::Instruction instruction(
Condition::AL,
arm::PsrTransfer{ .operand = 0,
.spsr = spsr,
.type = arm::PsrTransfer::Type::Msr,
.imm = false });
instruction.exec(cpu);
setr(0, old);
}
// We need these workarounds to just use the public API and not private
// fields. Assuming that these work correctly is necessary. Besides, all that
// matters is that the public API is correct.
uint32_t
CpuFixture::getr_(uint8_t r, CpuImpl& cpu) {
size_t addr = 13000;
size_t offset = r == 15 ? 4 : 0;
uint32_t word = bus.read_word(addr + offset);
CpuImpl tmp = cpu;
uint32_t ret = 0xFFFFFFFF;
uint8_t base = r ? 0 : 1;
// set R0/R1 = 0
arm::Instruction zero(
Condition::AL,
arm::DataProcessing{ .operand = 0u,
.rd = base,
.rn = 0,
.set = false,
.opcode = arm::DataProcessing::OpCode::MOV });
// get register
arm::Instruction get(
Condition::AL,
arm::SingleDataTransfer{ .offset = static_cast<uint16_t>(addr),
.rd = r,
.rn = base,
.load = false,
.write = false,
.byte = false,
.up = true,
.pre = true });
zero.exec(tmp);
get.exec(tmp);
addr += offset;
ret = bus.read_word(addr);
bus.write_word(addr, word);
return ret;
}
void
CpuFixture::setr_(uint8_t r, uint32_t value, CpuImpl& cpu) {
// set register
arm::Instruction set(
Condition::AL,
arm::DataProcessing{ .operand = value,
.rd = r,
.rn = 0,
.set = false,
.opcode = arm::DataProcessing::OpCode::MOV });
set.exec(cpu);
}

42
tests/cpu/cpu-fixture.hh Normal file
View File

@@ -0,0 +1,42 @@
#include "cpu/cpu-impl.hh"
using namespace matar;
class CpuFixture {
public:
CpuFixture()
: bus(Memory(std::array<uint8_t, Memory::BIOS_SIZE>(),
std::vector<uint8_t>(Header::HEADER_SIZE)))
, cpu(bus) {}
protected:
void exec(arm::InstructionData data, Condition condition = Condition::AL) {
arm::Instruction instruction(condition, data);
instruction.exec(cpu);
}
void exec(thumb::InstructionData data) {
thumb::Instruction instruction(data);
instruction.exec(cpu);
}
void reset(uint32_t value = 0) { setr(15, value + 8); }
uint32_t getr(uint8_t r) { return getr_(r, cpu); }
void setr(uint8_t r, uint32_t value) { setr_(r, value, cpu); }
Psr psr(bool spsr = false);
void set_psr(Psr psr, bool spsr = false);
Bus bus;
CpuImpl cpu;
private:
// hack to get a register
uint32_t getr_(uint8_t r, CpuImpl& cpu);
// hack to set a register
void setr_(uint8_t r, uint32_t value, CpuImpl& cpu);
};

View File

@@ -1 +1,6 @@
subdir('arm')
tests_sources += files(
'cpu-fixture.cc'
)
subdir('arm')
subdir('thumb')

990
tests/cpu/thumb/exec.cc Normal file
View File

@@ -0,0 +1,990 @@
#include "cpu/cpu-fixture.hh"
#include "cpu/cpu-impl.hh"
#include "cpu/thumb/instruction.hh"
#include "util/bits.hh"
#include <catch2/catch_test_macros.hpp>
using namespace matar;
#define TAG "[thumb][execution]"
using namespace thumb;
TEST_CASE_METHOD(CpuFixture, "Move Shifted Register", TAG) {
InstructionData data = MoveShiftedRegister{
.rd = 3, .rs = 5, .offset = 15, .opcode = ShiftType::LSL
};
MoveShiftedRegister* move = std::get_if<MoveShiftedRegister>(&data);
SECTION("LSL") {
setr(3, 0);
setr(5, 6687);
// LSL
exec(data);
CHECK(getr(3) == 219119616);
setr(5, 0);
// zero
exec(data);
CHECK(getr(3) == 0);
CHECK(psr().z());
}
SECTION("LSR") {
move->opcode = ShiftType::LSR;
setr(5, -1827489745);
// LSR
exec(data);
CHECK(getr(3) == 75301);
CHECK(!psr().n());
setr(5, 4444);
// zero flag
exec(data);
CHECK(getr(3) == 0);
CHECK(psr().z());
}
SECTION("ASR") {
setr(5, -1827489745);
move->opcode = ShiftType::ASR;
// ASR
exec(data);
CHECK(psr().n());
CHECK(getr(3) == 4294911525);
setr(5, 500);
// zero flag
exec(data);
CHECK(getr(3) == 0);
CHECK(psr().z());
}
}
TEST_CASE_METHOD(CpuFixture, "Add/Subtract", TAG) {
InstructionData data = AddSubtract{ .rd = 5,
.rs = 2,
.offset = 7,
.opcode = AddSubtract::OpCode::ADD,
.imm = false };
AddSubtract* add = std::get_if<AddSubtract>(&data);
setr(2, 378427891);
setr(7, -666666);
SECTION("ADD") {
// register
exec(data);
CHECK(getr(5) == 377761225);
add->imm = true;
setr(2, (1u << 31) - 1);
// immediate and overflow
exec(data);
CHECK(getr(5) == 2147483654);
CHECK(psr().v());
setr(2, -7);
// zero
exec(data);
CHECK(getr(5) == 0);
CHECK(psr().z());
}
add->imm = true;
SECTION("SUB") {
add->opcode = AddSubtract::OpCode::SUB;
setr(2, -((1u << 31) - 1));
add->offset = 4;
exec(data);
CHECK(getr(5) == 2147483645);
CHECK(psr().v());
setr(2, ~0u);
add->offset = -4;
// carry
exec(data);
CHECK(getr(5) == 3);
CHECK(psr().c());
setr(2, 0);
add->offset = 0;
// zero
exec(data);
CHECK(getr(5) == 0);
CHECK(psr().z());
}
}
TEST_CASE_METHOD(CpuFixture, "Move/Compare/Add/Subtract Immediate", TAG) {
InstructionData data = MovCmpAddSubImmediate{
.offset = 251, .rd = 5, .opcode = MovCmpAddSubImmediate::OpCode::MOV
};
MovCmpAddSubImmediate* move = std::get_if<MovCmpAddSubImmediate>(&data);
SECTION("MOV") {
exec(data);
CHECK(getr(5) == 251);
move->offset = 0;
// zero
exec(data);
CHECK(getr(5) == 0);
CHECK(psr().z());
}
SECTION("CMP") {
setr(5, 251);
move->opcode = MovCmpAddSubImmediate::OpCode::CMP;
CHECK(!psr().z());
exec(data);
CHECK(getr(5) == 251);
CHECK(psr().z());
// overflow
setr(5, -((1u << 31) - 1));
CHECK(!psr().v());
exec(data);
CHECK(getr(5) == 2147483649);
CHECK(psr().v());
}
SECTION("ADD") {
move->opcode = MovCmpAddSubImmediate::OpCode::ADD;
setr(5, (1u << 31) - 1);
// immediate and overflow
exec(data);
CHECK(getr(5) == 2147483898);
CHECK(psr().v());
setr(5, -251);
// zero
exec(data);
CHECK(getr(5) == 0);
CHECK(psr().z());
}
SECTION("SUB") {
// same as CMP but loaded
setr(5, 251);
move->opcode = MovCmpAddSubImmediate::OpCode::SUB;
CHECK(!psr().z());
exec(data);
CHECK(getr(5) == 0);
CHECK(psr().z());
// overflow
setr(5, -((1u << 31) - 1));
CHECK(!psr().v());
exec(data);
CHECK(getr(5) == 2147483398);
CHECK(psr().v());
}
}
TEST_CASE_METHOD(CpuFixture, "ALU Operations", TAG) {
InstructionData data =
AluOperations{ .rd = 1, .rs = 3, .opcode = AluOperations::OpCode::AND };
AluOperations* alu = std::get_if<AluOperations>(&data);
setr(1, 328940001);
setr(3, -991);
SECTION("AND") {
// 328940001 & -991
exec(data);
CHECK(getr(1) == 328939553);
CHECK(!psr().n());
setr(3, 0);
CHECK(!psr().z());
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("EOR") {
alu->opcode = AluOperations::OpCode::EOR;
// 328940001 ^ -991
exec(data);
CHECK(getr(1) == 3966027200);
CHECK(psr().n());
setr(3, 3966027200);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
CHECK(!psr().n());
}
SECTION("LSL") {
setr(3, 3);
alu->opcode = AluOperations::OpCode::LSL;
// 328940001 << 3
exec(data);
CHECK(getr(1) == 2631520008);
CHECK(psr().n());
setr(1, 0);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("LSR") {
alu->opcode = AluOperations::OpCode::LSR;
setr(3, 991);
// 328940001 >> 991
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
setr(1, -83885328);
setr(3, 5);
// -83885328 >> 5
exec(data);
CHECK(getr(1) == 131596311);
CHECK(!psr().z());
CHECK(!psr().n());
}
SECTION("ASR") {
alu->opcode = AluOperations::OpCode::ASR;
setr(3, 991);
// 328940001 >> 991
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
setr(1, -83885328);
setr(3, 5);
// -83885328 >> 5
exec(data);
CHECK(getr(1) == 4292345879);
CHECK(!psr().z());
CHECK(psr().n());
}
SECTION("ADC") {
alu->opcode = AluOperations::OpCode::ADC;
setr(3, (1u << 31) - 1);
Psr cpsr = psr();
cpsr.set_c(true);
set_psr(cpsr);
// 2147483647 + 328940001 + 1
exec(data);
CHECK(getr(1) == 2476423649);
CHECK(psr().v());
CHECK(psr().n());
CHECK(!psr().c());
setr(3, -328940001);
setr(1, 328940001);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("SBC") {
alu->opcode = AluOperations::OpCode::SBC;
setr(3, -((1u << 31) - 1));
Psr cpsr = psr();
cpsr.set_c(false);
set_psr(cpsr);
// 328940001 - -2147483647 - 1
exec(data);
CHECK(getr(1) == 2476423647);
CHECK(psr().v());
CHECK(psr().n());
CHECK(!psr().c());
setr(1, -34892);
setr(3, -34893);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("ROR") {
setr(3, 993);
alu->opcode = AluOperations::OpCode::ROR;
// 328940001 ROR 993
exec(data);
CHECK(getr(1) == 2311953648);
CHECK(psr().n());
CHECK(psr().c());
setr(1, 0);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("TST") {
alu->opcode = AluOperations::OpCode::TST;
// 328940001 & -991
exec(data);
// no change
CHECK(getr(1) == 328940001);
setr(3, 0);
CHECK(!psr().z());
// zero
exec(data);
CHECK(getr(1) == 328940001);
CHECK(psr().z());
}
SECTION("NEG") {
alu->opcode = AluOperations::OpCode::NEG;
// -(-991)
exec(data);
CHECK(getr(1) == 991);
setr(3, 0);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("CMP") {
alu->opcode = AluOperations::OpCode::CMP;
setr(3, -((1u << 31) - 1));
// 328940001 - -2147483647
exec(data);
// no change
CHECK(getr(1) == 328940001);
CHECK(psr().v());
CHECK(psr().n());
CHECK(!psr().c());
setr(1, -34892);
setr(3, -34892);
// zero
exec(data);
// no change (-34892)
CHECK(getr(1) == 4294932404);
CHECK(psr().z());
}
SECTION("CMN") {
alu->opcode = AluOperations::OpCode::CMN;
setr(3, (1u << 31) - 1);
// 2147483647 + 328940001
exec(data);
CHECK(getr(1) == 328940001);
CHECK(psr().v());
CHECK(psr().n());
CHECK(!psr().c());
setr(3, -328940001);
setr(1, 328940001);
// zero
exec(data);
CHECK(getr(1) == 328940001);
CHECK(psr().z());
}
SECTION("ORR") {
alu->opcode = AluOperations::OpCode::ORR;
// 328940001 | -991
exec(data);
CHECK(getr(1) == 4294966753);
CHECK(psr().n());
setr(1, 0);
setr(3, 0);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("MUL") {
alu->opcode = AluOperations::OpCode::MUL;
// 328940001 * -991 (lower 32 bits) (-325979540991 & 0xFFFFFFFF)
exec(data);
CHECK(getr(1) == 437973505);
setr(3, 0);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("BIC") {
alu->opcode = AluOperations::OpCode::BIC;
// 328940001 & ~ -991
exec(data);
CHECK(getr(1) == 448);
CHECK(!psr().n());
setr(3, ~0u);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
SECTION("MVN") {
alu->opcode = AluOperations::OpCode::MVN;
//~ -991
exec(data);
CHECK(getr(1) == 990);
CHECK(!psr().n());
setr(3, 24358);
// negative
exec(data);
CHECK(getr(1) == 4294942937);
CHECK(psr().n());
setr(3, ~0u);
// zero
exec(data);
CHECK(getr(1) == 0);
CHECK(psr().z());
}
}
TEST_CASE_METHOD(CpuFixture, "Hi Register Operations/Branch Exchange", TAG) {
InstructionData data = HiRegisterOperations{
.rd = 5, .rs = 15, .opcode = HiRegisterOperations::OpCode::ADD
};
HiRegisterOperations* hi = std::get_if<HiRegisterOperations>(&data);
setr(15, 3452948950);
setr(5, 958656720);
SECTION("ADD") {
exec(data);
CHECK(getr(5) == 116638374);
// hi + hi
hi->rd = 14;
hi->rs = 15;
setr(14, 42589);
exec(data);
CHECK(getr(14) == 3452991539);
}
SECTION("CMP") {
hi->opcode = HiRegisterOperations::OpCode::CMP;
exec(data);
// no change
CHECK(getr(5) == 958656720);
CHECK(!psr().n());
CHECK(!psr().c());
CHECK(!psr().v());
CHECK(!psr().z());
setr(15, 958656720);
// zero
exec(data);
// no change
CHECK(getr(5) == 958656720);
CHECK(psr().z());
}
SECTION("MOV") {
hi->opcode = HiRegisterOperations::OpCode::MOV;
exec(data);
CHECK(getr(5) == 3452948950);
}
SECTION("BX") {
hi->opcode = HiRegisterOperations::OpCode::BX;
hi->rs = 10;
SECTION("Arm") {
setr(10, 2189988);
exec(data);
CHECK(getr(15) == 2189988);
// switched to arm
CHECK(psr().state() == State::Arm);
}
SECTION("Thumb") {
setr(10, 2189989);
exec(data);
CHECK(getr(15) == 2189988);
// switched to thumb
CHECK(psr().state() == State::Thumb);
}
}
}
TEST_CASE_METHOD(CpuFixture, "PC Relative Load", TAG) {
InstructionData data = PcRelativeLoad{ .word = 380, .rd = 0 };
setr(15, 13804);
// 13804 + 380
bus.write_word(14184, 489753492);
CHECK(getr(0) == 0);
exec(data);
CHECK(getr(0) == 489753492);
}
TEST_CASE_METHOD(CpuFixture, "Load/Store with Register Offset", TAG) {
InstructionData data = LoadStoreRegisterOffset{
.rd = 3, .rb = 0, .ro = 7, .byte = false, .load = false
};
LoadStoreRegisterOffset* load = std::get_if<LoadStoreRegisterOffset>(&data);
setr(7, 9910);
setr(0, 1034);
setr(3, 389524259);
SECTION("store") {
// 9910 + 1034
CHECK(bus.read_word(10944) == 0);
exec(data);
CHECK(bus.read_word(10944) == 389524259);
// byte
load->byte = true;
bus.write_word(10944, 0);
exec(data);
CHECK(bus.read_word(10944) == 35);
}
SECTION("load") {
load->load = true;
bus.write_word(10944, 11123489);
exec(data);
CHECK(getr(3) == 11123489);
// byte
load->byte = true;
exec(data);
CHECK(getr(3) == 33);
}
}
TEST_CASE_METHOD(CpuFixture, "Load/Store Sign Extended Byte/Halfword", TAG) {
InstructionData data = LoadStoreSignExtendedHalfword{
.rd = 3, .rb = 0, .ro = 7, .s = false, .h = false
};
LoadStoreSignExtendedHalfword* load =
std::get_if<LoadStoreSignExtendedHalfword>(&data);
setr(7, 9910);
setr(0, 1034);
setr(3, 389524259);
SECTION("SH = 00") {
// 9910 + 1034
CHECK(bus.read_word(10944) == 0);
exec(data);
CHECK(bus.read_word(10944) == 43811);
}
SECTION("SH = 01") {
load->h = true;
bus.write_word(10944, 11123489);
exec(data);
CHECK(getr(3) == 47905);
}
SECTION("SH = 10") {
load->s = true;
bus.write_word(10944, 34521594);
exec(data);
// sign extended 250 byte (0xFA)
CHECK(getr(3) == 4294967290);
}
SECTION("SH = 11") {
load->s = true;
load->h = true;
bus.write_word(10944, 11123489);
// sign extended 47905 halfword (0xBB21)
exec(data);
CHECK(getr(3) == 4294949665);
}
}
TEST_CASE_METHOD(CpuFixture, "Load/Store with Immediate Offset", TAG) {
InstructionData data = LoadStoreImmediateOffset{
.rd = 3, .rb = 0, .offset = 110, .load = false, .byte = false
};
LoadStoreImmediateOffset* load =
std::get_if<LoadStoreImmediateOffset>(&data);
setr(0, 1034);
setr(3, 389524259);
SECTION("store") {
// 110 + 1034
CHECK(bus.read_word(1144) == 0);
exec(data);
CHECK(bus.read_word(1144) == 389524259);
// byte
load->byte = true;
bus.write_word(1144, 0);
exec(data);
CHECK(bus.read_word(1144) == 35);
}
SECTION("load") {
load->load = true;
bus.write_word(1144, 11123489);
exec(data);
CHECK(getr(3) == 11123489);
// byte
load->byte = true;
exec(data);
CHECK(getr(3) == 33);
}
}
TEST_CASE_METHOD(CpuFixture, "Load/Store Halfword", TAG) {
InstructionData data =
LoadStoreHalfword{ .rd = 3, .rb = 0, .offset = 110, .load = false };
LoadStoreHalfword* load = std::get_if<LoadStoreHalfword>(&data);
setr(0, 1034);
setr(3, 389524259);
SECTION("store") {
// 110 + 1034
CHECK(bus.read_word(1144) == 0);
exec(data);
CHECK(bus.read_word(1144) == 43811);
}
SECTION("load") {
load->load = true;
bus.write_word(1144, 11123489);
exec(data);
CHECK(getr(3) == 47905);
}
}
TEST_CASE_METHOD(CpuFixture, "SP Relative Load", TAG) {
InstructionData data =
SpRelativeLoad{ .word = 808, .rd = 1, .load = false };
SpRelativeLoad* load = std::get_if<SpRelativeLoad>(&data);
setr(1, 2349505744);
// sp
setr(13, 336);
SECTION("store") {
// 110 + 1034
CHECK(bus.read_word(1144) == 0);
exec(data);
CHECK(bus.read_word(1144) == 2349505744);
}
SECTION("load") {
load->load = true;
bus.write_word(1144, 11123489);
exec(data);
CHECK(getr(1) == 11123489);
}
}
TEST_CASE_METHOD(CpuFixture, "Load Address", TAG) {
InstructionData data = LoadAddress{ .word = 808, .rd = 1, .sp = false };
LoadAddress* load = std::get_if<LoadAddress>(&data);
// pc
setr(15, 336485);
// sp
setr(13, 69879977);
SECTION("PC") {
exec(data);
CHECK(getr(1) == 337293);
}
SECTION("SP") {
load->sp = true;
exec(data);
CHECK(getr(1) == 69880785);
}
}
TEST_CASE_METHOD(CpuFixture, "Add Offset to Stack Pointer", TAG) {
InstructionData data = AddOffsetStackPointer{ .word = 473 };
AddOffsetStackPointer* add = std::get_if<AddOffsetStackPointer>(&data);
// sp
setr(13, 69879977);
SECTION("positive") {
exec(data);
CHECK(getr(13) == 69880450);
}
SECTION("negative") {
add->word = -473;
exec(data);
CHECK(getr(13) == 69879504);
}
}
TEST_CASE_METHOD(CpuFixture, "Push/Pop Registers", TAG) {
InstructionData data =
PushPopRegister{ .regs = 0b11010011, .pclr = false, .load = false };
PushPopRegister* push = std::get_if<PushPopRegister>(&data);
// registers = 0, 1, 4, 6, 7
SECTION("push (store)") {
// populate registers
setr(0, 237164);
setr(1, 679785111);
setr(4, 905895898);
setr(6, 131313333);
setr(7, 131);
auto checker = [this]() {
// address
CHECK(bus.read_word(5548) == 237164);
CHECK(bus.read_word(5552) == 679785111);
CHECK(bus.read_word(5556) == 905895898);
CHECK(bus.read_word(5560) == 131313333);
CHECK(bus.read_word(5564) == 131);
};
// set stack pointer to top of stack
setr(13, 5568);
SECTION("without LR") {
exec(data);
checker();
CHECK(getr(13) == 5548);
}
SECTION("with LR") {
push->pclr = true;
// populate lr
setr(14, 999304);
// add another word on stack (5568 + 4)
setr(13, 5572);
exec(data);
CHECK(bus.read_word(5568) == 999304);
checker();
CHECK(getr(13) == 5548);
}
}
SECTION("pop (load)") {
push->load = true;
// populate memory
bus.write_word(5548, 237164);
bus.write_word(5552, 679785111);
bus.write_word(5556, 905895898);
bus.write_word(5560, 131313333);
bus.write_word(5564, 131);
auto checker = [this]() {
CHECK(getr(0) == 237164);
CHECK(getr(1) == 679785111);
CHECK(getr(2) == 0);
CHECK(getr(3) == 0);
CHECK(getr(4) == 905895898);
CHECK(getr(5) == 0);
CHECK(getr(6) == 131313333);
CHECK(getr(7) == 131);
for (uint8_t i = 0; i < 8; i++) {
setr(i, 0);
}
};
// set stack pointer to bottom of stack
setr(13, 5548);
SECTION("without SP") {
exec(data);
checker();
CHECK(getr(13) == 5568);
}
SECTION("with SP") {
push->pclr = true;
// populate next address
bus.write_word(5568, 93333912);
exec(data);
CHECK(getr(15) == 93333912);
checker();
CHECK(getr(13) == 5572);
}
}
}
TEST_CASE_METHOD(CpuFixture, "Multiple Load/Store", TAG) {
InstructionData data =
MultipleLoad{ .regs = 0b11010101, .rb = 2, .load = false };
MultipleLoad* push = std::get_if<MultipleLoad>(&data);
// registers = 0, 1, 4, 6, 7
SECTION("push (store)") {
// populate registers
setr(0, 237164);
setr(4, 905895898);
setr(6, 131313333);
setr(7, 131);
// set R2 (base) to top of stack
setr(2, 5568);
exec(data);
CHECK(bus.read_word(5548) == 237164);
CHECK(bus.read_word(5552) == 5568);
CHECK(bus.read_word(5556) == 905895898);
CHECK(bus.read_word(5560) == 131313333);
CHECK(bus.read_word(5564) == 131);
// write back
CHECK(getr(2) == 5548);
}
SECTION("pop (load)") {
push->load = true;
// populate memory
bus.write_word(5548, 237164);
bus.write_word(5552, 679785111);
bus.write_word(5556, 905895898);
bus.write_word(5560, 131313333);
bus.write_word(5564, 131);
// base
setr(2, 5548);
exec(data);
CHECK(getr(0) == 237164);
CHECK(getr(1) == 0);
CHECK(getr(2) == 5568); // write back
CHECK(getr(3) == 0);
CHECK(getr(4) == 905895898);
CHECK(getr(5) == 0);
CHECK(getr(6) == 131313333);
CHECK(getr(7) == 131);
}
}
TEST_CASE_METHOD(CpuFixture, "Conditional Branch", TAG) {
InstructionData data =
ConditionalBranch{ .offset = -192, .condition = Condition::EQ };
ConditionalBranch* branch = std::get_if<ConditionalBranch>(&data);
setr(15, 4589344);
SECTION("z") {
Psr cpsr = psr();
// condition is false
exec(data);
CHECK(getr(15) == 4589344);
cpsr.set_z(true);
set_psr(cpsr);
// condition is true
exec(data);
CHECK(getr(15) == 4589152);
}
SECTION("c") {
branch->condition = Condition::CS;
Psr cpsr = psr();
// condition is false
exec(data);
CHECK(getr(15) == 4589344);
cpsr.set_c(true);
set_psr(cpsr);
// condition is true
exec(data);
CHECK(getr(15) == 4589152);
}
SECTION("n") {
branch->condition = Condition::MI;
Psr cpsr = psr();
// condition is false
exec(data);
CHECK(getr(15) == 4589344);
cpsr.set_n(true);
set_psr(cpsr);
// condition is true
exec(data);
CHECK(getr(15) == 4589152);
}
SECTION("v") {
branch->condition = Condition::VS;
Psr cpsr = psr();
// condition is false
exec(data);
CHECK(getr(15) == 4589344);
cpsr.set_v(true);
set_psr(cpsr);
// condition is true
exec(data);
CHECK(getr(15) == 4589152);
}
}
TEST_CASE_METHOD(CpuFixture, "Software Interrupt", TAG) {
InstructionData data = SoftwareInterrupt{ .vector = 33 };
setr(15, 4492);
exec(data);
CHECK(psr().raw() == psr(true).raw());
CHECK(getr(14) == 4490);
CHECK(getr(15) == 33);
CHECK(psr().state() == State::Arm);
CHECK(psr().mode() == Mode::Supervisor);
}
TEST_CASE_METHOD(CpuFixture, "Unconditional Branch", TAG) {
InstructionData data = UnconditionalBranch{ .offset = -920 };
setr(15, 4589344);
exec(data);
CHECK(getr(15) == 4588424);
}
TEST_CASE_METHOD(CpuFixture, "Long Branch With Link", TAG) {
InstructionData data = LongBranchWithLink{ .offset = 3262, .high = false };
LongBranchWithLink* branch = std::get_if<LongBranchWithLink>(&data);
// high
setr(15, 4589344);
exec(data);
CHECK(getr(14) == 2881312);
// low
branch->high = true;
exec(data);
CHECK(getr(14) == 4589343);
CHECK(getr(15) == 2884574);
}

View File

@@ -0,0 +1,465 @@
#include "cpu/thumb/instruction.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "[thumb][disassembly]"
using namespace matar;
using namespace thumb;
TEST_CASE("Move Shifted Register", TAG) {
uint16_t raw = 0b0001001101100011;
Instruction instruction(raw);
MoveShiftedRegister* lsl = nullptr;
REQUIRE((lsl = std::get_if<MoveShiftedRegister>(&instruction.data)));
CHECK(lsl->rd == 3);
CHECK(lsl->rs == 4);
CHECK(lsl->offset == 13);
CHECK(lsl->opcode == ShiftType::ASR);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "ASR R3,R4,#13");
lsl->opcode = ShiftType::LSR;
CHECK(instruction.disassemble() == "LSR R3,R4,#13");
lsl->opcode = ShiftType::LSL;
CHECK(instruction.disassemble() == "LSL R3,R4,#13");
#endif
}
TEST_CASE("Add/Subtract", TAG) {
uint16_t raw = 0b0001111101001111;
Instruction instruction(raw);
AddSubtract* add = nullptr;
REQUIRE((add = std::get_if<AddSubtract>(&instruction.data)));
CHECK(add->rd == 7);
CHECK(add->rs == 1);
CHECK(add->offset == 5);
CHECK(add->opcode == AddSubtract::OpCode::SUB);
CHECK(add->imm == true);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "SUB R7,R1,#5");
add->imm = false;
CHECK(instruction.disassemble() == "SUB R7,R1,R5");
add->opcode = AddSubtract::OpCode::ADD;
CHECK(instruction.disassemble() == "ADD R7,R1,R5");
#endif
}
TEST_CASE("Move/Compare/Add/Subtract Immediate", TAG) {
uint16_t raw = 0b0010111001011011;
Instruction instruction(raw);
MovCmpAddSubImmediate* mov = nullptr;
REQUIRE((mov = std::get_if<MovCmpAddSubImmediate>(&instruction.data)));
CHECK(mov->offset == 91);
CHECK(mov->rd == 6);
CHECK(mov->opcode == MovCmpAddSubImmediate::OpCode::CMP);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "CMP R6,#91");
mov->opcode = MovCmpAddSubImmediate::OpCode::ADD;
CHECK(instruction.disassemble() == "ADD R6,#91");
mov->opcode = MovCmpAddSubImmediate::OpCode::SUB;
CHECK(instruction.disassemble() == "SUB R6,#91");
mov->opcode = MovCmpAddSubImmediate::OpCode::MOV;
CHECK(instruction.disassemble() == "MOV R6,#91");
#endif
}
TEST_CASE("ALU Operations", TAG) {
uint16_t raw = 0b0100000110011111;
Instruction instruction(raw);
AluOperations* alu = nullptr;
REQUIRE((alu = std::get_if<AluOperations>(&instruction.data)));
CHECK(alu->rd == 7);
CHECK(alu->rs == 3);
CHECK(alu->opcode == AluOperations::OpCode::SBC);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "SBC R7,R3");
#define OPCODE(op) \
alu->opcode = AluOperations::OpCode::op; \
CHECK(instruction.disassemble() == #op " R7,R3");
OPCODE(AND)
OPCODE(EOR)
OPCODE(LSL)
OPCODE(LSR)
OPCODE(ASR)
OPCODE(ADC)
OPCODE(SBC)
OPCODE(ROR)
OPCODE(TST)
OPCODE(NEG)
OPCODE(CMP)
OPCODE(CMN)
OPCODE(ORR)
OPCODE(MUL)
OPCODE(BIC)
OPCODE(MVN)
#undef OPCODE
#endif
}
TEST_CASE("Hi Register Operations/Branch Exchange", TAG) {
HiRegisterOperations* hi = nullptr;
uint16_t raw = 0b0100011000011010;
SECTION("both lo") {
Instruction instruction(raw);
REQUIRE((hi = std::get_if<HiRegisterOperations>(&instruction.data)));
CHECK(hi->rd == 2);
CHECK(hi->rs == 3);
}
SECTION("hi rd") {
raw |= 1 << 7;
Instruction instruction(raw);
REQUIRE((hi = std::get_if<HiRegisterOperations>(&instruction.data)));
CHECK(hi->rd == 10);
CHECK(hi->rs == 3);
}
SECTION("hi rs") {
raw |= 1 << 6;
Instruction instruction(raw);
REQUIRE((hi = std::get_if<HiRegisterOperations>(&instruction.data)));
CHECK(hi->rd == 2);
CHECK(hi->rs == 11);
}
if (hi)
CHECK(hi->opcode == HiRegisterOperations::OpCode::MOV);
SECTION("both hi") {
raw |= 1 << 6;
raw |= 1 << 7;
Instruction instruction(raw);
REQUIRE((hi = std::get_if<HiRegisterOperations>(&instruction.data)));
CHECK(hi->rd == 10);
CHECK(hi->rs == 11);
CHECK(hi->opcode == HiRegisterOperations::OpCode::MOV);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "MOV R10,R11");
hi->opcode = HiRegisterOperations::OpCode::ADD;
CHECK(instruction.disassemble() == "ADD R10,R11");
hi->opcode = HiRegisterOperations::OpCode::CMP;
CHECK(instruction.disassemble() == "CMP R10,R11");
hi->opcode = HiRegisterOperations::OpCode::BX;
CHECK(instruction.disassemble() == "BX R11");
#endif
}
}
TEST_CASE("PC Relative Load", TAG) {
uint16_t raw = 0b0100101011100110;
Instruction instruction(raw);
PcRelativeLoad* ldr = nullptr;
REQUIRE((ldr = std::get_if<PcRelativeLoad>(&instruction.data)));
// 230 << 2
CHECK(ldr->word == 920);
CHECK(ldr->rd == 2);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "LDR R2,[PC,#920]");
#endif
}
TEST_CASE("Load/Store with Register Offset", TAG) {
uint16_t raw = 0b0101000110011101;
Instruction instruction(raw);
LoadStoreRegisterOffset* ldr = nullptr;
REQUIRE((ldr = std::get_if<LoadStoreRegisterOffset>(&instruction.data)));
CHECK(ldr->rd == 5);
CHECK(ldr->rb == 3);
CHECK(ldr->ro == 6);
CHECK(ldr->byte == false);
CHECK(ldr->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STR R5,[R3,R6]");
ldr->byte = true;
CHECK(instruction.disassemble() == "STRB R5,[R3,R6]");
ldr->load = true;
CHECK(instruction.disassemble() == "LDRB R5,[R3,R6]");
ldr->byte = false;
CHECK(instruction.disassemble() == "LDR R5,[R3,R6]");
#endif
}
TEST_CASE("Load/Store Sign-Extended Byte/Halfword", TAG) {
uint16_t raw = 0b0101001110011101;
Instruction instruction(raw);
LoadStoreSignExtendedHalfword* ldr = nullptr;
REQUIRE(
(ldr = std::get_if<LoadStoreSignExtendedHalfword>(&instruction.data)));
CHECK(ldr->rd == 5);
CHECK(ldr->rb == 3);
CHECK(ldr->ro == 6);
CHECK(ldr->s == false);
CHECK(ldr->h == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STRH R5,[R3,R6]");
ldr->h = true;
CHECK(instruction.disassemble() == "LDRH R5,[R3,R6]");
ldr->s = true;
CHECK(instruction.disassemble() == "LDSH R5,[R3,R6]");
ldr->h = false;
CHECK(instruction.disassemble() == "LDSB R5,[R3,R6]");
#endif
}
TEST_CASE("Load/Store with Immediate Offset", TAG) {
uint16_t raw = 0b0110010110011101;
Instruction instruction(raw);
LoadStoreImmediateOffset* ldr = nullptr;
REQUIRE((ldr = std::get_if<LoadStoreImmediateOffset>(&instruction.data)));
CHECK(ldr->rd == 5);
CHECK(ldr->rb == 3);
// 22 << 4 when byte == false
CHECK(ldr->offset == 88);
CHECK(ldr->byte == false);
CHECK(ldr->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STR R5,[R3,#88]");
ldr->load = true;
CHECK(instruction.disassemble() == "LDR R5,[R3,#88]");
#endif
// byte
raw = 0b0111010110011101;
instruction = Instruction(raw);
INFO(instruction.data.index());
REQUIRE((ldr = std::get_if<LoadStoreImmediateOffset>(&instruction.data)));
CHECK(ldr->byte == true);
CHECK(ldr->offset == 22);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STRB R5,[R3,#22]");
ldr->load = true;
CHECK(instruction.disassemble() == "LDRB R5,[R3,#22]");
#endif
}
TEST_CASE("Load/Store Halfword", TAG) {
uint16_t raw = 0b1000011010011101;
Instruction instruction(raw);
LoadStoreHalfword* ldr = nullptr;
REQUIRE((ldr = std::get_if<LoadStoreHalfword>(&instruction.data)));
CHECK(ldr->rd == 5);
CHECK(ldr->rb == 3);
// 26 << 1
CHECK(ldr->offset == 52);
CHECK(ldr->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STRH R5,[R3,#52]");
ldr->load = true;
CHECK(instruction.disassemble() == "LDRH R5,[R3,#52]");
#endif
}
TEST_CASE("SP-Relative Load/Store", TAG) {
uint16_t raw = 0b1001010010011101;
Instruction instruction(raw);
SpRelativeLoad* ldr = nullptr;
REQUIRE((ldr = std::get_if<SpRelativeLoad>(&instruction.data)));
CHECK(ldr->rd == 4);
// 157 << 2
CHECK(ldr->word == 628);
CHECK(ldr->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STR R4,[SP,#628]");
ldr->load = true;
CHECK(instruction.disassemble() == "LDR R4,[SP,#628]");
#endif
}
TEST_CASE("Load Adress", TAG) {
uint16_t raw = 0b1010000110001111;
Instruction instruction(raw);
LoadAddress* add = nullptr;
REQUIRE((add = std::get_if<LoadAddress>(&instruction.data)));
// 143 << 2
CHECK(add->word == 572);
CHECK(add->rd == 1);
CHECK(add->sp == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "ADD R1,PC,#572");
add->sp = true;
CHECK(instruction.disassemble() == "ADD R1,SP,#572");
#endif
}
TEST_CASE("Add Offset to Stack Pointer", TAG) {
uint16_t raw = 0b1011000000100101;
Instruction instruction(raw);
AddOffsetStackPointer* add = nullptr;
REQUIRE((add = std::get_if<AddOffsetStackPointer>(&instruction.data)));
// 37 << 2
CHECK(add->word == 148);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "ADD SP,#148");
#endif
raw = 0b1011000010100101;
instruction = Instruction(raw);
REQUIRE((add = std::get_if<AddOffsetStackPointer>(&instruction.data)));
CHECK(add->word == -148);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "ADD SP,#-148");
#endif
}
TEST_CASE("Push/Pop Registers", TAG) {
uint16_t raw = 0b1011010000110101;
Instruction instruction(raw);
PushPopRegister* push = nullptr;
REQUIRE((push = std::get_if<PushPopRegister>(&instruction.data)));
CHECK(push->regs == 53);
CHECK(push->pclr == false);
CHECK(push->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "PUSH {R0,R2,R4,R5}");
push->pclr = true;
CHECK(instruction.disassemble() == "PUSH {R0,R2,R4,R5,LR}");
push->load = true;
CHECK(instruction.disassemble() == "POP {R0,R2,R4,R5,PC}");
push->pclr = false;
CHECK(instruction.disassemble() == "POP {R0,R2,R4,R5}");
#endif
}
TEST_CASE("Multiple Load/Store", TAG) {
uint16_t raw = 0b1100011001100101;
Instruction instruction(raw);
MultipleLoad* ldm = nullptr;
REQUIRE((ldm = std::get_if<MultipleLoad>(&instruction.data)));
CHECK(ldm->regs == 101);
CHECK(ldm->rb == 6);
CHECK(ldm->load == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "STMIA R6!,{R0,R2,R5,R6}");
ldm->load = true;
CHECK(instruction.disassemble() == "LDMIA R6!,{R0,R2,R5,R6}");
#endif
}
TEST_CASE("Conditional Branch", TAG) {
uint16_t raw = 0b1101100110110100;
Instruction instruction(raw);
ConditionalBranch* b = nullptr;
REQUIRE((b = std::get_if<ConditionalBranch>(&instruction.data)));
// (-76 << 1)
CHECK(b->offset == -152);
CHECK(b->condition == Condition::LS);
#ifdef DISASSEMBLER
// (-76 << 1) + PC (0) + 4
CHECK(instruction.disassemble() == "BLS #-148");
#endif
}
TEST_CASE("SoftwareInterrupt") {
uint16_t raw = 0b1101111100110011;
Instruction instruction(raw);
SoftwareInterrupt* swi = nullptr;
REQUIRE((swi = std::get_if<SoftwareInterrupt>(&instruction.data)));
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "SWI 51");
#endif
}
TEST_CASE("Unconditional Branch") {
uint16_t raw = 0b1110011100110011;
Instruction instruction(raw);
UnconditionalBranch* b = nullptr;
REQUIRE((b = std::get_if<UnconditionalBranch>(&instruction.data)));
// (2147483443 << 1)
REQUIRE(b->offset == -410);
#ifdef DISASSEMBLER
// (2147483443 << 1) + PC(0) + 4
CHECK(instruction.disassemble() == "B #-406");
#endif
}
TEST_CASE("Long Branch with link") {
uint16_t raw = 0b1111010011101100;
Instruction instruction(raw);
LongBranchWithLink* bl = nullptr;
REQUIRE((bl = std::get_if<LongBranchWithLink>(&instruction.data)));
// 1260 << 1
CHECK(bl->offset == 2520);
CHECK(bl->high == false);
#ifdef DISASSEMBLER
CHECK(instruction.disassemble() == "BL #2520");
bl->high = true;
CHECK(instruction.disassemble() == "BLH #2520");
#endif
}
#undef TAG

View File

@@ -0,0 +1,4 @@
tests_sources += files(
'instruction.cc',
'exec.cc'
)

8
tests/main.cc Normal file
View File

@@ -0,0 +1,8 @@
#include "util/loglevel.hh"
#include <catch2/catch_session.hpp>
int
main(int argc, char* argv[]) {
matar::set_log_level(matar::LogLevel::Off);
return Catch::Session().run(argc, argv);
}

123
tests/memory.cc Normal file
View File

@@ -0,0 +1,123 @@
#include "memory.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "[memory]"
using namespace matar;
class MemFixture {
public:
MemFixture()
: memory(std::array<uint8_t, Memory::BIOS_SIZE>(),
std::vector<uint8_t>(Header::HEADER_SIZE)) {}
protected:
Memory memory;
};
TEST_CASE_METHOD(MemFixture, "bios", TAG) {
memory.write(0, 0xAC);
CHECK(memory.read(0) == 0xAC);
memory.write(0x3FFF, 0x48);
CHECK(memory.read(0x3FFF) == 0x48);
memory.write(0x2A56, 0x10);
CHECK(memory.read(0x2A56) == 0x10);
}
TEST_CASE_METHOD(MemFixture, "board wram", TAG) {
memory.write(0x2000000, 0xAC);
CHECK(memory.read(0x2000000) == 0xAC);
memory.write(0x203FFFF, 0x48);
CHECK(memory.read(0x203FFFF) == 0x48);
memory.write(0x2022A56, 0x10);
CHECK(memory.read(0x2022A56) == 0x10);
}
TEST_CASE_METHOD(MemFixture, "chip wram", TAG) {
memory.write(0x3000000, 0xAC);
CHECK(memory.read(0x3000000) == 0xAC);
memory.write(0x3007FFF, 0x48);
CHECK(memory.read(0x3007FFF) == 0x48);
memory.write(0x3002A56, 0x10);
CHECK(memory.read(0x3002A56) == 0x10);
}
TEST_CASE_METHOD(MemFixture, "palette ram", TAG) {
memory.write(0x5000000, 0xAC);
CHECK(memory.read(0x5000000) == 0xAC);
memory.write(0x50003FF, 0x48);
CHECK(memory.read(0x50003FF) == 0x48);
memory.write(0x5000156, 0x10);
CHECK(memory.read(0x5000156) == 0x10);
}
TEST_CASE_METHOD(MemFixture, "video ram", TAG) {
memory.write(0x6000000, 0xAC);
CHECK(memory.read(0x6000000) == 0xAC);
memory.write(0x6017FFF, 0x48);
CHECK(memory.read(0x6017FFF) == 0x48);
memory.write(0x6012A56, 0x10);
CHECK(memory.read(0x6012A56) == 0x10);
}
TEST_CASE_METHOD(MemFixture, "oam obj ram", TAG) {
memory.write(0x7000000, 0xAC);
CHECK(memory.read(0x7000000) == 0xAC);
memory.write(0x70003FF, 0x48);
CHECK(memory.read(0x70003FF) == 0x48);
memory.write(0x7000156, 0x10);
CHECK(memory.read(0x7000156) == 0x10);
}
TEST_CASE("rom", TAG) {
// 32 megabyte ROM
Memory memory(std::array<uint8_t, Memory::BIOS_SIZE>(),
std::vector<uint8_t>(32 * 1024 * 1024));
SECTION("ROM1") {
memory.write(0x8000000, 0xAC);
CHECK(memory.read(0x8000000) == 0xAC);
memory.write(0x9FFFFFF, 0x48);
CHECK(memory.read(0x9FFFFFF) == 0x48);
memory.write(0x8ef0256, 0x10);
CHECK(memory.read(0x8ef0256) == 0x10);
}
SECTION("ROM2") {
memory.write(0xA000000, 0xAC);
CHECK(memory.read(0xA000000) == 0xAC);
memory.write(0xBFFFFFF, 0x48);
CHECK(memory.read(0xBFFFFFF) == 0x48);
memory.write(0xAEF0256, 0x10);
CHECK(memory.read(0xAEF0256) == 0x10);
}
SECTION("ROM3") {
memory.write(0xC000000, 0xAC);
CHECK(memory.read(0xC000000) == 0xAC);
memory.write(0xDFFFFFF, 0x48);
CHECK(memory.read(0xDFFFFFF) == 0x48);
memory.write(0xCEF0256, 0x10);
CHECK(memory.read(0xCEF0256) == 0x10);
}
}
#undef TAG

View File

@@ -4,11 +4,22 @@ tests_deps = [
src = include_directories('../src')
tests_sources = files()
tests_sources = files(
'main.cc',
'bus.cc',
'memory.cc'
)
subdir('cpu')
subdir('util')
catch2 = dependency('catch2-with-main', version: '>=3.4.0', static: true)
tests_cpp_args = []
if get_option('disassembler')
tests_cpp_args += '-DDISASSEMBLER'
endif
catch2 = dependency('catch2', version: '>=3.4.0', static: true)
catch2_tests = executable(
'matar_tests',
tests_sources,
@@ -16,6 +27,7 @@ catch2_tests = executable(
link_with: tests_deps,
include_directories: [inc, src],
build_by_default: false,
cpp_args: tests_cpp_args
)
test('catch2 tests', catch2_tests)

108
tests/util/bits.cc Normal file
View File

@@ -0,0 +1,108 @@
#include "util/bits.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "[util][bits]"
TEST_CASE("8 bits", TAG) {
uint8_t num = 45;
CHECK(get_bit(num, 0));
CHECK(!get_bit(num, 1));
CHECK(get_bit(num, 5));
CHECK(!get_bit(num, 6));
CHECK(!get_bit(num, 7));
set_bit(num, 6);
CHECK(get_bit(num, 6));
rst_bit(num, 6);
CHECK(!get_bit(num, 6));
chg_bit(num, 5, false);
CHECK(!get_bit(num, 5));
chg_bit(num, 5, true);
CHECK(get_bit(num, 5));
// 0b0110
CHECK(bit_range(num, 1, 4) == 6);
}
TEST_CASE("16 bits", TAG) {
uint16_t num = 34587;
CHECK(get_bit(num, 0));
CHECK(get_bit(num, 1));
CHECK(!get_bit(num, 5));
CHECK(!get_bit(num, 14));
CHECK(get_bit(num, 15));
set_bit(num, 14);
CHECK(get_bit(num, 14));
rst_bit(num, 14);
CHECK(!get_bit(num, 14));
chg_bit(num, 5, true);
CHECK(get_bit(num, 5));
// num = 45
chg_bit(num, 5, false);
CHECK(!get_bit(num, 5));
// 0b1000110
CHECK(bit_range(num, 2, 8) == 70);
}
TEST_CASE("32 bits", TAG) {
uint32_t num = 3194142523;
CHECK(get_bit(num, 0));
CHECK(get_bit(num, 1));
CHECK(get_bit(num, 12));
CHECK(get_bit(num, 29));
CHECK(!get_bit(num, 30));
CHECK(get_bit(num, 31));
set_bit(num, 30);
CHECK(get_bit(num, 30));
rst_bit(num, 30);
CHECK(!get_bit(num, 30));
chg_bit(num, 12, false);
CHECK(!get_bit(num, 12));
chg_bit(num, 12, true);
CHECK(get_bit(num, 12));
// 0b10011000101011111100111
CHECK(bit_range(num, 3, 25) == 5003239);
}
TEST_CASE("64 bits", TAG) {
uint64_t num = 58943208889991935;
CHECK(get_bit(num, 0));
CHECK(get_bit(num, 1));
CHECK(!get_bit(num, 10));
CHECK(get_bit(num, 55));
CHECK(!get_bit(num, 60));
set_bit(num, 63);
CHECK(get_bit(num, 63));
rst_bit(num, 63);
CHECK(!get_bit(num, 63));
chg_bit(num, 10, true);
CHECK(get_bit(num, 10));
chg_bit(num, 10, false);
CHECK(!get_bit(num, 10));
// 0b011010001
CHECK(bit_range(num, 39, 47) == 209);
}
#undef TAG

23
tests/util/crypto.cc Normal file
View File

@@ -0,0 +1,23 @@
#include "util/crypto.hh"
#include <catch2/catch_test_macros.hpp>
#define TAG "[util][crypto]"
TEST_CASE("sha256 matar", TAG) {
std::array<uint8_t, 5> data = { 'm', 'a', 't', 'a', 'r' };
CHECK(crypto::sha256(data) ==
"3b02a908fd5743c0e868675bb6ae77d2a62b3b5f7637413238e2a1e0e94b6a53");
}
TEST_CASE("sha256 forgis", TAG) {
std::array<uint8_t, 32> data = { 'i', ' ', 'p', 'u', 't', ' ', 't', 'h',
'e', ' ', 'n', 'e', 'w', ' ', 'f', 'o',
'r', 'g', 'i', 's', ' ', 'o', 'n', ' ',
't', 'h', 'e', ' ', 'j', 'e', 'e', 'p' };
CHECK(crypto::sha256(data) ==
"cfddca2ce2673f355518cbe2df2a8522693c54723a469e8b36a4f68b90d2b759");
}
#undef TAG

4
tests/util/meson.build Normal file
View File

@@ -0,0 +1,4 @@
tests_sources += files(
'bits.cc',
'crypto.cc'
)