Quiz #2 Topics Character codes Character codes Intel IA-32 architecture Intel IA-32 architecture...

Post on 23-Dec-2015

235 views 3 download

Tags:

Transcript of Quiz #2 Topics Character codes Character codes Intel IA-32 architecture Intel IA-32 architecture...

Quiz #2 TopicsQuiz #2 Topics Character codesCharacter codes Intel IA-32 architectureIntel IA-32 architecture

Registers, memory addressingRegisters, memory addressing Bytes, words, etc.Bytes, words, etc. Little-endian representationLittle-endian representation Floating-point unitFloating-point unit

Mostly MASMMostly MASM General form of a MASM programGeneral form of a MASM program Directives (TITLE, INCLUDE, etc.)Directives (TITLE, INCLUDE, etc.) Segments (.code, .data, etc.)Segments (.code, .data, etc.) Declare variables, constantsDeclare variables, constants Comments Comments Instruction formatInstruction format Instructions (mov, add, call, etc.)Instructions (mov, add, call, etc.) Trace MASM codeTrace MASM code Convert simple statements to MASMConvert simple statements to MASM Assembling, linking, loading, etc.Assembling, linking, loading, etc.

Today’s topicsToday’s topics More MASM programmingMore MASM programming

Addressing modesAddressing modes Conditional control structuresConditional control structures

DecisionDecisionRepetitionRepetition

IA-32 Operand ModesIA-32 Operand Modes

ImmediateImmediate constant or literal, OFFSET (memory constant or literal, OFFSET (memory address)address) Examples:Examples: PIPI equequ 3.141593.14159

sizesize DWORDDWORD 1010myNamemyName BYTEBYTE ”Barney””Barney”

movmov eax, eax, 1010movmov edx, edx, OFFSET myNameOFFSET myName

RegisterRegister register contentsregister contents Examples:Examples: movmov eaxeax, 10, 10

addadd eaxeax, , ebxebxmovmov size,size, eax eax

DirectDirect memory contentsmemory contents Examples:Examples: movmov eax, eax, sizesize

movmov sizesize,, eaxeax

Others (later)Others (later) Register indirect, Indexed, Base-indexed, StackRegister indirect, Indexed, Base-indexed, Stack

Instruction Operand Instruction Operand NotationNotation

SyntaxSyntax ExamplesExamples

MOVMOV mem,immmem,imm mov color,7mov color,7

SyntaxSyntax ExamplesExamples

MOVMOV reg,immreg,imm mov ecx,256mov ecx,256mov edx,OFFSET stringmov edx,OFFSET string

SyntaxSyntax ExamplesExamples

MOVMOV mem,accummem,accum mov total,eaxmov total,eax

MOVMOV accum,memaccum,mem mov al,stringmov al,stringNotes:

accum means “eax or some valid part of eax”

imm means “a literal or constant”

SyntaxSyntax ExamplesExamples

MOVMOV reg,regreg,reg mov dh,bhmov dh,bhmov edx,ecxmov edx,ecxmov ebp,espmov ebp,esp

MOVMOV mem,regmem,reg mov count,ecxmov count,ecx

MOVMOV reg,memreg,mem mov ebx,pointermov ebx,pointer

SyntaxSyntax ExamplesExamples

MOVMOV sreg,reg16sreg,reg16 mov ds, axmov ds, ax

MOVMOV sreg,mem16sreg,mem16 mov es,pos1mov es,pos1

MOVMOV reg16,sregreg16,sreg mov ax,dsmov ax,ds

MOVMOV mem16,sregmem16,sreg mov stack_save,ssmov stack_save,ss

Notes:

mem8 means “BYTE”

mem16 means “WORD”

mem32 means “DWORD”

sreg means CS, DS, ES, FS, GS, or SS

InvalidInvalid MOV statements MOV statements

.databVal BYTE 100bVal2 BYTE ?wVal WORD 2dVal DWORD 5.code

mov ds,45mov esi,wValmov eip,dValmov 25,bValmov bVal2,bVal

immediate move to DS not permittedsize mismatchEIP cannot be the destinationimmediate value cannot be destinationmemory-to-memory move not permitted

Branching executionBranching execution Sometimes it is necessary to interrupt Sometimes it is necessary to interrupt

sequential instruction executionsequential instruction execution EIPEIP is changed is changed Examples:Examples:

