Presentation is loading. Please wait.

Presentation is loading. Please wait.

2/27/2003 Lecture 6: Assembly Language Fundamentals Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine.

Similar presentations


Presentation on theme: "2/27/2003 Lecture 6: Assembly Language Fundamentals Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine."— Presentation transcript:

1 2/27/2003 Lecture 6: Assembly Language Fundamentals Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine

2 Outline General Concepts Basic Elements of Assembly Language Sample Program Assembling, Linking, and Debugging Data Allocation Symbolic Constants Real-Address Mode Programming

3 Protected Mode (1 of 2) 4 GB addressable RAM –(00000000 to FFFFFFFFh) Each program assigned a memory partition which is protected from other programs Designed for multitasking Supported by Linux & MS-Windows

4 Protected mode (2 of 2) Segment descriptor tables Program structure –code, data, and stack areas –CS, DS, SS segment descriptors –global descriptor table (GDT) MASM Programs use the Microsoft flat memory model

5 Multi-Segment Model Each program has a local descriptor table (LDT) –holds descriptor for each segment used by the program

6 Paging Supported directly by the CPU Divides each segment into 4096-byte blocks called pages Sum of all programs can be larger than physical memory Part of running program is in memory, part is on disk Virtual memory manager (VMM) – OS utility that manages the loading and unloading of pages Page fault – issued by CPU when a page must be loaded from disk

7 Components of an IA-32 Microcomputer Motherboard Video output Memory Input-output ports

8 Motherboard CPU socket External cache memory slots Main memory slots BIOS chips Sound synthesizer chip (optional) Video controller chip (optional) IDE, parallel, serial, USB, video, keyboard, joystick, network, and mouse connectors PCI bus connectors (expansion cards)

9 Intel D850MD Motherboard dynamic RAM Intel 486 socket Speaker IDE drive connectors mouse, keyboard, parallel, serial, and USB connectors AGP slot Battery Video Power connector memory controller hub Diskette connector PCI slots I/O Controller Firmware hub Audo chip Source: Intel® Desktop Board D850MD/D850MV Technical Product Specification

10 Video Output Video controller –on motherboard, or on expansion card –AGP (accelerated graphics port technology)accelerated graphics port technology Video memory (VRAM) Video CRT Display –uses raster scanning –horizontal retrace –vertical retrace Direct digital LCD monitors –no raster scanning required

11 Sample Video Controller (ATI Corp.) 128-bit 3D graphics performance powered by RAGE™ 128 PRO 3D graphics performance Intelligent TV-Tuner with Digital VCR TV-ON-DEMAND ™ Interactive Program Guide Still image and MPEG-2 motion video capture Video editing Hardware DVD video playback Video output to TV or VCR

12 Memory ROM –read-only memory EPROM –erasable programmable read-only memory Dynamic RAM (DRAM) –inexpensive; must be refreshed constantly Static RAM (SRAM) –expensive; used for cache memory; no refresh required Video RAM (VRAM) –dual ported; optimized for constant video refresh CMOS RAM –complimentary metal-oxide semiconductor –system setup information

13 Input-Output Ports USB (universal serial bus) –intelligent high-speed connection to devices –up to 12 megabits/second –USB hub connects multiple devices –enumeration: computer queries devices –supports hot connections Parallel –short cable, high speed –common for printers –bidirectional, parallel data transfer –Intel 8255 controller chip

14 Input-Output Ports (cont) Serial –RS-232 serial port –one bit at a time –uses long cables and modems –16550 UART (universal asynchronous receiver transmitter) –programmable in assembly language

15 Levels of Input-Output Level 3: Call a library function (C++, Java) –easy to do; abstracted from hardware; details hidden –slowest performance Level 2: Call an operating system function –specific to one OS; device-independent –medium performance Level 1: Call a BIOS (basic input-output system) function –may produce different results on different systems –knowledge of hardware required –usually good performance

16 Displaying a String of Characters When a HLL program displays a string of characters, the following steps take place:

17 ASM Programming levels ASM programs can perform input-output at each of the following levels:

18 Basic Elements - Numeric constants  A numeric literal is any combination of digits, plus: optional decimal point, exponent, sign: 5234 -5.5 26.0E+05  Use a radix symbol (suffix) to select binary, octal, decimal, or hexadecimal: h – hexadecimal d – decimal b – binary r – encoded real Examples: 30d, 6Ah, 42, 1101b Hexadecimal beginning with letter: 0A5h

19 Arithmetic Operators and Expressions + - * / ( ) can be used in arithmetic expressions These operators can only be used in constant expressions evaluated at assembly time Examples 98 10*20 -5 * 20 / 40 + 5

