Assembly Language for x 86 Processors 6 th

Assembly Language for x 86 Processors 6 th Edition Kip Irvine Chapter 3: Assembly Language Fundamentals Slides prepared by the author Revision date: 2/15/2010 (c) Pearson Education, 2010. All rights reserved. You may modify and copy this slide show for your personal use, or for use in the classroom, as long as this copyright statement, the author's name, and the title are not changed.

Directives and Instructions § Assembly language statements are either directives or instructions § Instructions are executable statements. They are translated by the assembler into machine instructions. Ex: call My. Sub mov ax, 5 ; transfer of control ; data transfer § Directives tells the assembler how to generate machine code, allocate storage, or define segments. They do not execute at run time. Ex: count BYTE 50 ; creates 1 byte ; of storage ; initialized to 50 2

A Template for Assembly Language Programs TITLE Program Template ; ; ; (Template. asm) Program Description: anything after the ‘; ’ is ignored Author: Creation Date: Revisions: Date: Modified by: INCLUDE Irvine 32. inc ; contains library procedures for IA-32 ; for 32 -bit protected mode programs. data ; data segment, read and write ; (insert variable declarations here). code ; code segment, read-only main PROC ; (insert executable instructions here) exit main ENDP ; (insert additional procedures here) END main This is the template to follow in all your programs Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 3

A Template for ASM if Irvine 32. inc is not Included § Irvine 32. inc: procedures and information for IA-32 library setup §. 386: identifies 80386 as required processor. Use. 586 for Pentium. §. model: set the running mode to 32 bit protected mode and use the MSWindows calling convention § main PROC: label of the entry point of the program § first instruction to execute § END: marks the end of the program and identifies the program’s startup procedure § exit: macro that halts the program then returns the control to the caller (here the Win 32 console) §. data and. code: beginning of the data segment and code 4 segment . 386. model flat, stdcall. stack 4096 Exit. Process PROTO, dw. Exit. Code: DWORD Dump. Regs PROTO. data ; data declarations. code main PROC … ; instructions here call Dump. Regs INVOKE Exit. Process, 0 main ENDP END main

The FLAT Memory Model § The. model flat directive tells the assembler to generate code that will run in protected mode and in 32 -bit mode § Also ask the assembler to do whatever is needed in order that code, stack, and data share the same 32 -bit memory segment § All the segment registers will be loaded with the correct values at load time and do not need to be changed by the programmer § Only the offset part of a logical address becomes relevant § Each data byte (or instruction) is referred to only by a 32 -bit offset address § The directives. code and. data mark the beginning of the code and data segments. They are used only for protection. code is read-only. data is read and write 5

Example: Adding and Subtracting Integers TITLE Add and Subtract (Add. Sub. asm) ; This program adds and subtracts 32 -bit integers. INCLUDE Irvine 32. inc. code main PROC mov eax, 10000 h ; EAX = 10000 h add eax, 40000 h ; EAX = 50000 h sub eax, 20000 h ; EAX = 30000 h call Dump. Regs ; display registers exit main ENDP END main Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 6

Assemble-Link Execute Cycle (Steps to Produce an Executable File) • 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. All 4 steps performed via the Visual Studio environment. No need to use command lines in a window. • See Getting started with MASM and Visual Studio 2012 at http: //www. asmirvine. com/ for instruction on assembling, linking and running ASM programs using Microsoft Visual Studio Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 7

Listing File • Use it to see how your program is compiled • Contains • • • source code addresses object code (machine language) segment names symbols (variables, procedures, and constants) • Example: add. Sub. lst Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 8

Map File • Information about each program segment: • • starting address ending address size segment type • Example: add. Sub. map (16 -bit version) Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 9

