EE Lab Manuls Fast Nu
EE Lab Manuls Fast Nu
AND ARCHITECTURE
LAB MANUAL
Date:
Page | 2
Lab Manual of Computer Organization and Architecture
Table of Contents
Sr. No. Description Page No.
1 List of Equipment 4
Page | 3
Lab Manual of Computer Organization and Architecture
List of Equipment
Software Tools
Page | 4
Lab Manual of Computer Organization and Architecture
EXPERIMENT-1
INTRODUCTION TO THE ASSEMBLER
OBJECTIVES
How to write a simple assembly language program for x86 (x88) real mode.
How to use the Assembler for editing, assembling and debugging an assembly
language program.
How to use the debugger interface for understanding the computer organization.
SOFTWARE TOOLS:
THEORY
For example,
will assemble test.asm into a .com file test.com and will produce a list file test.lst. By giving
the following command help on the nasm features is available: nasm –h With -hf, this will
also list the available output file formats, and what they are.
NASM will normally choose the name of your output file for you; precisely how it does this is
dependent on the object file format. For Microsoft object file formats (obj and win32), it will
remove the .asm extension from your source file name and substitute .obj. For the binary
format it will simply remove the extension, so that myfile.asm produces the output file myfile.
If the output file already exists, NASM will overwrite it, unless it has the same name as the
input file, in which case it will give a warning and use nasm.out as the output file name
Page | 5
Lab Manual of Computer Organization and Architecture
instead. For situations in which this behavior is unacceptable, NASM provides the -o
command-line option, which allows you to specify your desired output file name. You invoke
-o by following it with the name you wish for the output file, either with or without an
intervening space. For example:
nasm -f bin program.asm -o program.com
Note that this is a small o, and is different from a capital O, which is used to specify
the number of optimization passes required.
The -f Option: Specifying the Output File Format
If you do not supply the -f option to NASM, it will choose an output file format for
you itself. In the distribution versions of NASM, the default is always bin.
Like -o, the intervening space between -f and the output file format is optional; so “-f
bin” and “-fbin” are both valid.
The -l Option: Generating a Listing File
If you supply the -l option to NASM, followed (with the usual optional space) by a file
name, NASM will generate a source-listing file for you, in which addresses and generated
code are listed on the left, and the actual source code, with expansions of multi-line macros on
the right. For example:
If a list file is selected, you may turn off listing for a section of your source with [list -
], and turn it back on with [list +], (the default).
The -X Option: Selecting an Error Reporting Format
This option can be used to select an error reporting format for any error messages that
might be produced by NASM.
Two error reporting formats may be selected. They are the -Xvc option and the -Xgnu
option. The GNU format is the default and looks like this:
where filename.asm is the name of the source file in which the error was detected, 65 is the
source file line number on which the error was detected, “error” is the severity of the error
(this could be warning), and specific error message is a more detailed text message which
should help pinpoint the exact problem.
The other format, specified by -Xvc is the style used by Microsoft Visual C++ and
some other programs. It looks like this:
filename.asm(65) : error: specific error message
Page | 6
Lab Manual of Computer Organization and Architecture
Where the only difference is that the line number is in parentheses instead of being
delimited by colons.
The -E Option: Send Errors to a File
In NASM the “–E” option, which takes a filename argument that causes errors to be
sent to the specified files rather than standard error. Therefore you can redirect the errors into
a file by typing:
(As usual, a space between -i and the path name is allowed and optional).
NASM, in the interests of complete source-code portability, does not understand the
file naming conventions of the OS it is running on; the string you provide as an argument to
the -i option will be prepended exactly as written to the name of the include file. Therefore the
trailing backslash in the above example is necessary.
The -p Option: Pre-Include a File
NASM allows you to specify files to be pre-included into your source file, by the use
of the -p option. So running nasm myfile.asm -p myinc.inc is equivalent to running nasm
myfile.asm and placing the directive %include "myinc.inc" at the start of the file.
For consistency with the -I, -D and -U options, this option can also be specified as -P.
NASM Is Case-Sensitive
One simple difference is that NASM is case-sensitive. It makes a difference whether
you call your label foo, Foo or FOO. If you're assembling to DOS or OS/2 .OBJ files, you can
invoke the UPPERCASE directive to ensure that all symbols exported to other code modules
are forced to be upper case; but even then, within a single module,
NASM will distinguish between labels differing only in case.
(Extracted from [1], for more details please see [2])
Page | 7
Lab Manual of Computer Organization and Architecture
; A PROGRAM TO ADD TWO NUMBERS AND SUBTRACT A THIRD ONE FROM THE SUM
; USING REGISTERS
[ORG 0x0100]
MOV AX, 5 ; LOAD FIRST NUMBER IN AX
MOV BX, 12 ; LOAD SECOND NUMBER IN BX
ADD AX, BX ; ACCUMULATE SUM IN AX
MOV BX, 14 ; LOAD THIRD NUMBER IN BX
SUB AX, BX ; ACCUMULATE SUM IN AX
MOV AX, 0x4C00 ; TERMINATE PROGRAM
INT 0x21
Let us save this in a file named test.asm. Now we use NASM to assemble this program
using the command:
nasm test.asm –o test.com –l test.lst
Which generates two files, test.com and test.lst. Now we will use a debugger to
monitor the execution of this program. The debugger we are using is Advanced Fullscreen
Debugger (AFD). We will use the load command to load the com file, as shown in Figure 1.1.
Figure 1. 1
As shown in the Figure 1.1, the interface of the debugger is easy to understand and use. Using
F1 we can step through the code and see the changes taking place in the register contents.
PROBLEMS
Modify this program to generate the sum of four numbers, using registers, and watch its
execution in the debugger. Also explore the various functions available in the debugger (the
debugger has built-in context sensitive help).
Page | 8
Lab Manual of Computer Organization and Architecture
Page | 9
Lab Manual of Computer Organization and Architecture
EXPERIMENT-2
REGISTERS AND FLAGS
OBJECTIVES
How to interpret the different types of registers available in the IAPX86 architecture.
How to use the different types of registers and how to manipulate them in assembly
language.
How to interpret the function of flags and to use them effectively.
How to perform arithmetic operations with registers.
How to use the debugger for viewing the available registers and their function.
SOFTWARE TOOLS:
THEORY
The 8086 chip uses registers for performing operations. Following is a brief detail of their
functions:
General registers: There are four 16-bit general-purpose registers used primarily to contain
operands for arithmetic and logical operations.
Status and instruction registers: These special-purpose registers are used to record and
alter certain aspects of the 8086 processor state.
Status Flags: The status flags of the FLAGS register allow the results of one instruction to
influence later instructions. The arithmetic instructions use OF, SF, ZF, AF, PF, and CF. The
SCAS (Scan String), CMPS (Compare String), and LOOP instructions use ZF to signal that
their operations are complete. There are instructions to set, clear, and complement CF before
execution of an arithmetic instruction.
Control Flags: The control flag DF of the EFLAGS register controls string instructions.
Setting DF causes string instructions to auto-decrement; that is, to process strings from high
addresses to low addresses. Clearing DF causes string instructions to auto-increment, or to
Page | 10
Lab Manual of Computer Organization and Architecture
Instruction Pointer: The instruction pointer register (IP) contains the offset address, relative
to the start of the current code segment, of the next sequential instruction to be executed. The
instruction pointer is not directly visible to the programmer; it is controlled implicitly by
control-transfer instructions, interrupts, and exceptions.
Page | 11
Lab Manual of Computer Organization and Architecture
PROBLEMS
1. Write a program to calculate the square of 20 by using a loop that adds 20 to the
accumulator 20 times.
1. Give the value of the IP, zero flag, the carry flag, the sign flag, and the overflow flag
after each of the following instructions if AX is initialized with 0x1254 and BX is
initialized with 0x0FFF.
add ax, 0xEDAB
add ax, bx
addbx, 0xF001
REFERENCES
1. The Art Of Assembly Language Programming, http://webster.cs.ucr.edu/Page_win32/
2. Intel 80386 Reference Programmer's Manual, http://www.logix.cz/michal/doc/i386/
3. Assembly Language Programming Book by Belal Mohammad Hashmi, NUCES
FAST, Lahore, Pakistan
4. Assembly Tutorial, http://www.geocities.com/SiliconValley/6112/asm0100.htm
Page | 12
Lab Manual of Computer Organization and Architecture
EXPERIMENT-3
MEMORY SYSTEM
OBJECTIVES
THEORY
Depending on the machine, a processor can access one or more bytes from memory at a time.
The number of bytes accessed simultaneously from main memory is called word length of
machine. Generally, all machines are byte-addressable i.e.; every byte stored in memory has a
unique address. However, word length of a machine is typically some integral multiple of a
byte. Therefore, the address of a word must be the address of one of its constituting bytes. In
this regard, one of the following methods of addressing (also known as byte ordering) may be
used.
Big Endian– the higher byte is stored at lower memory address (i.e. Big Byte first). MIPS,
Apple, Sun SPARC are some of the machines in this class .
Little Endian - the lower byte is stored at lower memory address (i.e. Little Byte first). Intel’s
machines use little endian.
Consider for example, storing 0xA2B1C3D4 in main memory. The two byte orderings are illustrated in
Figure 3.1
Figure 3. 1
Memory Models
In earlier processors like 8080 and 8085 the linear memory model was used to access memory.
Flat/ Linear Memory Model – memory appears to a program as a single, contiguous address
space of 4GB. Code, data, and stack are all contained in this address space, also called the
linear address space
Page | 13
Lab Manual of Computer Organization and Architecture
8080 and 8085 could access a total memory of 64K using the 16 lines of their address bus.
When designing iAPX88 the Intel designers wanted to remain compatible with 8080 and 8085
however 64K was too small to continue with, for their new processor. The three logical parts
of a program (data, code and stack) should appear as three distinct units in memory, but
making this division is not possible in the linear memory model. The segmented memory
model does allow this distinction.
The processor sees code from the code window and data from the data window. The size of
one window is restricted to 64K. 8085 software fits in just one such window. It sees code,
data, and stack from this one window, so downward compatibility is attained. However the
maximum memory iAPX88 can access is 1MB which can be accessed with 20 bits. Compare
this with the 64K of 8085 that were accessed using 16 bits. The idea is that the 64K window
just discussed can be moved anywhere in the whole 1MB. The four segment registers
discussed in the Intel register architecture are used for this purpose. Therefore four windows
can exist at one time. For example one window that is pointed to by the CS register contains
the currently executing code.
Segment Registers
The segment registers hold the segment selectors which are special pointers that point to start
of individual segments in memory. The use of segment registers is dependent on the memory
management model in use. When using the segmented memory model, each segment is loaded with
a different memory address as shown in the Figure 3.1
Figure 3. 2
Page | 14
Lab Manual of Computer Organization and Architecture
The segment registers (CS, DS, SS, ES, FS, and GS) hold 16-bit segment selectors. To access
a particular segment in memory, the segment selector for that segment must be present in the
appropriate segment register. Each of the segment registers is associated with one of three
types of storage: code, data, or stack. The DS, ES, FS, and GS registers point to four data
segments. The availability of four data segments permits efficient and secure access to
different types of data structures.
The CS register contains the segment selector for the code segment, where the
instructions being executed are stored. The processor fetches instructions from the code
segment, using a logical address that consists of the segment selector in the CS register and the
contents of the IP (Instruction Pointer) register. The CS register opens a 64K window in the
1MB memory and then IP works to select code from this window as offsets. IP is 16 bit wide
and works only inside this window and cannot go outside of this 64K in any case. If the
window is moved i.e. the CS register is changed, IP will change its behavior accordingly and
start selecting from the new window. The IP register always works relatively, relative to the
segment base stored in the CS register.
Figure 3. 3
Example:
The program we wrote when loaded into memory had a value of 0100 in IP register and some
value say 1DDD in the CS register. Making both 20 bit numbers, the segment base is 1DDD0
and the offset is 00100 and adding them we get the physical memory address of 1DED0 where
the opcode B80500 is placed.
Page | 15
Lab Manual of Computer Organization and Architecture
Problems:
1. Fill in the tables (table 3.1 and table 3.2) to show storage of 0xABDADDBA at address
1996 in the memory of a machine using (i) little endian (ii) big
endian byte ordering.
table3. 1 table3. 2
2. Calculate the physical memory address generated by the following segment offset
pairs.
a) 1DDD:0436
b) 1234:7920
c) 74F0:2123
d) 0000:6727
e) FFFF:4336
3. Write instructions to do the following.
a. Copy contents of memory location with offset 0025 in the current data segment into
AX.
b. Copy AX into memory location with offset 0FFF in the current data segment.
c. Move contents of memory location with offset 0010 to memory location with offset
002F in the current data segment.
Page | 16
Lab Manual of Computer Organization and Architecture
EXPERIMENT-4
SIMULATING CACHE USING MIPS SIMULATOR
OBJECTIVES
SOFTWARE TOOLS:
THEORY
EXPERIMENT
Create a new project in MipsIt using the steps mentioned in the given document.
Compile code1.c and load it to the simulator
Open the simulator and disable both cache
Run the simulation and note down the execution time in Table 4.1
Now enable the instruction cache only with default settings. Reload the code and
simulate it. Note down the execution time in table 4.1.
Next, enable the data cache only and note down the time
Now enable both cache (data+ instruction) and note down the time
Table 4.1
Instruction Data cache Both caches
Scenario No Cache
Cache only only
Time
Enable both cache with default values. Play the simulation. Open the Instruction Cache
block by double clicking on it. What type of mapping is used by this cache? Looking at
the default values, calculate the word offset bits, cache line bits and tag bits and verify
it with simulator block diagram.
Page | 17
Lab Manual of Computer Organization and Architecture
Table 4.2
INSTRUCTION CACHE DATA CACHE
Hit Count Hit Count
Table 4.3
Reload the code, open the cache and memory windows, then press play. During
simulation, verify by noting down the observations of Data Cache and Memory
Locations that with “Write through” method, every time the processor writes to a
cached memory location both the cache and the underlying memory locations are
updated.
Now change the data cache write policy to “Write back”. What are the changes you see
in the cache block?
Page | 18
Lab Manual of Computer Organization and Architecture
Verify by noting down the observations of Data Cache and Memory Locations that
with “Write Back” method, when a write is made to system memory at a location that
is currently cached, the new data is only written to the cache, not actually written to the
system memory. Later, if another memory location needs to use the cache line where
this data is stored, it is saved ("written back") to the system memory and then the line
can be used by the new address.
Considering the total execution time, comment which write policy is better?
Write in detail the types of caches, their use and different functionalities.
Page | 19
Lab Manual of Computer Organization and Architecture
EXPERIMENT-5
ADDRESSING MODES
OBJECTIVES
How to modify the memory contents.
How to use various addressing modes.
How to use the registers associated with memory.
How to use segmentation.
How use instructions like CALL, RET, PUSH and POP etc. with reference to the
stack.
SOFTWARE TOOLS:
THEORY
Stack Implementation:
Stack operations are facilitated by three registers:
1. The stack segment (SS) register. Stacks are implemented in memory. A system may
have a number of stacks that is limited only by the maximum number of segments. A
stack may be up to 4 gigabytes long, the maximum length of a segment. One stack is
directly addressable at the address located by SS. This is the current stack, often
referred to simply as "the" stack. SS is used automatically by the processor for all stack
operations.
2. The stack pointer (SP) registers points to the top of the push-down stack. It is
referenced implicitly by PUSH and POP operations, subroutine calls and returns, and
interrupt operations. When an item is pushed onto the stack, the processor decrements
SP, then writes the item at the new position. When an item is popped off the stack, the
processor copies it from the top position, then increments ESP. In other words, the
stack grows down in memory toward lesser addresses.
3. The stack-frame base pointer (BP) register is the best choice of register for accessing
data structures, variables and dynamically allocated work space within the stack. BP is
often used to access elements on the stack relative to a fixed point on the stack rather
than relative to the current top of stack. It typically identifies the base address of the
current stack frame established for the current procedure. When BP is used as the base
register in an offset calculation, the offset is calculated automatically in the current
stack segment (i.e., the segment currently selected by SS). Because SS does not have
to be explicitly specified, instruction encoding in such cases is more efficient. BP can
also be used to index into segments addressable via other segment registers. [2 and 3]
Page | 20
Lab Manual of Computer Organization and Architecture
Figure 5. 1
Addressing Modes
The x86 processors support the register addressing mode, the immediate addressing
mode, the indirect addressing mode, the indexed addressing mode, and the direct addressing
mode. The following paragraphs explain each of these modes:
Register Addressing Mode: Register operands are the easiest to understand. Consider the
following forms of the MOV instruction:
MOV AX, AX
MOV AX, BX
MOV AX, CX
MOV AX, DX
The first instruction accomplishes absolutely nothing. It copies the value from the AX register
back into the AX register. The remaining three instructions copy the value of BX, CX and DX
into AX. Note that the original values of BX, CX, and DX remain the same. The first operand
(the destination) is not limited to AX; you can move values to any of these registers.
Immediate Addressing Mode: Constants are also pretty easy to deal with. Consider the
following instructions:
MOV AX, 25H
MOV BX, 195H
MOV CX, 2056H
MOV DX, 1000H
These instructions are all pretty straightforward; they load their respective registers with the
specified hexadecimal constant.
Direct Addressing Mode: There are three addressing modes which deal with accessing data in
memory. These addressing modes take the following forms:
MOV AX, [1000]
Page | 21
Lab Manual of Computer Organization and Architecture
The first instruction above uses the direct addressing mode to load AX with the 16 bit value
stored in memory starting at location 1000 hex.
Indirect Addressing Mode:
MOV AX, [BX]
MOV AX, [1000+BX]
The MOV AX, [BX] instruction loads AX from the memory location specified by the contents
of the BX register. This is an indirect addressing mode. Rather than using the value in BX,
this instruction accesses to the memory location whose address appears in BX. Note that the
following two instructions:
MOV BX, 1000
MOV AX, [BX]
are equivalent to the single instruction:
Indexed Addressing Mode: The last memory addressing mode is the indexed addressing
mode. An example of this memory addressing mode is
The call instructions take the same forms as the jmp instructions except there is no short (two
byte) intra-segment call.
Page | 22
Lab Manual of Computer Organization and Architecture
The call disp16 instruction uses relative addressing. You can compute the effective address of
the target by adding this 16 bit displacement with the return address (like the relative jmp
instructions, the displacement is the distance from the instruction following the call to the
target address).
The call adrs32 instruction uses the direct addressing mode. A 32 bit segmented address
immediately follows the call opcode. This form of the call instruction copies that value
directly into the CS:IPregister pair. In many respects, this is equivalent to the immediate
addressing mode since the value this instruction copies into the CS:IPregister pair
immediately follows the instruction.
Call mem16 uses the memory indirect addressing mode. Like the jmp instruction, this form of
the call instruction fetches the word at the specified memory location and uses that word's
value as the target address.
Call reg16 works just like the memory indirect call above, except it uses the 16 bit value in a
register for the target address. This instruction is really the same instruction as the call mem16
instruction. Both forms specify their effective address using a modreg- r/m byte. For the call
reg16 form, the mod bits contain 11b so the r/m field specifies a register rather than a memory
addressing mode. Of course, this instruction also pushes the 16 bit offset of the next
instruction onto the stack as the return address.
The call mem32 instruction is a far indirect call. The memory address specified by this
instruction must be a double word value. This form of the call instruction fetches the 32 bit
segmented address at the computed effective address and copies this double word value into
the cs:ip register pair. This instruction also copies the 32 bit segmented address of the next
Page | 23
Lab Manual of Computer Organization and Architecture
instruction onto the stack (it pushes the segment value first and the offset portion second).
Like the call mem16 instruction, you can use any valid memory addressing mode with this
instruction:
It is relatively easy to synthesize the call instruction using two or three other 80x86
instructions. You could create the equivalent of a near call using a push and a jmp instruction:
A far call would be similar, you'd need to add a push CS instruction before the two
instructions above to push a far return address on the stack.
The ret (return) instruction returns control to the caller of a subroutine. It does so by popping
the return address off the stack and transferring control to the instruction at this return address.
Intrasegment (near) returns pop a 16 bit return address off the stack into the ip register. An
intersegment (far) return pops a 16 bit offset into the ip register and then a 16 bit segment
value into the cs register. These instructions are effectively equal to the following:
retn: pop ip
retf: popdcs:ip
Clearly, you must match a near subroutine call with a near return and a far subroutine call with
a corresponding far return. If you mix near calls with far returns or vice versa, you will leave
the stack in an inconsistent state and you probably will not return to the proper instruction
after the call. Of course, another important issue when using the CALL and RET instructions
is that you must make sure your subroutine doesn't push something onto the stack and then fail
to pop it off before trying to return to the caller. Stack problems are a major cause of errors in
assembly language subroutines. [2]
PUSH REG16
POP REG16
PUSH SEGREG
POP SEGREG (EXCEPT CS)
PUSH MEMORY
POP MEMORY
PUSHF
POPF
Page | 24
Lab Manual of Computer Organization and Architecture
The first two instructions push and pop a 16 bit general purpose register. This is a compact
(one byte) version designed specifically for registers.
The third pair of push/pop instructions let you push or pop an 80x86 segment register. Note
that the instructions that push FS and GS are longer than those that push CS, DS, ES, and SS.
You can only push the CS register (popping the CS register would create some interesting
program flow control problems).
The fourth pair of push/pop instructions allow you to push or pop the contents of a memory
location. On the 80286 and earlier, this must be a 16 bit value.
The pushf and popf instructions allow you to push/pop the processor status register (the flags).
Notice three things about the 80x86 hardware stack. First, it is always in the stack segment
(wherever SS points). Second, the stack grows down in memory. That is, as you push values
onto the stack the CPU stores them into successively lower memory locations. Finally, the
80x86 hardware stack pointer (SS:SP) always contains the address of the value on the top of
the stack (the last value pushed on the stack).
You can use the 80x86 hardware stack for temporarily saving registers and variables, passing
parameters to a procedure, allocating storage for local variables, and other uses. The push and
pop instructions are extremely valuable for manipulating these items on the stack.
(Extracted from [1], [2] and [4])
Problems:
1. Write an assembly language program, which selects the smallest, largest, and equal
number among the three 4 byte numbers stored in variables. And store these smallest,
largest, and equal numbers at some memory place. Use values given in Figure 5.2 but at
evaluation time values can be changed
Note: Do not use extended registers, if you want to use extended registers then use 8 byte
numbers for the above process. (This is not the input from the keyboard and output to the
console.)
Page | 25
Lab Manual of Computer Organization and Architecture
Figure 5. 2
}
3. Write the code to shift the whole stack at the offset of 0X20 from the current stack
location. Note: (You have to shift the data placed at the stack as well)
REFERENCES
1. Wikipedia, Free Online Encyclopedia,
http://en.wikipedia.org/wiki/X86#Real_mode
2. The Art Of Assembly Language Programming,
http://webster.cs.ucr.edu/Page_win32/
3. Intel 80386 Reference Programmer's Manual,
http://www.logix.cz/michal/doc/i386/
4. Assembly Language Programming Book by Belal Mohammad Hashmi, NUCES FAST,
Lahore, Pakistan
Page | 26
Lab Manual of Computer Organization and Architecture
EXPERIMENT-6
MEMORY ADDRESSING
OBJECTIVES
How to modify the memory contents.
How to use segmentation.
SOFTWARE TOOLS:
THEORY
Effective Address:
All the addressing mechanisms in iAPX88 return a number called effective address. For
example in base + offset addressing, neither the base nor the offset alone tells the desired cell
in memory to be accessed. It is only after the addition is done that the processor knows which
cell to be accessed. This number which came as the result of addition is called the effective
address. But the effective address is just an offset and is meaningless without a segment. Only
after the segment is known, we can form the physical address that is needed to access a
memory cell.
Example:
For example if BX=0100, SI=0200, and CS=1000 and the memory access under consideration
is [cs:bx+si+0x0700], the effective address formed is bx+si+0700 = 0100 + 0200 + 0700 =
0A00. Now multiplying the segment value by 16 makes it 10000 and adding the effective
address 00A00 forms the physical address 10A00 inside Code Segment (CS).
There are a few common mistakes done in forming a valid memory access. Part of a register
cannot be used to access memory. Like BX is allowed to hold an address but BL or BH are
not. Address is 16bit and must be contained in a 16 bit register. BX-SI is not possible. The
only thing that we
can do is addition of a base register with an index register. Any other operation is disallowed.
BX+BP and SI+DI are both disallowed as we cannot have two base or two index registers in
one memory access. One has to be a base register and the other has to be an index register and
that is the reason of naming them differently.
Problems:
Page | 27
Lab Manual of Computer Organization and Architecture
1. What is the effective address generated by the following combinations if they are
valid. If not, give reason. Initially BX=0x0100, SI=0x0010, DI=0x0001,
BP=0x0200, and SP=0xFFFF
a. bx-si
b. bx-bp
c. bx+10
d. bx-10
e. bx+sp
f. bx+di
2. Write an assembly language program, which changes the case of letters given in
the input string e.g given in Figure 6.1, string length and letter will be different at
evaluation time. And write the results in the output string. Input and Output strings
are to declare in the DATA segment.
Figure 6. 1
3. Write a program to add ten numbers using register + offset addressing mode.
Page | 28
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 7
BRANCHING
OBJECTIVES
To understand various jump instructions
To get familiarize with Relative Addressing
To get an idea of types of jump instructions
SOFTWARE TOOLS:
THEORY
RELATIVE ADDRESSING
Consider that, if inside the debugger, an instruction is shown as JMP 0119 and the location
0119 contains the original first instruction of the logic of our program. This jump is
unconditional, it will always be taken. Now looking at the opcode for this instruction, we see
EB1600 where EB is the opcode and 1600 is the operand to it. 1600 is 0016 in proper word
order. 0119 is not given as a parameter rather 0016 is given. This is position relative
addressing in contrast to absolute addressing. It is not telling the exact address rather it is
telling how much forward or backward to go from the current position of IP in the current
code segment. So the instruction means to add 0016 to the IP register. At the time of execution
of the first instruction at 0100 IP was pointing to the next instruction at 0103, so after adding
16 it became 0119, the desired target location. The mechanism is important to know, however
all calculations in this mechanism are done by the assembler and by the processor. We just use
a label with the JMP instruction and are ensured that the instruction at the target label will be
the one to be executed.
Types of JUMP:
The three types of jump, near, short, and far, differ in the size of instruction and the range of
memory they can jump to with the smallest short form of two bytes and a range of just 256
bytes to the far form of four bytes and a range covering the whole memory. Size of address for
all three types of jumps is given in Figure 7.1
Page | 29
Lab Manual of Computer Organization and Architecture
Figure 7. 1
Short Jump
If the offset is stored in a single byte as in 75F2 with the opcode 75 and operand F2, the jump
is called a short jump. F2 is added to IP as a signed byte. If the byte is negative the
complement is negated from IP otherwise the byte is added. Unconditional jumps can be short,
near, and far. Conditional jumps can only be short. A short jump can go +127 bytes ahead in
code and -128 bytes backwards and no more.
This is the limitation of a byte in singed representation.
Near Jump
When the relative address stored with the instruction is in 16 bits as in the last example the
jump is called a near jump. Using a near jump we can jump anywhere within a segment. If we
add a large number it will wrap around to the lower part. A negative number actually is a large
number and works this way using the wraparound behavior.
Far Jump
Far jump is not position relative but is absolute. Both segment and offset must be given to a
far jump. The previous two jumps were used to jump within a segment. Sometimes we may
need to go from one code segment to another, and near and short jumps cannot take us there.
Far jump must be used and a two byte segment and a two byte offset are given to it. It loads
CS with the segment part and IP with the offset part. Execution therefore resumes from that
location in physical memory. The three instructions that have a far form are JMP, CALL, and
RET, are related to program control. Far capability makes intra segment control possible.
Page | 30
Lab Manual of Computer Organization and Architecture
Exercise:
1. If AX=8FFF and BX=0FFF and “cmp ax, bx” is executed, which of the following
jumps will be taken? Each part is independent of others. Also give the value of Z, S,
and C flags.
a. jg greater
b. jl smaller
c. ja above
d. jb below
2. Write a program to search a particular element from an array using binary search. If
the element is found set AX to one and otherwise to zero.
3. Write a program to calculate the factorial of a number where factorial is defined as:
factorial(x) = x*(x-1)*(x-2)*...*1
factorial(0) = 1
Page | 31
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 8
BIT MANIPULATIONS
OBJECTIVES
To be able to use shifting and rotation instructions
To get familiarize with logical instructions
SOFTWARE TOOLS:
THEORY
Figure 8. 1
Figure 8. 2
Page | 32
Lab Manual of Computer Organization and Architecture
Figure 8. 3
The left shifting operation is basically multiplication by 2 while the right shifting operation is
division by two. However for signed numbers division by two can be accomplished by using
shift arithmetic right and not shift logical right. The left shift operation is equivalent to
multiplication except when an important bit is dropped from the left. The overflow flag will
signal this condition if it occurs and can be checked with JO. For division by 2 of a signed
number logical right shifting will give a wrong answer for a negative number as the zero
inserted from the left will change its sign. To retain the sign flag and still effectively divide by
two the shift arithmetic right instruction must be used on signed numbers.
Figure 8. 4
Figure 8. 5
Page | 33
Lab Manual of Computer Organization and Architecture
Figure 8. 6
Figure 8. 7
Logical Operations include: AND, OR, XOR, NOT. Refer to the instruction set for the syntax.
MASKING OPERATIONS
Another use of AND is to make selective bits zero in its destination operand. The source
operand is loaded with a mask containing one at positions which are retain their old value and
zero at positions which are to be zeroed. The effect of applying this operation on the
destination with mask in the source is to clear the desired bits. This operation is called
masking. For example if the lower nibble is to be cleared then the operation can be applied
with F0 in the source. The upper nibble will retain its old value and the lower nibble will be
cleared.
Page | 34
Lab Manual of Computer Organization and Architecture
The operation can be used as a masking operation to set selective bits. The bits in the mask are
cleared at positions which are to retain their values, and are set at positions which are to be set.
For example to set the lower nibble of the destination operand, the operation should be applied
with a mask of 0F in the source. The upper nibble will retain its value and the lower nibble
will be set as a result.
Selective Bit Inversion
XOR can also be used as a masking operation to invert selective bits. The bits in the mask are
cleared at positions, which are to retain their values, and are set at positions, which are to be
inverted. For example to invert the lower nibble of the destination operand, the operand should
be applied with a mask of 0F in the source. The upper nibble will retain its value and the lower
nibble will be set as a result. Compare this with NOT which inverts everything. XOR on the
other hand allows inverting selective bits.
Problems
2. AX contains a non-zero number. Count the number of ones in it and store the result
back in AX. Repeat the process on the result (AX) until AX contains one. Calculate in
BX the number of iterations it took to make AX one. For example BX should contain 2
in the following case:
AX = 1100 0101 1010 0010 (input – 7 ones)
AX = 0000 0000 0000 0111 (after first iteration – 3 one)
AX = 0000 0000 0000 0011 (after second iteration – 2 one)
AX = 0000 0000 0000 0010 (after second iteration – 1 one)
AX = 0000 0000 0000 0001 STOP
3. Implement the following multiplication algorithm in Figure 8.1 (for unsigned numbers)
we discussed in class. Use n = 16
Page | 35
Lab Manual of Computer Organization and Architecture
Figure 8. 8
POST LAB:
Modify code of exercise – 3 to implement Booth’s algorithm.
Page | 36
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 9
SUBROUTINES AND STACK
OBJECTIVES
To be able to write subroutines in assembly
To understand basic concepts of stack
SOFTWARE TOOLS:
THEORY
In every processor, instructions are available to divert temporarily and to divert permanently.
The instructions for permanent diversion in 8088 are the jump instructions, while the
instruction for temporary diversion is the CALL instruction.
The ret (return) instruction returns control to the caller of a subroutine. It does so by popping
the return address off the stack and transferring control to the instruction at this return address.
Page | 37
Lab Manual of Computer Organization and Architecture
Notice three things about the 80x86 hardware stack. First, it is always in the stack segment
(wherever SS points). Second, the stack grows down in memory. That is, as you push values
onto the stack the CPU stores them into successively lower memory locations. Finally, the
80x86 hardware stack pointer (SS:SP) always contains the address of the value on the top of
the stack (the last value pushed on the stack). You can use the 80x86 hardware stack for
temporarily saving registers and variables, passing parameters to a procedure, allocating
storage for local variables, and other uses.
Exercise
1. Write a subroutine “insert” to insert elements in an array "data" from a to b with
difference of c
a=ax, b=bx, c=cx
Example.
a=1,b=10,c=2
insert(); // after calling the subroutine the array should be 1,3,5,7,9
a++
c++
insert(); // after calling the subroutine the array should be 2,5,8
2. PART – A:
Consider the following piece of code where 5 function (r1,r2,r3,r4,r5) are defined
Write a function “addtoset” that takes offset of each function and remembers this offset
in an array that can hold a maximum of 5 offsets. Write another function “callset” that
makes a call to all functions in the set one by one.
Page | 38
Lab Manual of Computer Organization and Architecture
PART- B:
Rewrite callset such that it does not use a CALL or a JMP to invoke the functions.
HINT: Setup the stack appropriately such that the RET will execute the first function,
its RET execute the next and so on till the last RET returns to the caller of “callset”
[org 0x0100]
….
jmp end
addtoSet:
…
ret
callSet:
….
ret
callByStack:
….
ret
r1:
add ax,0x0001
ret
r2:
add ax,0x0002
ret
r3:
add ax,0x0003
ret
r4:
add ax,0x0004
ret
r5:
add ax,0x0005
ret
Page | 39
Lab Manual of Computer Organization and Architecture
end:
mov ax, 0x4c00 ; terminate program
int 0x21
offsets: dw 0,0,0,0,0
Page | 40
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 10
EXECUTION TIME
OBJECTIVES
How to calculate the execution time for a piece of code.
How to interpret the different execution times of various instructions.
How to write efficient codes.
How to evaluate a particular program with respect to its performance measure
SOFTWARE TOOLS:
THEORY
Instruction cycle
The instruction cycle is the time period during which one instruction is fetched from memory
and executed when a computer is given an instruction in machine language. There are
typically five stages of an instruction cycle that the CPU carries out:
"Fetch the instruction" from memory. This step brings the instruction into the instruction
register, a circuit that holds the instruction so that it can be decoded and executed.
Steps 1 and 2 are called the fetch cycle and are the same for each instruction. Steps 3 and 4
are called the execute cycle and will change with each instruction. The term refers to both
the series of four steps and also the amount of time that it takes to carry out the four steps.
An instruction cycle also is called a machine cycle and fetch-and-execute cycle.
Execution Time:
The execution time of a program consists of many factors, most of which are ignored (such as
waits for I/O, instruction fetch times, pipeline delays, etc.)
Page | 41
Lab Manual of Computer Organization and Architecture
Example:
Consider two programs having three types of instructions given as follows in table 10.1:
Table10.1
Solution:
(Note: Since both programs are executing on the same machine, the T factor can be ignored
while calculating ET.)
The instruction count for program 2 is higher than program 1. Still it runs faster than program
1 as obvious from the execution time calculation
This implies that we cannot use a single metric such as instruction count or CPI for measuring
the performance.
Page | 42
Lab Manual of Computer Organization and Architecture
When comparing two different machines, the factor T (time per clock cycle) must be taken
into consideration as well.
Exercise:
1. Find the execution time of the following codes:
Code -A
; sorting a list of three numbers using bubble sort
[ORG 0x0100]
JMP LOOP1
DATA: DB 10, 5, 6
MOV BX, 0x00
LOOP1:
MOV AL, [DATA+BX] ; LOAD NUMBER IN AX
CMP AL, [DATA+BX+1] ; COMPARE WITH NEXT NUMBER
JL NOSWAP ; NO SWAP IF ALREADY IN ORDER
MOV DL, byte[DATA+BX+1] ; LOAD SECOND ELEMENT IN DX
MOV byte [DATA+BX+1], AL ; STORE FIRST NUMBER IN SECOND
MOV byte [DATA+BX], DL ; STORE SECOND NUMBER IN FIRST
NOSWAP:
ADD BX, 1 ; ADVANCE BX TO NEXT INDEX
CMP BX, 2 ; ARE WE AT LAST INDEX
JNE LOOP1 ; IF NOT COMPARE NEXT TWO
MOV AX, 0X4C00 ; TERMINATE PROGRAM
INT 0X21
Code –B
[ORG 0x0100]
MOV BX, 0x00
start:
MOV AL, [DATA+BX] ; LOAD NUMBER IN AX
ADD AH,AL
ADD BX, 0x01
CMP BX, 0x0A
JNE start
MOV AX, 0X4C00 ; TERMINATE PROGRAM
INT 0X21
DATA: DB 1,2,3,4,5,6,7,8,9,10
Page | 43
Lab Manual of Computer Organization and Architecture
2. Write a program to find the GCD (Greatest common divisor) of two numbers M and
N, placed in the memory, according to following algorithm.
a. Divide M by N, getting Quotient Q and Remainder R.
b. If R = 0, Stop, N is the GCD of M and N.
c. If R ≠ 0, replace M by N and N by R and go to step (a).
Page | 44
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 11
USING BIOS SERVICES AND DOS FUNCTIONS
OBJECTIVES
The objective of this experiment is to introduce BIOS and DOS interrupt service routines to be
utilized in assembly language programs. In this experiment, you will use BIOS and DOS
services to write programs that can do the following: • Read a character/string from the
keyboard • Output a character/string to the display monitor • Clear the display screen • and
display cursor at a desired location on the screen
SOFTWARE TOOLS:
THEORY
The Basic Input Output System (BIOS) is a set of x86 subroutines stored in Read-Only
Memory (ROM) that can be used by any operating system (DOS, Windows, Linux, etc) for
low-level input/output to various devices. Some of the services provided by BIOS are also
provided by DOS. In fact, a large number of DOS services make use of BIOS services. There
are different types of interrupts available which are divided into several categories as shown
below in table 11.1:
Table11. 1
BIOS and DOS interrupt routines provide a number of services that can be used to write
programs. These services include formatting disks, creating disk files, reading from or writing
to files, reading from keyboard, writing to display monitor, etc. The software interrupt
instruction INT is used for calling these services.
Positions on the screen are referenced using (row, column) coordinates. The upper left corner
has coordinates (0,0). For an 80 x 25 display, the rows are 0-24 and the columns are 0-79
shown in figure 11.1.
Page | 45
Lab Manual of Computer Organization and Architecture
Figure 11. 1
Character input with echo (INT 21H, Function 01H): Reads a character from the standard
input device (usually the keyboard) and echoes it to the standard output device (usually the
display screen), or waits until a character is available. Example given in figure 11.2.
Figure 11. 2
Character input without echo (INT 21H, Function 07H): Reads a character from the
standard input device (usually the keyboard) without echoing it to the standard output device,
or waits until a character is available. This function can be used when you don’t want the input
characters to appear on the display, for example, in the case of password entry. Example given
in figure 11.3
Figure 11. 3
Page | 46
Lab Manual of Computer Organization and Architecture
Display Character (INT 21H, Function 02H): Displays a character at the standard output
device (usually the display screen). Example given in figure 11.4
Figure 11. 4
Exit program and return control to DOS (INT 21H, Function 4CH): Terminates current
process and returns control either to the parent process or DOS. Example given in figure 11.5
Figure 11. 5
Set Video Mode (INT 10H, Function 00H): Selects the video mode and clears the screen
automatically. Example given in figure 11.6
Figure 11. 6
Set Cursor Position (INT 10H, Function 02H): Sets the position of the display cursor by
specifying the character coordinates. Example given in figure 11.7
Figure 11. 7
Page | 47
Lab Manual of Computer Organization and Architecture
Problem
1. Write a code to read a key from the keyboard, and displays the next character on
screen. For example, if ‘e’ is pressed then ‘f’ is displayed
2. Write a code to clear screen, and displays following string. The string has a
background color = white and foreground color = black
“Hello World”
3. Write an assembly code that performs following functions
a. Clear the screen
b. Write “C” on screen at coordinates (12,40)
c. Wait for a key to be pressed ,
d. If a ‘L’ is pressed, display ‘Left’ on left of ‘C’ (output = Left C)
e. If a ‘R’ pressed, display ‘Right’ on right of ‘C’ (Output = Right C)
Page | 48
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 12
INSTRUCTION PIPELINE
OBJECTIVES
Understanding instruction pipeline using MIPS Simulator
To understand different pipeline hazards
SOFTWARE TOOLS:
THEORY
WinMIPS64 Simulator
WinMIPS64 is a Windows based simulator of a pipelined implementation of the MIPS64 64-
bit processor. The user interface of simulator comprises a main window that appears with
seven child windows and a status line at the bottom. The seven child windows are Pipeline,
Code, Data, Registers, Statistics, Cycles and Terminal windows shown in Figure 12.1.
Figure 12. 1
You may refer to winmips64_Tutorial.pdf for detailed instructions to use this simulator.
Page | 49
Lab Manual of Computer Organization and Architecture
Instruction Pipelining
MIPS pipeline consists of five stages given in Figure 12.2. All stages are described in table
12.1
Figure 12. 2
Table12. 1
As, different instructions are present at different stages of the pipeline at any one clock cycle,
new registers are needed between each successive stages of the pipeline. These pipeline
registers contain all control information that is needed by that instruction. These registers are
referred to by the pair of stages:
• IF/ID
• ID/ALU
• ALU/MEM
• MEM/WB
If n is total number of instructions, each having k stages, and ?is the time of each stage then
execution time, speedup and throughput are defined as follows:
Speedup = tnp / tp
Page | 50
Lab Manual of Computer Organization and Architecture
Pipeline Hazards
A pipeline hazard is a situation that prevents the next instruction in the instruction stream from
executing during its designated clock cycle. A pipeline hazard is a source of performance
degradation. There are three classes of hazards:
Structural Hazards:
They arise from resource conflicts when the hardware cannot support all possible
combinations of instructions in simultaneous overlapped execution.
Data Hazards:
They arise when an instruction depends on the result of a previous instruction in a way that is
exposed by the overlapping of instructions in the pipeline.
Control Hazards:
They arise from the pipelining of branches and other instructions that change the PC.
Exercise - 1
Save the code given in Figure 12.3 in \winmips64 folder with .s extension. Open command
prompt and compile it using command asmfilename.s. Open the .s file WinMIPS64. Simulate
the code step by step by pressing F7.
.data
A: .word 4
B: .word 5
C: .word 0
.text
main:
dadd r1, r2, r3 ;r1=r2+r3
dadd r6, r5, r4 ;r5 =r5+r4
halt
Figure 12. 3
Page | 51
Lab Manual of Computer Organization and Architecture
B. If this code is run for non-pipeline architecture, what would be the total execution
time?
C. If this code is run for non-pipeline architecture, what would be the throughput?
E. Calculate speedup
G. Compare your solution with the result of simulator. Paste the statistics window here.
Exercise – 2
Figure 12. 4
Page | 52
Lab Manual of Computer Organization and Architecture
A. Do you find any pipeline hazard(s) in this code? If yes, which one? Also, tell the cause
of hazard.
B. Simulate the code, and observe that how the hazard has been handled in the pipeline.
Paste the screenshot of the pipeline + statistics window.
Exercise – 3
Run the code given in figure 12.5. in the simulator and answer the following questions
.text
main:
ld r6, 0(r0) ; r6 =0
ld r4, 4(r1) ; r4=4
dsub r2, r6, r4 ;r2=r6-r4
dmul r2, r6, r1 ;r2=r6xr1
daddi r2, r2, 4 ;r2=r2+4
halt
Figure 12. 5
C. How many pipeline hazards are there? Mention all the hazards with their causes.
Page | 53
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 13
STRING INSTRUCTIONS
OBJECTIVES
To be able to use string instructions
To be able to use index registers SI and DI for string operations.
SOFTWARE TOOLS:
THEORY
There are just 5 block processing instructions in 8088. In the primitiveform, the instructions
themselves operate on a single cell of memory at onetime. However a special prefix repeats
the instruction in hardware called theREP prefix. The REP prefix allows these instructions to
operate on a numberof data elements in one instruction. This is not like a loop; rather
thisrepetition is hard coded in the processor. The five instructions are STOS,LODS, CMPS,
SCAS, and MOVS called store string, load string, comparestring, scan string, and move string
respectively. MOVS is the instructionthat allows memory to memory moves, as was discussed
in the exceptions tothe memory to memory movement rules. String instructions are
complexinstruction in that they perform a number of tasks against one instruction.And with
the REP prefix they perform the task of a complex loop in oneinstruction. This causes drastic
speed improvements in operations on largeblocks of memory. The reduction in code size and
the improvement in speedare the two reasons why these instructions were introduced in the
8088processor.
There are a number of common things in these instructions. Firstly theyall work on a block of
data. DI and SI are used to access memory. SI and DIare called source index and destination
index because of string instructions.Whenever an instruction needs a memory source, DS:SI
holds the pointer toit. An override is possible that can change the association from DS but
thedefault is DS. Whenever a string instruction needs a memory destination,ES:DI holds the
pointer to it. No override is possible in this case. Whenever a byte register is needed, AL holds
the value. Whenever a word register is usedAX holds the value. For example STOS stores a
register in memory so AL orAX is the register used and ES:DI points to the destination. The
LODSinstruction loads from memory to register so the source is pointed to byDS:SI and the
register used is AL or AX.
String instructions work on a block of data. A block has a start and anend. The instructions can
work from the start towards the end and from theend towards the start. In fact they can work in
both directions, and theymust be allowed to work in both directions otherwise certain
operations withoverlapping blocks become impossible. This problem is discussed in
Page | 54
Lab Manual of Computer Organization and Architecture
detaillater. The direction of movement is controlled with the Direction Flag (DF) inthe flags
register. If this flag is cleared the direction is from lower addressestowards higher addresses
and if this flag is set the direction is from higheraddresses to lower addresses. If DF is cleared,
this is called the autoincrementmode of string instruction, and if DF is set, this is called the
autodecrementmode. There are two instructions to set and clear the directionflag.
Every string instruction has two variants; a byte variant and a wordvariant. For example the
two variants of STOS are STOSB and STOSW.Similarly the variants for the other string
instructions are attained byappending a B or a W to the instruction name. The operation of
each of thestring instructions and each of the repetition prefixes is discussed below.
REP Prefix
REP repeats the following string instruction CX times. The use of CX isimplied with the REP
prefix. The decrement in CX doesn’t affect any flags andthe jump is also independent of the
flags, just like JCXZ.
REPE and REPNE Prefixes
REPE or REPZ repeat the following string instruction while the zero flag isset and REPNE or
REPNZ repeat the following instruction while the zero flagis not set. REPE or REPNE are
used with the SCAS or CMPS instructions. The other string instructions have nothing to do
with the condition sincethey are performing no comparison. Also the initial state of flags
before thestring instruction does not affect the operation. The most complex operationof the
string instruction is with these prefixes.
STOS
STOS transfers a byte or word from register AL or AX to the string elementaddressed by
ES:DI and updates DI to point to the next location. STOS isoften used to clear a block of
memory or fill it with a constant.The implied source will always be in AL or AX. If DF is
clear, DI will beincremented by one or two depending on whether STOSB or STOSW is
used.If DF is set DI will be decremented by one or two depending on whetherSTOSB or
STOSW is used. If REP is used before this instruction, the processwill be repeated CX times.
CX is called the counter register because of thespecial treatment given to it in the LOOP and
JCXZ instructions and the REPset of prefixes. So if REP is used with STOS the whole block
of memory willbe filled with a constant value. REP will always decrement CX like the
LOOPinstruction and this cannot be changed with the direction flag. It is alsoindependent of
whether the byte or the word variant is used. It alwaysdecrements by one; therefore CX has
count of repetitions and not the countof bytes.
Page | 55
Lab Manual of Computer Organization and Architecture
LODS
LODS transfers a byte or word from the source location DS:SI to AL or AXand updates SI to
point to the next location. LODS is generally used in a loopand not with the REP prefix since
the value previously loaded in the registeris overwritten if the instruction is repeated and only
the last value of theblock remains in the register.
Page | 56
Lab Manual of Computer Organization and Architecture
mov bp, sp
push es
push ax
push cx
push si
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+10] ; multiply with y position
add ax, [bp+12] ; add x position
shl ax, 1 ; turn into byte offset
mov di,ax ; point di to required location
mov si, [bp+6] ; point si to string
mov cx, [bp+4] ; load length of string in cx
mov ah, [bp+8] ; load attribute in ah
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 10
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
push word [length] ; push message length
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
Page | 57
Lab Manual of Computer Organization and Architecture
SCAS
SCAS compares a source byte or word in register AL or AX with thedestination string element
addressed by ES:DI and updates the flags. DI isupdated to point to the next location. SCAS is
often used to locate equality orin-equality in a string through the use of an appropriate
prefix.SCAS is a bit different from the other instructions. This is more like theCMP
instruction in that it does subtraction of its operands. The prefixesREPE (repeat while equal)
and REPNE (repeat while not equal) are used withthis instruction. The instruction is used to
locate a byte in AL in the block ofmemory. When the first equality or inequality is
encountered; both haveuses. For example this instruction can be used to search for a 0 in a
nullterminated string to calculate the length of the string. In this form REPNEwill be used to
repeat while the null is not there.
Example 3: ; Printing “hello world” with a null terminated string
; hello world printing with a null terminated string
[org 0x0100]
jmp start
message: db 'hello world', 0 ; null terminated string
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
; subroutine to print a string
; takes the x position, y position, attribute, and address of a null
; terminated string as parameters
printstr: push bp
mov bp, sp
push es
push ax
push cx
push si
push di
push ds
pop es ; load ds in es
mov di, [bp+4] ; point di to string
mov cx, 0xffff ; load maximum number in cx
xor al, al ; load a zero in al
repne scasb ; find zero in the string
mov ax, 0xffff ; load maximum number in ax
sub ax, cx ; find change in cx
dec ax ; exclude null from length
jz exit ; no printing if string is empty
mov cx, ax ; load string length in cx
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+8] ; multiply with y position
add ax, [bp+10] ; add x position
Page | 58
Lab Manual of Computer Organization and Architecture
MOVS
MOVS transfers a byte or word from the source location DS:SI to thedestination ES:DI and
updates SI and DI to point to the next locations.MOVS is used to move a block of memory.
The DF is important in the case ofoverlapping blocks. For example when the source and
destination blocksoverlap and the source is below the destination copy must be done
upwardswhile if the destination is below the source copy must be done downwards.We cannot
perform both these copy operations properly if the direction flagwas not provided. If the
source is below the destination and an upwards copyis used the source to be copied is
destroyed. If however the copy is donedownwards the portion of source destroyed is the one
that has already been copied. Therefore we need the control of the direction flag to handle
thisproblem.
CMPS
Page | 59
Lab Manual of Computer Organization and Architecture
CMPS subtracts the source location DS:SI from the destination locationES:DI. Source and
Destination are unaffected. SI and DI are updatedaccordingly. CMPS compares two blocks of
memory for equality or inequalityof the block. It subtracts byte by byte or word by word. If
used with a REPEor a REPNE prefix is repeats as long as the blocks are same or as long
asthey are different. For example it can be used for find a substring. Asubstring is a string that
is contained in another string. For example “has” iscontained in “Mary has a little lamp.”
Using CMPS we can do the operation ofa complex loop in a single instruction. Only the REPE
and REPNE prefixesare meaningful with this instruction.
Problems:
2. Write a strcpy function to copy the larger string found in above function in to memory
location named Larger and copy the smaller string in the memory location named
smallerusing string instructions.
3. Write a strlen function to find the lengthof given string using string instructions.
Page | 60
Lab Manual of Computer Organization and Architecture
EXPERIMENT- 14
MULTITASKING
OBJECTIVE:
To run two tasking using timer interrupt and observing their
multitasking behavior.
SOFTWARE TOOLS:
THEORY:
If we have two different programs A and B. Program A is broken, its state saved, and returned
to B instead of A. By looking at the instruction set, we can immediately say that nothing can
stop us from doing that.
IRET will return to whatever CS and IP it finds on the stack. Now B is interrupted somehow,
its state saved, and we return back to A. A will have no way of knowing that it was interrupted
as its entire environment has been restored. It never knew the debugger took control when it
was debugged. It sill has no way of gaining this knowledge. If this work of breaking and
restoring programs is done at high speed the user will feel that all the programs are running at
the same time where actually they are being switched to and forth at high speed.
EXAMPLE 14.1
The example given in Figure 14.1 shows how we can change flow of execution form one task
to another. The two subroutines rotate bars by changing characters at the two corners of the
screen and have infinite loops. By hooking the timer interrupts and saving and restoring the
registers of the tasks one by one, it appears that both tasks are running simultaneously.
Page | 61
Lab Manual of Computer Organization and Architecture
Page | 62
Lab Manual of Computer Organization and Architecture
Figure 14. 1
Question: Insert another task in above example that displays the rotating bar in the center of
the screen on first row. (Now total three rotating bars will be displayed on the screen
simultaneously).
Write two tasks first task is an up counter and second is a down counter. Now run the tasks
using multitasking and show the result of up counter at Screen top left corner and result of
down counter at top left corner.
Page | 63
Lab Manual of Computer Organization and Architecture
Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of
copying may entail ZERO in that experiment. Second instance of copying may be reported to
DC. This may result in awarding FAIL in the lab course.
Page | 64
Lab Manual of Computer Organization and Architecture
Remember that the voltage of the electricity and the available electrical current in EE
labs has enough power to cause death/injury by electrocution. It is around 50V/10 mA
that the “cannot let go” level is reached. “The key to survival is to decrease our
exposure to energized circuits.”
If a person touches an energized bare wire or faulty equipment while grounded,
electricity will instantly pass through the body to the ground, causing a harmful,
potentially fatal, shock.
Each circuit must be protected by a fuse or circuit breaker that will blow or “trip”
when its safe carrying capacity is surpassed. If a fuse blows or circuit breaker trips
repeatedly while in normal use (not overloaded), check for shorts and other faults in
the line or devices. Do not resume use until the trouble is fixed.
It is hazardous to overload electrical circuits by using extension cords and multi-plug
outlets. Use extension cords only when necessary and make sure they are heavy
enough for the job. Avoid creating an “octopus” by inserting several plugs into a multi-
plug outlet connected to a single wall outlet. Extension cords should ONLY be used on
a temporary basis in situations where fixed wiring is not feasible.
Dimmed lights, reduced output from heaters and poor monitor pictures are all
symptoms of an overloaded circuit. Keep the total load at any one time safely below
maximum capacity.
If wires are exposed, they may cause a shock to a person who comes into contact with
them. Cords should not be hung on nails, run over or wrapped around objects, knotted
or twisted. This may break the wire or insulation. Short circuits are usually caused by
bare wires touching due to breakdown of insulation. Electrical tape or any other kind
of tape is not adequate for insulation!
Electrical cords should be examined visually before use for external defects such as:
Fraying (worn out) and exposed wiring, loose parts, deformed or missing parts,
damage to outer jacket or insulation, evidence of internal damage such as pinched or
crushed outer jacket. If any defects are found the electric cords should be removed
from service immediately.
Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
Plug your heavy current consuming or any other large appliances into an outlet that is
not shared with other appliances. Do not tamper with fuses as this is a potential fire
hazard. Do not overload circuits as this may cause the wires to heat and ignite
insulation or other combustibles.
Keep lab equipment properly cleaned and maintained.
Ensure lamps are free from contact with flammable material. Always use lights bulbs
with the recommended wattage for your lamp and equipment.
Be aware of the odor of burning plastic or wire.
ALWAYS follow the manufacturer recommendations when using or installing new lab
equipment. Wiring installations should always be made by a licensed electrician or
other qualified person. All electrical lab equipment should have the label of a testing
laboratory.
Page | 65
Lab Manual of Computer Organization and Architecture
Be aware of missing ground prong and outlet cover, pinched wires, damaged casings
on electrical outlets.
Inform Lab engineer / Lab assistant of any failure of safety preventive measures and
safe practices as soon you notice it. Be alert and proceed with caution at all times in
the laboratory.
Conduct yourself in a responsible manner at all times in the EE Labs.
Follow all written and verbal instructions carefully. If you do not understand a
direction or part of a procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT
BEFORE PROCEEDING WITH THE ACTIVITY.
Never work alone in the laboratory. No student may work in EE Labs without the
presence of the Lab engineer / Lab assistant.
Perform only those experiments authorized by your teacher. Carefully follow all
instructions, both written and oral. Unauthorized experiments are not allowed.
Be prepared for your work in the EE Labs. Read all procedures thoroughly before
entering the laboratory. Never fool around in the laboratory. Horseplay, practical
jokes, and pranks are dangerous and prohibited.
Always work in a well-ventilated area.
Observe good housekeeping practices. Work areas should be kept clean and tidy at all
times.
Experiments must be personally monitored at all times. Do not wander around the
room, distract other students, startle other students or interfere with the laboratory
experiments of others.
Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or
baggy clothing are a hazard in the laboratory. Long hair must be tied back, and
dangling jewelry and baggy clothing must be secured. Shoes must completely cover
the foot.
Know the locations and operating procedures of all safety equipment including fire
extinguisher. Know what to do if there is a fire during a lab period; “Turn off
equipment, if possible and exit EE lab immediately.”
Page | 66
Lab Manual of Computer Organization and Architecture
Introduction
The ability to control the flow of the program, letting it make decisions on what code to
execute, is important to the programmer. The if-else statement allows the programmer to
control if a program enters a section of code or not based on whether a given condition is true
or false. If-else statements control conditional branching.
if ( expression )
statement1
else
statement2
If the value of expression is nonzero, statement1 is executed. If the optional else is present,
statement2 is executed if the value of expression is zero. In this lab, we use this construct to
select an action based upon the user's input, or a predefined parameter.
Page | 67
Lab Manual of Computer Organization and Architecture
Objective:
Design:
#include<iostream>
Usingnamespacestd;
Intmain()
{
inti,temp,d,revrs=0;
}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";
}
}
Screen shots of the output for various inputs are shown in Figure 2:
The conditional statement made this implementation possible; without conditional branching,
it is not possible to achieve this objective.
Page | 68
Lab Manual of Computer Organization and Architecture
Issues:
Encountered bugs and issues; how were they identified and resolved.
Conclusions:
Applications:
Page | 69