SlideShare a Scribd company logo
-----------------------------------------------------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_bw
jktjpc
 
망고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 Diploma
mustkeem khan
 
OSTEP Chapter2 Introduction
OSTEP Chapter2 IntroductionOSTEP Chapter2 Introduction
OSTEP Chapter2 Introduction
Shuya 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.pdf
marketing413921
 
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
Eleanor 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.docx
katherncarlyle
 
runtimestack
runtimestackruntimestack
runtimestack
Teddy Hsiung
 
codings related to avr micro controller
codings related to avr micro controllercodings related to avr micro controller
codings related to avr micro controller
Syed 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 .docx
gordienaysmythe
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
Dr Karthikeyan Periasamy
 
Buffer OverFlow
Buffer OverFlowBuffer OverFlow
Buffer OverFlow
Rambabu Duddukuri
 
8 bit single cycle processor
8 bit single cycle processor8 bit single cycle processor
8 bit single cycle processor
Dhaval 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
 
Yg byev2e
Yg byev2eYg byev2e
Yg byev2e
longphi2812
 
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
kinan keshkeh
 
Concurrency
ConcurrencyConcurrency
Concurrency
Mårten Rånge
 
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
kinan keshkeh
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
HSA 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.pdf
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
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
annikasarees
 
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdfSummary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
Summary of JavaScripthttpsen.wikipedia.orgwikiJavaScripthtt.pdf
annikasarees
 
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
annikasarees
 
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
annikasarees
 
F(-) Sol.pdf
                     F(-)                                      Sol.pdf                     F(-)                                      Sol.pdf
F(-) Sol.pdf
annikasarees
 
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
annikasarees
 
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
annikasarees
 

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

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 

Recently uploaded (20)

How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 

-----------------------------------------------------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(); } } }