-----------------------------------------------------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

PPTX
C Exam Help
PDF
Realization of an 8 bit pipelined microprocessor in verilog hdl
PPTX
C Homework Help
PPTX
PPT
W9_2: Jumps and loops
PDF
multi cycle in microprocessor 8086 sy B-tech
PDF
Computer Organization
PDF
Documento de acrobat2
C Exam Help
Realization of an 8 bit pipelined microprocessor in verilog hdl
C Homework Help
W9_2: Jumps and loops
multi cycle in microprocessor 8086 sy B-tech
Computer Organization
Documento de acrobat2

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

PDF
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
PDF
unit1.pdf
Ā 
PPTX
Introduction to Microprocesso programming and interfacing.pptx
PDF
Arduino
PDF
The ProblemUsing C programming language write a program that simul.pdf
PDF
PPT
Instructions_introductionM2.1.about.microcontrollerppt
PPTX
Assembly Language Compiler Implementation
PDF
Microprocessor 8086-lab-mannual
PPT
Al2ed chapter2
PDF
Maximizing CPU Efficiency: A Comprehensive Exploration of Pipelining in Compu...
DOCX
Microcontroller (8051) general and simple alp n cprograms
PPTX
Basic computer organization design
PDF
Interpreter, Compiler, JIT from scratch
PDF
8051 instruction set
PPT
8086 arch instns
PPT
B.sc cs-ii-u-2.2-overview of register transfer, micro operations and basic co...
PDF
ARM Holings presentation for the worldd.pdf
PPTX
Instructionsetof8086 by Alwani
PPTX
Memory Reference Instructions
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
unit1.pdf
Ā 
Introduction to Microprocesso programming and interfacing.pptx
Arduino
The ProblemUsing C programming language write a program that simul.pdf
Instructions_introductionM2.1.about.microcontrollerppt
Assembly Language Compiler Implementation
Microprocessor 8086-lab-mannual
Al2ed chapter2
Maximizing CPU Efficiency: A Comprehensive Exploration of Pipelining in Compu...
Microcontroller (8051) general and simple alp n cprograms
Basic computer organization design
Interpreter, Compiler, JIT from scratch
8051 instruction set
8086 arch instns
B.sc cs-ii-u-2.2-overview of register transfer, micro operations and basic co...
ARM Holings presentation for the worldd.pdf
Instructionsetof8086 by Alwani
Memory Reference Instructions

More from annikasarees (20)

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

Recently uploaded (20)

PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PPTX
Computer Architecture Input Output Memory.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
PDF
My India Quiz Book_20210205121199924.pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
Τίμαιος είναι Ļ†Ī¹Ī»ĪæĻƒĪæĻ†Ī¹ĪŗĻŒĻ‚ Γιάλογος του Πλάτωνα
PDF
HVAC Specification 2024 according to central public works department
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
Unit 4 Computer Architecture Multicore Processor.pptx
Environmental Education MCQ BD2EE - Share Source.pdf
B.Sc. DS Unit 2 Software Engineering.pptx
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
Computer Architecture Input Output Memory.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Cambridge-Practice-Tests-for-IELTS-12.docx
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Weekly quiz Compilation Jan -July 25.pdf
Hazard Identification & Risk Assessment .pdf
CHAPTER IV. MAN AND BIOSPHERE AND ITS TOTALITY.pptx
My India Quiz Book_20210205121199924.pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
What if we spent less time fighting change, and more time building what’s rig...
FORM 1 BIOLOGY MIND MAPS and their schemes
Τίμαιος είναι Ļ†Ī¹Ī»ĪæĻƒĪæĻ†Ī¹ĪŗĻŒĻ‚ Γιάλογος του Πλάτωνα
HVAC Specification 2024 according to central public works department
Share_Module_2_Power_conflict_and_negotiation.pptx
LDMMIA Reiki Yoga Finals Review Spring Summer

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