0% found this document useful (0 votes)
55 views

Electric Network Analysis Lab

This document provides instructions for Lab 4 on stack operations, procedures, and conditional instructions in x86 assembly language. The lab goals are to use stack memory with PUSH and POP, define and call procedures, use Irvine library procedures for input/output, and implement logical problems with conditional jumps. The document describes stack operations, procedures using RET and CALL, the USES operator, and Irvine library procedures for integer and string input/output. Students are to complete the lab individually and seek help if needed from instructors.

Uploaded by

Download Klye
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Electric Network Analysis Lab

This document provides instructions for Lab 4 on stack operations, procedures, and conditional instructions in x86 assembly language. The lab goals are to use stack memory with PUSH and POP, define and call procedures, use Irvine library procedures for input/output, and implement logical problems with conditional jumps. The document describes stack operations, procedures using RET and CALL, the USES operator, and Irvine library procedures for integer and string input/output. Students are to complete the lab individually and seek help if needed from instructors.

Uploaded by

Download Klye
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Electrical EngineeringDepartment – ITU

EE243L: Microcontrollers and Interfacing Lab

Course Instructor: Dated:

Lab Engineer 1: Semester:

Lab Engineer 2: Session:

Lab 4 –Stack Operations, Procedures and Conditional Instructions in


x86 Assembly Language

Report Viva Total


Name Roll number Scaled to 10
(out of 22) (out of 5) (out of 15)

Muhammad Farhan Ali BSEE19036

Checked on: ____________________________

Signature: ____________________________

1
EE243L: Microcontrollers and Interfacing Lab

4 Stack Operations, Procedures and Conditional


Instructions in x86 Assembly Language
Introduction
This lab introduces students to stack operations, defining and using procedures and conditional jump statements.

Lab goals
This lab will enable students to achieve the following:
 Use stack memory using PUSH and POP instructions to write assembly language programs
 Define procedures and call these procedures to perform certain tasks in program
 Learn how to use Irvine library procedures to input and output data on console screen
 Implement logical problems using conditional jump statements

Lab conduct
1. You have to perform this experiment using Visual Studio 2015 and Irvine libraries for MASM.
2. You are required to work individually; everyone must attempt to understand the purpose of assembly language
coding and simulated set up for the given experiment.
3. In case some aspect of the lab experiment is not understood,you are advised to seek help from the instructor, lab
engineer or the TA.

Lab details
4.1 Stack operations: PUSH and POP
4.1.1 Runtime stack
“Stack” is a section of main memory that is accessible to the processor in a Last-In, First-Out (LIFO) manner.
The runtime stack is a memory array managed directly by the CPU, using the ESP (Extended Stack Pointer) register. In
32-bit mode, ESP register holds a 32-bit offset into some location on the stack. We rarely manipulate ESP directly;
instead, it is indirectly modified by instructions such as CALL, RET, PUSH, and POP. ESP always points to the last
value to be added to, or pushed on to the top of stack.
There are several important uses of runtime stacks in programs:
 A stack makes a convenient temporary save area for registers when they are used for more than one purpose. After
they are modified, they can be restored to their original values.
 When the CALL instruction executes, the CPU saves the current subroutine’s return address on the stack.
 When calling a subroutine, you pass input values called arguments by pushing them on the stack.
 The stack provides temporary storage for local variables inside subroutines.
4.1.2 PUSH instruction
The PUSH instruction first decrements ESP and then copies a source operand into the stack. A 16-bit operand causes
ESP to be decremented by 2. A 32-bit operand causes ESP to be decremented by 4. There are three instruction formats:
PUSH reg/mem16
PUSH reg/mem32
PUSH imm32

2
Lab-4

4.1.3 POP instruction


The POP instruction first copies the contents of the stack element pointed to by ESP into a 16- or 32-bit destination
operand and then increments ESP. If the operand is 16 bits, ESP is incremented by 2; if the operand is 32 bits, ESP is
incremented by 4:
POP reg/mem16
POP reg/mem32

4.2 Procedures: RET and CALL instructions


