def read_asm_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return [re.sub(r'#.*', '', line).strip() for line in lines if line.strip()]
def parse_labels_and_instructions(instructions):
labels = {}
parsed_instructions = []
pc = 0
for line in instructions:
if ':' in line:
label, line = line.split(':', 1)
labels[label.strip()] = pc
line = line.strip()
if line:
parsed_instructions.append(line)
pc += 4
return parsed_instructions, labels
def print_registers(reg):
print("Registers:")
for i in range(0, 32, 4):
print(f"{i:2}: {reg[f'{i}']:10} | {i+1:2}: {reg[f'{i+1}']:10} | {i+2:2}: {reg[f'{i+2}']:10} | {i+3:2}: {reg[f'{i+3}']:10}")
print()
def print_memory(memory):
print("Memory:")
non_zero_addresses = [address for address, value in memory.items() if value != 0]
if not non_zero_addresses:
print("\nAll memory values are 0.\n")
return
min_address = min(non_zero_addresses)
max_address = max(non_zero_addresses)
start_address = min_address - (min_address % 4)
while max_address - start_address < 32 * 4:
max_address += 4
for address in range(start_address, max_address + 1, 16):
for offset in range(0, 16, 4):
current_address = address + offset
value = memory.get(current_address, 0)
print(f"M[{current_address:5}]: {value:10}", end=" | ")
print()
print()
def sim(inD, labels, reg, memory, binList):
PC = 0
counts = {
'Total': 0,
'ALU': 0,
'Jump': 0,
'Branch': 0,
'Memory': 0,
'Other': 0,
'Special': 0
}
mode = input("Enter 'n' for single instruction mode, 'a' for automatic mode: ")
single_step = True if mode == 'n' else False
pc_to_mc = {pc: mc for pc, mc in zip(range(0, len(binList) * 4, 4), binList)}
code
while PC in inD:
curr = inD[PC]
part = curr.replace(",", "").split(" ")
if single_step:
print("\n" + "=" * 80)
print("Executing Instruction:")
print("Assembly Code:", curr)
mc = pc_to_mc.get(PC)
if mc is not None:
print("Machine Code:", mc)
else:
print("No machine code found for this PC.")
print("PC before execution:", PC)
if part[0] == 'addi':
reg[part[1]] = reg[part[2]] + int(part[3])
counts['ALU'] += 1
PC += 4
elif part[0] == 'beq':
rs = reg[part[1]]
rt = reg[part[2]]
label = part[3]
if rs == rt:
PC = labels[label]
else:
PC += 4
counts['Branch'] += 1
elif part[0] == 'bne':
rs = reg[part[1]]
rt = reg[part[2]]
label = part[3]
if rs != rt:
PC = labels[label]
else:
PC += 4
counts['Branch'] += 1
elif part[0] == 'j':
label = part[1]
if label in labels:
PC = labels[label]
counts['Jump'] += 1
elif part[0] == 'lw':
rt = part[1]
imm, rs_reg = part[2].split('(')
rs_reg = rs_reg[:-1]
mem_address = reg[rs_reg] + int(imm)
reg[rt] = memory.get(mem_address, 0)
counts['Memory'] += 1
PC += 4
elif part[0] == 'sw':
rt = part[1]
imm, rs_reg = part[2].split('(')
rs_reg = rs_reg[:-1]
mem_address = reg[rs_reg] + int(imm)
memory[mem_address] = reg[rt]
counts['Memory'] += 1
PC += 4
elif part[0] == 'add':
reg[part[1]] = reg[part[2]] + reg[part[3]]
counts['ALU'] += 1
PC += 4
elif part[0] == 'sub':
reg[part[1]] = reg[part[2]] - reg[part[3]]
counts['ALU'] += 1
PC += 4
elif part[0] == 'slt':
reg[part[1]] = 1 if reg[part[2]] < reg[part[3]] else 0
counts['ALU'] += 1
PC += 4
elif part[0] == 'and':
reg[part[1]] = reg[part[2]] & reg[part[3]]
counts['ALU'] += 1
PC += 4
elif part[0] == 'sll':
reg[part[1]] = reg[part[2]] << int(part[3])
counts['ALU'] += 1
PC += 4
elif part[0] == 'srl':
reg[part[1]] = reg[part[2]] >> int(part[3])
counts['ALU'] += 1
PC += 4
elif part[0] == 'or':
reg[part[1]] = reg[part[2]] | reg[part[3]]
counts['ALU'] += 1
PC += 4
elif part[0] == 'xor':
reg[part[1]] = reg[part[2]] ^ reg[part[3]]
counts['ALU'] += 1
PC += 4
elif part[0] == 'syscall':
syscall_num = reg['$v0']
if syscall_num == 1: # Print integer
print("Output:", reg['$a0'])
elif syscall_num == 4: # Print string
print("Output:", end="")
string_address = reg['$a0']
while memory.get(string_address, 0) != 0:
print(chr(memory[string_address]), end="")
string_address += 1
print() # Newline after string
elif syscall_num == 10: # Exit
print("Exiting program.")
break
else:
print(f"Unknown syscall: {syscall_num}")
counts['Special'] += 1
PC += 4
counts['Total'] += 1
if single_step:
print_registers(reg)
print_memory(memory)
print("PC after execution:", PC)
input("Press Enter to continue...")
if not single_step:
print_registers(reg)
print_memory(memory)
print("Instruction counts:", counts)
def main():
file_path = "program.asm" # Using "program.asm" as the file path
instructions = read_asm_file(file_path)
code
parsed_instructions, labels = parse_labels_and_instructions(instructions)
memory = {}
reg = {f"${i}": 0 for i in range(32)}
bin_instructions = [convert_to_binary(inst, labels, pc * 4) for pc, inst in enumerate(parsed_instructions)]
print("Assembly to Machine Code Conversion:")
for i, binary in enumerate(bin_instructions):
if binary: # Check if binary is not None
print(f"{parsed_instructions[i]} -> {binary}")
else:
print(f"{parsed_instructions[i]} -> Invalid instruction")
inD = {pc * 4: instr for pc, instr in enumerate(parsed_instructions)}
sim(inD, labels, reg, memory, bin_instructions)
if name == "main":
main()
To convert and execute a given assembly program correctly using the MIPS simulator, the current code implementation seems to be incomplete or incorrect, especially with regard to how it interprets and translates assembly instructions into machine code and the subsequent simulation. Here's a more guided approach to ensure the assembly language is correctly parsed, converted, and executed:
Steps to Correct the Implementation:
Input Validation:
Ensure that the assembly code is valid and follows the expected syntax for MIPS assembly language. Pay attention to directives like .data and .text and ensure they are being correctly processed.
Parsing Improvements:
Ensure that labels are correctly associated with their respective program counters (PC).
Handle data directives (.data, .word, .asciiz, etc.) properly and understand how they translate into memory.
Opcode and Funct Mapping:
Ensure that the opcodes and funct codes are correct for instructions. Note that li (load immediate) is not a native MIPS instruction but is translated into addi with register $zero as the source.
Instruction Conversion:
Address and fix issues in the conversion of each type of instruction: R-type, I-type, and J-type.
Implement handling for non-opcode instructions like .word, .asciiz, handling them according to MIPS standards.
Machine Code Execution:
Implement a more robust execution process, ensuring the instructions are fetched, decoded, and executed correctly.
Include memory management if the .data section is involved, serving data as either an integer or an ASCII string.
Syscalls Handling:
Implement a handler for syscalls. In MIPS, these are triggered by setting a register ($v0, typically) to a code that indicates the operation to perform (like print integer, print string, read integer, etc.).
Debug Information:
Ensure the ability to trace the execution of each instruction with detailed debug information, which includes printing the current instruction, PC, registers, and memory contents after each step (with separate modes for step-by-step and automatic).
Here is a simplified approach to address some issues:
Key Functions Update:
Assembly Parsing: Ensure .data and .text are processed, organizing code and data appropriately.
Symbol Table: Build a comprehensive symbol table for jump addresses and variable locations.
Instruction Converting: Add conversion capabilities for pseudo-instructions, handling them directly or converting them into native MIPS instructions.
Execution Simulation:
Utilize syscall correctly to simulate interaction like I/O operations.
Implement branching, jumping, and arithmetic operations correctly by updating the program counter and register file.
Note: Each section should have access to more error handling and correction mechanisms to ensure valid assembly instructions are processed correctly and accurately converted to machine code.
Testing:
Ensure that testing scenarios cover various instructions and edge cases:
Typical Arithmetic: Use different and boundary cases for add, sub, etc.
Loads and Stores: Utilize both regular and edge cases for accessing memory.
Control flow: Verify branching and jumping logic in forward and backward directions.
System Calls: Validate different syscall options and their respective arguments.
By ensuring that each key functional block of the simulator fulfills its expected operation with extensive testing and validation, you can create a robust and effective MIPS simulator.
Certainly! I'll provide a complete example that can handle some basic MIPS assembly operations, including parsing instructions, converting them to binary, and simulating the execution. This version will focus on a more systematic handling of the assembly code input and simulation environment.
Note: This won't encompass every possible MIPS instruction and more complex scenarios like advanced directives or detailed syscall handling but should give a clear structure for a basic simulation.
python
import re
def read_asm_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return [re.sub(r'#.*', '', line).strip() for line in lines if line.strip()]
def parse_labels_and_instructions(instructions):
labels = {}
parsed_instructions = []
pc = 0
for line in instructions:
if ':' in line:
label, line = line.split(':', 1)
labels[label.strip()] = pc
line = line.strip()
if line:
parsed_instructions.append(line)
pc += 4
return parsed_instructions, labels
def convert_to_binary(instruction, labels, current_pc):
opcodes = {
"addi": "001000",
"beq": "000100",
"bne": "000101",
"j": "000010",
"lw": "100011",
"sw": "101011",
"and": "000000",
"or": "000000",
"slt": "000000",
"add": "000000",
"sub": "000000",
"sll": "000000",
"srl": "000000",
"xor": "000000",
"nor": "000000"
}
functs = {
"and": "100100",
"or": "100101",
"slt": "101010",
"add": "100000",
"sub": "100010",
"sll": "000000",
"srl": "000010",
"xor": "100110",
"nor": "100111"
}
parts = instruction.replace(",", "").split()
op = parts[0]
if op not in opcodes:
return None
try:
if op == "li":
return convert_to_binary(f"addi {parts[1]} $zero {parts[2]}", labels, current_pc)
elif op in ["addi", "lw", "sw"]:
rt = format(int(parts[1][1:]), '05b')
imm, rs_reg = parts[2].split('(')
rs = format(int(rs_reg[1:-1]), '05b')
imm = format(int(imm) & 0xFFFF, '016b')
return f"{opcodes[op]}{rs}{rt}{imm}"
elif op in ["beq", "bne"]:
rs = format(int(parts[1][1:]), '05b')
rt = format(int(parts[2][1:]), '05b')
label = parts[3]
if label in labels:
offset = ((labels[label] - (current_pc + 4)) >> 2)
imm = format(offset & 0xFFFF, '016b')
else:
imm = "0000000000000000"
return f"{opcodes[op]}{rs}{rt}{imm}"
elif op == "j":
label = parts[1]
if label in labels:
address = labels[label] >> 2
return f"{opcodes[op]}{format(address, '026b')}"
else:
return None
else:
rd = format(int(parts[1][1:]), '05b')
rs = format(int(parts[2][1:]), '05b')
rt = format(int(parts[3][1:]), '05b')
shamt = "00000"
funct = functs[op]
return f"{opcodes[op]}{rs}{rt}{rd}{shamt}{funct}"
except:
return None
def print_registers(reg):
print("Registers:")
for i in range(0, 32, 4):
print(f"${i:2}: {reg[f'${i}']:10} "
f"| ${i+1:2}: {reg[f'${i+1}']:10} "
f"| ${i+2:2}: {reg[f'${i+2}']:10} "
f"| ${i+3:2}: {reg[f'${i+3}']:10}")
print()
def print_memory(memory):
print("Memory:")
non_zero_addresses = [address for address, value in memory.items() if value != 0]
if not non_zero_addresses:
print("\nAll memory values are 0.\n")
return
min_address = min(non_zero_addresses)
max_address = max(non_zero_addresses)
start_address = min_address - (min_address % 4)
while max_address - start_address < 32 * 4:
max_address += 4
for address in range(start_address, max_address + 1, 16):
for offset in range(0, 16, 4):
current_address = address + offset
value = memory.get(current_address, 0)
print(f"M[{current_address:5}]: {value:10}", end=" | ")
print()
print()
def run_simulation(parsed_instructions, labels):
memory = {}
reg = {f"${i}": 0 for i in range(32)}
PC = 0
counts = {'Total': 0, 'ALU': 0, 'Jump': 0, 'Branch': 0, 'Memory': 0, 'Other': 0, 'Special': 0}
bin_instructions = [convert_to_binary(inst, labels, pc * 4) for pc, inst in enumerate(parsed_instructions)]
sim_mode = input("Enter 'n' for single instruction mode, 'a' for automatic mode: ")
single_step = True if sim_mode == 'n' else False
inD = {pc * 4: instr for pc, instr in enumerate(parsed_instructions)}
while PC in inD:
current_instr = inD[PC]
parts = current_instr.replace(",", "").split()
if single_step:
print("\n" + "=" * 80)
print("Executing Instruction:")
print("Assembly Code:", current_instr)
mc = bin_instructions[PC // 4]
if mc:
print("Machine Code:", mc)
print("PC before execution:", PC)
op_code = parts[0]
if op_code == 'addi':
reg[parts[1]] = reg[parts[2]] + int(parts[3])
counts['ALU'] += 1
elif op_code == 'beq':
if reg[parts[1]] == reg[parts[2]]:
PC = labels[parts[3]]
else:
PC += 4
counts['Branch'] += 1
elif op_code == 'bne':
if reg[parts[1]] != reg[parts[2]]:
PC = labels[parts[3]]
else:
PC += 4
counts['Branch'] += 1
elif op_code == 'j':
PC = labels[parts[1]]
counts['Jump'] += 1
elif op_code == 'lw':
mem_address = reg[parts[2].strip('()')] + int(parts[1])
reg[parts[0]] = memory.get(mem_address, 0)
counts['Memory'] += 1
elif op_code == 'sw':
mem_address = reg[parts[2].strip('()')] + int(parts[1])
memory[mem_address] = reg[parts[0]]
counts['Memory'] += 1
elif op_code == 'add':
reg[parts[1]] = reg[parts[2]] + reg[parts[3]]
counts['ALU'] += 1
elif op_code == 'sub':
reg[parts[1]] = reg[parts[2]] - reg[parts[3]]
counts['ALU'] += 1
elif op_code == 'slt':
reg[parts[1]] = 1 if reg[parts[2]] < reg[parts[3]] else 0
counts['ALU'] += 1
elif op_code == 'and':
reg[parts[1]] = reg[parts[2]] & reg[parts[3]]
counts['ALU'] += 1
elif op_code == 'or':
reg[parts[1]] = reg[parts[2]] | reg[parts[3]]
counts['ALU'] += 1
elif op_code == 'xor':
reg[parts[1]] = reg[parts[2]] ^ reg[parts[3]]
counts['ALU'] += 1
elif op_code == 'sll':
reg[parts[1]] = reg[parts[2]] << int(parts[3])
counts['ALU'] += 1
elif op_code == 'srl':
reg[parts[1]] = reg[parts[2]] >> int(parts[3])
counts['ALU'] += 1
elif op_code == 'syscall':
syscall(reg, memory)
counts['Special'] += 1
if op_code not in ['beq', 'bne', 'j']:
PC += 4
counts['Total'] += 1
if single_step:
print_registers(reg)
print_memory(memory)
print("PC after execution:", PC)
input("Press Enter to continue...")
if not single_step:
print_registers(reg)
print_memory(memory)
print("Instruction counts:", counts)
def syscall(reg, memory):
syscall_num = reg['$v0']
if syscall_num == 1:
print(f"Output (int): {reg['$a0']}")
elif syscall_num == 4:
print("Output (string):", end="")
string_address = reg['$a0']
while memory.get(string_address, 0) != 0:
print(chr(memory[string_address]), end="")
string_address += 1
print()
elif syscall_num == 10:
print("Exiting program.")
exit()
else:
print(f"Unknown syscall: {syscall_num}")
def main():
file_path = "program.asm" # Path to the assembly program file
instructions = read_asm_file(file_path)
parsed_instructions, labels = parse_labels_and_instructions(instructions)
print("Assembly to Machine Code Conversion:")
binary_conversion = [convert_to_binary(inst, labels, pc * 4) for pc, inst in enumerate(parsed_instructions)]
for i, binary in enumerate(binary_conversion):
if binary:
print(f"{parsed_instructions[i]} -> {binary}")
else:
print(f"{parsed_instructions[i]} -> Invalid instruction")
run_simulation(parsed_instructions, labels)
if __name__ == "__main__":
main()
Explanation:
File Read and Parsing: The code reads the assembly file and extracts instructions while ignoring comments.
Label and Instructions Handling: It processes labels and creates mappings between instruction addresses and labels.
Instruction Conversion: Converts each assembly instruction to its binary form, paying attention to special cases like li.
Simulation Setup: Initializes registers and memory, processes each instruction, and performs operations as per the instruction set.
Execution Mode: Offers stepping through code one instruction at a time or running automatically.
Syscall Handling: Basic implementation for specific syscall operations. Extend this for more functionality if needed.
This framework should aid in the initial setup and handling of MIPS assembly instructions, and can be extended for more advanced features and instructions.
The message indicating "Invalid instruction" for operations like syscall, la, and li suggests that these pseudo-instructions or specific operations are not directly handled or converted in your MIPS assembler code.
Let's tackle each of these in order to handle them correctly in your MIPS simulator:
Handling Syscall Instructions
In MIPS, a syscall is an operation used to perform system-level instructions, like printing to the console or exiting the program. This is a special instruction that doesn't translate directly into binary like other operations.
Ensure your assembler logic recognizes syscall and the associated registers ($v0 for the syscall number and argument registers like $a0).
Handling li (Load Immediate)
The li instruction is a pseudo-instruction. It's often translated into addi if the immediate value fits within 16 bits or into a series of instructions if it doesn't.
For simple purposes:
Convert li $a0, value to addi $a0, $zero, value for positive numbers that fit.
Handling la (Load Address)
la is another pseudo-instruction that loads the address of a label into a register. This can be simplified by using the direct address if known:
If you're handling .data sections and memory labels, you might want to set an address map and resolve these in your conversion logic.
Updated Functionality in Pseudo-Instruction Conversion
Let's make some updates to handle these pseudo-instructions.
We will modify convert_to_binary() to correctly parse these operations and update parse_labels_and_instructions() if needed to support .data segments.
Here's an example showing how you can interpret these:
To incorporate correctly the changes in the simulation:
Parse and Map Labels Correctly for la: Ensure that .data labels are managed.
Implement a Correct System Call Mechanism syscall: Previously, syscalls were mapped directly without binary conversion.
Fix Error Handling for Jumps: Ensure jumps and branches correctly interact with labels when setting the program counter.
This code should enable the proper interpretation of common MIPS pseudo-instructions like la, li, and syscall-related logic. However, remember that this is a simplified model; advanced functionality might be required for complex applications, including dynamic memory handling and detailed syscall responses.
The error output you are encountering seems to indicate that the assembler part of your MIPS simulator is not correctly handling certain types of instructions, particularly pseudo-instructions and data declarations. Here's how we can address these issues:
Key Areas to Address
Data Section Handling:
Ensure that .data sections are correctly parsed and mapped to memory.
Handle directives such as .word and .asciiz to properly store data in memory.
Pseudo-Instructions:
Implement support for li (load immediate), often a combination of operations if values are larger, but can be simplified to addi for smaller values.
Implement support for la (load address) to resolve label addresses.
Syscall Handling:
Ensure syscall operations are interpreted correctly and add their binary representation to your conversion logic.
Separating Text and Data Segments:
Ensure your interpreter differentiates between the two segments for handling accordingly.
Here's a corrected and simplified version to handle these constructs:
python
import re
def read_asm_file(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
return [re.sub(r'#.*', '', line).strip() for line in lines if line.strip()]
def parse_labels_and_instructions(instructions):
labels = {}
parsed_instructions = []
pc = 0
data_mode = False
memory = {}
current_address = 0x10000000 # Starting address for data section
for line in instructions:
if line.startswith(".data"):
data_mode = True
continue
elif line.startswith(".text"):
data_mode = False
pc = 0
continue
if data_mode:
if ':' in line:
label, line = line.split(':', 1)
labels[label.strip()] = current_address
line = line.strip()
if line.startswith('.word'):
line = line.replace('.word', '').strip()
values = line.split(',')
for value in values:
memory[current_address] = int(value)
current_address += 4
elif line.startswith('.asciiz'):
line = line.replace('.asciiz', '').strip().strip('"')
for char in line:
memory[current_address] = ord(char)
current_address += 1
memory[current_address] = 0 # Null-terminate the string
current_address += 1
else:
if ':' in line:
label, line = line.split(':', 1)
labels[label.strip()] = pc
line = line.strip()
if line:
parsed_instructions.append(line)
pc += 4
return parsed_instructions, labels, memory
def convert_to_binary(instruction, labels, current_pc):
opcodes = {
"addi": "001000",
"beq": "000100",
"bne": "000101",
"j": "000010",
"lw": "100011",
"sw": "101011",
"and": "000000",
"or": "000000",
"slt": "000000",
"add": "000000",
"sub": "000000",
"sll": "000000",
"srl": "000000",
"xor": "000000",
"nor": "000000",
"syscall": "000000"
}
functs = {
"and": "100100",
"or": "100101",
"slt": "101010",
"add": "100000",
"sub": "100010",
"sll": "000000",
"srl": "000010",
"xor": "100110",
"nor": "100111",
"syscall": "001100"
}
parts = instruction.replace(",", "").split()
op = parts[0]
try:
if op == "li":
rd = format(int(parts[1][1:]), '05b')
rs = format(0, '05b') # $zero register
imm = format(int(parts[2]) & 0xFFFF, '016b')
return f"{opcodes['addi']}{rs}{rd}{imm}"
elif op == "la":
rd = format(int(parts[1][1:]), '05b')
address = labels.get(parts[2], 0)
imm = format(address & 0xFFFF, '016b')
rs = format(0, '05b') # $zero register
return f"{opcodes['addi']}{rs}{rd}{imm}"
elif op == "syscall":
return f"{opcodes[op]}00000000000000000000{functs[op]}"
elif op in ["addi", "lw", "sw"]:
rt = format(int(parts[1][1:]), '05b')
if op in ["lw", "sw"]:
offset, rs_reg = parts[2].split('(')
rs = format(int(rs_reg[1:-1]), '05b')
imm = format(int(offset) & 0xFFFF, '016b')
else:
rs = format(int(parts[2][1:]), '05b')
imm = format(int(parts[3]) & 0xFFFF, '016b')
return f"{opcodes[op]}{rs}{rt}{imm}"
elif op in ["beq", "bne"]:
rs = format(int(parts[1][1:]), '05b')
rt = format(int(parts[2][1:]), '05b')
label = parts[3]
if label in labels:
offset = ((labels[label] - (current_pc + 4)) >> 2)
imm = format(offset & 0xFFFF, '016b')
else:
imm = "0000000000000000"
return f"{opcodes[op]}{rs}{rt}{imm}"
elif op == "j":
label = parts[1]
if label in labels:
address = labels[label] >> 2
return f"{opcodes[op]}{format(address, '026b')}"
else:
rd = format(int(parts[1][1:]), '05b')
rs = format(int(parts[2][1:]), '05b')
rt = format(int(parts[3][1:]), '05b')
shamt = "00000"
funct = functs[op]
return f"{opcodes[op]}{rs}{rt}{rd}{shamt}{funct}"
except Exception as e:
print(f"Error converting instruction: {instruction} -> {e}")
return None
def display_registers(reg):
print("Registers:")
for i in range(0, 32, 4):
print(f"${i:2}: {reg[f'${i}']:10} "
f"| ${i+1:2}: {reg[f'${i+1}']:10} "
f"| ${i+2:2}: {reg[f'${i+2}']:10} "
f"| ${i+3:2}: {reg[f'${i+3}']:10}")
print()
def display_memory(memory):
print("Memory:")
addresses = sorted(memory.keys())
for addr in addresses:
print(f"Address {addr:08x}: {memory[addr]}")
print()
def run_simulation(parsed_instructions, labels, memory):
reg = {f"${i}": 0 for i in range(32)}
PC = 0
sim_mode = input("Enter 'n' for single instruction mode, 'a' for automatic mode: ")
single_step = (sim_mode == 'n')
bin_instructions = [convert_to_binary(inst, labels, pc * 4) for pc, inst in enumerate(parsed_instructions)]
inD = {pc * 4: inst for pc, inst in enumerate(parsed_instructions)}
while PC in inD:
current_instruction = inD[PC]
parts = current_instruction.replace(",", "").split()
if single_step:
print("\n" + "=" * 80)
print("Executing Instruction:")
print("Assembly Code:", current_instruction)
mc = bin_instructions[PC // 4]
if mc:
print("Machine Code:", mc)
print("PC before execution:", PC)
op_code = parts[0]
if op_code == 'addi':
reg[parts[1]] = reg[parts[2]] + int(parts[3])
elif op_code == 'beq':
if reg[parts[1]] == reg[parts[2]]:
PC = labels[parts[3]]
else:
PC += 4
elif op_code == 'bne':
if reg[parts[1]] != reg[parts[2]]:
PC = labels[parts[3]]
else:
PC += 4
elif op_code == 'j':
PC = labels[parts[1]]
elif op_code == 'lw':
offset, base = parts[2].split('(')
address = reg[base.strip(')')] + int(offset)
reg[parts[1]] = memory.get(address, 0)
elif op_code == 'sw':
offset, base = parts[2].split('(')
address = reg[base.strip(')')] + int(offset)
memory[address] = reg[parts[1]]
elif op_code == 'add':
reg[parts[1]] = reg[parts[2]] + reg[parts[3]]
elif op_code == 'sub':
reg[parts[1]] = reg[parts[2]] - reg[parts[3]]
elif op_code == 'slt':
reg[parts[1]] = 1 if reg[parts[2]] < reg[parts[3]] else 0
elif op_code == 'and':
reg[parts[1]] = reg[parts[2]] & reg[parts[3]]
elif op_code == 'or':
reg[parts[1]] = reg[parts[2]] | reg[parts[3]]
elif op_code == 'xor':
reg[parts[1]] = reg[parts[2]] ^ reg[parts[3]]
elif op_code == 'sll':
reg[parts[1]] = reg[parts[2]] << int(parts[3])
elif op_code == 'srl':
reg[parts[1]] = reg[parts[2]] >> int(parts[3])
elif op_code == 'syscall':
syscall(reg, memory)
if op_code not in ['beq', 'bne', 'j']:
PC += 4
if single_step:
display_registers(reg)
display_memory(memory)
print("PC after execution:", PC)
input("Press Enter to continue...")
if not single_step:
display_registers(reg)
display_memory(memory)
def syscall(reg, memory):
syscall_num = reg['$v0']
if syscall_num == 1:
print(f"Output (int): {reg['$a0']}")
elif syscall_num == 4:
print("Output (string):", end="")
string_address = reg['$a0']
while memory.get(string_address, 0) != 0:
print(chr(memory[string_address]), end="")
string_address += 1
print()
elif syscall_num == 10:
print("Exiting program.")
exit()
else:
print(f"Unknown syscall: {syscall_num}")
def main():
file_path = "program.asm"
instructions = read_asm_file(file_path)
parsed_instructions, labels, memory = parse_labels_and_instructions(instructions)
print("Assembly to Machine Code Conversion:")
for i, binary in enumerate([convert_to_binary(inst, labels, pc * 4) for pc, inst in enumerate(parsed_instructions)]):
if binary:
print(f"{parsed_instructions[i]} -> {binary}")
else:
print(f"{parsed_instructions[i]} -> Invalid instruction")
run_simulation(parsed_instructions, labels, memory)
if __name__ == "__main__":
main()
Key Changes:
Data Section Parsing: The program now correctly translates .data into memory, handling .word and .asciiz.
Pseudo-Instructions: li and la are simplified for direct use.
Text and Data Sections: The given assembler identifies between .text and .data sections.
Syscall Handling: Implemented the syscall mechanism to handle specific syscall numbers, including print and exit options.
Ensure you adapt this code to reflect the actual structure and complexity of your assembly programs and that you test extensively with simple and complex scenarios.