Lab Set I (New)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Microcomputers and Interfacing

Lab Set I
Assembling, Link, And Run an Assembly Program

Objective: Introduce tools and how to use them to assemble link and run
assembly programs.
Required knowledge, skill and materials:
● Knowledge of command-line Interface usage is required, basics commands to change directory and
run commands.
● Software
o MASM32 (Windows 16 bit & 32-bit assembler), NASM (Linux 16, 32 & 64-bit assembler)
are assemblers. If you already have VS code, installing MASM / TASM extension.
o Visual Studio (For 64-bit MASM, VS Express or VS Community is fine).
o Debug.exe: Helps you to disassemble or debug 16-bit or 32-bit binary files (In 32-bit
system you can find it inside system32 folder)
o DOS Box: is required if you want to run Debug.exe and 16-bit real mode executables on 64
bit windows system because 64-bit windows doesn’t support 16-bit real mode applications
anymore.
o Emu8086, 8086 emulator for 32 bit and 64 bit environment

Grading:
i. Attend the lab session and demonstrate your work. You must sign attendance sheet.
ii. Write a brief report and submit HERE addressing those questions labeled with “Q” .

Introduction:
8086 is a 16-bit processor with 16-bit registers. Various processors with 32-bit or 64-bit capabilities that share
the same architecture as the 8086 are known as the x86 family. There are two main categories of processor
usage: the first is in personal computer lines, where processors are used under operating system control, such
as in desktops, laptops, and handheld devices. The second category is in microcontrollers, typically used for
embedded system purposes. In this lab series, the focus will be on the first usage, where you'll need to create
executables in a format that the underlying operating system can understand (e.g., EXE files in Windows).
Subsequent labs will cover programming microcontrollers and interfacing with sensors.

Part 1: Getting started


a. Write, assemble and link your first 16-bit real mode assembly program
Read Appendix A

Before you start, make sure that you have installed MASM32 or equivalent assembler.

1. Copy Eg.asm code bellow into a new notepad or notepad++ and save it in your working directory
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

a. You can make “C:\masm32\bin” (if you have installed MASM32 in ‘C’) your working
directory by running cd /D c:\masm32\bin.
b. Or make sure to append “path” environment variable with “c:\masm32\bin” (location of
“ml.exe”) by running set PATH=%PATH%;C:\masm32\bin and continue to working in your
default working directory.
2. Run this command ml /c Eg.asm to assemble without linking (/c)
3. Run this command link16 Eg.obj to link and create executable
4. Now you have a 16-bit executable program (Eg.exe); unfortunately, it only runs on 16 or 32-bit OS
but not on 64-bit OS; hence, you need to use emulator for 16-bit real mode executable such as
DOSBox.

//Eg.asm
// *******************************************************
;Hello World example
.MODEL SMALL
.DATA
msg db "Hello, World!$"
.CODE
MAIN PROC FAR
mov ax,seg msg
mov ds,ax
mov dx, offset msg
mov ah, 9 ;
int 21H
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
// *******************************************************

b. Run your Hello World program


Before you start make sure that you have installed Dos box or equivalent emulator
1. Open DOSBox, mount your working director where you have saved “Eg.asm”
Eg. If saved in MASM installation folder in drive C, run: mount X C:\masm32\bin followed by X:
2. Type “Eg.exe” and press enter; if you see “Hello World!” congratulations! It’s a success.

Part 2: Debugging your 16-bit binary code


