diff --git a/src/emulator.h b/src/emulator.h index 34601ea..f6a3cb2 100644 --- a/src/emulator.h +++ b/src/emulator.h @@ -1,9 +1,14 @@ +#ifndef __EMULATOR__ +#define __EMULATOR__ #include "global.h" /************************************ * DEFINITIONS ************************************/ +#define BYTE_BITS 8 +#define WORD_BITS 32 + /************************************ * STRUCTS ************************************/ @@ -20,4 +25,6 @@ typedef struct { word pc; byte memory[MEMORY_SIZE]; PState conditionCodes; -} Machine; \ No newline at end of file +} Machine; + +#endif diff --git a/src/print.c b/src/print.c new file mode 100644 index 0000000..c12322e --- /dev/null +++ b/src/print.c @@ -0,0 +1,49 @@ +#include +#include +#include "print.h" +#include "emulator.h" + +#define UNSET_CONDITION_CODE_CHAR '-' + +// Prints the current machine state into the provided stream +void printState(Machine *state, FILE *stream) { + printRegisters(state, stream); + printMemory(state, stream); +} + +// Prints the current machine registers into the provided stream +void printRegisters(Machine *state, FILE *stream) { + fprintf(stream, "Registers:\n"); + for (int i = 0; i < REGISTER_COUNT; i++) { + fprintf(stream, "X%02d\t= %u\n", i, state->registers[i]); + } + fprintf(stream, "PC\t= %u\n", state->pc); + fprintf(stream, "PSTATE\t: %c%c%c%c", state->conditionCodes.Negative ? 'N' : UNSET_CONDITION_CODE_CHAR, + state->conditionCodes.Zero ? 'Z' : UNSET_CONDITION_CODE_CHAR, + state->conditionCodes.Carry ? 'C' : UNSET_CONDITION_CODE_CHAR, + state->conditionCodes.Overflow ? 'V' : UNSET_CONDITION_CODE_CHAR); +} + +// Returns the word starting at the provided address +// Converts 4 bytes into one word +word readWord(Machine *state, word address) { + word result = 0; + int bytesPerWord = WORD_BITS / BYTE_BITS - 1; + for (int i = 0; i <= bytesPerWord; i++) + result |= (word) state->memory[address + i] << (BYTE_BITS * (bytesPerWord - i)); + return result; +} + +// Prints all non-zero memory locations into the provided stream +void printMemory(Machine *state, FILE *stream) { + fprintf(stream, "\nNon-zero memory:\n"); + + // print memory 4 byte aligned + for (int addr = 0; addr < MEMORY_SIZE; addr+= 4) { + word data = readWord(state, addr); + if (data != 0) { + fprintf(stream, "0x%08x: 0x%08x\n", addr, data); + } + } + +} diff --git a/src/print.h b/src/print.h new file mode 100644 index 0000000..f344731 --- /dev/null +++ b/src/print.h @@ -0,0 +1,6 @@ +#include +#include "emulator.h" + +void printState(Machine *state, FILE *stream); +void printRegisters(Machine *state, FILE *stream); +void printMemory(Machine *state, FILE *stream);