Integer Constants • Optional leading + or – sign • binary, decimal, hexadecimal, or octal digits • Common radix characters: • • • h – hexadecimal q/o – octal d – decimal b – binary r – encoded real 1011 h 1011 q or 1011 o 1011 d or 1011 (base 10 is the default) 1011 b 3 F 800000 r = +1. 0 (topic of Chap 12) -26. E 5+05 , 2. , +3. 0 , … • More examples: 30 d, 6 Ah, -42, 1101 b • Hexadecimal beginning with letter: 0 A 5 h • A 5 h is not a number (must start with digit 0) Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 10

Character and String Constants • Enclose character in single or double quotes • 'A‘ , "x" • ASCII character = 1 byte • Enclose strings in single or double quotes • "ABC" • 'xyz‘ , “ 123” (this is a string, not a number) • Each character occupies a single byte • Embedded quotes: • 'Say "Goodnight, " Gracie' Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 11

Reserved Words and Identifiers • Reserved words cannot be used as identifiers • Instruction mnemonics, directives, type attributes, operators, predefined symbols • See MASM reference in Appendix A • Identifiers are programmer-chosen names • • • Variable, constant, procedure, code label 1 to 247 characters, including digits not case sensitive first character must be a letter, _, @, ? , or $ Cannot be the same as an assembler reserved word Avoid using ‘@’ as first character since many keywords start with it. Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 12

Directives • Commands that are recognized and acted upon by the assembler • Not part of the Intel instruction set; but used by the assembler (i. e. the compiler) to direct the OS to perform certain tasks. • Used to declare code, data areas, select memory model, declare procedures, etc. • not case sensitive • Different assemblers have different directives • NASM not the same as MASM, for example Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 13

Instructions • Assembled into machine code by assembler • Executed at runtime by the CPU • We use the Intel IA-32 instruction set • Always INCLUDE Irvine 32. inc in your programs • An instruction contains: • • Label Mnemonic Operand Comment (optional) (required) (depends on the instruction) (optional) Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 14

Mnemonics and Operands • Instruction Mnemonics • memory aid • examples: MOV, ADD, SUB, MUL, INC, DEC • Operands • • constant expression register memory (data label) Constants and constant expressions are often called immediate values Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 15

Instruction Format Examples • No operands • stc ; set Carry flag • One operand • inc eax • dec my. Byte • Two operands ; register ; memory (there also 3 -operand instructions, but they are rare) • add ebx, ecx • sub my. Byte, 25 • add eax, 36 * 25 ; register, register ; memory, constant ; register, constant-expression • All instructions are in the. code segment of programs Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 16

Example: Adding and Subtracting Integers TITLE Add and Subtract (Add. Sub. asm) ; This program adds and subtracts 32 -bit integers. INCLUDE Irvine 32. inc. code main PROC mov eax, 10000 h ; EAX = 10000 h add eax, 40000 h ; EAX = 50000 h sub eax, 20000 h ; EAX = 30000 h call Dump. Regs ; display content of registers exit main ENDP END main Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 17

Example Output Program output, showing registers and flags: EAX=00030000 EBX=7 FFDF 000 ECX=00000101 EDX=FFFF ESI=0000 EDI=0000 EBP=0012 FFF 0 ESP=0012 FFC 4 EIP=00401024 EFL=00000206 CF=0 Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. SF=0 ZF=0 OF=0 18

Suggested Coding Standards • Indentation and spacing • code and data labels – no indentation • executable instructions – indent 4 -5 spaces • comments: right side of page, aligned vertically • 1 -3 spaces between instruction and its operands • ex: mov ax, bx • 1 -2 blank lines between procedures Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 19

Alternative Version of Add. Sub (If not including Irvine 32. inc) TITLE Add and Subtract (Add. Sub. Alt. asm) ; This program adds and subtracts 32 -bit integers. . 386. MODEL flat, stdcall. STACK 4096 Exit. Process PROTO, dw. Exit. Code: DWORD Dump. Regs PROTO. code main PROC mov eax, 10000 h add eax, 40000 h sub eax, 20000 h call Dump. Regs INVOKE Exit. Process, 0 main ENDP END main Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. ; EAX = 10000 h ; EAX = 50000 h ; EAX = 30000 h 20