20 Character and String Constants  ASCII characters and constants are enclosed in single or double quotes  Examples: "A" or 'A' 'xyz' or "XYZ" "I am learning assembly" "Don't do it"  "12345" is a string (5 bytes) 12345 is a number (2 or 4 bytes)  Embedded quotes: 'Say "Goodnight," Gracie'

21 Statements  General form of a statement [name] [mnemonic] [operands] [; comment] where [] indicate "sometimes may be omitted"  Maximum length: 128 characters per line  Continuation character: \. Code Here: mov eax,count ; Data, using WORD myArray WORD 1000h,2000h \ 3000h,4000h Data name Operands Comment mnemonic Label

22 Statements: Instructions  Converted into machine language at assembly time  Executed during run time  Sample statements mov EAX, x ; z = x + 10 - y; add EAX, 10 sub EAX, y Store: mov z, EAX inc counter ; counter++;

23 Statements: Directives  Tell the assembler how you want the code generated –Not part of the Intel instruction set –Used to declare code, data areas, select memory model, declare procedures, etc.  Different assemblers have different directives –NASM != MASM, for example  Examples: title This is the program title on printed listings....data.code main proc

24 Names  A name identifies either: a label, a variable, a symbolic constant (name given to a constant) or a keyword (assembler-reserved word).  May contain letters, digits, "_", "@", or "$"  First character must be a letter, _, @, or $  Case insensitive  Max of 247 characters  Examples (Legal): x, counter, Bill, Y2K, my_balance, @@myfile, _array  Examples (Illegal): 12x, interest%, my balance, add

25 Labels Labels are used as markers for program jumps –marks the address (offset) of code and data –must end with a colon (:) Example: mov EBX, X cmp EBX, 0 jl Error ; jump if X < 0... Error: mov EBX, Y

26 Keywords (Reserved Words) Instruction mnemonics, directives, type attributes, operators, predefined symbols Keywords have predefined meanings and cannot be used for anything else Examples: end, proc, EAX, add, sub, mov, byte Example: The following is illegal Mov BYTE 21 ; Define Mov as a variable

27 Mnemonics and Operands  Instruction Mnemonics –"reminder" –examples: MOV, ADD, SUB, MUL, INC, DEC  Operands –constant (immediate value) –constant expression –register –memory (data label)

28 Comments  Comments are good! –explain the program's purpose –when it was written, and by whom –revision information –tricky coding techniques –application-specific explanations  Single-line comments –begin with semicolon (;)  Multi-line comments –begin with COMMENT directive and a programmer- chosen character –end with the same programmer-chosen character

29 Instruction Format Examples  No operands –stc; set Carry flag  One operand –inc eax; register –inc myByte; memory  Two operands –add ebx,ecx; register, register –sub myByte,25; memory, constant –add eax,36 * 25; register, expression

30 Sample Program TITLE Add and Subtract (AddSub.asm) ; This program adds and subtracts 32-bit integers. INCLUDE Irvine32.inc.code main PROC mov eax,10000h; EAX = 10000h add eax,40000h; EAX = 50000h sub eax,20000h; EAX = 30000h call DumpRegs; display registers exit main ENDP END main

31 More directives

32 Sample Program Example Output Program output, showing registers and flags: EAX=00030000 EBX=7FFDF000 ECX=00000101 EDX=FFFFFFFF ESI=00000000 EDI=00000000 EBP=0012FFF0 ESP=0012FFC4 EIP=00401024 EFL=00000206 CF=0 SF=0 ZF=0 OF=0

33 Suggested Coding Standards (1 of 2)  Some approaches to capitalization –capitalize nothing –capitalize everything –capitalize all reserved words, including instruction mnemonics and register names –capitalize only directives and operators  Other suggestions –descriptive identifier names –spaces surrounding arithmetic operators –blank lines between procedures

34 Suggested Coding Standards (2 of 2)  Indentation and spacing –code and data labels – no indentation –executable instructions – indent 4-5 spaces –comments: begin at column 40-45, aligned vertically –1-3 spaces between instruction and its operands ex: mov ax,bx –1-2 blank lines between procedures

35 Sample Program (Alternative Version) TITLE Add and Subtract (AddSubAlt.asm) ; This program adds and subtracts 32-bit integers..386.MODEL flat,stdcall.STACK 4096 ExitProcess PROTO, dwExitCode:DWORD DumpRegs PROTO.code main PROC mov eax,10000h; EAX = 10000h add eax,40000h; EAX = 50000h sub eax,20000h; EAX = 30000h call DumpRegs INVOKE ExitProcess,0 main ENDP END main

