I've started writing a virtual machine as a pet project (pet project #3 actually) and, without boring you with the details, I'll just say that the instructions are stored in a vector of CInstruction. CInstruction is a very basic class:
Code:
class CInstruction {
public:
byte opcode;
byte operands[2];
};
In the virtual machine class the Run method iterates through this vector and "does the right thing" based on the instructions opcode. However at the end of each run, I have the instruction 253, with the operands 253, 253, appear out of nowhere. I assume it's a random value in the vector but I'm not sure how it got there.
Here's the run method:
Code:
int CVirtualMachine::Run()
{
CInstruction inst = nextInstruction();
while (inst.opcode != 0x05) {
#ifdef DEBUG
std::cout << "\nDEBUG: ip : " << (unsigned) inst.opcode << " " << (unsigned) inst.operands[0] <<
", " << (unsigned) inst.operands[1] << endl;
#endif
switch (inst.opcode) {
case 0x00: // nop
break;
case 0x05: // end
endProgram(inst.operands);
break;
case 0x06: // movl l, r
movl(inst.operands);
break;
default:
throw BadInstruction();
}
inst = nextInstruction();
}
return 0;
}
The vector is simply defined in the class as
Code:
vector<CInstruction> instructions;
Then it isn't touched until my main driver program calls LoadDebug:
Code:
bool CVirtualMachine::LoadDebug(vector<CInstruction> program)
{
for (unsigned i = 0; i < program.size(); i++)
instructions.push_back(program[i]);
return true;
}
LoadDebug is just there so I can feed it "raw instructions" until I start to write an assembler.
Oh, here's nextInstruction:
Code:
CInstruction CVirtualMachine::nextInstruction()
{
return instructions[ip++];
}
I think that's all that could affect the instructions vector.
Help!
Oh yeah in case you were wondering it's all coming along nicely otherwise. Here's a sample output for your pleasure:
Code:
DEBUG: ip : 6 10, 1
DEBUG: Registers:
r0: 10
r1: 0
r2: 0
r3: 0
DEBUG: ip : 6 255, 3
DEBUG: Registers:
r0: 10
r1: 0
r2: 255
r3: 0
DEBUG: ip : 253 253, 253
*** ERROR ***
Bad Instruction!
Press any key to continue