Skip to content

A simple LC-3 virtual machine in C with Python-based assembler support. Run and debug LC-3 assembly programs on your computer

Notifications You must be signed in to change notification settings

mike-rambil/writing-a-vm

Repository files navigation

LC-3 Virtual Machine

Note: This project is based on the Write your Own Virtual Machine tutorial by Justin Meiners and Ryan Pendleton, and is intended for learning purposes.

This project is a simple LC-3 virtual machine written in C. It allows you to run LC-3 binary programs on your computer.

Project Structure

  • lc3-vm.c: Source code for the LC-3 virtual machine.
  • lc3-vm.exe: Compiled executable of the virtual machine.
  • hello-world.asm: Sample LC-3 assembly program.
  • lc3-asm/: Submodule containing a pure Python LC-3 assembler (paul-nameless/lc3-asm).

Getting Started

1. Clone the Repository and Submodules

If you haven't already, initialize submodules after cloning:

git submodule update --init --recursive

2. Assemble Your LC-3 Assembly File

Use the Python assembler in the lc3-asm submodule:

python lc3-asm/lc3.py hello-world.asm

This will generate a hex string in hello-world-out.obj (not a binary file).

3. Convert Hex String to Binary

The assembler outputs a hex string, not a binary file. Convert it to a binary .obj file with this Python one-liner:

python -c "import re; d=open('hello-world-out.obj').read(); h=re.sub(r'[^0-9a-fA-F]', '', d); h = h[:-1] if len(h) % 2 else h; open('hello-world.obj','wb').write(bytes.fromhex(h))"

4. Run the Program on the VM

In PowerShell, use ./ to run executables in the current directory:

./lc3-vm.exe hello-world.obj

Troubleshooting

  • PowerShell: 'lc3-vm.exe' is not recognized

    • Use ./lc3-vm.exe instead of lc3-vm.exe to run the executable in the current directory.
  • Unknown instruction: 0

    • This means the VM tried to execute an invalid instruction (0x0000). Possible causes:

      • The object file is empty or not assembled correctly.
      • The object file format is not compatible (check that the first two bytes are the origin, e.g., 0x3000).
      • You are running the wrong or an empty file.
    • Make sure you assemble with:

      python lc3-asm/lc3.py hello-world.asm

      convert the hex string to binary:

      python -c "import re; d=open('hello-world-out.obj').read(); h=re.sub(r'[^0-9a-fA-F]', '', d); h = h[:-1] if len(h) % 2 else h; open('hello-world.obj','wb').write(bytes.fromhex(h))"

      and then run:

      ./lc3-vm.exe hello-world.obj

Optional: Debugging

You can use the disassembler provided in the submodule to inspect your object file:

python lc3-asm/disasm.py hello-world.obj

References

About

A simple LC-3 virtual machine in C with Python-based assembler support. Run and debug LC-3 assembly programs on your computer

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published