In higher level languages, it is often deemed useful to divide the program into subroutines. In assembly language, such
subroutines are called “procedures”. A procedure is declared using the PROC and ENDP directives. It must be assigned a
name (a valid identifier). Each program we have written so far contains a procedure named main, for example:
main PROC
.
.
main ENDP
4.2.1 RET instruction
When you create a procedure other than your program’s startup/main procedure, end it with a RET instruction. RET
forces the CPU to return to the location from where the procedure was called.
sample PROC
.
.
ret
sample ENDP
4.2.2 CALLinstruction
The CALL instruction calls a procedure by directing the processor to begin execution at a new memory location. The
procedure uses a RET (return from procedure) instruction to bring the processor back to the point in the program where
the procedure was called. Mechanically speaking, the CALL instruction pushes its return address on the stack and copies
the called procedure’s address into the instruction pointer. When the procedure is ready to return, its RET instruction
pops the return address from the stack into the instruction pointer. In 32-bit mode, the CPU executes the instruction in
memory pointed to by EIP (instruction pointer register).
The syntax for CALL instruction is as follows:
CALL sample
4.2.3 USES operator
The USES operator, coupled with the PROC directive, lets you list the names of all registers modified within a
procedure. USES tells the assembler to do two things: First, generate PUSH instructions that save the registers on the
stack at the beginning of the procedure. Second, generate POP instructions that restore the register values at the end of
the procedure. The USES operator immediately follows PROC, and is itself followed by a list of registers on the same
line separated by spaces or tabs (not commas). For example:
sample PROC USES esi ecx
4.2.4 Procedureexample
The following example calls a procedure ArraySum that sums a word array. The USES operator in the procedure
definition statement ensures that the values of ESI and ECX are restored after the procedure is called.
.386
.model flat, stdcall
.stack 4096

3
EE243L: Microcontrollers and Interfacing Lab

ExitProcess PROTO, dwExitCode:DWORD


.data
array DWORD 10000h,20000h,30000h,40000h,50000h
theSum DWORD ?
.code
main PROC
mov esi,OFFSET array ; ESI points to array
mov ecx,LENGTHOF array ; ECX = array count
call ArraySum ; calculate the sum
mov theSum,eax ; returned in EAX
INVOKE ExitProcess,0
main ENDP
;-----------------------------------------------------
; ArraySum
; Calculates the sum of an array of 32-bit integers.
; Receives: ESI = the array offset
; ECX = number of elements in the array
; Returns: EAX = sum of the array elements
;-----------------------------------------------------
ArraySum PROC USES esi ecx
mov eax,0 ; set the sum to zero
L1:
add eax,[esi] ; add each integer to sum
add esi,TYPE DWORD ; point to next integer
loop L1 ; repeat for array size
ret ; sum is in EAX
ArraySum ENDP
END main

4.3 Irvinelibrary procedures


4.3.1 Integerinput: ReadInt
The “ReadInt” procedure reads a 32-bit signed integer from the keyboard and returns the value in EAX. The user can
type an optional leading plus or minus sign, and the rest of the number may only consist of digits. ReadInt sets the
Overflow flag and displays an error message if the value entered cannot be represented as a 32-bit signed integer (range:
-2,147,483,648 to +2,147,483,647). The return value is calculated from all valid digits found until a non-digit character is
encountered. For example, if the user enters +123ABC, the value returned is +123. See the sample call below:
.data
intVal SDWORD ?
.code
call ReadInt
mov intVal,eax
4.3.2 String input: ReadString
The “ReadString” procedure reads a string from the keyboard, stopping when the user presses the Enter key. The offset
of a buffer is passed in EDX and ECX is set to the maximum number of characters the user can enter, plus 1 (to save
space for the terminating null byte). The procedure returns the count of the number of characters typed by the user in
EAX. See below a sample call to ReadString:
.data
buffer BYTE 21 DUP(0) ; input buffer
byteCount DWORD ? ; holds counter
.code
mov edx,OFFSET buffer ; point to the buffer

4
Lab-4

mov ecx,SIZEOF buffer ; specify max characters