Skip ahead (e.g., skip the Skip ahead (e.g., skip the elseelse block) block) Jump backwards (e.g., repeat a section of Jump backwards (e.g., repeat a section of

code)code) Call a procedureCall a procedure

Conditional / Unconditional branchingConditional / Unconditional branching Label requiredLabel required

MASM LabelsMASM Labels Same rules as other identifiersSame rules as other identifiers May not be any previously defined May not be any previously defined

identifieridentifier Label definition ends with Label definition ends with ::

Don’t use Don’t use :: when referencing the label when referencing the label Specifies the Specifies the memory addressmemory address of the of the

associated instructionassociated instruction … … just like a variable namejust like a variable name

Good practice to put Good practice to put label:label: on a on a separate line.separate line.

Unconditional branchingUnconditional branching

Instruction format is Instruction format is jmpjmp labellabel label: label: should be inside the same should be inside the same

procedureprocedure MASM allows jumps to labels in other MASM allows jumps to labels in other

procedures, but execution will certainly procedures, but execution will certainly get lost in space.get lost in space.

Conditional branchingConditional branching

Used for:Used for: if structures (decisions, alternation)if structures (decisions, alternation) loop structures (repetition, iteration)loop structures (repetition, iteration)

In general, MASM requires you to build In general, MASM requires you to build your own control structuresyour own control structures

Note: in the following discussion, status Note: in the following discussion, status bits (flags) are bits (flags) are Set (means status bit is set to 1)Set (means status bit is set to 1) Cleared (means status bit is set to 0)Cleared (means status bit is set to 0)

looploop instruction instruction Instruction format is Instruction format is looploop labellabel

label: label: should be inside the same procedure, should be inside the same procedure, beforebefore the the looploop instruction instruction

Used for counted loops. Implements a “for” Used for counted loops. Implements a “for” loop.loop.

Conditional branchConditional branch Decrements ecx, if ecx is not zero, branch to Decrements ecx, if ecx is not zero, branch to labellabel

ProblemProblem if ecx is changed inside the loop body if ecx is changed inside the loop body ProblemProblem if ecx starts at 0, or ecx becomes if ecx starts at 0, or ecx becomes

negativenegative Exercise great care when constructing nested Exercise great care when constructing nested

“loop” loops“loop” loops

looploop Example ExampleFind sum of integers from 1 to Find sum of integers from 1 to

1010; initialize accumulator, first number,; initialize accumulator, first number,; and loop control; and loop control

movmov eax, 0eax, 0movmov ebx, 1ebx, 1movmov ecx, 10ecx, 10

sumLoop:sumLoop: ; add numbers from 1 to 10; add numbers from 1 to 10addadd eax, ebxeax, ebxincinc ebxebxlooploop sumLoopsumLoop

; Print result; Print resultcallcall WriteDecWriteDec

; ...; ...

Conditional branchingConditional branching

We need a way to control branching by We need a way to control branching by checking some other types of checking some other types of conditionsconditions

Examples:Examples: Some repetitive tasks can not be counted Some repetitive tasks can not be counted

in advancein advance IF-THEN-ELSE structuresIF-THEN-ELSE structures

MASM provides a way to compare two MASM provides a way to compare two operandsoperands

CMPCMP Instruction Instruction

Compares the destination operand to Compares the destination operand to the source operandthe source operand Non-destructive subtraction of source Non-destructive subtraction of source

from destination (destination operand is from destination (destination operand is not changed)not changed)

Syntax: Syntax: CMP CMP destination, sourcedestination, source

CMPCMP Instruction (unsigned) Instruction (unsigned)

Example: Example: destinationdestination is equal to is equal to sourcesource

mov al,5cmp al,5 ; Zero flag set

CMPCMP Instruction (unsigned) Instruction (unsigned) Example: Example: destinationdestination < < sourcesource

mov al,4cmp al,5 ; Carry flag set

CMPCMP Instruction (unsigned) Instruction (unsigned)

Example: Example: destinationdestination > > sourcesource

mov al,6cmp al,5 ; ZF = 0, CF = 0

(both the Zero and Carry flags are cleared)

CMPCMP Instruction (signed) Instruction (signed)

Example: destination > sourceExample: destination > source

mov al,5cmp al,-2 ; Sign flag == Overflow flag

