0% found this document useful (0 votes)
9 views10 pages

SPCC EXP 1 Saif

The document outlines the design and implementation of a two-pass assembler for the X86 machine, detailing the assembler's function as a translator from assembly language to machine language. It describes the structure of various tables used during the assembly process, including the Machine Opcode Table, Pseudo Opcode Table, Symbol Table, Literal Table, and Base Table. Additionally, it provides a program example that demonstrates a simple loop incrementing a register and storing the result in memory, along with the Java code for the assembler.

Uploaded by

saif.221230.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

SPCC EXP 1 Saif

The document outlines the design and implementation of a two-pass assembler for the X86 machine, detailing the assembler's function as a translator from assembly language to machine language. It describes the structure of various tables used during the assembly process, including the Machine Opcode Table, Pseudo Opcode Table, Symbol Table, Literal Table, and Base Table. Additionally, it provides a program example that demonstrates a simple loop incrementing a register and storing the result in memory, along with the Java code for the assembler.

Uploaded by

saif.221230.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

221230 Saif Madre SPCC B batch

EXPERIMENT NO. 1
AIM: To Design and implement two pass assembler for X86 machine.
THEORY:
An assembler is a language translator that takes as input assembly language program &
generates its machine language equivalent along with the information required by the
loader.
The rules in ALP state that the symbol should be defined somewhere in the course of
the program .Hence there may be some cases in which the reference to the symbol is
made prior to its definition & such a reference is called as Forward Reference . Due to
Forward Reference the assembler cannot assemble the instructions & such a problem
is called as Forward Reference Problem.
To resolve Forward Reference Problem we make two passes over the input program.
The purpose of Pass1 is to define the symbols & literals encountered in the program.
The purpose of Pass2 is to assemble the instructions & assemble the data.
The database consists of the following tables:

MOT [Machine Opcode Table]


Mnemonic opcode Binary opcode Instruction length Instruction format

MOT is a fixed length table i.e. no entries are made in it in either of the passes.
In Pass1 it is consulted to obtain instruction length [update LC]. In Pass2 it is consulted
to obtain binary opcode, instruction length & instruction format.

POT [Pseudo Opcode table]


Pseudo opcode Address of routine to process pseudo
opcode

POT is a fixed length table ie no entries are made in it in either of the passes. In both the
passes it is consulted to process pseudo opcodes like START, USING, DROP, DC, DS, etc

ST [Symbol Table]
Symbol Value Length Relocation [R/A]

ST is used for keeping track of symbols that are defined in the program.
221230 Saif Madre SPCC B batch

In Pass1 whenever a symbol is defined an entry is made in the symbol table.


In Pass2 ST is used for generating the address of the symbols.

LT [Literal Table]
Literal Value Length Relocation [R/A]

LT is used for keeping track of symbols that are defined in the program. In Pass1
whenever a literal is defined an entry is made in the LT. In Pass2 LT is used for generating
the address of the literals.

BT [Base Table]
Availability indicator Contents of base register
1 ‘n’
:
15 ‘n’
BT is used to keep track on the contents of the base register.
In Pass1 BT is not required.
In Pass2 BT is used for processing USING & DROP statements.

PROGRAM:
SIMPLE LOOP THAT INCREMENTS A REGISTER AND STORES THE RESULT IN MEMORY.

How the Program Works


1. Initialization:
The program sets up the base register and initializes R1 to 0 and R2 to 10.
2. Loop:
The program enters a loop where it:
Increments R1 by 1.
Stores the value of R1 in COUNT.
Compares R1 with R2.
Repeats the loop if R1 is not equal to R2.
3. Termination:
After the loop ends, the program loads the final value of R1 into register 3 and
branches to the address in register 14.

LINE BY LINE
1. Program Start:
o PROG1 START 0: The program starts at memory location 0.
2. Base Register Setup:
o USING *,15: Register 15 is used as the base register.
3. Load Address into Register:
o LA 15,SETUP: Loads the address of SETUP into register 15.
221230 Saif Madre SPCC B batch