Data Definition Statement • A data definition statement declares a variable and allocates memory for the variable. The allocation directive defines the type of the variable. • May optionally assign a name (label) to the data • Syntax: [name] directive initializer [, initializer] var 1 BYTE 10 var 2 SWORD AFh, ? , -2, +7, 0 BC 9 h • All initializers become binary data in memory • All variable declarations are in the. data segment of programs Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 21

Defining BYTE and SBYTE Data 8 -bit unsigned integer and 8 -bit signed integer type Each of the following defines a single byte of storage: value 1 BYTE 'A' ; character constant value 2 BYTE 0 ; smallest unsigned byte value 3 BYTE 255 ; largest unsigned byte value 4 SBYTE -128 ; smallest signed byte value 5 SBYTE +127 ; largest signed byte value 6 BYTE ? ; uninitialized byte • MASM does not prevent you from initializing a BYTE with a negative value, but it's considered poor style. • If you declare a SBYTE variable, the Microsoft debugger will automatically display its value in decimal with a leading sign. Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 22
![Defining [S]Byte Arrays Examples that use multiple initializers: list 1 BYTE 10, 20, 30, Defining [S]Byte Arrays Examples that use multiple initializers: list 1 BYTE 10, 20, 30,](http://slidetodoc.com/presentation_image/39492c9912d2c2a367c060c8b0970c7d/image-23.jpg)
Defining [S]Byte Arrays Examples that use multiple initializers: list 1 BYTE 10, 20, 30, 40 list 2 BYTE 10, 20, 30, 40 BYTE 50, 60, 70, 80 BYTE 81, 82, 83, 84 list 3 BYTE ? , 32, 41 h, 0010 b list 4 BYTE 0 Ah, 20 h, ‘A’, 22 h A question mark (? ) in the initializer leaves the initial value of the variable undefined. Ex: c SBYTE ? ; c is undefined Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 23

Defining Strings (1 of 3) • A string is implemented as an array of characters • For convenience, it is usually enclosed in quotation marks • It often will be null-terminated • Character type is BYTE • Examples: str 1 BYTE "Enter your name", 0 str 2 BYTE 'Error: halting program', 0 str 3 BYTE 'A', 'E', 'I', 'O', 'U‘ greeting BYTE "Welcome to the Encryption Demo program " BYTE "created by Kip Irvine. ", 0 Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 24

Defining Strings (2 of 3) • To continue a single string across multiple lines, end each line with a comma: menu BYTE "Checking Account", 0 dh, 0 ah, "1. Create a new account", 0 dh, 0 ah, "2. Open an existing account", 0 dh, 0 ah, "3. Credit the account", 0 dh, 0 ah, "4. Debit the account", 0 dh, 0 ah, "5. Exit", 0 ah, "Choice> ", 0 Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 25

Defining Strings (3 of 3) • End-of-line character sequence: • 0 Dh = carriage return • 0 Ah = line feed str 1 BYTE "Enter your name: ", 0 Dh, 0 Ah BYTE "Enter your address: ", 0 new. Line BYTE 0 Dh, 0 Ah, 0 • Line continuation character () • Concatenates two source code lines into a single statement • greeting 1 BYTE “Welcome to the Encryption Demo Program”, 0 • greeting 1 BYTE “Welcome to the Encryption Demo Program”, 0 Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 26

Using the DUP Operator • Use DUP to allocate (create space for) an array of any type or for a string. Syntax: [var_name] TYPE counter DUP ( argument ) • Counter and argument must be constants or constant expressions. DUP must be used only with data allocation directives. var 1 BYTE 20 DUP(0) ; 20 bytes, all equal to zero var 2 BYTE 20 DUP(? ) ; 20 bytes, uninitialized var 3 BYTE 4 DUP("STACK") ; 20 bytes: "STACKSTACK" var 4 BYTE 10, 3 DUP(0), 20 ; 5 bytes Var 5 BYTE 2 DUP( ‘a’ , 2 DUP ( ‘b’ ) ) ; 6 bytes : ‘abbabb’ Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 27

Defining WORD and SWORD Data • 16 -bit unsigned & signed integer type • Define storage for 16 -bit integers • or double characters • single value or multiple values word 1 word 2 word 3 word 4 my. List array WORD SWORD WORD 65535 ; largest unsigned value – 32768 ; smallest signed value ? ; uninitialized, unsigned "AB" ; double characters 1, 2, 3, 4, 5 ; array of words 5 DUP(? ) ; uninitialized array Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 28

Defining DWORD and SDWORD Data 32 -bit unsigned & signed integer type Storage definitions for signed and unsigned 32 -bit integers: val 1 val 2 val 3 val 4 DWORD SDWORD 12345678 h – 2147483648 20 DUP(? ) – 3, – 2, – 1, 0, 1 Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. ; ; unsigned array 29

Defining QWORD, TBYTE, Real Data 64 -bit integer, 80 -bit integer, and real types Storage definitions for quadwords, tenbyte values, and real numbers: quad 1 QWORD val 1 TBYTE r. Val 1 REAL 4 r. Val 2 REAL 8 precision r. Val 3 REAL 10 precision Short. Array 12345678 h 100000123456789 Ah -2. 1 ; 4 -byte single-precision 3. 2 E-260 ; 8 -byte double 4. 6 E+4096 ; 10 -byte extended REAL 4 20 DUP(0. 0) Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 30

Offset Address of Variables and Data § The optional variable name is a label marking its address in the data segment. § The (offset) address of a variable is the address of its first byte. § Ex: If the following data segment starts at address 0. . data Var 1 BYTE “ABC” Var 2 BYTE “DEFG” 31 § § § The address of Var 1 is 0 = the address of ‘A’ The address of ‘B’ is 1 The address of ‘C’ is 2 The address of Var 2 is 3 The address of ‘E’ is 4 …

Little Endian Order • All data types larger than a byte store their individual bytes in reverse order. The least significant byte occurs at the first (lowest) memory address. • Example: val 1 DWORD 12345678 h Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 32

Little Endian Order § Ex: A WORD 1234 h, 5678 h ; allocates 2 words § Intel’s x 86 are little endian processors: the lowest order byte (of a word or double word) is always stored at the lowest address. § Ex: if variable A (above) is located at address 0, we have: § address: 0 1 2 3 § value: 34 h 12 h 78 h 56 h 33

Little Endian Order § Ex: B DWORD 12345678 h ; allocates 1 double word § If variable B is located at address of 0, we have: § address: 0 1 2 3 § value: 78 h 56 h 34 h 12 h § If a value fits into a byte, it will be stored in the lowest ordered byte available. Ex: V WORD ‘A’ § the value will be stored as: address: 0 1 value: 41 h 00 h 34

Legacy Data Directives § Legacy data directives are also supported by NASM and TASM. § Var 1 DB -128 ; 8 -bit integer type (signed or unsigned) § Var 2 DW +32768 ; 16 -bit integer type (signed or unsigned) § Var 3 DD 1. 2 ; 32 -bit integer/real (signed or unsigned) § Var 4 DQ 3. 2 E-260 ; 64 -bit integer/real (signed or unsigned) § Var 5 DT 4. 6 E+4096 ; 80 -bit integer/real (signed or unsigned) The Legacy Data Directives do not distinguish between signed or unsigned data 35

Adding Variables to Add. Sub TITLE Add and Subtract, Version 2 (Add. Sub 2. asm) ; This program adds and subtracts 32 -bit unsigned ; integers and stores the sum in a variable. INCLUDE Irvine 32. inc. data val 1 DWORD 10000 h val 2 DWORD 40000 h val 3 DWORD 20000 h final. Val DWORD ? . code main PROC mov eax, val 1 ; start with 10000 h add eax, val 2 ; add 40000 h sub eax, val 3 ; subtract 20000 h mov final. Val, eax ; store the result (30000 h) call Dump. Regs ; display the registers exit main ENDP END main Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 36

Equal-Sign Directive • name = integer expression • • expression is a 32 -bit integer (expression or constant) may be redefined name is called a symbolic constant No memory is allocated for a constant • ASM substitutes name with value (of expression) in each occurrence of name • good programming style to use symbols COUNT = 500 ; this is a constant, not a variable mov ax, COUNT ; AX ← 500 A = (-3 * 8) + 2 B = (A+2)/2 ; constants can be defined in terms of another constants Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 37

Calculating the Size of a Word Array Divide total number of bytes by 2 (the size of a word) list WORD 1000 h, 2000 h, 3000 h, 4000 h List. Size = ($ - list) / 2 ; List. Size is a constant ; evaluated at runtime Difference ($ - list) is the number of bytes The $ operator (current location counter) returns the offset associated with the current program statement The constant must follow immediately after the array whose size you want to calculate Works for any type: BYTE, DWORD, QWORD, … etc Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 38

EQU Directive • Define a symbol as either an integer or text expression. • Cannot be redefined PI EQU <3. 1416> ; text expression Mat 1 EQU 10 * 10 ; integer expression Mat 2 EQU <10*10> ; text expression press. Key EQU <"Press any key to continue. . . ", 0>. data prompt BYTE press. Key ; prompt ← “Press any …”, 0 “ M 1 WORD Mat 1 ; M 1 WORD 100 M 2 WORD Mat 2 ; M 2 WORD 10 * 10 P REAL 4 PI ; P REAL 4 3. 1416 Text must be enclosed with <. . . > (useful for real value) Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 39

TEXTEQU Directive • Define a symbol as either an integer or text expression. • Called a text macro • Can be redefined at any time continue. Msg TEXTEQU <"Do you wish to continue (Y/N)? "> row. Size = 5. data prompt 1 BYTE textmacro continue. Msg count TEXTEQU %(row. Size * 2) expression setup. AL TEXTEQU <mov al, count> ; assigns the content of a ; evaluates the integer ; assigns text . code setup. AL ; generates: "mov al, 10" Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 40

Exercise 1 § Suppose that the following data segment starts at address 0. data A WORD 1, 2 B WORD 6 ABCh Z EQU 232 C BYTE 'ABCD' § § 41 A) Find the address of variable A. B) Find the address of variable B. C) Find the address of variable C. D) Find the address of character ‘C’.

