10
0

Added all codes.

This commit is contained in:
K
2025-01-07 22:00:12 +05:30
parent 5197bcdb76
commit c45d47e193
31 changed files with 1732 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
# Assignment-A1 - Pass 1 assembler
try:
source = open('source.txt','r')
data = source.read()
print('File read successfully\n\n')
source.seek(0)
except FileNotFoundError: #A little bit of exception handling
print('\n\n\nFile Not found. Create a source.txt first.\n\n\n ')
except IOError:
print('There was an IO error')
LT_index = 0 #index of LT table
ST_index = 0 #index of ST table
add = 0 # address in source code
MOT = {'STOP': '00','ADD': '01','SUB': '02','MULT': '03','MOVER': '04','MOVEM': '05','COMP': '06','BC': '07','DIV': '08','READ': '09','PRINT': '10','START': '01','END': '02','ORIGIN': '03','LTORG': '05','DS': '01','DC': '02','AREG,': '01','BREG,': '02','EQ':'01'}
ST = []
code=[]
LT=[]
MC = []
# LT, ST are lists of lists. code= intermediate code table
def classy(text):
'''This function will return the class of the word to be inputted in the Intermediate table'''
text = text.upper()
if text in ['STOP','ADD','SUB', 'MULT','MOVER','MOVEM','COMP','BC','DIV','READ', 'PRINT']:
return 'IS'
elif text in ['START','END','ORIGIN','LTORG']:
return 'AD'
elif text in ['DS','DC']:
return 'DL'
elif text in ['AREG,','BREG,']: return 'RG'
elif text in ['EQ']: return 'CC'
else: return 'None'
def handle_start():
'''This function gives you the starting address of the code'''
line= source.readline()
words=line.split()
if words[0].upper()=='START':
return int(words[1])
else:
print("No Start Statement! Abort!\n")
return 0
def pass1():
add=handle_start()
if not add:
print("Ending Pass 1 due to Above error.")
return
global ST_index, LT_index # to modify global variables, use global keyword
while True:
line=source.readline()# handlestart function reads line 1 and we start from the second line.
if not line:
break
words= line.split()
for w in words:
w=w.upper()
if w[0]=='=':
entry=[LT_index,w, add]
LT.append(entry)
LT_index +=1
elif classy(w)== 'None':
for term in ST:
if w== term[1]: break # I check if the label is already present in ST.
else:
entry=[ST_index,w, add]
ST.append(entry)
ST_index +=1
add+=1
print('LT:')
for a in LT:
print(a)
print('\n\n\nST:')
for a in ST:
print(a)
def intermediate():
source.seek(0)
while True:
entry=[]
ind = 0
line=source.readline()
if not line:
break
words=line.split()
for w in words:
w=w.upper()
if classy(w)!='None': #it is a directive
entry.append((classy(w),MOT[w]))
elif w[0]== '=': #it is a literal.
for a in LT:
if a[1]==w:
ind = a[0]
break
entry.append(('L',ind))
else: #it is a symbol
for a in ST:
if a[1]==w:
ind = a[0]
break
entry.append(('S',ind))
code.append(entry)
print("\nThe Intermediate code is:")
for entry in code:
print(entry)
pass1()
intermediate()
+4
View File
@@ -0,0 +1,4 @@
Start 100
Label MOVER AREG, =5
add areg, =999
sub breg, x
+35
View File
@@ -0,0 +1,35 @@
#include <jni.h>
#include <stdio.h>
#include "A3.h"
// NOTE: The contents of this file can be referenced from A3.h which is the generated header file
// Refer explanation for more info: https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/EXPLANATION.md
JNIEXPORT jint JNICALL Java_A3_add(JNIEnv *env, jobject obj, jint a, jint b) { // Function for addition
jint result = a + b;
printf("\n%d + %d = %d\n", a, b, result);
return result; // Return the result
}
JNIEXPORT jint JNICALL Java_A3_sub(JNIEnv *env, jobject obj, jint a, jint b) { // Function for subtraction
jint result = a - b;
printf("\n%d - %d = %d\n", a, b, result);
return result; // Return the result
}
JNIEXPORT jint JNICALL Java_A3_mul(JNIEnv *env, jobject obj, jint a, jint b) { // Function for multiplication
jint result = a * b;
printf("\n%d * %d = %d\n", a, b, result);
return result; // Return the result
}
JNIEXPORT jint JNICALL Java_A3_div(JNIEnv *env, jobject obj, jint a, jint b) { // Function for division
if (b == 0) {
printf("Error: Division by zero.\n");
return 0; // Return 0 or handle error appropriately
}
jint result = a / b;
printf("\n%d / %d = %d\n", a, b, result);
return result; // Return the result
}
+47
View File
@@ -0,0 +1,47 @@
// WARNING!!!
// THIS FILE IS INCLUDED ONLY FOR REFERENCE
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class A3 */
#ifndef _Included_A3
#define _Included_A3
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: A3
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_A3_add
(JNIEnv *, jobject, jint, jint);
/*
* Class: A3
* Method: sub
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_A3_sub
(JNIEnv *, jobject, jint, jint);
/*
* Class: A3
* Method: mul
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_A3_mul
(JNIEnv *, jobject, jint, jint);
/*
* Class: A3
* Method: div
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_A3_div
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
+67
View File
@@ -0,0 +1,67 @@
// Importing basic stuff
import java.io.*; // Used for I/O operations
import java.util.*; // Contains basic utilities
class A3 {
// Class name has to be same as file name for Java
static {
// Used for loading the .so (on Linux) or .dll (on Windows) file when running
// This is the main so called "dynamic library"
System.loadLibrary("A3");
}
// Function declaration
// private indicates the function is private, duh!
// Use of native indicates the function body will be written in a language other than Java, such as C/C++
private native int add(int a, int b); // For addition
private native int sub(int a, int b); // For subtraction
private native int mul(int a, int b); // For multiplication
private native int div(int a, int b); // For division
public static void main(String[] args) { // the main function
Scanner sc = new Scanner(System.in); // For taking input
int a, b;// Declaring variables for calculation
int choice = 0; // Declaring variable for switch-case
// Take input for a and b values
System.out.print("\nValue of a:\t");
a = sc.nextInt();
System.out.print("\nValue of b:\t");
b = sc.nextInt();
// Main menu
while (true) {
System.out.println("----- MAIN MENU -----");
System.out.println("1 -> Addition");
System.out.println("2 -> Subtraction");
System.out.println("3 -> Multiplication");
System.out.println("4 -> Division");
System.out.println("5 -> Exit");
System.out.println("Choose an option:\t");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Result: " + new A3().add(a, b));
break;
case 2:
System.out.println("Result: " + new A3().sub(a, b));
break;
case 3:
System.out.println("Result: " + new A3().mul(a, b));
break;
case 4:
System.out.println("Result: " + new A3().div(a, b));
break;
case 5:
System.out.println("## END OF CODE");
System.exit(0);
default:
System.out.println("Please choose a valid option.");
break;
}
}
}
}
@@ -0,0 +1,39 @@
# Explanation
This file contains explanation for dynamic linking library program (Assignment-A3)
---
Please note the files referred in this guide:
- [A3.java](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.java)
- [A3.c](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.c)
- [A3.h](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.h)
---
- We're using Java for writing the main program.
- To demonstrate Dynamic Linking Library (DLL) in Java, we'll be declaring functions in Java and implementing them in C (can be C/C++).
- First, we create a Java program `A3.java`,
- This is the main Java file containing function definition and the main function.
- Functions (add, sub, mul, div) in `A3` class in this file are native functions, meaning their body is written in C/C++ in a different file.
- After creating this file, you need to compile it. To do so, run `javac A3.java` (assuming you're already in the directory that contains this file).
- Now, we will generate the header file. For this, run `javac -h . A3.java`.
- There will be a new file called `A3.h` in your current working directory,
- This is the header file.
- It contains signatures for native functions we created in the Java file.
- Thus, there's **no need to memorized boilerplate in `A3.c`** since the functions defined in that file can be found in the header file. I have included the [A3.h](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.h) file in this folder for reference. Note that it is automatically generated.
- Create a new `A3.c` file which is the C program file containing function definitions (for add, sub, mul, div)
- Define all the functions (add, sub, mul, div)
- Then, we have to compile the C program file, i.e. `A3.c`. For this, run `gcc -shared -o libA3.so -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" A3.c`,
- `gcc` -> GNU compiler for C program
- `-shared` -> tells the compiler to create a shared file (.so) instead of a regular executable file
- `-o libA3.so` -> tells the compiler to save the output to `libA3.so` file
- `fPIC` -> stands for Position-Independent Code. Needed for creating shared libraries.
- `-I"$JAVA_HOME/include"` and `-I"$JAVA_HOME/include/linux"` -> `-I` flag used for specifiying directories to include. Values in double quotes are directories
- `A3.c` -> name of the C program file to compile
- Lastly, run the program using `java -Djava.library.path=. A3`
- `java` -> Loads Java Virtual Machine (JVM)
- `-Djava.library.path=.` -> `-D` is used to set a system property. In this case, were setting the `java.library.path` (for .so or .dll files) property.
- `A3` -> name of the Java class containing the main method
---
+69
View File
@@ -0,0 +1,69 @@
## Steps to run this code
These are the steps to run code for Assignment-A3.
---
### Refer [EXPLANATION](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/EXPLANATION.md) to understand how everything works.
> [!IMPORTANT]
> Tested on Linux and Windows.
### Prerequisites
1. open-jdk (version 11 or higher)
2. gcc
3. Set open-jdk and gcc as environment variables using bin folder in path (For Windows Users only)
4. Common sense
### Steps For Linux
1. Compile `A3.java`:
```shell
javac A3.java
```
2. Generate header file:
```shell
javac -h . A3.java
```
3. Compile C code:
```shell
gcc -shared -o libA3.so -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" A3.c
```
> [!NOTE]
> If you get an error saying _"fatal error: jni.h: No such file or directory"_, this might be because you haven't set `$JAVA_HOME` environment variable. Usually JVM stuff is in `/usr/lib/jvm/java-<version>-openjdk-amd64`. To set `JAVA_HOME` environment variable, run: `export $JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64` (for version 17, adjust for your version accordingly.)
4. Run program:
```shell
java -Djava.library.path=. A3
```
### Steps For Windows
1. Compile `A3.java`:
```shell
javac A3.java
```
2. Generate header file:
```shell
javac -h . A3.java
```
3. Set `JAVA_HOME` to the path of your jdk file location:
> Note that this is my file location for jdk. It may differ for you.
```shell
set JAVA_HOME=C:\Program Files\openjdk-23.0.1_windows-x64_bin\jdk-23.0.1
```
4. Compile C code:
```shell
gcc -shared -o A3.dll -fPIC -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" A3.c
```
5. Run program:
```shell
java -Djava.library.path=. A3
```
+100
View File
@@ -0,0 +1,100 @@
# Assignment-A2 - Two-pass macro processor code in Python
# BEGINNING OF CODE
# Required databases
macro_definition_table = {} # Storing all macro definitions with their names
macro_name_table = {} # Storing macro names and their index
##########################################################################
def process_pass1(source_code):
mdt_index = 0
macro_definition = []
current_macro_name = None
inside_macro = False
for line in source_code:
tokens = line.strip().split() # store each word of the line of source code
if (not tokens): # skips blank lines
continue
if (tokens[0] == 'MACRO'): # beginning of macro definition
inside_macro = True
continue
if (inside_macro == True and tokens[0] == 'MEND'): # if end of macro is reached
inside_macro = False
macro_definition_table[current_macro_name] = macro_definition[:]
macro_name_table[current_macro_name] = mdt_index
mdt_index += len(macro_definition)
macro_definition = []
current_macro_name = None
continue
if (inside_macro == True): # processing contents of macro
if (not current_macro_name):
current_macro_name = tokens[0]
macro_definition.append(line.strip())
##########################################################################
def process_pass2(source_code):
output = []
inside_macro = False
for line in source_code:
tokens = line.strip().split()
if (not tokens or tokens[0] == 'MACRO'): # skipping spaces, MACRO and MEND keywords
inside_macro = True
continue
elif (tokens[0] == 'MEND'):
inside_macro = False
continue
if inside_macro:
continue
macro_name = tokens[0]
if macro_name in macro_name_table: # expand macro from source code
args = tokens[1:]
macro_def = macro_definition_table[macro_name]
for expanded_line in macro_def:
for i, arg in enumerate(args):
expanded_line = expanded_line.replace(f"&ARG{i+1}", arg)
output.append(expanded_line)
else: # append line if not a macro
output.append(line.strip())
return output
##########################################################################
def display():
print("Macro Name Table (MNT):")
for name, index in macro_name_table.items():
print(f"Macro Name: {name} | Index: {index}")
print("Macro Definition Table (MDT):")
for name, definition in macro_definition_table.items():
print(f"Macro: {name}")
for line in definition:
print(f"\t{line}")
##########################################################################
source_code = [
"MACRO",
"INCR &ARG1",
"ADD &ARG1, ONE",
"MEND",
"MACRO",
"DECR &ARG1",
"SUB &ARG1, ONE",
"MEND",
"START",
"INCR A",
"DECR B",
"END"
]
##########################################################################
process_pass1(source_code)
display()
print("PASS 2:")
expanded_code = process_pass2(source_code)
for i in expanded_code:
print(i)
# END OF CODE