4. Clear Register:
o SR R1,R1: Clears register R1 by subtracting it from itself.
5. Load Literal into Register:
o L R2,=F'10': Loads the literal value 10 into register R2.
6. Loop Start:
o LOOP: Marks the start of a loop.
7. Increment Register:
o A R1,=F'1': Adds 1 to register R1.
8. Store Register Value:
o ST R1,COUNT: Stores the value in R1 into the memory location COUNT.
9. Compare Registers:
o C R1,R2: Compares the value in R1 with the value in R2.
10. Branch if Not Equal:
o BNE LOOP: Branches back to LOOP if R1 is not equal to R2.
11. Load Register:
o LR 3,R1: Loads the value in R1 into register 3.
12. Branch to Register 14:
o BR 14: Branches to the address in register 14.
13. Literal Pool:
o LTORG: Generates a literal pool for literals like =F'1' and =F'10'.
14. Define Storage:
o COUNT DS F: Defines a fullword (4 bytes) of storage labeled COUNT.
15. End of Program:
o END: Marks the end of the program.

Code
TwoPassAssembler.java :

import java.util.*; class SymTuple {


import java.io.*; String symbol, ra;
int value, length;
class Tuple {
String mnemonic, bin_opcode, type; SymTuple(String s1, int i1, int i2, String s2)
int length; {
symbol = s1;
// Default constructor value = i1;
Tuple() {} length = i2;
ra = s2;
Tuple(String s1, String s2, String s3, String }
s4) { }
mnemonic = s1;
bin_opcode = s2; class LitTuple {
length = Integer.parseInt(s3); String literal, ra;
type = s4; int value, length;
}
} // Default constructor
LitTuple() {}
221230 Saif Madre SPCC B batch

StringTokenizer st = new
LitTuple(String s1, int i1, int i2, String s2) { StringTokenizer(s, " ", false);
literal = s1; String s_arr[] = new
value = i1; String[st.countTokens()];
length = i2; for (int i = 0; i < s_arr.length; i++) {
ra = s2; s_arr[i] = st.nextToken();
} }
} if (searchPot1(s_arr) == false) {
searchMot1(s_arr);
class TwoPassAssembler { out_pass1.println(s);
static int lc; }
static List<Tuple> mot; lclist.add(lc);
static List<String> pot; }
static List<SymTuple> symtable; int j;
static List<LitTuple> littable; String output = new String();
static List<Integer> lclist; System.out.println("Symbol Table:");
static Map<Integer, Integer> basetable; System.out.println("Symbol Value
static PrintWriter out_pass2; Length R/A");
static PrintWriter out_pass1; for (SymTuple i : symtable) {
static int line_no; output = String.format("%-10s %-8d %-
8d %s", i.symbol, i.value, i.length, i.ra);
public static void main(String args[]) System.out.println(output);
throws Exception { out_symtable.println(output);
initializeTables(); }
System.out.println("====== PASS 1 System.out.println("\nLiteral Table:");
======\n"); System.out.println("Literal Value
pass1(); Length R/A");
System.out.println("\n====== PASS 2 for (LitTuple i : littable) {
======\n"); output = String.format("%-10s %-8d %-
pass2(); 8d %s", i.literal, i.value, i.length, i.ra);
} System.out.println(output);
out_littable.println(output);
static void pass1() throws Exception { }
BufferedReader input = new }
BufferedReader(new
InputStreamReader(new static void pass2() throws Exception {
FileInputStream("input.txt"))); line_no = 0;
out_pass1 = new PrintWriter(new out_pass2 = new PrintWriter(new
FileWriter("output_pass1.txt"), true); FileWriter("output_pass2.txt"), true);
PrintWriter out_symtable = new BufferedReader input = new
PrintWriter(new BufferedReader(new
FileWriter("out_symtable.txt"), true); InputStreamReader(new
PrintWriter out_littable = new FileInputStream("output_pass1.txt")));
PrintWriter(new String s;
FileWriter("out_littable.txt"), true); System.out.println("Pass 2 input:");
String s; while((s = input.readLine()) != null) {
while ((s = input.readLine()) != null) { System.out.println(s);
221230 Saif Madre SPCC B batch

StringTokenizer st = new switch(potval) {


StringTokenizer(s, " ", false); case 1:
String s_arr[] = new // DS or DC statement
String[st.countTokens()]; String x = s[i+1];
for(int i=0 ; i < s_arr.length ; i++) { int index = x.indexOf("F");
s_arr[i] = st.nextToken(); if(i == 1) {
} symtable.add(new SymTuple(s[0],
if(searchPot2(s_arr) == false) { lc, 4, "R"));
searchMot2(s_arr); }
} if(index != 0) {
line_no++; // Ends with F
} l = Integer.parseInt(x.substring(0,
System.out.println("\nPass 2 output:"); x.length()-1));
input = new BufferedReader(new l *= 4;
InputStreamReader(new } else {
FileInputStream("output_pass2.txt"))); // Starts with F
while((s = input.readLine()) != null) { for(int j=i+1 ; j<s.length ; j++) {
System.out.println(s); l += 4;
} }
} }
lc += l;
static boolean searchPot1(String[] s) { return true;
int i = 0;
int l = 0; case 2:
int potval = 0; // EQU statement
if(!s[2].equals("*")) {
if(s.length == 3) { symtable.add(new SymTuple(s[0],
i = 1; Integer.parseInt(s[2]), 1, "A"));
} } else {
s = tokenizeOperands(s); symtable.add(new SymTuple(s[0],
lc, 1, "R"));
if(s[i].equalsIgnoreCase("DS") || }
s[i].equalsIgnoreCase("DC")) { return true;
potval = 1;
} case 3:
if(s[i].equalsIgnoreCase("EQU")) { // START statement
potval = 2; symtable.add(new SymTuple(s[0],
} Integer.parseInt(s[2]), 1, "R"));
if(s[i].equalsIgnoreCase("START")) { return true;
potval = 3;
} case 4:
if(s[i].equalsIgnoreCase("LTORG")) { // LTORG statement
potval = 4; ltorg(false);
} return true;
if(s[i].equalsIgnoreCase("END")) {
potval = 5; case 5:
} // END statement
ltorg(true);
221230 Saif Madre SPCC B batch

return true; while(lc%8 != 0) {


} lc++;
return false; }
} }
lt.value = lc;
static void searchMot1(String[] s) { lc += 4;
Tuple t = new Tuple(); while(itr.hasNext()) {
int i = 0; lt = itr.next();
if(s.length == 3) { lt.value = lc;
i = 1; lc += 4;
} }
s = tokenizeOperands(s); }
for(int j=i+1 ; j < s.length ; j++) {
if(s[j].startsWith("=")) { static boolean searchPot2(String[] s) {
littable.add(new int i = 0;
LitTuple(s[j].substring(1, s[j].length()), -1, 4,
"R")); if(s.length == 3) {
} i = 1;
} }
if((i == 1) && if(Collections.binarySearch(pot, s[i]) >=
(!s[0].equalsIgnoreCase("END"))) { 0) {
symtable.add(new SymTuple(s[0], lc, if(s[i].equalsIgnoreCase("USING")) {
4, "R")); s = tokenizeOperands(s);
}
for(Tuple x : mot) { if(s[i+1].equals("*")) {
if(s[i].equals(x.mnemonic)) { s[i+1] = lclist.get(line_no) + "";
t = x; } else {
break; for(int j=i+1 ; j<s.length ; j++) {
} int value = getSymbolValue(s[j]);
} if(value != -1) {
lc += t.length; s[j] = value + "";
} }
}
static void ltorg(boolean isEnd) { }
Iterator<LitTuple> itr = littable.iterator();
LitTuple lt = new LitTuple(); basetable.put(Integer.valueOf(s[i+2].trim()),
boolean isBroken = false; Integer.valueOf(s[i+1].trim()));
while(itr.hasNext()) { }
lt = itr.next(); return true;
if(lt.value == -1) { }
isBroken = true; return false;
break; }
}
} static void searchMot2(String[] s) {
if(!isBroken) { Tuple t = null; // Initialize t as null
return; int i = 0;
} int j;
if(!isEnd) {
221230 Saif Madre SPCC B batch

if (s.length == 3) { output += " ";


i = 1; }
} for (j = i + 1; j < s.length; j++) {
s = tokenizeOperands(s); int value = getSymbolValue(s[j]);
if (value != -1) {
// Search for the mnemonic in the MOT s[j] = value + "";
for (Tuple x : mot) { }
if (s[i].equals(x.mnemonic)) { }
t = x; // Assign the found Tuple to t output += s[i + 1];
break; for (j = i + 2; j < s.length; j++) {
} output += ", " + s[j];
} }
} else {
// Check if t is still null (mnemonic not output = s[i];
found in MOT) for (j = s[i].length(); j < 6; j++) {
if (t == null) { output += " ";
System.err.println("Error: Mnemonic '" + }
s[i] + "' not found in MOT."); for (j = i + 1; j < s.length - 1; j++) {
return; int value = getSymbolValue(s[j]);
} if (value != -1) {
s[j] = value + "";
String output = new String(); }
String mask = new String(); }
if (s[i].equals("BNE")) { s[j] = createOffset(s[j]);
mask = "7"; output += s[i + 1];
} else if (s[i].equals("BR")) { for (j = i + 2; j < s.length; j++) {
mask = "15"; output += ", " + s[j];
} else { }
mask = "0"; }
} out_pass2.println(output);
}
if (s[i].startsWith("B")) {
if (s[i].endsWith("R")) { static String createOffset(String s) {
s[i] = "BCR"; String original = s;
} else { Integer[] key =
s[i] = "BC"; basetable.keySet().toArray(new Integer[0]);
} int offset, new_offset;
List<String> temp = new ArrayList<>(); int index = 0;
for (String x : s) { int value = -1;
temp.add(x); int index_reg = 0;
} if(s.startsWith("=")) {
temp.add(i + 1, mask); value = getLiteralValue(s);
s = temp.toArray(new String[0]); } else {
} int paranthesis = s.indexOf("(");
String index_string = new String();
if (t.type.equals("RR")) { if(paranthesis != -1) {
output = s[i]; s = s.substring(0, s.indexOf("("));
for (j = s[i].length(); j < 6; j++) {
221230 Saif Madre SPCC B batch

index_string = List<String> temp = new LinkedList<>();


original.substring(original.indexOf("(")+1, for(int j=0 ; j<s.length-1 ; j++) {
original.indexOf(")")); temp.add(s[j]);
index_reg = }
getSymbolValue(index_string); StringTokenizer st = new
} StringTokenizer(s[s.length-1], " ,", false);
value = getSymbolValue(s); while(st.hasMoreTokens()) {
} temp.add(st.nextToken());
offset = Math.abs(value - }
basetable.get(key[index])); s = temp.toArray(new String[0]);
for(int i=1 ; i<key.length ; i++) { return s;
new_offset = Math.abs(value - }
basetable.get(key[i]));
if(new_offset < offset) { static void initializeTables() throws
offset = new_offset; Exception {
index = i; symtable = new LinkedList<>();
} littable = new LinkedList<>();
} lclist = new ArrayList<>();
String result = offset + "(" + index_reg + ", basetable = new HashMap<>();
" + key[index] + ")"; mot = new LinkedList<>();
return result; pot = new LinkedList<>();
} String s;
BufferedReader br;
static int getSymbolValue(String s) { br = new BufferedReader(new
for(SymTuple st : symtable) { InputStreamReader(new
if(s.equalsIgnoreCase(st.symbol)) { FileInputStream("mot.txt")));
return st.value; while((s = br.readLine()) != null) {
} StringTokenizer st = new
} StringTokenizer(s, " ", false);
return -1; mot.add(new Tuple(st.nextToken(),
} st.nextToken(), st.nextToken(),
st.nextToken()));
static int getLiteralValue(String s) { }
s = s.substring(1, s.length()); br = new BufferedReader(new
for(LitTuple lt : littable) { InputStreamReader(new
if(s.equalsIgnoreCase(lt.literal)) { FileInputStream("pot.txt")));
return lt.value; while((s = br.readLine()) != null) {
} pot.add(s);
} }
return -1; Collections.sort(pot);
} }
}
static String[] tokenizeOperands(String[]
s) {
221230 Saif Madre SPCC B batch

input.txt : mot.txt:

pot.txt:
221230 Saif Madre SPCC B batch

OUTPUT

Conclusion:
Thus, we have successfully implemented two pass Assembler.

You might also like