4 C 61 46 69 6 E Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 42

Real-Address Mode Programming (1 of 2) • Generate 16 -bit MS-DOS Programs • Advantages • enables calling of MS-DOS and BIOS functions • no memory access restrictions • Disadvantages • must be aware of both segments and offsets • cannot call Win 32 functions (Windows 95 onward) • limited to 640 K program memory Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 43

Real-Address Mode Programming (2 of 2) • Requirements • INCLUDE Irvine 16. inc • Initialize DS to the data segment: mov ax, @data mov ds, ax Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 44

Add and Subtract, 16 -Bit Version TITLE Add and Subtract, Version 2 (Add. Sub 2 r. asm) INCLUDE Irvine 16. inc. data val 1 DWORD 10000 h val 2 DWORD 40000 h val 3 DWORD 20000 h final. Val DWORD ? . code main PROC mov ax, @data ; initialize DS mov ds, ax mov eax, val 1 ; get first value add eax, val 2 ; add second value sub eax, val 3 ; subtract third value mov final. Val, eax ; store the result call Dump. Regs ; display registers exit main ENDP END main Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 45

Summary • Integer expression, character constant • directive – interpreted by the assembler • instruction – executes at runtime • code, data, and stack segments • source, listing, object, map, executable files • Data definition directives: • BYTE, SBYTE, WORD, SWORD, DWORD, SDWORD, QWORD, TBYTE, REAL 4, REAL 8, and REAL 10 • DUP operator, location counter ($) • Symbolic constant • EQU and TEXTEQU Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 46

4 C 61 46 69 6 E Irvine, Kip R. Assembly Language for x 86 Processors 6/e, 2010. 47
- Slides: 47