a. Now you will dump memory content, disassemble and debug your program. Refer here for commands of
debug.exe. Before you start, make sure to saved “debug.exe” (a 16 bit application) in your working
directory of DOSBox.
1. Copy the following code and save it as “Eg2.asm”
2. Assemble and link the code
3. Open DOSBox and run “debug Eg2.exe”
4. Type ‘d’; this shall dump the code segment memory content
Q What do you see? Explain each of the 3 columns.
5. Type ‘u’; this shall unassembled (disassemble) the binary code.
Q What do you see? Explain each of the 3 columns.
6. Type p =0000 14 ; this will execute 14 lines starting from logical address CS:0000.
7. Type r ; this will display content of all registers
Q What is the value of SUM? Is it actually the sum of data1 and data2? Assuming you don’t have the
source code (Eg2.asm) try to modify Eg2.exe so that the bug (logical error) will be fixed (Character

2
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

‘A’ was expected instead of ‘7’. Note that 65 and 55 are ASCII codes of characters ‘A’ and ‘7’
respectively. What method is used to insure that downloaded programs are not modified
unauthorized, as you did?
8. Now, type ‘?’ and play around with commands.

// Eg2.asm
// *******************************************************
;Eg.asm
.MODEL SMALL
.STACK 64
;
.DATA
DATA1 DB 60
DATA2 DB 5
SUM DB ?
;
.CODE
MAIN PROC FAR
MOV AX,@DATA
MOV DS,AX
MOV AL,DATA1
MOV BL,DATA2
SUB AL,BL
MOV AH,02
MOV DL,AL
INT 21H
MOV SUM,AL
MOV AH,4CH
INT 21H
MAIN ENDP
END MAIN
// *******************************************************

Result of Part two step 4 and 5

3
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

Part 3: Working on emu8086

Now, you will use emu8086 which simulates the 8086 processors and has built-in assembler and debugger on
top. Read Appendix C
1. Open emu8086.exe
2. From the file -> examples menu, open stepper motor. Note that this assembly code uses a
virtual stepper motor connected to virtual port 7
3. Click on emulate and observe the stepper motor.
4. Then click on single step to go through the code line by line (debug) and understand how it
works.
Q What is the step angle of the motor in half and in full step mode.
Q Modify the code so that the stepper motor rotates clockwise by 90⁰ whenever you press the up-
arrow key and the reverse when you press the down-arrow key.
Hint: use mov ah,0
int 16h
to get scan code for up and down keys and cmp instruction to choose among two directions. Note that

4
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

Part 4: Assembly programming for 32-bit or 64-bit environment


You can build assembly program in Microsoft Visual Studio which have built in MASM32 and
MASM64. You can also easily call assembly functions in “*.asm” file from c++ or C codes; even you
can code inline assembly function in 32-bit mode (not supported in 64-bit mode)

a. Building a 32-bit assembly program


Before you start make sure that you have installed MS Visual Studio for C++ (Community version is ok)

1. Open Visual Studio, Create a New empty c++ Project and name it MASM
2. Under solution explorer, right click on MASM and choose “Build Dependencies-> Build
Customizations and select masm(.target, .props).
3. Right click on MASM again and choose Properties, then select Link-> System->SubSystem choose
WINDOWS (/Subsystem:Windows)
4. Go to Configuration Properties -> Linker -> Advanced. In Advanced at the top should be Entry Point.
Type in main
5. Right click on MASM again Add->new Item->c++ File and give it a name as eg4.asm
6. Now copy and paste the following code. Right click at main PROC and select Run to Cursor to start
debugging.
7. Now from Debug->Windows open Registers, Memory and Disassembly windows to check the actual
register values and memory content of your computer then continue to debug line by line.
Q From the disassembly window, how many memory space does the “MOV eax,DATA1” instruction use

(optinal)
8. Open File->open->file open Eg.exe (of previous exercise) and try to modify to display your name
instead of “Hello World”. Never try to edit working executable in such away unless

Eg4.asm
// *******************************************************
.386
.model flat, stdcall
.stack 4096
.data
DATA1 DD 52H
DATA2 DD 29H
SUM DD ?
.code
main PROC
MOV eax,DATA1
MOV ebx, DATA2
SUB eax,ebx
MOV SUM,eax
main endp
end
// *******************************************************
b. Building a 64-bit assembly program
1. Follow the same procedure 1 to 4 in (a), and copy the following code (Eg5.asm) instead of
Eg4.asm
2. Change programing environment from x86 to x64 from drop down menu

5
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

3. Now copy and paste the following code. Right click at main PROC and select Run to Cursor to start
debugging.

Eg5.asm
// *******************************************************

.DATA
DATA1 DQ 52H
DATA2 DQ 29H
SUM DQ ?
.CODE
main PROC
MOV rax,DATA1
MOV rbx, DATA2
SUB rax,rbx
MOV SUM,rax

main endp
end
// *******************************************************
Q What is the basic difference between the codes in Eg4.asm and Eg5.asm?

c. Dump , disassemble and debug a 32/64-bit executable program using dumpbin.exe


1. Open Developer Command Prompt for VS (installed with visual studio) from start menu and
change the path to your working directory.
2. Copy and save Eg4.exe and Eg5.exe into you working directory
3. Type dumpbin /all Eg4.exe and then dumpbin /all Eg5.exe. Obser the different headers.
You will get the actual binary code under .text header
4. Now type dumpbin /disasm Eg4.exe and dumpbin /disasm Eg5.exe, you will get dissembled
code.
Q Is there any difference between machine codes for SUB in 32-bit and 64-bit instructions? What other
differences did you observe?
Q Now, to correct the know logical error, use any hex edit to modify the binary code (VS Binary Editor
or HxD Editor for Linux, MAC and Win). How did you correct it?

6
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

Appendix A: Introduction to MASM

 Originally developed by Microsoft for MSDOS operating system;


 Support a wide variety of macro facilities and structured programming;
 Support for 16-bit and 32-bit versions;
 The latest version is called MASM32 V6.14

Assemble-Link Execute Cycle


The following diagram describes the steps from creating a source program through executing the
compiled program. If the source code is modified, Steps 2 through 4 must be repeated.

Microsoft Assembler (ML) •


• The ML program assembles and links one or more assembly language source files
• Syntax: ML [options] filename [[options] filename] … [/link linkoptions]
• For example, assembles the source file hello.asm and produces the object file hello.obj
ML /c hello.asm. The /c prevents auto linking which is good in case you don’t want the
default 32-bit linker.
• The options parameter consists of zero or more command-line options;
• You can use either a slash (/) or dash (-) before each option;
• Multiple options are allowed but they must be separated by at least one space;
• Note that the command-line options are case sensitive.
ML Command-Line Options •
• /? – Display a summary of ML command-line syntax
• /c – Assembles only. Does not link –
 E.g. ML /c hello.asm
• /Cu – Maps all identifiers to uppercase – E.g. ML /Cu hello.asm
• /Fefilename – Names the executable file.
 Note that the filename is limited to only 8 characters in 16 bit systems.
 E.g. ML /FeHi.exe hello.asm

7
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

Appendix B: Registers and Memory Management


Processor Registers in x86 family
The width of a CPU’s registers is defined by its architecture. So if you have a 64-bit CPU, your registers
will be 64 bits wide. The x86 family has 8 registers shared whose prefix depends on the architecture as
shown below:

Fig: Registers in x86 architecture

You can see that a 64-bit processor supports smaller register addressing by providing a mechanism to
address portion of its 64 bit registers. For example the accumulator register ‘A’ has different prefix,
RAX, EAX, AX, AH, AL, to address the whole 64 bit, 32 bit, 16 bit, higher 8 bit or lower 8 bit
respectively.

Processor operating modes of different operating systems

The operating mode of an OS determines whether it can run 16-bit real mode program or not. Even
though 16-bit real mode program cannot be run on 64-bit OS which doesn’t support real mode, a 64-
bit processor still supports real mode. BIOS systems run in real mode (legacy mode) before they load
OS and elevate the mode by setting the "Protected Mode Enable" flag (PE) inside control register
(CR0). SO how can your run real mode programs?

Fig: operating modes

You can still have many options to solve this problem


 Use Virtual Machine (install 16-bt or 32-bit OS inside a virtual machine)
 Use 8086 simulators
 Dual boot with 32-bit OS which supports 16-bit real mode
 Convert the 16-bit real mode program into 16-bit protected mode

8
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

You might wonder at this point why to stick to the old 16-bit real mode if you can write a 32-bit or 64
bit protected mod program that can run on 64-bit system; the reason is:
 we are working on native 8086 assembly language for educational purpose and using Link16
which generates 16-bit real mode executable.
 There are 16-bit microcontrollers working in this mode
 BIOS system have components programed in this mode.

Memory addressing models

Real mode
This is the legacy 8086 segmented memory model. Segments can be up to 64 KB in size (16-bit
addresses within a segment) and the maximum address space is limited to 220 bytes (1 MB). This is the
mode used by the PC BIOS. This the what 8086 uses.

Fig: Real-Mode Addressing

Table: Intel Memory model in real mode


Model Data Code Definition

Tiny* near CS=DS=SS

Small near** near DS=SS

Medium near** far DS=SS, multiple code segments

Compact far near single code segment, multiple data segments


Large far far multiple code and data segments

Huge huge far multiple code and data segments; single array may be >64 KB
* In the Tiny model, all four segment registers point to the same segment.
** In all models with near data pointers, SS equals DS.
*** Stack is always limited to at most 64 KByte.

Flat memory model (Linear memory model)


This model features a 4 GB linear, contiguous address space from address 0x00000000 to
0xffffffff.
Segmented memory model (Protected mode)
In this model, memory appears as a group of independent address spaces, called segments (e.g., code
segment, data segment, stack segment, etc.). The logical address is a combination of the segment

9
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

selector and the offset (address within the segment). While certain segments are associated with specific
operations (e.g., code, stack), the processor supports 16,383 segments, each of which can address up to
232 bytes (4 GB). A full memory address, called a far pointer is a 16-bit segment descriptor and a 32-
bit offset within the segment.

Fig: Segment registers in 32-bit processors


The 80386 (32-bit processor) introduced two new general-purpose data segment registers, FS and GS,
to the original set of four segment registers (CS, DS, SS, and ES).

Fig: Protected-Mode Addressing

In this addressing mode, the processor maintains base address for the descriptor table in two of its
registers called GDTR and LDTR and uses segment selector as offset address and calculates the
physical address of the selected segment descriptor. Content of the selector segment descriptor will be
copied and maintained in hidden part of the segment registers. Descriptors are created by compilers,
linkers, loaders, or the operating system, not by applications programmers. Once the descriptor is found,
its base address is added to the offset address for example from IP register to get the linear address.
A segment descriptor table is an array of 8-byte (64 bit) segment descriptors saved in the memory.

Fig: A Segment Descriptor

10
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

The x86-64 architecture disables segmentation in long mode (64-bit mode) creating a flat 64-bit linear-
address space; in this mode, CS, SS, DS, and ES are forced to 0, and the segment limit to 264. x86-
64 architecture maintains all the segment registers for use of the compatible mode and of course it
routinely uses FS and GS for special purposes. The primary purpose of segment registers was to get
around address space limitation in a 16-bit DOS world to address more address space than your registers
can in flat model. Now in 64 bit, since you can address large RAM size (practically 256TB extendable
up to 4 EB which is equivalent to all words ever spoken by human being) you don’t need segment
registers for their original purposed. However, the protection associated with segmentation will not be
there.

Memory Paging

 Available in the 80386 and up


 Allows a linear address (virtual address) of a program to be located in any portion of physical
memory and even the d
 The paging unit is controlled by the microprocessors control registers
 It can be switched on/off with 31 bit in CR0 control register

Fig: Turning protected mode on / off

Fig: Processor control register


Fig: Turning paging on/off

The 4 GB linear address space is divided into 1048576 pages of 4 kB (also supports 4 MB page size).
Usually virtual memory is much larger than implemented one. When accessing memory page that is
not in physical memory an exception is generated. The exception allows the supervisor software to load
required page (e.g. from HDD) transparently to the user program. The “new” page is loaded into
physical memory in place of some other page which must be written on HDD. During such operation
address translation is required. To make paging fast, buffer and cache memory are usually used.
.

Fig: Virtual address translation

11
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

Appendix C: Emu8086 Virtual Devise

Stepper Motor - port 7 (byte)


 The virtual stepper motor in emu8086 is controlled by sending data to i/o port 7.
 Stepper motor is electric motor that can be precisely controlled by signals from a computer.
 The motor turns through a precise angle each time it receives a signal. by varying the rate at which
signal pulses are produced, the motor can be run at different speeds or turned through an exact
angle and then stopped.
 This is a basic 3-phase stepper motor, it has 3 magnets controlled by bits 0, 1 and 2. other bits (3..7)
are unused.
 When magnet is working it becomes red. The arrow in the left upper corner shows the direction of
the last motor move. Green line is here just to see that it is really rotating.

For example, the code below will do three clock-wise


half-steps:

MOV AL, 001b ; initialize.


OUT 7, AL

MOV AL, 011b ; half step 1.


OUT 7, AL

MOV AL, 010b ; half step 2.


OUT 7, AL

MOV AL, 110b ; half step 3.


OUT 7, AL

Half-stepping
During half-stepping, the drive alternates between two phases on and a single phase on. This
increases the angular resolution.
Full-stepping
During full-step driving two phases are always on so the motor will provide its maximum rated
torque

Appendix D: DOS API vs Windows API


The int 21h is a DOS API interrupt; such DOS interrupts are not available to 32 bit or 64-bit
windows systems. All such interrupts should be converted into equivalent Windows API calls. In
this lab, you will use MASM in visual studio because MASM64 is only available in Visual Studio.
32-bit MS VS programming in c/c++ supports inline assembly function coding, but 64-bit
programing doesn’t. However, both 32-bit and 64-bit c/c++ programing can easily call assembly
functions from asm file.
Here is an alternative “hello World” in assembly using windows API, it is not that simple. You
need to use few libraries from MASM32 installation.

Hello World in 32 bit windows


// *******************************************************
.386

12
AAiT, SECE
Microcomputers and Interfacing - Lab Set I - Draft III- Kinde M. 2024

.model flat,stdcall
option casemap:none
include c:\masm32\include\windows.inc
include c:\masm32\include\kernel32.inc
include c:\masm32\include\user32.inc
includelib c:\masm32\lib\kernel32.lib
includelib c:\masm32\lib\user32.lib

.data

Caption db "Assemblu Program!",0


msg db "Hello World!",0

.code
main:
invoke MessageBox, NULL, addr msg, addr Caption, MB_OK
invoke ExitProcess, NULL
end main
// *******************************************************

13

You might also like