36 Program Template TITLE Program Template (Template.asm) ; Program Description: ; Author: ; Creation Date: ; Revisions: ; Date: Modified by: INCLUDE Irvine32.inc.data ; (insert variables here).code main PROC ; (insert executable instructions here) exit main ENDP ; (insert additional procedures here) END main

37 Assembling and Running Programs Source file (.asm) Text editor Assembler Object file (.obj) Listing file (.lst) Linker Link library (.lib) Executable program (.exe) Map file (.map) OS Loader Output ML

38 Assembling  Two staged process: –Assemble: Converts assembly language into machine language. Uses source file, outputs object file and optionally the list file –Link: Connects (links) the different.obj and library files together to create the executable file. Uses the object file(s) and optionally a library. Outputs executable file and optionally map file  Both done with ML command

39 Link library Link libraries contain pre-assembled code Widely use in high level languages for built-in functions such "cout" in C+ + and imported of system functions in Java.

40 make32.bat  Called a batch file  Run it to assemble and link programs  Contains a command that executes ML.EXE (the Microsoft Assembler)  Contains a command that executes LINK32.EXE (the 32-bit Microsoft Linker)  Command-Line syntax: make32 progName (use make16.bat to assemble and link Real-mode programs)

41 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: addSub.lstaddSub.lst

42 Map File  Information about each program segment: –starting address –ending address –size –segment type  Example: addSub.mapaddSub.map

43 Defining variables Symbolic name for a location in memory During assembly, the value of a variable name is its offset from the beginning of the segment! Examples: –Name BYTE "Joe Brown" –Cost WORD 14

44 Intrinsic Data Types (1 of 2)  BYTE, SBYTE –8-bit unsigned integer; 8-bit signed integer  WORD, SWORD –16-bit unsigned & signed integer  DWORD, SDWORD –32-bit unsigned & signed integer  QWORD –64-bit integer  TBYTE –80-bit integer

45 Intrinsic Data Types (2 of 2) REAL4 –4-byte IEEE short real REAL8 –8-byte IEEE long real REAL10 –10-byte IEEE extended real

46 Data Allocations General format [name] type initialvalue [, initialvalue] … Initial value can be left undefined - use ? Example:.data X BYTE 2, 24h Y WORD 18h, 126h Z BYTE ? 0 X 1 X+1 2 Y 3 4 Y+2 5 6 Z 02 24 18 00 26 01 Data segment ??

47 Multiple Initializers list1 BYTE 10,20,30,40 list2 BYTE 10,20,30,40 BYTE 50,60,70,80 BYTE 81,82,83,84 list3 BYTE ?,32,41h,00100010b list4 BYTE 0Ah,20h,‘A’,22h Examples that use multiple initializers:

48 Characters Characters can be represented by the character or their ASCII value. Values: Signed -128 to 127, Unsigned 0 to 255 Example : 5 ways to store 'A': FiveAs BYTE 'A',"A",65,41h,01000001b String examples str1 BYTE "Enter your name",0 str2 BYTE 'Error: halting program',0 str3 BYTE 'A','E','I','O','U' greeting BYTE "Welcome to the Encryption Demo program " BYTE "created by Kip Irvine.",0 Characters in strings are stored in order, one character per byte

49 Strings (1 of 3) A string is implemented as an array of characters –For convenience, it is usually enclosed in quotation marks –It usually has a null byte at the end Examples: str1 BYTE "Enter your name",0 str2 BYTE 'Error: halting program',0 str3 BYTE 'A','E','I','O','U' greeting BYTE "Welcome to the Encryption Demo program " BYTE "created by Kip Irvine.",0

50 Strings (2 of 3) To continue a single string across multiple lines, end each line with a comma: menu BYTE "Checking Account",0dh,0ah,0dh,0ah, "1. Create a new account",0dh,0ah, "2. Open an existing account",0dh,0ah, "3. Credit the account",0dh,0ah, "4. Debit the account",0dh,0ah, "5. Exit",0ah,0ah, "Choice> ",0

51 Strings (3 of 3) End-of-line character sequence: –0Dh = carriage return –0Ah = line feed str1 BYTE "Enter your name: ",0Dh,0Ah BYTE "Enter your address: ",0 newLine BYTE 0Dh,0Ah,0 Idea: Define all strings used by your program in the same area of the data segment.

52 DUP Operator Used to assign multiple copies of the value Counter and argument must be constants or constant expressions Example WORD 10 DUP (0) ; 10 zero words QWORD 20 DUP (?) ; 20 unitialized quads BYTE 30 DUP (' '); 30 blanks (bytes) Example Matrix WORD 2 DUP(1, 2 DUP (2, 3)) generates:Matrix 1 2 3 2 3 1 2 3 2 3 (20 bytes)