call ReadString ; input the string
mov byteCount,eax ; number of characters
ReadString automatically inserts a null terminator in memory at the end of the string. The following is a hexadecimal and
ASCII dump of the first 8 bytes of buffer after the user has entered the string “ABCDEFG”:
41 42 43 44 45 46 47 00
4.3.3 Display an integer: WriteInt
The “WriteInt” procedure writes a 32-bit signed integer to the console window in decimal format with a leading sign and
no leading zeros. Integer to be displayed is passed in EAX. See below a sample call to WriteInt:
mov eax,216543
call WriteInt ; displays: "+216543"
4.3.4 Display a string: WriteString
The “WriteString” procedure writes a null-terminated string to the console window. String’s offset is passed in EDX. See
below WriteString sample call:
.data
prompt BYTE "Enter your name: ",0
.code
mov edx,OFFSET prompt
call WriteString

4.4 Conditional JUMP instructions


Logical structures like if-else present in higher-level languages can be implemented using comparisons and conditional
jump statements in assembly language. Two steps are involved in executing such a conditional statement: First, an
operation such as CMP, AND or SUB modifies the CPU status flags. Second, a conditional jump instruction tests the
flags and causes a branch to a new address. Let’s look at the following example:
cmp eax, 0
jz L1 ; jump if ZF = 1
.
.
L1:
The CMP instruction compares EAX register with zero, and jumps to label L1 if the Zero flag was set by the CMP
instruction.
Although there are many conditional jump instructions in assembly, you will only require one or two of the following to
complete this lab:
Table 4.1: Conditional jump instructions

Mnemonic Description
JZ Jump if zero
JNZ Jump if not zero
JC Jump if carry
JNC Jump if not carry
JL Jump if lower for signed comparison
JG Jump if greater for signed comparison
JE Jump if equal
JNE Jump if not equal

5
EE243L: Microcontrollers and Interfacing Lab

4.5 DIV instruction


The unsigned division instruction DIV divides a dividend stored in AX (16-bit), DX:AX (32-bit), EDX:EAX (64-bit) by
a 8-, 16- or 32-bit operand that can be a memory location or a register. The quotient is stored in AL, AX and EAX and
remainder in AH, DX and EDX respectively. The syntax is as follows:
DIV reg/mem8
DIV reg/mem16
DIV reg/mem32

Lab tasks
1. The following program sums a DWORD integer array and stores the result in a new variable “theSum”. It uses a
procedure “ArraySum” that is defined below the main procedure. You are required to run this program in debugging
mode line-by-line and record the changes in relevant registers after each line executes. Ignore the lines that are not
executed (data and directive lines).
Statement Registers
.386
.model flat, stdcall
.stack 4096
ExitProcess PROTO,
dwExitCode:DWORD
.data
array DWORD 10000h,
20000h, 30000h, 40000h,
50000h
theSum DWORD ?
.code
main PROC
mov esi,OFFSET array EIP = 00741021 ESI = 00744000
mov ecx,LENGTHOF
ECX = 00000005 EIP = 00741026
array
call ArraySum
mov theSum,eax
INVOKE ExitProcess,0
main ENDP
ArraySum PROC EIP = 00741037 ESP = 003FF9FC
push esi EIP = 00741038 ESP = 003FF9F8
push ecx EIP = 00741039 ESP = 003FF9F4
mov eax,0 EAX = 00000000 EIP = 0074103E
L1:
add eax,[esi] EAX = 00010000EIP = 00741040EFL = 00000206
add esi,TYPE DWORD ESI = 00744004EIP = 00741043EFL = 00000202PE = 0
loop L1 ECX = 00000004EIP = 0074103EEAX = 00030000EIP = 00741040EFL = 00000206
pop ecx ECX = 00000005EIP = 00741046ESP = 00F6FA34
pop esi ESI = 00744000EIP = 00741047 ESP = 00F6FA38
ret
ArraySum ENDP
END main
2. Define a procedure named “factorial_proc” that returns in EAX the factorial of a number saved in EBX. Use this
procedure to find factorial of each element in the array my_arr initialized as below and store each factorial at its
respective place in a new array arr_factorial.
my_arr WORD 1, 3, 5, 7, 9

6
Lab-4

Paste screenshot of code and Memory window showing final result here:

