Added all codes.
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
# Assignment A1 - Pass 1 and pass 2 assembler
|
||||
# Example Opcode Table (OPTAB)
|
||||
OPTAB = {
|
||||
"LOAD": "01",
|
||||
"STORE": "02",
|
||||
"ADD": "03",
|
||||
"SUB": "04",
|
||||
"JMP": "05"
|
||||
}
|
||||
|
||||
# Example Assembler Directives
|
||||
DIRECTIVES = ["START", "END", "WORD", "RESW", "RESB"]
|
||||
|
||||
# Symbol Table (SYMTAB) and Intermediate Code
|
||||
SYMTAB = {}
|
||||
intermediate_code = []
|
||||
|
||||
# Pass-I: Generates the symbol table and intermediate code
|
||||
def pass1(input_lines):
|
||||
locctr = 0
|
||||
start_address = 0
|
||||
for line in input_lines:
|
||||
label, opcode, operand = parse_line(line.strip())
|
||||
|
||||
if opcode == "START":
|
||||
start_address = int(operand)
|
||||
locctr = start_address
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
continue
|
||||
|
||||
# Process label
|
||||
if label:
|
||||
if label in SYMTAB:
|
||||
print(f"Error: Duplicate symbol {label}")
|
||||
SYMTAB[label] = locctr
|
||||
|
||||
# Process opcode
|
||||
if opcode in OPTAB:
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
locctr += 3 # Assume all instructions are 3 bytes
|
||||
elif opcode in DIRECTIVES:
|
||||
if opcode == "WORD":
|
||||
locctr += 3
|
||||
elif opcode == "RESW":
|
||||
locctr += 3 * int(operand)
|
||||
elif opcode == "RESB":
|
||||
locctr += int(operand)
|
||||
elif opcode == "END":
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
break
|
||||
else:
|
||||
print(f"Error: Invalid opcode {opcode}")
|
||||
|
||||
return start_address, intermediate_code
|
||||
|
||||
# Parse a line of input (splits line into label, opcode, operand)
|
||||
def parse_line(line):
|
||||
parts = line.split()
|
||||
label = parts[0] if len(parts) == 3 else None
|
||||
opcode = parts[1] if len(parts) == 3 else parts[0]
|
||||
operand = parts[2] if len(parts) == 3 else parts[1] if len(parts) == 2 else None
|
||||
return label, opcode, operand
|
||||
|
||||
# Pass-II: Generates the final machine code
|
||||
def pass2(start_address, intermediate_code):
|
||||
final_code = []
|
||||
for locctr, label, opcode, operand in intermediate_code:
|
||||
if opcode in OPTAB:
|
||||
machine_code = OPTAB[opcode]
|
||||
if operand in SYMTAB:
|
||||
address = format(SYMTAB[operand], '04X') # 4-digit hex address
|
||||
else:
|
||||
address = '0000' # Default if symbol not found
|
||||
final_code.append(f"{locctr:04X} {machine_code} {address}")
|
||||
elif opcode == "WORD":
|
||||
final_code.append(f"{locctr:04X} {int(operand):06X}")
|
||||
elif opcode == "RESW" or opcode == "RESB":
|
||||
final_code.append(f"{locctr:04X} ----")
|
||||
elif opcode == "END":
|
||||
final_code.append(f"{locctr:04X} END")
|
||||
return final_code
|
||||
|
||||
# Main function to read the input file and run both passes
|
||||
def main():
|
||||
# Read the assembly code from input.txt
|
||||
with open("assemblerIP.txt", "r") as file:
|
||||
input_lines = file.readlines()
|
||||
|
||||
# Run Pass-I
|
||||
start_address, intermediate_code = pass1(input_lines)
|
||||
|
||||
# Display Symbol Table and Intermediate Code
|
||||
print("\nPass-I Output:")
|
||||
print("Symbol Table (SYMTAB):", SYMTAB)
|
||||
print("\nIntermediate Code:")
|
||||
for entry in intermediate_code:
|
||||
print(entry)
|
||||
|
||||
# Run Pass-II
|
||||
final_code = pass2(start_address, intermediate_code)
|
||||
|
||||
# Display Final Machine Code
|
||||
print("\nPass-II Output (Final Machine Code):")
|
||||
for code in final_code:
|
||||
print(code)
|
||||
|
||||
# Run the main function
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,8 @@
|
||||
COPY START 1000
|
||||
FIRST LOAD ALPHA
|
||||
ADD BETA
|
||||
STORE GAMMA
|
||||
ALPHA WORD 5
|
||||
BETA RESW 1
|
||||
GAMMA RESB 1
|
||||
END FIRST
|
||||
@@ -0,0 +1,109 @@
|
||||
try:
|
||||
source = open('source1.txt', 'r')
|
||||
print("File is read successfully.")
|
||||
source.seek(0)
|
||||
except FileNotFoundError:
|
||||
print('\n\n\nsource2.txt file not found. Create it first!\n\n\n')
|
||||
except IOError:
|
||||
print('The source file has an IO error')
|
||||
|
||||
MDT = [] # Macro Definition Table
|
||||
MNT = [] # Macro Name Table
|
||||
LIT = [] # Literal Table
|
||||
LPT = [] # Literal Pool Table
|
||||
|
||||
|
||||
def macroman(line):
|
||||
name = line.split()[1]
|
||||
entry = []
|
||||
entry.append(line.strip())
|
||||
while True:
|
||||
line = source.readline().upper()
|
||||
if not line:
|
||||
print('No MEND found for: ', name)
|
||||
return
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
elif 'MEND' in line:
|
||||
global MDT, MNT
|
||||
entry.append(line.strip())
|
||||
MNT.append([len(MNT) + 1, name, len(MDT) + 1])
|
||||
MDT.extend(entry)
|
||||
return
|
||||
else:
|
||||
entry.append(line.strip())
|
||||
# Check for literals and add to the literal table
|
||||
for word in line.split():
|
||||
if word.startswith('='): # Assuming literals start with '='
|
||||
if word not in LIT:
|
||||
LIT.append(word)
|
||||
|
||||
|
||||
def pass1():
|
||||
global MDT, MNT, LIT
|
||||
while True:
|
||||
line = source.readline().upper()
|
||||
if not line: break
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
|
||||
print('\nMNT:')
|
||||
for a in MNT:
|
||||
print(a)
|
||||
|
||||
print('\nMDT:')
|
||||
for i, a in enumerate(MDT, start=1):
|
||||
print(i, ' ', a)
|
||||
|
||||
print('\nLIT:')
|
||||
for i, lit in enumerate(LIT, start=1):
|
||||
print(i, ' ', lit)
|
||||
|
||||
|
||||
pass1()
|
||||
|
||||
|
||||
def inserter(sline, name):
|
||||
global MDT, MNT
|
||||
sline = ''
|
||||
for a in MNT:
|
||||
if a[1] == name:
|
||||
add = a[2]
|
||||
break
|
||||
while True:
|
||||
if 'MEND' in MDT[add]:
|
||||
break
|
||||
sline += MDT[add] + '\n'
|
||||
add += 1
|
||||
return sline
|
||||
|
||||
|
||||
def pass2():
|
||||
source.seek(0)
|
||||
output = open('output.txt', 'w')
|
||||
output.close()
|
||||
output = open('output.txt', 'a+')
|
||||
|
||||
while True:
|
||||
sline = source.readline().upper()
|
||||
if not sline: break
|
||||
for a in MNT:
|
||||
if a[1] in sline and 'MACRO' not in sline:
|
||||
sline = inserter(sline, a[1])
|
||||
d = sline.strip()
|
||||
# Check for literals in the output line
|
||||
for word in d.split():
|
||||
if word.startswith('='):
|
||||
if word not in LPT: # If not already in the literal pool table
|
||||
LPT.append(word)
|
||||
|
||||
if d not in MDT:
|
||||
output.write(sline)
|
||||
|
||||
print('done.')
|
||||
print('\nLPT:')
|
||||
for i, lpt in enumerate(LPT, start=1):
|
||||
print(i, ' ', lpt)
|
||||
|
||||
|
||||
pass2()
|
||||
@@ -0,0 +1,13 @@
|
||||
MACRO FIBO
|
||||
MOVE A, =5
|
||||
ADD A, B
|
||||
MEND
|
||||
|
||||
MACRO SUM
|
||||
ADD A, B
|
||||
MOVE C, =100
|
||||
MEND
|
||||
|
||||
START:
|
||||
FIBO
|
||||
SUM
|
||||
@@ -0,0 +1,23 @@
|
||||
def fcfs_scheduling(processes, n):
|
||||
processes.sort(key=lambda x: x[1])
|
||||
completion_time = 0
|
||||
waiting_time = []
|
||||
turnaround_time = []
|
||||
|
||||
for process in processes:
|
||||
pid, arrival_time, burst_time = process
|
||||
|
||||
if completion_time < arrival_time:
|
||||
completion_time = arrival_time
|
||||
|
||||
completion_time += burst_time
|
||||
turnaround_time.append(completion_time - arrival_time)
|
||||
waiting_time.append(completion_time - arrival_time - burst_time)
|
||||
|
||||
print("\nFCFS Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 5], [2, 1, 3], [3, 2, 8], [4, 3, 6]]
|
||||
fcfs_scheduling(processes, len(processes))
|
||||
@@ -0,0 +1,23 @@
|
||||
def priority_scheduling(processes, n):
|
||||
processes.sort(key=lambda x: (x[2], x[1]))
|
||||
completion_time = 0
|
||||
waiting_time = []
|
||||
turnaround_time = []
|
||||
|
||||
for process in processes:
|
||||
pid, arrival_time, priority, burst_time = process
|
||||
|
||||
if completion_time < arrival_time:
|
||||
completion_time = arrival_time
|
||||
|
||||
completion_time += burst_time
|
||||
turnaround_time.append(completion_time - arrival_time)
|
||||
waiting_time.append(completion_time - arrival_time - burst_time)
|
||||
|
||||
print("\nPriority (Non-Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Priority, Burst Time
|
||||
processes = [[1, 0, 1, 5], [2, 1, 3, 3], [3, 2, 2, 8], [4, 3, 4, 6]]
|
||||
priority_scheduling(processes, len(processes))
|
||||
@@ -0,0 +1,36 @@
|
||||
def round_robin(processes, n, quantum):
|
||||
remaining_time = [bt for _, _, bt in processes]
|
||||
t = 0
|
||||
waiting_time = [0] * n
|
||||
turnaround_time = [0] * n
|
||||
complete = [False] * n
|
||||
|
||||
while True:
|
||||
done = True
|
||||
|
||||
for i in range(n):
|
||||
if remaining_time[i] > 0:
|
||||
done = False
|
||||
|
||||
if remaining_time[i] > quantum:
|
||||
t += quantum
|
||||
remaining_time[i] -= quantum
|
||||
else:
|
||||
t += remaining_time[i]
|
||||
waiting_time[i] = t - processes[i][2] - processes[i][1]
|
||||
remaining_time[i] = 0
|
||||
|
||||
if done:
|
||||
break
|
||||
|
||||
for i in range(n):
|
||||
turnaround_time[i] = processes[i][2] + waiting_time[i]
|
||||
|
||||
print("\nRound Robin (Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 10], [2, 1, 4], [3, 2, 5], [4, 3, 3]]
|
||||
quantum = 2
|
||||
round_robin(processes, len(processes), quantum)
|
||||
@@ -0,0 +1,48 @@
|
||||
import sys
|
||||
|
||||
def sjf_preemptive(processes, n):
|
||||
remaining_time = [bt for _, _, bt in processes]
|
||||
complete = 0
|
||||
t = 0
|
||||
minm = sys.maxsize
|
||||
shortest = 0
|
||||
finish_time = 0
|
||||
check = False
|
||||
waiting_time = [0] * n
|
||||
turnaround_time = [0] * n
|
||||
|
||||
while complete != n:
|
||||
for j in range(n):
|
||||
if processes[j][1] <= t and remaining_time[j] < minm and remaining_time[j] > 0:
|
||||
minm = remaining_time[j]
|
||||
shortest = j
|
||||
check = True
|
||||
|
||||
if not check:
|
||||
t += 1
|
||||
continue
|
||||
|
||||
remaining_time[shortest] -= 1
|
||||
minm = remaining_time[shortest] if remaining_time[shortest] > 0 else sys.maxsize
|
||||
|
||||
if remaining_time[shortest] == 0:
|
||||
complete += 1
|
||||
check = False
|
||||
finish_time = t + 1
|
||||
waiting_time[shortest] = finish_time - processes[shortest][2] - processes[shortest][1]
|
||||
|
||||
if waiting_time[shortest] < 0:
|
||||
waiting_time[shortest] = 0
|
||||
|
||||
t += 1
|
||||
|
||||
for i in range(n):
|
||||
turnaround_time[i] = processes[i][2] + waiting_time[i]
|
||||
|
||||
print("\nSJF (Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 8], [2, 1, 4], [3, 2, 9], [4, 3, 5]]
|
||||
sjf_preemptive(processes, len(processes))
|
||||
@@ -0,0 +1,28 @@
|
||||
def best_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
best_idx = -1
|
||||
best_size = float('inf')
|
||||
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i] and memory_blocks[j] - process_sizes[i] < best_size:
|
||||
best_size = memory_blocks[j] - process_sizes[i]
|
||||
best_idx = j
|
||||
|
||||
if best_idx != -1:
|
||||
allocation[i] = best_idx
|
||||
memory_blocks[best_idx] -= process_sizes[i]
|
||||
|
||||
print("\nBest Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
best_fit(memory_blocks, process_sizes)
|
||||
@@ -0,0 +1,22 @@
|
||||
def first_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i]:
|
||||
allocation[i] = j
|
||||
memory_blocks[j] -= process_sizes[i]
|
||||
break
|
||||
|
||||
print("\nFirst Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
first_fit(memory_blocks, process_sizes)
|
||||
@@ -0,0 +1,25 @@
|
||||
def next_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
next_index = 0
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
while next_index < len(memory_blocks):
|
||||
if memory_blocks[next_index] >= process_sizes[i]:
|
||||
allocation[i] = next_index
|
||||
memory_blocks[next_index] -= process_sizes[i]
|
||||
next_index = (next_index + 1) % len(memory_blocks) # Move to next block
|
||||
break
|
||||
next_index += 1
|
||||
|
||||
print("\nNext Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
next_fit(memory_blocks, process_sizes)
|
||||
@@ -0,0 +1,28 @@
|
||||
def worst_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
worst_idx = -1
|
||||
worst_size = -1
|
||||
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i] and memory_blocks[j] > worst_size:
|
||||
worst_size = memory_blocks[j]
|
||||
worst_idx = j
|
||||
|
||||
if worst_idx != -1:
|
||||
allocation[i] = worst_idx
|
||||
memory_blocks[worst_idx] -= process_sizes[i]
|
||||
|
||||
print("\nWorst Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
worst_fit(memory_blocks, process_sizes)
|
||||
@@ -0,0 +1,31 @@
|
||||
class LRU:
|
||||
def __init__(self, capacity):
|
||||
self.capacity = capacity
|
||||
self.cache = {}
|
||||
self.order = []
|
||||
|
||||
def refer(self, page):
|
||||
if page not in self.cache:
|
||||
if len(self.cache) >= self.capacity:
|
||||
lru_page = self.order.pop(0) # Remove least recently used page
|
||||
del self.cache[lru_page]
|
||||
else:
|
||||
self.order.remove(page) # Remove page to update its order
|
||||
self.cache[page] = True
|
||||
self.order.append(page)
|
||||
|
||||
def display(self):
|
||||
print("Current Pages in Memory (LRU):", list(self.cache.keys()))
|
||||
|
||||
# Simulate LRU
|
||||
def lru_simulation(pages, capacity):
|
||||
lru = LRU(capacity)
|
||||
for page in pages:
|
||||
lru.refer(page)
|
||||
lru.display()
|
||||
|
||||
# Example Pages and Capacity
|
||||
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
||||
capacity = 3
|
||||
print("LRU Page Replacement Simulation:")
|
||||
lru_simulation(pages, capacity)
|
||||
@@ -0,0 +1,44 @@
|
||||
class Optimal:
|
||||
def __init__(self, capacity):
|
||||
self.capacity = capacity
|
||||
self.cache = []
|
||||
|
||||
def refer(self, page, future):
|
||||
if page not in self.cache:
|
||||
if len(self.cache) < self.capacity:
|
||||
self.cache.append(page)
|
||||
else:
|
||||
farthest_page = self.find_farthest_page(future)
|
||||
index = self.cache.index(farthest_page)
|
||||
self.cache[index] = page
|
||||
|
||||
def find_farthest_page(self, future):
|
||||
farthest = -1
|
||||
farthest_page = None
|
||||
for page in self.cache:
|
||||
if page not in future:
|
||||
return page
|
||||
try:
|
||||
index = future.index(page)
|
||||
if index > farthest:
|
||||
farthest = index
|
||||
farthest_page = page
|
||||
except ValueError:
|
||||
continue
|
||||
return farthest_page
|
||||
|
||||
def display(self):
|
||||
print("Current Pages in Memory (Optimal):", self.cache)
|
||||
|
||||
# Simulate Optimal Page Replacement
|
||||
def optimal_simulation(pages, capacity):
|
||||
optimal = Optimal(capacity)
|
||||
for i in range(len(pages)):
|
||||
optimal.refer(pages[i], pages[i + 1:])
|
||||
optimal.display()
|
||||
|
||||
# Example Pages and Capacity
|
||||
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
||||
capacity = 3
|
||||
print("\nOptimal Page Replacement Simulation:")
|
||||
optimal_simulation(pages, capacity)
|
||||
@@ -0,0 +1,19 @@
|
||||
# Python version
|
||||
|
||||
---
|
||||
|
||||
- This folder contains Python versions of all codes.
|
||||
- All codes have been tested.
|
||||
- **ROUND ROBIN DOES NOT WORK AS INTENDED.**
|
||||
|
||||
---
|
||||
|
||||
- [Assignment-A1 (Pass 1 and pass 2 assembler)](Assignment-A1%20%28Assembler%29)
|
||||
- [Assignment-A2 (Pass 1 and pass 2 macro)](Assignment-A2%20%28Macro%29) // Alternate version available in [Codes/Group A](../Group%20A/Code-A2.py) folder.
|
||||
- [Assignment-A3 (DLL)](../Group%20A/Assignment-A3) - This code is from "Codes/Group A" folder
|
||||
- [Assignment-B4 (Mutex and Semaphore)](../Group%20B/Code-B4.cpp) - This code is from "Codes/Group B" folder
|
||||
- [Assignment-B5 (CPU scheduling)](Assignment-B5%20%28CPU%20Scheduling%29)
|
||||
- [Assignment-B6 (Memory placement)](Assignment-B6%20%28Memory%20placement%29)
|
||||
- [Assignment-B7 (Page replacement)](Assignment-B7%20%28Page%20replacement%29)
|
||||
|
||||
---
|
||||
Reference in New Issue
Block a user