53 Adding Variables to AddSub TITLE Add and Subtract, Version 2 (AddSub2.asm) ; This program adds and subtracts 32-bit unsigned ; integers and stores the sum in a variable. INCLUDE Irvine32.inc.data val1 DWORD 10000h val2 DWORD 40000h val3 DWORD 20000h finalVal DWORD ?.code main PROC mov eax,val1; start with 10000h add eax,val2; add 40000h sub eax,val3; subtract 20000h mov finalVal,eax; store the result (30000h) call DumpRegs; display the registers exit main ENDP END main

54 Declaring Unitialized Data Use the.data? directive to declare an unintialized data segment:.data? Within the segment, declare variables with "?" initializers: smallArray DWORD 10 DUP(?) Advantage: the program's EXE file size is reduced.

55 Pointers Consider MyString BYTE "This is a string" pMyString WORD MyString pMyString is a two byte pointer to MyString. It contains the offset of MyString within the data segment.

56 Symbolic constants Allow naming constants Similar to C+ + code const int numElements = 20; const int numWords = 2 * numElements; or in Java public static final int numVal = 40; They are not assigned storage locations in assembly Values cannot change at runtime They can be defined anywhere in the program

57 Equal-sign Directive Examples numValues = 25 min = 5 max = min + 100 Similar to C++ code const int numValues = 25; const int min = 5; const int max = min + 100; IMPORTANT: The values of constants are substituted for the constant name during assembly time. They a NOT evaluated during execution time.

58 Equal-sign directive Examples: Cost = 10 mov EAX, Cost This is the same as mov EAX, 10 Equal sign directives can be used to define doublewords

59 Equal-sign Directive - Redefinition Equal-sign directives can be reassigned Example: Cost = 10... Cost = 20... Cost = Cost + 10

60 EQU Directive Can be used to define integer or text Cannot be redefined Examples MaxWord EQU 32767 NumValues EQU MaxWord/100 CR EQU 0Dh True EQU 1 ; define boolean values False EQU 0 No EQU 'NO'

61 TEXTEQU Directive Used to create a text macro. Formats: name TEXTEQU name TEXTEQU textmacro name TEXTEQU %constExpr Used to define sequence of characters that will be substituted for "name" Can be redefined

62 TEXTEQU Directive Example ContMsg TEXTEQU CR = 0Dh LF = 0Ah Ending = '$' Then Msg BYTE ContMsg, CR, LF, Ending assembles as Msg BYTE "Press return", 0Dh, 0Ah, '$'

63 TEXTEQU Directive Example copy TEXTEQU ArithReg TEXTEQU Ten = 10 then copy ArithReg, Ten assembles as mov AX, 10

64 TEXTEQU Directive continueMsg TEXTEQU rowSize = 5.data prompt1 BYTE continueMsg count TEXTEQU %(rowSize * 2) ; evaluates the expression move TEXTEQU setupAL TEXTEQU.code setupAL; generates: "mov al,10"

65 Comparison = and EQU - value substitution TEXTEQU - text substitution = and TEXTEQU allow redefinition EQU does not EQU allows floating point substitions = does not EQU and TEXTEQU allow = does not

66 The $ operator  The $ operator returns the current value of the location counter. We can use it to compute the string length at assembly time..data LongString BYTE “This is a piece of text that I“ BYTE “want to type on 2 separate lines” LongString_length = ($ - LongString)  Note that we do not need to give a name to every line...

67 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 Win32 functions (Windows 95 onward) –limited to 640K program memory

68 Real-Address Mode Programming (2 of 2)  Requirements –INCLUDE Irvine16.inc –Initialize DS to the data segment: mov ax,@data mov ds,ax

69 Add and Subtract, 16-Bit Version TITLE Add and Subtract, Version 2 (AddSub2.asm) INCLUDE Irvine16.inc.data val1 DWORD 10000h val2 DWORD 40000h val3 DWORD 20000h finalVal DWORD ?.code main PROC mov ax,@data; initialize DS mov ds,ax mov eax,val1; get first value add eax,val2; add second value sub eax,val3; subtract third value mov finalVal,eax; store the result call DumpRegs; display registers exit main ENDP END main

70 CSCE 380 Department of Computer Science and Computer Engineering Pacific Lutheran University 2/27/2003


Download ppt "2/27/2003 Lecture 6: Assembly Language Fundamentals Assembly Language for Intel-Based Computers 4th edition Kip R. Irvine."

Similar presentations


Ads by Google