3. Write a program that inputs from user a string of maximum 20 characters. The prompt displayed on screen should be
as follows:
Please enter a string of maximum 20 characters:
The program then checks whether the string is a palindrome or not and outputs accordingly on DOS screen one of
the following strings:
Yes, a palindrome!
No, not a palindrome…
Paste screenshot of code and console window showing one instance of both cases (palindrome, not palindrome):

7
EE243L: Microcontrollers and Interfacing Lab

4. Write a procedure that returns a 0 in EBX if the remainder of the division of a numberkept in EAX register by a
number in any register of your choice (size should be 16 bits) is zero and returns 1 in EBX if the remainder is non-
zero. Paste here screenshot of code and Registers window showing final output:

8
Lab-4

9
EE243L: Microcontrollers and Interfacing Lab

Assessment Rubric for Lab 4


Task Performance Max Excellent Good Poor Obtainedmarks
metric marks
1 Ability to identify 6 Notes down contents Notes down contents Notes down contents of
registers relevant of ESP and EIP after of ESP and EIP after ESP and EIP after
to CALL, RET, PUSH, POP, CALL PUSH, POP, CALL PUSH, POP, CALL &
PUSH & POP & RET instructions & RET instructions RET instructions and
instructions and and also records the and also records the also records the value of
recording correct value of other value of other other registers in use
value of other registers in use with registers in use with 1 with 9 to 13 errors (2, 1,
registers no errors (6) to 8 errors (5, 4, 3) 0)
2 Definition of a 1 Defines Defines factorial_proc Is unable to define
procedure factorial_proc by by using PROC factorial_proc (0)
using PROC directive and uses
directive and uses RET instruction
RET instruction inside the procedure
inside the procedure with syntax or
with no syntax errors runtime errors (0.5)
(1)
2 Choice of MUL 1 Chooses 16-bit Chooses Chooses 8-bit version of
version for the version of MUL to unnecessarily higher MUL (0)
result of factorial accommodate version of MUL (0.5)
factorial of 9 (1)
2 Use of procedure 3 Uses factorial_proc Uses factorial_proc Uses factorial_proc
inside loop and inside a loop to find inside a loop to find inside loop but has
result of factorial factorials of elements factorials of elements syntactic errors or
array of arr and stores of arr and stores result produces result that has
result in arr_factorial in arr_factorial with 1 3 – 5 errors (1, 0)
with no error (3) to 2 errors (2)
2 Presentation of 1 Pastes screenshots of Presents the result in Does not present the
results for Task 2 memory window in an unclear manner result in the manual (0)
in manual VS showing (0.5)
arr_factorial or
records the same in
text (1)
3 String display and 2 Includes Irvine.inc, Includes Irvine.inc, Can neither display the
string input from and uses WriteString and uses WriteString prompt nor input from
user and ReadString and ReadString user (0)
procedures to display procedures to display
prompt in console prompt in console
window and store window and store
user input in buffer user input in buffer
array with no error array but the result
(2) has errors either in
displaying prompt or
reading string (1)
3 Interpretation of 4 Understands problem Understands problem Cannot interpret the
problem statement statement and devises statement and devises problem, or is unable to
and a solution to check a solution to check for devise a method to
implementation for palindrome, palindrome, check palindrome and in
implements it in code implements it in code the case a result is
with accurate result with minor logical obtained, it is not
(4) errors that yield correct (1, 0)
inaccurate result (3,
2)
3 Presentation of 1 Pastes screenshots of Presents the result in Does not present the
results for Task 3 console window an unclear manner result in the manual (0)
in manual showing accurate (0.5)
result of a
palindrome check (1)
4 Use of DIV 3 Uses DIV instruction Uses DIV instruction Does not use the DIV
instruction to accurately to find out to find out if the instruction in the correct
check divisibility if the division of two division of two manner and does not
numbers returns a 0 numbers returns a 0 create a procedure that

10
Lab-4

remainder and remainder and creates implements the


defines a procedure a procedure but the divisibility check (0)
that returns the result results are erroneous
in EBX as required due to incorrect
(3) register manipulation
inside procedure (2,
1)
Max marks (total): 22 Obtained marks (total):

Lab Engineer: Faculty:

Signature: ________________________ Signature: ________________________


Date: ____________________________ Date: ____________________________

11

You might also like