SlideShare a Scribd company logo
1 of 34
Download to read offline
-----------------------------------------------------CPU.java---------------------------------------------------
--------------------------------------------------------
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class CPU
{
/*
Declare required registers
*/
static int PC = 0, SP = 1000, IR, AC, X, Y, timerFlag, num_of_instructions = 0;
static int systemStack_top = 2000, userStack_top = 1000;
static boolean userMode = true; // initially set it to true.
// On interrupt set it to false to indicate
//kernel mode
static boolean processingInterrupt = false; // flag to avoid nested interrupt execution
public static void main(String args[])
{
String fileName = null;
// check the command line argument length
if(args.length == 2)
{
fileName = args[0];
timerFlag = Integer.parseInt(args[1]); // set timer ineterrupt value
}
else // if incorrect number of parameters then exit
{
System.out.println("Incorrect number of parameters. Process ended.");
System.exit(0);
}
try
{
/*
Create child process and set up I/O streams
*/
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java Memory");
OutputStream os = proc.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = proc.getInputStream();
Scanner memory_reader = new Scanner(is); // direct input stream to a Scanner object
// Send file name to child process
fileNameToMemory(pw, is, os, fileName);
// this loop will keep the communication going between CPU and memory
while (true)
{
// check to see if timer interrupt has occured
if(num_of_instructions > 0
&& (num_of_instructions % timerFlag) == 0 && processingInterrupt == false)
{
// process the interrupt
processingInterrupt = true;
interruptFromTimer(pw, is, memory_reader, os);
}
// read instruction from memory
int value = readFromMemory(pw, is, memory_reader, os, PC);
if (value != -1)
{
processInstruction(value, pw, is, memory_reader, os);
}
else
break;
}
proc.waitFor();
int exitVal = proc.exitValue();
System.out.println("Process exited: " + exitVal);
}
catch (IOException | InterruptedException t)
{
t.printStackTrace();
}
}
/*
function to send file name to memory
*/
private static void fileNameToMemory(PrintWriter pw, InputStream is, OutputStream os,
String fileName)
{
pw.printf(fileName + " "); //send filename to memory
pw.flush();
}
// function to read data at given address from memory
private static int readFromMemory(PrintWriter pw, InputStream is, Scanner memory_reader,
OutputStream os, int address)
{
checkMemoryViolation(address);
pw.printf("1," + address + " ");
pw.flush();
if (memory_reader.hasNext())
{
String temp = memory_reader.next();
if(!temp.isEmpty())
{
int temp2 = Integer.parseInt(temp);
return (temp2);
}
}
return -1;
}
//function to tell child process to write data at the given address in memory
private static void writeToMemory(PrintWriter pw, InputStream is, OutputStream os, int
address, int data) {
pw.printf("2," + address + "," + data + " "); //2 at the start on string indicates write
pw.flush();
}
// function to process an instruction received from the memory
private static void processInstruction(int value, PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
IR = value; //store instruction in Instruction register
int operand; //to store operand
switch(IR)
{
case 1: //Load the value into the AC
PC++; // increment counter to get operand
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = operand;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 2: // Load the value at the address into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 3: // Load the value from the address found in the address into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
operand = readFromMemory(pw, is, memory_reader, os, operand);
AC = readFromMemory(pw, is, memory_reader, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 4: // Load the value at (address+X) into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand + X);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 5: //Load the value at (address+Y) into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand + Y);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 6: //Load from (Sp+X) into the AC
AC = readFromMemory(pw, is, memory_reader, os, SP + X);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 7: //Store the value in the AC into the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
writeToMemory(pw, is, os, operand, AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 8: //Gets a random int from 1 to 100 into the AC
Random r = new Random();
int i = r.nextInt(100) + 1;
AC = i;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 9: //If port=1, writes AC as an int to the screen
//If port=2, writes AC as a char to the screen
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if(operand == 1)
{
System.out.print(AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
}
else if (operand == 2)
{
System.out.print((char)AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
}
else
{
System.out.println("Error: Port = " + operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
System.exit(0);
break;
}
case 10: // Add the value in X to the AC
AC = AC + X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 11: //Add the value in Y to the AC
AC = AC + Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 12: //Subtract the value in X from the AC
AC = AC - X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 13: //Subtract the value in Y from the AC
AC = AC - Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 14: //Copy the value in the AC to X
X = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 15: //Copy the value in X to the AC
AC = X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 16: //Copy the value in the AC to Y
Y = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 17: //Copy the value in Y to the AC
AC = Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 18: //Copy the value in AC to the SP
SP = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 19: //Copy the value in SP to the AC
AC = SP;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 20: // Jump to the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 21: // Jump to the address only if the value in the AC is zero
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if (AC == 0)
{
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
}
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 22: // Jump to the address only if the value in the AC is not zero
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if (AC != 0)
{
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
}
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 23: //Push return address onto stack, jump to the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
pushValueToStack(pw, is, os,PC+1);
userStack_top = SP;
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 24: //Pop return address from the stack, jump to the address
operand = popValueFromStack(pw, is, memory_reader, os);
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 25: //Increment the value in X
X++;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 26: //Decrement the value in X
X--;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 27: // Push AC onto stack
pushValueToStack(pw, is, os,AC);
PC++;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 28: //Pop from stack into AC
AC = popValueFromStack(pw, is, memory_reader, os);
PC++;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 29: // Int call. Set system mode, switch stack, push SP and PC, set new SP and PC
processingInterrupt = true;
userMode = false;
operand = SP;
SP = 2000;
pushValueToStack(pw, is, os, operand);
operand = PC + 1;
PC = 1500;
pushValueToStack(pw, is, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
break;
case 30: //Restore registers, set user mode
PC = popValueFromStack(pw, is, memory_reader, os);
SP = popValueFromStack(pw, is, memory_reader, os);
userMode = true;
num_of_instructions++;
processingInterrupt = false;
break;
case 50: // End Execution
if(processingInterrupt == false)
num_of_instructions++;
System.exit(0);
break;
default:
System.out.println("Unknown error - default");
System.exit(0);
break;
}
}
// function to check if user program if trying to access system memory and stack
private static void checkMemoryViolation(int address)
{
if(userMode && address > 1000)
{
System.out.println("Error: User tried to access system stack. Process exiting.");
System.exit(0);
}
}
// function to handle interrupts caused by the timer
private static void interruptFromTimer(PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
int operand;
userMode = false;
operand = SP;
SP = systemStack_top;
pushValueToStack(pw, is, os, operand);
operand = PC;
PC = 1000;
pushValueToStack(pw, is, os, operand);
}
// function to push a value to the appropriate stack
private static void pushValueToStack(PrintWriter pw, InputStream is, OutputStream os, int
value)
{
SP--;
writeToMemory(pw, is, os, SP, value);
}
// function to pop a value from the appropriate stack
private static int popValueFromStack(PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
int temp = readFromMemory(pw, is, memory_reader, os, SP);
writeToMemory(pw, is, os, SP, 0);
SP++;
return temp;
}
// function to debug program
/*private static void printDebug(String desc, int value)
{
System.out.println("");
System.out.println(desc);
System.out.println("PC = " + PC + " SP = " + SP + " AC = " + AC + " X = " + X + "
Y = " + Y);
System.out.println("instructions = " + num_of_instructions + " timerFlag = " +
timerFlag);
System.out.println("user mode = " + userMode + " value read from mem = " + value);
System.out.println("processing Interrupt = " + processingInterrupt);
}*/
}
--------------------------------------------------------------Memory.java--------------------------------------
---------------------------------------------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Memory
{
final static int [] memory = new int[2000]; // int array to implement memory
public static void main(String args[])
{
try
{
//Create a File object and a scanner to read it
Scanner CPU_reader = new Scanner(System.in);
File file = null;
if(CPU_reader.hasNextLine()) // read file name from CPU
{
file = new File(CPU_reader.nextLine());
if(!file.exists()) //exit if file not found
{
System.out.println("File not found");
System.exit(0);
}
}
// call function to read file and initialize memory array
readFile(file);
String line;
int temp2;
/*
This while loop will keep on reading instructions from the CPU process
and perform the read or write function appropriately
*/
while(true)
{
if(CPU_reader.hasNext())
{
line = CPU_reader.nextLine(); //read the comma delimited line sent by the CPU
if(!line.isEmpty())
{
String [] j = line.split(","); //split the line to get the necessary tokens
// if first token is 1 then CPU is requesting to read
// from an address
if(j[0].equals("1"))
{
temp2 = Integer.parseInt(j[1]);
System.out.println(read(temp2));// send requested data to CPU
}
// else it will be 2, which means CPu is requesting to
// write data at a particular address
else
{
int i1 = Integer.parseInt(j[1]);
int i2 = Integer.parseInt(j[2]);
write(i1,i2); // invoke the write function
}
}
else
break;
}
else
break;
}
} catch(NumberFormatException e)
{
e.printStackTrace();
}
}
// function to read the data in the address provided by the CPU
public static int read(int address)
{
return memory[address];
}
// function to write data into an address based on intruction given by CPU
public static void write(int address, int data)
{
memory[address] = data;
}
// function to read instructions from file and initialize memory
private static void readFile(File file) {
try
{
Scanner scanner = new Scanner(file);
String temp;
int temp_int;
int i = 0;
/*
* Read the file to load memory instructions
*/
while(scanner.hasNext())
{
//if integer found then write to memory array
if(scanner.hasNextInt())
{
temp_int = scanner.nextInt();
memory[i++] = temp_int;
}
else
{
temp = scanner.next();
// if token starts with ".", then move the counter appropriately
if(temp.charAt(0) == '.')
{
i = Integer.parseInt(temp.substring(1));
}
// else if the token is a comment then skip the line
else if(temp.equals("//"))
{
scanner.nextLine();
}
// skip the line if anything else
else
scanner.nextLine();
}
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
}
Solution
-----------------------------------------------------CPU.java---------------------------------------------------
--------------------------------------------------------
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class CPU
{
/*
Declare required registers
*/
static int PC = 0, SP = 1000, IR, AC, X, Y, timerFlag, num_of_instructions = 0;
static int systemStack_top = 2000, userStack_top = 1000;
static boolean userMode = true; // initially set it to true.
// On interrupt set it to false to indicate
//kernel mode
static boolean processingInterrupt = false; // flag to avoid nested interrupt execution
public static void main(String args[])
{
String fileName = null;
// check the command line argument length
if(args.length == 2)
{
fileName = args[0];
timerFlag = Integer.parseInt(args[1]); // set timer ineterrupt value
}
else // if incorrect number of parameters then exit
{
System.out.println("Incorrect number of parameters. Process ended.");
System.exit(0);
}
try
{
/*
Create child process and set up I/O streams
*/
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java Memory");
OutputStream os = proc.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = proc.getInputStream();
Scanner memory_reader = new Scanner(is); // direct input stream to a Scanner object
// Send file name to child process
fileNameToMemory(pw, is, os, fileName);
// this loop will keep the communication going between CPU and memory
while (true)
{
// check to see if timer interrupt has occured
if(num_of_instructions > 0
&& (num_of_instructions % timerFlag) == 0 && processingInterrupt == false)
{
// process the interrupt
processingInterrupt = true;
interruptFromTimer(pw, is, memory_reader, os);
}
// read instruction from memory
int value = readFromMemory(pw, is, memory_reader, os, PC);
if (value != -1)
{
processInstruction(value, pw, is, memory_reader, os);
}
else
break;
}
proc.waitFor();
int exitVal = proc.exitValue();
System.out.println("Process exited: " + exitVal);
}
catch (IOException | InterruptedException t)
{
t.printStackTrace();
}
}
/*
function to send file name to memory
*/
private static void fileNameToMemory(PrintWriter pw, InputStream is, OutputStream os,
String fileName)
{
pw.printf(fileName + " "); //send filename to memory
pw.flush();
}
// function to read data at given address from memory
private static int readFromMemory(PrintWriter pw, InputStream is, Scanner memory_reader,
OutputStream os, int address)
{
checkMemoryViolation(address);
pw.printf("1," + address + " ");
pw.flush();
if (memory_reader.hasNext())
{
String temp = memory_reader.next();
if(!temp.isEmpty())
{
int temp2 = Integer.parseInt(temp);
return (temp2);
}
}
return -1;
}
//function to tell child process to write data at the given address in memory
private static void writeToMemory(PrintWriter pw, InputStream is, OutputStream os, int
address, int data) {
pw.printf("2," + address + "," + data + " "); //2 at the start on string indicates write
pw.flush();
}
// function to process an instruction received from the memory
private static void processInstruction(int value, PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
IR = value; //store instruction in Instruction register
int operand; //to store operand
switch(IR)
{
case 1: //Load the value into the AC
PC++; // increment counter to get operand
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = operand;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 2: // Load the value at the address into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 3: // Load the value from the address found in the address into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
operand = readFromMemory(pw, is, memory_reader, os, operand);
AC = readFromMemory(pw, is, memory_reader, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 4: // Load the value at (address+X) into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand + X);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 5: //Load the value at (address+Y) into the AC
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
AC = readFromMemory(pw, is, memory_reader, os, operand + Y);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 6: //Load from (Sp+X) into the AC
AC = readFromMemory(pw, is, memory_reader, os, SP + X);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 7: //Store the value in the AC into the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
writeToMemory(pw, is, os, operand, AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 8: //Gets a random int from 1 to 100 into the AC
Random r = new Random();
int i = r.nextInt(100) + 1;
AC = i;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 9: //If port=1, writes AC as an int to the screen
//If port=2, writes AC as a char to the screen
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if(operand == 1)
{
System.out.print(AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
}
else if (operand == 2)
{
System.out.print((char)AC);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
}
else
{
System.out.println("Error: Port = " + operand);
if(processingInterrupt == false)
num_of_instructions++;
PC++;
System.exit(0);
break;
}
case 10: // Add the value in X to the AC
AC = AC + X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 11: //Add the value in Y to the AC
AC = AC + Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 12: //Subtract the value in X from the AC
AC = AC - X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 13: //Subtract the value in Y from the AC
AC = AC - Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 14: //Copy the value in the AC to X
X = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 15: //Copy the value in X to the AC
AC = X;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 16: //Copy the value in the AC to Y
Y = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 17: //Copy the value in Y to the AC
AC = Y;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 18: //Copy the value in AC to the SP
SP = AC;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 19: //Copy the value in SP to the AC
AC = SP;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 20: // Jump to the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 21: // Jump to the address only if the value in the AC is zero
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if (AC == 0)
{
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
}
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 22: // Jump to the address only if the value in the AC is not zero
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
if (AC != 0)
{
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
}
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 23: //Push return address onto stack, jump to the address
PC++;
operand = readFromMemory(pw, is, memory_reader, os, PC);
pushValueToStack(pw, is, os,PC+1);
userStack_top = SP;
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 24: //Pop return address from the stack, jump to the address
operand = popValueFromStack(pw, is, memory_reader, os);
PC = operand;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 25: //Increment the value in X
X++;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 26: //Decrement the value in X
X--;
if(processingInterrupt == false)
num_of_instructions++;
PC++;
break;
case 27: // Push AC onto stack
pushValueToStack(pw, is, os,AC);
PC++;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 28: //Pop from stack into AC
AC = popValueFromStack(pw, is, memory_reader, os);
PC++;
if(processingInterrupt == false)
num_of_instructions++;
break;
case 29: // Int call. Set system mode, switch stack, push SP and PC, set new SP and PC
processingInterrupt = true;
userMode = false;
operand = SP;
SP = 2000;
pushValueToStack(pw, is, os, operand);
operand = PC + 1;
PC = 1500;
pushValueToStack(pw, is, os, operand);
if(processingInterrupt == false)
num_of_instructions++;
break;
case 30: //Restore registers, set user mode
PC = popValueFromStack(pw, is, memory_reader, os);
SP = popValueFromStack(pw, is, memory_reader, os);
userMode = true;
num_of_instructions++;
processingInterrupt = false;
break;
case 50: // End Execution
if(processingInterrupt == false)
num_of_instructions++;
System.exit(0);
break;
default:
System.out.println("Unknown error - default");
System.exit(0);
break;
}
}
// function to check if user program if trying to access system memory and stack
private static void checkMemoryViolation(int address)
{
if(userMode && address > 1000)
{
System.out.println("Error: User tried to access system stack. Process exiting.");
System.exit(0);
}
}
// function to handle interrupts caused by the timer
private static void interruptFromTimer(PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
int operand;
userMode = false;
operand = SP;
SP = systemStack_top;
pushValueToStack(pw, is, os, operand);
operand = PC;
PC = 1000;
pushValueToStack(pw, is, os, operand);
}
// function to push a value to the appropriate stack
private static void pushValueToStack(PrintWriter pw, InputStream is, OutputStream os, int
value)
{
SP--;
writeToMemory(pw, is, os, SP, value);
}
// function to pop a value from the appropriate stack
private static int popValueFromStack(PrintWriter pw, InputStream is, Scanner
memory_reader, OutputStream os)
{
int temp = readFromMemory(pw, is, memory_reader, os, SP);
writeToMemory(pw, is, os, SP, 0);
SP++;
return temp;
}
// function to debug program
/*private static void printDebug(String desc, int value)
{
System.out.println("");
System.out.println(desc);
System.out.println("PC = " + PC + " SP = " + SP + " AC = " + AC + " X = " + X + "
Y = " + Y);
System.out.println("instructions = " + num_of_instructions + " timerFlag = " +
timerFlag);
System.out.println("user mode = " + userMode + " value read from mem = " + value);
System.out.println("processing Interrupt = " + processingInterrupt);
}*/
}
--------------------------------------------------------------Memory.java--------------------------------------
---------------------------------------------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Memory
{
final static int [] memory = new int[2000]; // int array to implement memory
public static void main(String args[])
{
try
{
//Create a File object and a scanner to read it
Scanner CPU_reader = new Scanner(System.in);
File file = null;
if(CPU_reader.hasNextLine()) // read file name from CPU
{
file = new File(CPU_reader.nextLine());
if(!file.exists()) //exit if file not found
{
System.out.println("File not found");
System.exit(0);
}
}
// call function to read file and initialize memory array
readFile(file);
String line;
int temp2;
/*
This while loop will keep on reading instructions from the CPU process
and perform the read or write function appropriately
*/
while(true)
{
if(CPU_reader.hasNext())
{
line = CPU_reader.nextLine(); //read the comma delimited line sent by the CPU
if(!line.isEmpty())
{
String [] j = line.split(","); //split the line to get the necessary tokens
// if first token is 1 then CPU is requesting to read
// from an address
if(j[0].equals("1"))
{
temp2 = Integer.parseInt(j[1]);
System.out.println(read(temp2));// send requested data to CPU
}
// else it will be 2, which means CPu is requesting to
// write data at a particular address
else
{
int i1 = Integer.parseInt(j[1]);
int i2 = Integer.parseInt(j[2]);
write(i1,i2); // invoke the write function
}
}
else
break;
}
else
break;
}
} catch(NumberFormatException e)
{
e.printStackTrace();
}
}
// function to read the data in the address provided by the CPU
public static int read(int address)
{
return memory[address];
}
// function to write data into an address based on intruction given by CPU
public static void write(int address, int data)
{
memory[address] = data;
}
// function to read instructions from file and initialize memory
private static void readFile(File file) {
try
{
Scanner scanner = new Scanner(file);
String temp;
int temp_int;
int i = 0;
/*
* Read the file to load memory instructions
*/
while(scanner.hasNext())
{
//if integer found then write to memory array
if(scanner.hasNextInt())
{
temp_int = scanner.nextInt();
memory[i++] = temp_int;
}
else
{
temp = scanner.next();
// if token starts with ".", then move the counter appropriately
if(temp.charAt(0) == '.')
{
i = Integer.parseInt(temp.substring(1));
}
// else if the token is a comment then skip the line
else if(temp.equals("//"))
{
scanner.nextLine();
}
// skip the line if anything else
else
scanner.nextLine();
}
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
}

More Related Content

Similar to -----------------------------------------------------CPU.java------.pdf

Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bwjktjpc
 
망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15종인 전
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++mustkeem khan
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diplomamustkeem khan
 
OSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionOSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionShuya Osaki
 
The following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdfThe following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdfmarketing413921
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and CEleanor McHugh
 
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docxkatherncarlyle
 
codings related to avr micro controller
codings related to avr micro controllercodings related to avr micro controller
codings related to avr micro controllerSyed Ghufran Hassan
 
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxcmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxgordienaysmythe
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processorDhaval Kaneria
 
start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()Kiwamu Okabe
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptkinan keshkeh
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptkinan keshkeh
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - CompilationsHSA Foundation
 

Similar to -----------------------------------------------------CPU.java------.pdf (20)

Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bw
 
망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15망고100 보드로 놀아보자 15
망고100 보드로 놀아보자 15
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
 
OSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionOSTEP Chapter2 Introduction
OSTEP Chapter2 Introduction
 
The following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdfThe following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdf
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx
#define ENABLE_COMMANDER#define ENABLE_REPORTER#include c.docx
 
runtimestack
runtimestackruntimestack
runtimestack
 
codings related to avr micro controller
codings related to avr micro controllercodings related to avr micro controller
codings related to avr micro controller
 
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docxcmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
 
Buffer OverFlow
Buffer OverFlowBuffer OverFlow
Buffer OverFlow
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processor
 
start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()start_printf: dev/ic/com.c comstart()
start_printf: dev/ic/com.c comstart()
 
Yg byev2e
Yg byev2eYg byev2e
Yg byev2e
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Shapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop conceptShapes and calculate (area and contour) / C++ oop concept
Shapes and calculate (area and contour) / C++ oop concept
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
 

More from annikasarees

You will want to look at electronegativity differ.pdf
                     You will want to look at electronegativity differ.pdf                     You will want to look at electronegativity differ.pdf
You will want to look at electronegativity differ.pdfannikasarees
 
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf
Well 1-Heptanol is a straight chained 7 carbon mo.pdfannikasarees
 
The rings cannot attach to each other on C atoms .pdf
                     The rings cannot attach to each other on C atoms .pdf                     The rings cannot attach to each other on C atoms .pdf
The rings cannot attach to each other on C atoms .pdfannikasarees
 
Waters bent structure leads to its polar nature.pdf
                     Waters bent structure leads to its polar nature.pdf                     Waters bent structure leads to its polar nature.pdf
Waters bent structure leads to its polar nature.pdfannikasarees
 
The given set of values cannot be represented as .pdf
                     The given set of values cannot be represented as .pdf                     The given set of values cannot be represented as .pdf
The given set of values cannot be represented as .pdfannikasarees
 
Solution containing HCN and NaCN in ions form as .pdf
                     Solution containing HCN and NaCN in ions form as .pdf                     Solution containing HCN and NaCN in ions form as .pdf
Solution containing HCN and NaCN in ions form as .pdfannikasarees
 
moles = molarity x volume = 6 molL x (51000) L .pdf
                     moles = molarity x volume = 6 molL x (51000) L .pdf                     moles = molarity x volume = 6 molL x (51000) L .pdf
moles = molarity x volume = 6 molL x (51000) L .pdfannikasarees
 
Molarity = moles volume(liter) Moles = molarity.pdf
                     Molarity = moles volume(liter)  Moles = molarity.pdf                     Molarity = moles volume(liter)  Moles = molarity.pdf
Molarity = moles volume(liter) Moles = molarity.pdfannikasarees
 
lone pairs of electrons also occupy the orbitals .pdf
                     lone pairs of electrons also occupy the orbitals .pdf                     lone pairs of electrons also occupy the orbitals .pdf
lone pairs of electrons also occupy the orbitals .pdfannikasarees
 
What is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfWhat is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfannikasarees
 
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfYes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfannikasarees
 
The transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfThe transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfannikasarees
 
the issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfthe issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfannikasarees
 
Statement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfStatement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfannikasarees
 
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfSummary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfannikasarees
 
SolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfSolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfannikasarees
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfannikasarees
 
please give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfplease give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfannikasarees
 
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfPetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfannikasarees
 

More from annikasarees (20)

You will want to look at electronegativity differ.pdf
                     You will want to look at electronegativity differ.pdf                     You will want to look at electronegativity differ.pdf
You will want to look at electronegativity differ.pdf
 
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf                     Well 1-Heptanol is a straight chained 7 carbon mo.pdf
Well 1-Heptanol is a straight chained 7 carbon mo.pdf
 
The rings cannot attach to each other on C atoms .pdf
                     The rings cannot attach to each other on C atoms .pdf                     The rings cannot attach to each other on C atoms .pdf
The rings cannot attach to each other on C atoms .pdf
 
Waters bent structure leads to its polar nature.pdf
                     Waters bent structure leads to its polar nature.pdf                     Waters bent structure leads to its polar nature.pdf
Waters bent structure leads to its polar nature.pdf
 
The given set of values cannot be represented as .pdf
                     The given set of values cannot be represented as .pdf                     The given set of values cannot be represented as .pdf
The given set of values cannot be represented as .pdf
 
Solution containing HCN and NaCN in ions form as .pdf
                     Solution containing HCN and NaCN in ions form as .pdf                     Solution containing HCN and NaCN in ions form as .pdf
Solution containing HCN and NaCN in ions form as .pdf
 
moles = molarity x volume = 6 molL x (51000) L .pdf
                     moles = molarity x volume = 6 molL x (51000) L .pdf                     moles = molarity x volume = 6 molL x (51000) L .pdf
moles = molarity x volume = 6 molL x (51000) L .pdf
 
Molarity = moles volume(liter) Moles = molarity.pdf
                     Molarity = moles volume(liter)  Moles = molarity.pdf                     Molarity = moles volume(liter)  Moles = molarity.pdf
Molarity = moles volume(liter) Moles = molarity.pdf
 
lone pairs of electrons also occupy the orbitals .pdf
                     lone pairs of electrons also occupy the orbitals .pdf                     lone pairs of electrons also occupy the orbitals .pdf
lone pairs of electrons also occupy the orbitals .pdf
 
What is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdfWhat is the relationship between Accounting and an Accounting inform.pdf
What is the relationship between Accounting and an Accounting inform.pdf
 
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdfYes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
Yes,all macromolecule are passed from nuclear pore envelope to cytop.pdf
 
The transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdfThe transport of sodium ions and glucose into the cell is through sy.pdf
The transport of sodium ions and glucose into the cell is through sy.pdf
 
the issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdfthe issue of camera and cell phone privecy is importent many cell ph.pdf
the issue of camera and cell phone privecy is importent many cell ph.pdf
 
Statement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdfStatement showing distribution of income to XavierThus answer will.pdf
Statement showing distribution of income to XavierThus answer will.pdf
 
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfSummary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
 
SolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdfSolutionBy observing the graph , the graph the given function is .pdf
SolutionBy observing the graph , the graph the given function is .pdf
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdf
 
F(-) Sol.pdf
                     F(-)                                      Sol.pdf                     F(-)                                      Sol.pdf
F(-) Sol.pdf
 
please give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdfplease give the name of author so that i can give u solution manual .pdf
please give the name of author so that i can give u solution manual .pdf
 
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdfPetTest.javaimport java.util.Scanner; public class PetTest {.pdf
PetTest.javaimport java.util.Scanner; public class PetTest {.pdf
 

Recently uploaded

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

-----------------------------------------------------CPU.java------.pdf

  • 1. -----------------------------------------------------CPU.java--------------------------------------------------- -------------------------------------------------------- import java.io.*; import java.util.Random; import java.util.Scanner; public class CPU { /* Declare required registers */ static int PC = 0, SP = 1000, IR, AC, X, Y, timerFlag, num_of_instructions = 0; static int systemStack_top = 2000, userStack_top = 1000; static boolean userMode = true; // initially set it to true. // On interrupt set it to false to indicate //kernel mode static boolean processingInterrupt = false; // flag to avoid nested interrupt execution public static void main(String args[]) { String fileName = null; // check the command line argument length if(args.length == 2) { fileName = args[0]; timerFlag = Integer.parseInt(args[1]); // set timer ineterrupt value } else // if incorrect number of parameters then exit { System.out.println("Incorrect number of parameters. Process ended."); System.exit(0); } try
  • 2. { /* Create child process and set up I/O streams */ Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("java Memory"); OutputStream os = proc.getOutputStream(); PrintWriter pw = new PrintWriter(os); InputStream is = proc.getInputStream(); Scanner memory_reader = new Scanner(is); // direct input stream to a Scanner object // Send file name to child process fileNameToMemory(pw, is, os, fileName); // this loop will keep the communication going between CPU and memory while (true) { // check to see if timer interrupt has occured if(num_of_instructions > 0 && (num_of_instructions % timerFlag) == 0 && processingInterrupt == false) { // process the interrupt processingInterrupt = true; interruptFromTimer(pw, is, memory_reader, os); } // read instruction from memory int value = readFromMemory(pw, is, memory_reader, os, PC); if (value != -1) { processInstruction(value, pw, is, memory_reader, os); } else break;
  • 3. } proc.waitFor(); int exitVal = proc.exitValue(); System.out.println("Process exited: " + exitVal); } catch (IOException | InterruptedException t) { t.printStackTrace(); } } /* function to send file name to memory */ private static void fileNameToMemory(PrintWriter pw, InputStream is, OutputStream os, String fileName) { pw.printf(fileName + " "); //send filename to memory pw.flush(); } // function to read data at given address from memory private static int readFromMemory(PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os, int address) { checkMemoryViolation(address); pw.printf("1," + address + " "); pw.flush(); if (memory_reader.hasNext()) { String temp = memory_reader.next(); if(!temp.isEmpty()) { int temp2 = Integer.parseInt(temp); return (temp2); } }
  • 4. return -1; } //function to tell child process to write data at the given address in memory private static void writeToMemory(PrintWriter pw, InputStream is, OutputStream os, int address, int data) { pw.printf("2," + address + "," + data + " "); //2 at the start on string indicates write pw.flush(); } // function to process an instruction received from the memory private static void processInstruction(int value, PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os) { IR = value; //store instruction in Instruction register int operand; //to store operand switch(IR) { case 1: //Load the value into the AC PC++; // increment counter to get operand operand = readFromMemory(pw, is, memory_reader, os, PC); AC = operand; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 2: // Load the value at the address into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 3: // Load the value from the address found in the address into the AC
  • 5. PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); operand = readFromMemory(pw, is, memory_reader, os, operand); AC = readFromMemory(pw, is, memory_reader, os, operand); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 4: // Load the value at (address+X) into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand + X); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 5: //Load the value at (address+Y) into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand + Y); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 6: //Load from (Sp+X) into the AC AC = readFromMemory(pw, is, memory_reader, os, SP + X); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 7: //Store the value in the AC into the address
  • 6. PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); writeToMemory(pw, is, os, operand, AC); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 8: //Gets a random int from 1 to 100 into the AC Random r = new Random(); int i = r.nextInt(100) + 1; AC = i; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 9: //If port=1, writes AC as an int to the screen //If port=2, writes AC as a char to the screen PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); if(operand == 1) { System.out.print(AC); if(processingInterrupt == false) num_of_instructions++; PC++; break; } else if (operand == 2) { System.out.print((char)AC); if(processingInterrupt == false) num_of_instructions++; PC++; break;
  • 7. } else { System.out.println("Error: Port = " + operand); if(processingInterrupt == false) num_of_instructions++; PC++; System.exit(0); break; } case 10: // Add the value in X to the AC AC = AC + X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 11: //Add the value in Y to the AC AC = AC + Y; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 12: //Subtract the value in X from the AC AC = AC - X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 13: //Subtract the value in Y from the AC AC = AC - Y; if(processingInterrupt == false) num_of_instructions++; PC++;
  • 8. break; case 14: //Copy the value in the AC to X X = AC; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 15: //Copy the value in X to the AC AC = X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 16: //Copy the value in the AC to Y Y = AC; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 17: //Copy the value in Y to the AC AC = Y; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 18: //Copy the value in AC to the SP SP = AC; if(processingInterrupt == false) num_of_instructions++; PC++;
  • 9. break; case 19: //Copy the value in SP to the AC AC = SP; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 20: // Jump to the address PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 21: // Jump to the address only if the value in the AC is zero PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); if (AC == 0) { PC = operand; if(processingInterrupt == false) num_of_instructions++; break; } if(processingInterrupt == false) num_of_instructions++; PC++; break; case 22: // Jump to the address only if the value in the AC is not zero PC++; operand = readFromMemory(pw, is, memory_reader, os, PC);
  • 10. if (AC != 0) { PC = operand; if(processingInterrupt == false) num_of_instructions++; break; } if(processingInterrupt == false) num_of_instructions++; PC++; break; case 23: //Push return address onto stack, jump to the address PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); pushValueToStack(pw, is, os,PC+1); userStack_top = SP; PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 24: //Pop return address from the stack, jump to the address operand = popValueFromStack(pw, is, memory_reader, os); PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 25: //Increment the value in X X++; if(processingInterrupt == false) num_of_instructions++; PC++; break;
  • 11. case 26: //Decrement the value in X X--; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 27: // Push AC onto stack pushValueToStack(pw, is, os,AC); PC++; if(processingInterrupt == false) num_of_instructions++; break; case 28: //Pop from stack into AC AC = popValueFromStack(pw, is, memory_reader, os); PC++; if(processingInterrupt == false) num_of_instructions++; break; case 29: // Int call. Set system mode, switch stack, push SP and PC, set new SP and PC processingInterrupt = true; userMode = false; operand = SP; SP = 2000; pushValueToStack(pw, is, os, operand); operand = PC + 1; PC = 1500; pushValueToStack(pw, is, os, operand); if(processingInterrupt == false) num_of_instructions++;
  • 12. break; case 30: //Restore registers, set user mode PC = popValueFromStack(pw, is, memory_reader, os); SP = popValueFromStack(pw, is, memory_reader, os); userMode = true; num_of_instructions++; processingInterrupt = false; break; case 50: // End Execution if(processingInterrupt == false) num_of_instructions++; System.exit(0); break; default: System.out.println("Unknown error - default"); System.exit(0); break; } } // function to check if user program if trying to access system memory and stack private static void checkMemoryViolation(int address) { if(userMode && address > 1000) { System.out.println("Error: User tried to access system stack. Process exiting."); System.exit(0); } } // function to handle interrupts caused by the timer
  • 13. private static void interruptFromTimer(PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os) { int operand; userMode = false; operand = SP; SP = systemStack_top; pushValueToStack(pw, is, os, operand); operand = PC; PC = 1000; pushValueToStack(pw, is, os, operand); } // function to push a value to the appropriate stack private static void pushValueToStack(PrintWriter pw, InputStream is, OutputStream os, int value) { SP--; writeToMemory(pw, is, os, SP, value); } // function to pop a value from the appropriate stack private static int popValueFromStack(PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os) { int temp = readFromMemory(pw, is, memory_reader, os, SP); writeToMemory(pw, is, os, SP, 0); SP++; return temp; } // function to debug program /*private static void printDebug(String desc, int value) { System.out.println(""); System.out.println(desc); System.out.println("PC = " + PC + " SP = " + SP + " AC = " + AC + " X = " + X + " Y = " + Y);
  • 14. System.out.println("instructions = " + num_of_instructions + " timerFlag = " + timerFlag); System.out.println("user mode = " + userMode + " value read from mem = " + value); System.out.println("processing Interrupt = " + processingInterrupt); }*/ } --------------------------------------------------------------Memory.java-------------------------------------- --------------------------------------------------- import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Memory { final static int [] memory = new int[2000]; // int array to implement memory public static void main(String args[]) { try { //Create a File object and a scanner to read it Scanner CPU_reader = new Scanner(System.in); File file = null; if(CPU_reader.hasNextLine()) // read file name from CPU { file = new File(CPU_reader.nextLine()); if(!file.exists()) //exit if file not found { System.out.println("File not found"); System.exit(0); } } // call function to read file and initialize memory array
  • 15. readFile(file); String line; int temp2; /* This while loop will keep on reading instructions from the CPU process and perform the read or write function appropriately */ while(true) { if(CPU_reader.hasNext()) { line = CPU_reader.nextLine(); //read the comma delimited line sent by the CPU if(!line.isEmpty()) { String [] j = line.split(","); //split the line to get the necessary tokens // if first token is 1 then CPU is requesting to read // from an address if(j[0].equals("1")) { temp2 = Integer.parseInt(j[1]); System.out.println(read(temp2));// send requested data to CPU } // else it will be 2, which means CPu is requesting to // write data at a particular address else { int i1 = Integer.parseInt(j[1]); int i2 = Integer.parseInt(j[2]); write(i1,i2); // invoke the write function } } else break; }
  • 16. else break; } } catch(NumberFormatException e) { e.printStackTrace(); } } // function to read the data in the address provided by the CPU public static int read(int address) { return memory[address]; } // function to write data into an address based on intruction given by CPU public static void write(int address, int data) { memory[address] = data; } // function to read instructions from file and initialize memory private static void readFile(File file) { try { Scanner scanner = new Scanner(file); String temp; int temp_int; int i = 0; /* * Read the file to load memory instructions */ while(scanner.hasNext()) { //if integer found then write to memory array
  • 17. if(scanner.hasNextInt()) { temp_int = scanner.nextInt(); memory[i++] = temp_int; } else { temp = scanner.next(); // if token starts with ".", then move the counter appropriately if(temp.charAt(0) == '.') { i = Integer.parseInt(temp.substring(1)); } // else if the token is a comment then skip the line else if(temp.equals("//")) { scanner.nextLine(); } // skip the line if anything else else scanner.nextLine(); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } Solution
  • 18. -----------------------------------------------------CPU.java--------------------------------------------------- -------------------------------------------------------- import java.io.*; import java.util.Random; import java.util.Scanner; public class CPU { /* Declare required registers */ static int PC = 0, SP = 1000, IR, AC, X, Y, timerFlag, num_of_instructions = 0; static int systemStack_top = 2000, userStack_top = 1000; static boolean userMode = true; // initially set it to true. // On interrupt set it to false to indicate //kernel mode static boolean processingInterrupt = false; // flag to avoid nested interrupt execution public static void main(String args[]) { String fileName = null; // check the command line argument length if(args.length == 2) { fileName = args[0]; timerFlag = Integer.parseInt(args[1]); // set timer ineterrupt value } else // if incorrect number of parameters then exit { System.out.println("Incorrect number of parameters. Process ended."); System.exit(0); } try {
  • 19. /* Create child process and set up I/O streams */ Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("java Memory"); OutputStream os = proc.getOutputStream(); PrintWriter pw = new PrintWriter(os); InputStream is = proc.getInputStream(); Scanner memory_reader = new Scanner(is); // direct input stream to a Scanner object // Send file name to child process fileNameToMemory(pw, is, os, fileName); // this loop will keep the communication going between CPU and memory while (true) { // check to see if timer interrupt has occured if(num_of_instructions > 0 && (num_of_instructions % timerFlag) == 0 && processingInterrupt == false) { // process the interrupt processingInterrupt = true; interruptFromTimer(pw, is, memory_reader, os); } // read instruction from memory int value = readFromMemory(pw, is, memory_reader, os, PC); if (value != -1) { processInstruction(value, pw, is, memory_reader, os); } else break; }
  • 20. proc.waitFor(); int exitVal = proc.exitValue(); System.out.println("Process exited: " + exitVal); } catch (IOException | InterruptedException t) { t.printStackTrace(); } } /* function to send file name to memory */ private static void fileNameToMemory(PrintWriter pw, InputStream is, OutputStream os, String fileName) { pw.printf(fileName + " "); //send filename to memory pw.flush(); } // function to read data at given address from memory private static int readFromMemory(PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os, int address) { checkMemoryViolation(address); pw.printf("1," + address + " "); pw.flush(); if (memory_reader.hasNext()) { String temp = memory_reader.next(); if(!temp.isEmpty()) { int temp2 = Integer.parseInt(temp); return (temp2); } } return -1;
  • 21. } //function to tell child process to write data at the given address in memory private static void writeToMemory(PrintWriter pw, InputStream is, OutputStream os, int address, int data) { pw.printf("2," + address + "," + data + " "); //2 at the start on string indicates write pw.flush(); } // function to process an instruction received from the memory private static void processInstruction(int value, PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os) { IR = value; //store instruction in Instruction register int operand; //to store operand switch(IR) { case 1: //Load the value into the AC PC++; // increment counter to get operand operand = readFromMemory(pw, is, memory_reader, os, PC); AC = operand; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 2: // Load the value at the address into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 3: // Load the value from the address found in the address into the AC PC++;
  • 22. operand = readFromMemory(pw, is, memory_reader, os, PC); operand = readFromMemory(pw, is, memory_reader, os, operand); AC = readFromMemory(pw, is, memory_reader, os, operand); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 4: // Load the value at (address+X) into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand + X); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 5: //Load the value at (address+Y) into the AC PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); AC = readFromMemory(pw, is, memory_reader, os, operand + Y); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 6: //Load from (Sp+X) into the AC AC = readFromMemory(pw, is, memory_reader, os, SP + X); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 7: //Store the value in the AC into the address PC++;
  • 23. operand = readFromMemory(pw, is, memory_reader, os, PC); writeToMemory(pw, is, os, operand, AC); if(processingInterrupt == false) num_of_instructions++; PC++; break; case 8: //Gets a random int from 1 to 100 into the AC Random r = new Random(); int i = r.nextInt(100) + 1; AC = i; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 9: //If port=1, writes AC as an int to the screen //If port=2, writes AC as a char to the screen PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); if(operand == 1) { System.out.print(AC); if(processingInterrupt == false) num_of_instructions++; PC++; break; } else if (operand == 2) { System.out.print((char)AC); if(processingInterrupt == false) num_of_instructions++; PC++; break; }
  • 24. else { System.out.println("Error: Port = " + operand); if(processingInterrupt == false) num_of_instructions++; PC++; System.exit(0); break; } case 10: // Add the value in X to the AC AC = AC + X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 11: //Add the value in Y to the AC AC = AC + Y; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 12: //Subtract the value in X from the AC AC = AC - X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 13: //Subtract the value in Y from the AC AC = AC - Y; if(processingInterrupt == false) num_of_instructions++; PC++; break;
  • 25. case 14: //Copy the value in the AC to X X = AC; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 15: //Copy the value in X to the AC AC = X; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 16: //Copy the value in the AC to Y Y = AC; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 17: //Copy the value in Y to the AC AC = Y; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 18: //Copy the value in AC to the SP SP = AC; if(processingInterrupt == false) num_of_instructions++; PC++; break;
  • 26. case 19: //Copy the value in SP to the AC AC = SP; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 20: // Jump to the address PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 21: // Jump to the address only if the value in the AC is zero PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); if (AC == 0) { PC = operand; if(processingInterrupt == false) num_of_instructions++; break; } if(processingInterrupt == false) num_of_instructions++; PC++; break; case 22: // Jump to the address only if the value in the AC is not zero PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); if (AC != 0)
  • 27. { PC = operand; if(processingInterrupt == false) num_of_instructions++; break; } if(processingInterrupt == false) num_of_instructions++; PC++; break; case 23: //Push return address onto stack, jump to the address PC++; operand = readFromMemory(pw, is, memory_reader, os, PC); pushValueToStack(pw, is, os,PC+1); userStack_top = SP; PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 24: //Pop return address from the stack, jump to the address operand = popValueFromStack(pw, is, memory_reader, os); PC = operand; if(processingInterrupt == false) num_of_instructions++; break; case 25: //Increment the value in X X++; if(processingInterrupt == false) num_of_instructions++; PC++; break;
  • 28. case 26: //Decrement the value in X X--; if(processingInterrupt == false) num_of_instructions++; PC++; break; case 27: // Push AC onto stack pushValueToStack(pw, is, os,AC); PC++; if(processingInterrupt == false) num_of_instructions++; break; case 28: //Pop from stack into AC AC = popValueFromStack(pw, is, memory_reader, os); PC++; if(processingInterrupt == false) num_of_instructions++; break; case 29: // Int call. Set system mode, switch stack, push SP and PC, set new SP and PC processingInterrupt = true; userMode = false; operand = SP; SP = 2000; pushValueToStack(pw, is, os, operand); operand = PC + 1; PC = 1500; pushValueToStack(pw, is, os, operand); if(processingInterrupt == false) num_of_instructions++;
  • 29. break; case 30: //Restore registers, set user mode PC = popValueFromStack(pw, is, memory_reader, os); SP = popValueFromStack(pw, is, memory_reader, os); userMode = true; num_of_instructions++; processingInterrupt = false; break; case 50: // End Execution if(processingInterrupt == false) num_of_instructions++; System.exit(0); break; default: System.out.println("Unknown error - default"); System.exit(0); break; } } // function to check if user program if trying to access system memory and stack private static void checkMemoryViolation(int address) { if(userMode && address > 1000) { System.out.println("Error: User tried to access system stack. Process exiting."); System.exit(0); } } // function to handle interrupts caused by the timer private static void interruptFromTimer(PrintWriter pw, InputStream is, Scanner
  • 30. memory_reader, OutputStream os) { int operand; userMode = false; operand = SP; SP = systemStack_top; pushValueToStack(pw, is, os, operand); operand = PC; PC = 1000; pushValueToStack(pw, is, os, operand); } // function to push a value to the appropriate stack private static void pushValueToStack(PrintWriter pw, InputStream is, OutputStream os, int value) { SP--; writeToMemory(pw, is, os, SP, value); } // function to pop a value from the appropriate stack private static int popValueFromStack(PrintWriter pw, InputStream is, Scanner memory_reader, OutputStream os) { int temp = readFromMemory(pw, is, memory_reader, os, SP); writeToMemory(pw, is, os, SP, 0); SP++; return temp; } // function to debug program /*private static void printDebug(String desc, int value) { System.out.println(""); System.out.println(desc); System.out.println("PC = " + PC + " SP = " + SP + " AC = " + AC + " X = " + X + " Y = " + Y); System.out.println("instructions = " + num_of_instructions + " timerFlag = " +
  • 31. timerFlag); System.out.println("user mode = " + userMode + " value read from mem = " + value); System.out.println("processing Interrupt = " + processingInterrupt); }*/ } --------------------------------------------------------------Memory.java-------------------------------------- --------------------------------------------------- import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Memory { final static int [] memory = new int[2000]; // int array to implement memory public static void main(String args[]) { try { //Create a File object and a scanner to read it Scanner CPU_reader = new Scanner(System.in); File file = null; if(CPU_reader.hasNextLine()) // read file name from CPU { file = new File(CPU_reader.nextLine()); if(!file.exists()) //exit if file not found { System.out.println("File not found"); System.exit(0); } } // call function to read file and initialize memory array readFile(file);
  • 32. String line; int temp2; /* This while loop will keep on reading instructions from the CPU process and perform the read or write function appropriately */ while(true) { if(CPU_reader.hasNext()) { line = CPU_reader.nextLine(); //read the comma delimited line sent by the CPU if(!line.isEmpty()) { String [] j = line.split(","); //split the line to get the necessary tokens // if first token is 1 then CPU is requesting to read // from an address if(j[0].equals("1")) { temp2 = Integer.parseInt(j[1]); System.out.println(read(temp2));// send requested data to CPU } // else it will be 2, which means CPu is requesting to // write data at a particular address else { int i1 = Integer.parseInt(j[1]); int i2 = Integer.parseInt(j[2]); write(i1,i2); // invoke the write function } } else break; } else
  • 33. break; } } catch(NumberFormatException e) { e.printStackTrace(); } } // function to read the data in the address provided by the CPU public static int read(int address) { return memory[address]; } // function to write data into an address based on intruction given by CPU public static void write(int address, int data) { memory[address] = data; } // function to read instructions from file and initialize memory private static void readFile(File file) { try { Scanner scanner = new Scanner(file); String temp; int temp_int; int i = 0; /* * Read the file to load memory instructions */ while(scanner.hasNext()) { //if integer found then write to memory array if(scanner.hasNextInt())
  • 34. { temp_int = scanner.nextInt(); memory[i++] = temp_int; } else { temp = scanner.next(); // if token starts with ".", then move the counter appropriately if(temp.charAt(0) == '.') { i = Integer.parseInt(temp.substring(1)); } // else if the token is a comment then skip the line else if(temp.equals("//")) { scanner.nextLine(); } // skip the line if anything else else scanner.nextLine(); } } } catch (FileNotFoundException ex) { ex.printStackTrace(); } } }