The comparisons shown here are performed with signed integers.

mov al,-1cmp al,5 ; Sign flag != Overflow flag

Example: destination < Example: destination < sourcesource

Conditional JumpsConditional Jumps

Jumps Based On . . .Jumps Based On . . . Specific flagsSpecific flags EqualityEquality Unsigned comparisonsUnsigned comparisons Signed ComparisonsSigned Comparisons

JJcondcond Instruction Instruction A conditional jump instruction branches to a A conditional jump instruction branches to a

label when specific register or flag label when specific register or flag conditions are metconditions are met

Usually the next instruction after Usually the next instruction after cmpcmp Examples:Examples:

JBJB, , JCJC jump to a label if the jump to a label if the CarryCarry flag is set flag is set JEJE, , JZJZ jump to a label if the jump to a label if the ZeroZero flag is set flag is set JSJS jumps to a label if the jumps to a label if the SignSign flag is set flag is set JNEJNE, , JNZJNZ jump to a label if the jump to a label if the ZeroZero flag is flag is

clearedcleared JECXZJECXZ jumps to a label if ECX equals 0 jumps to a label if ECX equals 0

Jumps Based on Specific Jumps Based on Specific FlagsFlags

Jumps Based on EqualityJumps Based on Equality

Jumps Based on Unsigned Jumps Based on Unsigned ComparisonsComparisons

Jumps Based on Signed Jumps Based on Signed ComparisonsComparisons

Compare and JumpCompare and Jump

cmp eax,ebxja Larger

• Task: Jump to a label if unsigned EAX is greater than EBX

• Solution: Use CMP, followed by JA

cmp eax,ebxjg Greater

• Task: Jump to a label if signed EAX is greater than EBX

• Solution: Use CMP, followed by JG

Compare and JumpCompare and Jump

cmp eax,Val1jbe L1 ; below or equal

• Jump to label L1 if unsigned EAX is less than or equal to Val1

cmp eax,Val1jle L1

• Jump to label L1 if signed EAX is less than or equal to Val1

Conditional Loop Instructions Conditional Loop Instructions (Use after (Use after CMPCMP))

LOOPZ and LOOPELOOPZ and LOOPE Syntax: Syntax:

LOOPE LOOPE destinationdestination

LOOPZLOOPZ destination destination Logic: Logic:

ECX ECX ECX – 1 ECX – 1 if ECX > 0 and ZF=1, jump to if ECX > 0 and ZF=1, jump to destinationdestination

Conditional Loop Instructions Conditional Loop Instructions (Use after (Use after CMPCMP))

LOOPNZ and LOOPNELOOPNZ and LOOPNE Syntax: Syntax:

LOOPNZ LOOPNZ destinationdestination

LOOPNELOOPNE destination destination Logic: Logic:

ECX ECX ECX – 1; ECX – 1; if ECX > 0 and ZF=0, jump to if ECX > 0 and ZF=0, jump to destinationdestination

Conditional DirectivesConditional Directives .IF, .ELSE, .ELSEIF, and .ENDIF .WHILE, .ENDW .REPEAT, .UNTIL

Not required for this course It’s OK to use these in programming

assignments, but you must know the “hard way” for exams and quizzes

Block-Structured Block-Structured IFIF Statements Statements You can create assembly language You can create assembly language

control structures that are equivalent control structures that are equivalent

to statements written in C++/Java/etc..to statements written in C++/Java/etc.. Example:Example:

mov eax,op1cmp eax,op2jne L1mov X,1jmp L2

L1: mov X,2L2:

if( op1 == op2 ) X = 1;else X = 2;

Assembly Language Control Assembly Language Control StructuresStructures

Extend the idea to create your own Extend the idea to create your own if-thenif-then if-then-elseif-then-else if-then-elseif-elseif-then-elseif-else compound conditionscompound conditions while loopwhile loop do-while loopdo-while loop for loopfor loop nested structures, switch structures, etc.nested structures, switch structures, etc.

if-thenif-then

check check conditioncondition using using CMPCMP if if conditioncondition is is falsefalse, jump to , jump to endThenendThen

(Note: test for (Note: test for complementcomplement of of conditioncondition)) code for TRUE blockcode for TRUE block endThen:endThen:

if-then-else (Method 1)if-then-else (Method 1)

check check conditioncondition using using CMPCMP if if conditioncondition is is falsefalse, jump to , jump to falseBlockfalseBlock

(Note: test for (Note: test for complementcomplement of of conditioncondition)) code for TRUE blockcode for TRUE block jump tojump to endFalse endFalse falseBlock:falseBlock: code for FALSE blockcode for FALSE block endFalse:endFalse:

if-then-else (Method 2)if-then-else (Method 2)

check check conditioncondition using using CMPCMP if if conditioncondition is is truetrue, jump to , jump to trueBlocktrueBlock code for FALSE blockcode for FALSE block jump tojump to endTrue endTrue trueBlock:trueBlock: code for TRUE blockcode for TRUE block endTrue:endTrue:

if-then-elseif-elseif-then-elseif-else check check condition1condition1 using using CMPCMP if if condition1condition1 is is truetrue, jump to , jump to trueBlock1trueBlock1 check check condition2 condition2 using using CMPCMP if if condition2condition2 is is truetrue, jump to , jump to trueBlock2trueBlock2 code for FALSE blockcode for FALSE block jump tojump to endBlock endBlock trueBlock1:trueBlock1: code for TRUE block1code for TRUE block1 jump tojump to endBlock endBlock trueBlock2:trueBlock2: code for TRUE block2code for TRUE block2 endBlock:endBlock:

Compound conditions (AND)Compound conditions (AND)

check check condition1condition1 using using CMPCMP if if condition1condition1 is is falsefalse, jump to , jump to falseBlockfalseBlock check check condition2 condition2 using using CMPCMP if if condition2condition2 is is falsefalse, jump to , jump to falseBlockfalseBlock code for TRUE blockcode for TRUE block jump tojump to endBlock endBlock falseBlockfalseBlock code for FALSE blockcode for FALSE block endBlock:endBlock:

Compound conditions (OR)Compound conditions (OR)

check check condition1condition1 using using CMPCMP if if condition1condition1 is is truetrue, jump to , jump to trueBlocktrueBlock check check condition2 condition2 using using CMPCMP if if condition2condition2 is is truetrue, jump to , jump to trueBlocktrueBlock code for FALSE blockcode for FALSE block jump tojump to endBlock endBlock trueBlocktrueBlock code for TRUE blockcode for TRUE block endBlock:endBlock:

Pretest loop (while)Pretest loop (while)

initialize loop control variable(s)initialize loop control variable(s) top:top: check check condition condition using using CMPCMP if if conditioncondition is is falsefalse, jump to , jump to endWhileendWhile code for LOOP BODYcode for LOOP BODY

(including (including loop control updateloop control update)) jump tojump to top top endWhile:endWhile:

Example pre-test loopExample pre-test loopDouble x until x>1000Double x until x>1000

; initialize accumulator; initialize accumulator

movmov eax, xeax, x

dblLoop:dblLoop: ; Double x while x <= 1000; Double x while x <= 1000

cmpcmp eax, 1000eax, 1000

jaja endLoopendLoop

addadd eax, eaxeax, eax

jmpjmp dblLoopdblLoop

endLoop:endLoop:

movmov x, eaxx, eax

; ...; ...

Posttest loop (do-while)Posttest loop (do-while)

top:top: code for LOOP BODYcode for LOOP BODY

(including (including loop control updateloop control update)) check check condition condition using using CMPCMP if if conditioncondition is is truetrue, jump to , jump to toptop

Example post-test loopExample post-test loopDouble x until x>1000Double x until x>1000

; initialize accumulator; initialize accumulator

movmov eax, xeax, x

dblLoop:dblLoop: ; Double x while x <= 1000; Double x while x <= 1000

addadd eax, eaxeax, eax

cmpcmp eax, 1000eax, 1000

jbejbe dblLoopdblLoop

movmov x, eaxx, eax

; ...; ...

Note: may want initial test for x>1000Note: may want initial test for x>1000

Various solutionsVarious solutions

Any control structure may be Any control structure may be implemented in a variety of ways.implemented in a variety of ways.

Experiment!Experiment!

QuestionsQuestions??

Quiz #2 ThursdayQuiz #2 Thursday

Program #2Program #2 is assigned is assigned

Learn the MASM instructions!Learn the MASM instructions!

Experiment! Experiment! Experiment!! Experiment!! Experiment!!!Experiment!!!