VS 에서 작성한 풀소스  1~100  까지의 숫자 중 짝수만을 더한 구문을


C언어와 asm 으로 작성



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
 

int main()
{
//일반적인 C언어 더하기 구문
    int total = 0;
    int i = 0;
    for (int i=0;i<=100;i+=2)
    {
        total += i;
    }
 
 
    total = 0;
 

//어셈으로 작성한 더하기 구문
    __asm 
    {
        pushad
 
        mov eax, 0
 
        LP:
 
        add eax, 2
 
        add total, eax
 
        cmp eax , 100
        jnge LP
 
        popad
    }
 
    std::cout << total << std::endl;
 
 
    return 0;
}
 
cs





VS, C언어 작성하여 생성된 asm


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int total = 0;
 
 mov         dword ptr [total],0  
 
    int i = 0;
 
 mov         dword ptr [i],0  
 
    for (int i=0;i<=100;i+=2)
 
 mov         dword ptr [ebp-24h],0  
 
 jmp         main+48h (0F91FA8h)  
 
 mov         eax,dword ptr [ebp-24h]  
 
 add         eax,2  
 
 mov         dword ptr [ebp-24h],eax  
 
 cmp         dword ptr [ebp-24h],64h  
 
 jg          main+59h (0F91FB9h)  
 
    {
 
        total += i;
 
 mov         eax,dword ptr [total]  
 
 add         eax,dword ptr [ebp-24h]  
 
 mov         dword ptr [total],eax  
 
    }
 
 jmp         main+3Fh (0F91F9Fh)  
 
 
cs




직접 작성한 asm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
total = 0;
 
    __asm 
    {

        pushad

        mov eax, 0
 
        LP:

        add eax, 2
 
        add total, eax
 
        cmp eax , 100
 
        jnge LP
 
 
 
        popad
 
    }
cs




반응형


cmp 를 사용하게 되면 


cmp eax, 8 

의 경우 이 값이 같은지 비교해 보고 내부 플래그값을 세팅해놓는다


그 이후 


jp(jump) 명령어들 중에서 원하는 명령어를 써주면 LOOP : 레이블로 점프하게 된다



 


jne ( jumpe not equal) 같지 않으면 LOOP 로 간다음

다시 eax 를 1 증가 시킨다


if( i < 1000 )  조건이 성립할때까지 반복함   


즉 이 코드는 do while 문과 유사한 형태로 볼 수 있다





tip : eax 값을 초기에 10을 넣고 하나씩 감소 시키다가 eax 가 0 이 되는 순간 내부 zero 플래그의 상태 값이  1로 변경된다

이때 사용하는 점프문은 jz, jnz 등이 있다




반응형


CPU 와 FPU 는  서로 다른 CPU 인데 현재에 들어서는 CPU 안에FPU가 탑재 되어 있는 방식이다


즉 CPU 안에 레지스터공간(EAX, EDX, 등등...)이 따로 존재 하듯이 FPU 안에도 FPU 만의 레지스터가 따로 존재한다(ST0~ST7 , c0, c2, c3 등등....)



CPU에서 점프를 할때 JZ 등으로 바로 점프 할 수 있으나 FPU 는 float 를 계산하기 위한 전용 처리 장치이기 때문에


float 연산은 FPU 에서 처리 하고 이에 대한 비교 연산이 FPU 내의 C0 , C2, C3  플래그에 기록 되게 되는데 이것을


CPU 의 상태 플래그로 넘겨 줘야 CPU에서 점프처리가 가능하게 된다



과정


1. fcmp 로 float 값을 비교

2. fstsw ax  로 fpu 상태 레지스터 값을 ax로 복사한다

3. sahf 로 ah 를 상태 레지스터로 (EFLAGS(SF:ZF:0:AF:0:PF:1:CF) = AH;)

4. 점프(점프는 unsigned 와 패리티 비트 관련된 걸로 할 수 있는데 c0, c2, c3 값이 세팅 되는 것이 부모 있는 수치에 관련된 플레그로 세팅되지 않기 때문)

          : FPU 는 캐리처리 없이 연산 됨으로



SAHFLoad SF, ZF, AF, PF, and CF from AH into EFLAGS register.



이미지로 간략히 나타내면 다음 처럼 그릴 수 있다






축약 과정


원래는 위 처럼 동작 하지만 이를 간소화ㅎ여 실행 할 수 있는 명령어 FCOMI 가 있다

1. fcmp 로 float 값을 비교

2. FCOMI ST(0), ST(1)       이 명령어가 FPU 레지스터 플래그 들을 CPU 상태 레지스터플래그로 옮겨주는 작업도 처리해준다, 펜티업 프로 이상에서 작동

4. 점프(점프는 unsigned 와 패리티 비트 관련된 걸로 할 수 있는데 c0, c2, c3 값이 세팅 되는 것이 부모 있는 수치에 관련된 플레그로 세팅되지 않기 때문)

          : FPU 는 캐리처리 없이 연산 됨으로




반응형



x86 Instruction Set Reference

Derived from the September 2014 version of the Intel® 64 and IA-32 Architectures Software Developer’s Manual, volumes 2A and 2B.

More info at zneak/x86doc

This reference is not perfect. It's been mechanically separated into distinct files by a dumb script. It may be enough to replace the official documentation on your weekend reverse engineering project, but in doubt, go get the official and freely available documentation.

Download documentation set

AAAASCII Adjust After Addition
AADASCII Adjust AX Before Division
AAMASCII Adjust AX After Multiply
AASASCII Adjust AL After Subtraction
ADCAdd with Carry
ADCXUnsigned Integer Addition of Two Operands with Carry Flag
ADDAdd
ADDPDAdd Packed Double-Precision Floating-Point Values
ADDPSAdd Packed Single-Precision Floating-Point Values
ADDSDAdd Scalar Double-Precision Floating-Point Values
ADDSSAdd Scalar Single-Precision Floating-Point Values
ADDSUBPDPacked Double-FP Add/Subtract
ADDSUBPSPacked Single-FP Add/Subtract
ADOXUnsigned Integer Addition of Two Operands with Overflow Flag
AESDECPerform One Round of an AES Decryption Flow
AESDECLASTPerform Last Round of an AES Decryption Flow
AESENCPerform One Round of an AES Encryption Flow
AESENCLASTPerform Last Round of an AES Encryption Flow
AESIMCPerform the AES InvMixColumn Transformation
AESKEYGENASSISTAES Round Key Generation Assist
ANDLogical AND
ANDNLogical AND NOT
ANDNPDBitwise Logical AND NOT of Packed Double-Precision Floating-Point Values
ANDNPSBitwise Logical AND NOT of Packed Single-Precision Floating-Point Values
ANDPDBitwise Logical AND of Packed Double-Precision Floating-Point Values
ANDPSBitwise Logical AND of Packed Single-Precision Floating-Point Values
ARPLAdjust RPL Field of Segment Selector
BEXTRBit Field Extract
BLENDPDBlend Packed Double Precision Floating-Point Values
BLENDPSBlend Packed Single Precision Floating-Point Values
BLENDVPDVariable Blend Packed Double Precision Floating-Point Values
BLENDVPSVariable Blend Packed Single Precision Floating-Point Values
BLSIExtract Lowest Set Isolated Bit
BLSMSKGet Mask Up to Lowest Set Bit
BLSRReset Lowest Set Bit
BOUNDCheck Array Index Against Bounds
BSFBit Scan Forward
BSRBit Scan Reverse
BSWAPByte Swap
BTBit Test
BTCBit Test and Complement
BTRBit Test and Reset
BTSBit Test and Set
BZHIZero High Bits Starting with Specified Bit Position
CALLCall Procedure
CBWConvert Byte to Word/Convert Word to Doubleword/Convert Doubleword to Quadword
CDQConvert Word to Doubleword/Convert Doubleword to Quadword
CDQEConvert Byte to Word/Convert Word to Doubleword/Convert Doubleword to Quadword
CLACClear AC Flag in EFLAGS Register
CLCClear Carry Flag
CLDClear Direction Flag
CLFLUSHFlush Cache Line
CLIClear Interrupt Flag
CLTSClear Task-Switched Flag in CR0
CMCComplement Carry Flag
CMOVccConditional Move
CMPCompare Two Operands
CMPPDCompare Packed Double-Precision Floating-Point Values
CMPPSCompare Packed Single-Precision Floating-Point Values
CMPSCompare String Operands
CMPSBCompare String Operands
CMPSDCompare String Operands
CMPSDCompare Scalar Double-Precision Floating-Point Values
CMPSQCompare String Operands
CMPSSCompare Scalar Single-Precision Floating-Point Values
CMPSWCompare String Operands
CMPXCHGCompare and Exchange
CMPXCHG16BCompare and Exchange Bytes
CMPXCHG8BCompare and Exchange Bytes
COMISDCompare Scalar Ordered Double-Precision Floating-Point Values and Set EFLAGS
COMISSCompare Scalar Ordered Single-Precision Floating-Point Values and Set EFLAGS
CPUIDCPU Identification
CQOConvert Word to Doubleword/Convert Doubleword to Quadword
CRC32Accumulate CRC32 Value
CVTDQ2PDConvert Packed Dword Integers to Packed Double-Precision FP Values
CVTDQ2PSConvert Packed Dword Integers to Packed Single-Precision FP Values
CVTPD2DQConvert Packed Double-Precision FP Values to Packed Dword Integers
CVTPD2PIConvert Packed Double-Precision FP Values to Packed Dword Integers
CVTPD2PSConvert Packed Double-Precision FP Values to Packed Single-Precision FP Values
CVTPI2PDConvert Packed Dword Integers to Packed Double-Precision FP Values
CVTPI2PSConvert Packed Dword Integers to Packed Single-Precision FP Values
CVTPS2DQConvert Packed Single-Precision FP Values to Packed Dword Integers
CVTPS2PDConvert Packed Single-Precision FP Values to Packed Double-Precision FP Values
CVTPS2PIConvert Packed Single-Precision FP Values to Packed Dword Integers
CVTSD2SIConvert Scalar Double-Precision FP Value to Integer
CVTSD2SSConvert Scalar Double-Precision FP Value to Scalar Single-Precision FP Value
CVTSI2SDConvert Dword Integer to Scalar Double-Precision FP Value
CVTSI2SSConvert Dword Integer to Scalar Single-Precision FP Value
CVTSS2SDConvert Scalar Single-Precision FP Value to Scalar Double-Precision FP Value
CVTSS2SIConvert Scalar Single-Precision FP Value to Dword Integer
CVTTPD2DQConvert with Truncation Packed Double-Precision FP Values to Packed Dword Integers
CVTTPD2PIConvert with Truncation Packed Double-Precision FP Values to Packed Dword Integers
CVTTPS2DQConvert with Truncation Packed Single-Precision FP Values to Packed Dword Integers
CVTTPS2PIConvert with Truncation Packed Single-Precision FP Values to Packed Dword Integers
CVTTSD2SIConvert with Truncation Scalar Double-Precision FP Value to Signed Integer
CVTTSS2SIConvert with Truncation Scalar Single-Precision FP Value to Dword Integer
CWDConvert Word to Doubleword/Convert Doubleword to Quadword
CWDEConvert Byte to Word/Convert Word to Doubleword/Convert Doubleword to Quadword
DAADecimal Adjust AL after Addition
DASDecimal Adjust AL after Subtraction
DECDecrement by 1
DIVUnsigned Divide
DIVPDDivide Packed Double-Precision Floating-Point Values
DIVPSDivide Packed Single-Precision Floating-Point Values
DIVSDDivide Scalar Double-Precision Floating-Point Values
DIVSSDivide Scalar Single-Precision Floating-Point Values
DPPDDot Product of Packed Double Precision Floating-Point Values
DPPSDot Product of Packed Single Precision Floating-Point Values
EMMSEmpty MMX Technology State
ENTERMake Stack Frame for Procedure Parameters
EXTRACTPSExtract Packed Single Precision Floating-Point Value
F2XM1Compute 2x–1
FABSAbsolute Value
FADDAdd
FADDPAdd
FBLDLoad Binary Coded Decimal
FBSTPStore BCD Integer and Pop
FCHSChange Sign
FCLEXClear Exceptions
FCMOVccFloating-Point Conditional Move
FCOMCompare Floating Point Values
FCOMICompare Floating Point Values and Set EFLAGS
FCOMIPCompare Floating Point Values and Set EFLAGS
FCOMPCompare Floating Point Values
FCOMPPCompare Floating Point Values
FCOSCosine
FDECSTPDecrement Stack-Top Pointer
FDIVDivide
FDIVPDivide
FDIVRReverse Divide
FDIVRPReverse Divide
FFREEFree Floating-Point Register
FIADDAdd
FICOMCompare Integer
FICOMPCompare Integer
FIDIVDivide
FIDIVRReverse Divide
FILDLoad Integer
FIMULMultiply
FINCSTPIncrement Stack-Top Pointer
FINITInitialize Floating-Point Unit
FISTStore Integer
FISTPStore Integer
FISTTPStore Integer with Truncation
FISUBSubtract
FISUBRReverse Subtract
FLDLoad Floating Point Value
FLD1Load Constant
FLDCWLoad x87 FPU Control Word
FLDENVLoad x87 FPU Environment
FLDL2ELoad Constant
FLDL2TLoad Constant
FLDLG2Load Constant
FLDLN2Load Constant
FLDPILoad Constant
FLDZLoad Constant
FMULMultiply
FMULPMultiply
FNCLEXClear Exceptions
FNINITInitialize Floating-Point Unit
FNOPNo Operation
FNSAVEStore x87 FPU State
FNSTCWStore x87 FPU Control Word
FNSTENVStore x87 FPU Environment
FNSTSWStore x87 FPU Status Word
FPATANPartial Arctangent
FPREMPartial Remainder
FPREM1Partial Remainder
FPTANPartial Tangent
FRNDINTRound to Integer
FRSTORRestore x87 FPU State
FSAVEStore x87 FPU State
FSCALEScale
FSINSine
FSINCOSSine and Cosine
FSQRTSquare Root
FSTStore Floating Point Value
FSTCWStore x87 FPU Control Word
FSTENVStore x87 FPU Environment
FSTPStore Floating Point Value
FSTSWStore x87 FPU Status Word
FSUBSubtract
FSUBPSubtract
FSUBRReverse Subtract
FSUBRPReverse Subtract
FTSTTEST
FUCOMUnordered Compare Floating Point Values
FUCOMICompare Floating Point Values and Set EFLAGS
FUCOMIPCompare Floating Point Values and Set EFLAGS
FUCOMPUnordered Compare Floating Point Values
FUCOMPPUnordered Compare Floating Point Values
FWAITWait
FXAMExamine ModR/M
FXCHExchange Register Contents
FXRSTORRestore x87 FPU, MMX, XMM, and MXCSR State
FXSAVESave x87 FPU, MMX Technology, and SSE State
FXTRACTExtract Exponent and Significand
FYL2XCompute y ∗ log2x
FYL2XP1Compute y ∗ log2(x +1)
HADDPDPacked Double-FP Horizontal Add
HADDPSPacked Single-FP Horizontal Add
HLTHalt
HSUBPDPacked Double-FP Horizontal Subtract
HSUBPSPacked Single-FP Horizontal Subtract
IDIVSigned Divide
IMULSigned Multiply
INInput from Port
INCIncrement by 1
INSInput from Port to String
INSBInput from Port to String
INSDInput from Port to String
INSERTPSInsert Packed Single Precision Floating-Point Value
INSWInput from Port to String
INT 3Call to Interrupt Procedure
INT nCall to Interrupt Procedure
INTOCall to Interrupt Procedure
INVDInvalidate Internal Caches
INVLPGInvalidate TLB Entries
INVPCIDInvalidate Process-Context Identifier
IRETInterrupt Return
IRETDInterrupt Return
JMPJump
JccJump if Condition Is Met
LAHFLoad Status Flags into AH Register
LARLoad Access Rights Byte
LDDQULoad Unaligned Integer 128 Bits
LDMXCSRLoad MXCSR Register
LDSLoad Far Pointer
LEALoad Effective Address
LEAVEHigh Level Procedure Exit
LESLoad Far Pointer
LFENCELoad Fence
LFSLoad Far Pointer
LGDTLoad Global/Interrupt Descriptor Table Register
LGSLoad Far Pointer
LIDTLoad Global/Interrupt Descriptor Table Register
LLDTLoad Local Descriptor Table Register
LMSWLoad Machine Status Word
LOCKAssert LOCK# Signal Prefix
LODSLoad String
LODSBLoad String
LODSDLoad String
LODSQLoad String
LODSWLoad String
LOOPLoop According to ECX Counter
LOOPccLoop According to ECX Counter
LSLLoad Segment Limit
LSSLoad Far Pointer
LTRLoad Task Register
LZCNTCount the Number of Leading Zero Bits
MASKMOVDQUStore Selected Bytes of Double Quadword
MASKMOVQStore Selected Bytes of Quadword
MAXPDReturn Maximum Packed Double-Precision Floating-Point Values
MAXPSReturn Maximum Packed Single-Precision Floating-Point Values
MAXSDReturn Maximum Scalar Double-Precision Floating-Point Value
MAXSSReturn Maximum Scalar Single-Precision Floating-Point Value
MFENCEMemory Fence
MINPDReturn Minimum Packed Double-Precision Floating-Point Values
MINPSReturn Minimum Packed Single-Precision Floating-Point Values
MINSDReturn Minimum Scalar Double-Precision Floating-Point Value
MINSSReturn Minimum Scalar Single-Precision Floating-Point Value
MONITORSet Up Monitor Address
MOVMove
MOVMove to/from Control Registers
MOVMove to/from Debug Registers
MOVAPDMove Aligned Packed Double-Precision Floating-Point Values
MOVAPSMove Aligned Packed Single-Precision Floating-Point Values
MOVBEMove Data After Swapping Bytes
MOVDMove Doubleword/Move Quadword
MOVDDUPMove One Double-FP and Duplicate
MOVDQ2QMove Quadword from XMM to MMX Technology Register
MOVDQAMove Aligned Double Quadword
MOVDQUMove Unaligned Double Quadword
MOVHLPSMove Packed Single-Precision Floating-Point Values High to Low
MOVHPDMove High Packed Double-Precision Floating-Point Value
MOVHPSMove High Packed Single-Precision Floating-Point Values
MOVLHPSMove Packed Single-Precision Floating-Point Values Low to High
MOVLPDMove Low Packed Double-Precision Floating-Point Value
MOVLPSMove Low Packed Single-Precision Floating-Point Values
MOVMSKPDExtract Packed Double-Precision Floating-Point Sign Mask
MOVMSKPSExtract Packed Single-Precision Floating-Point Sign Mask
MOVNTDQStore Double Quadword Using Non-Temporal Hint
MOVNTDQALoad Double Quadword Non-Temporal Aligned Hint
MOVNTIStore Doubleword Using Non-Temporal Hint
MOVNTPDStore Packed Double-Precision Floating-Point Values Using Non-Temporal Hint
MOVNTPSStore Packed Single-Precision Floating-Point Values Using Non-Temporal Hint
MOVNTQStore of Quadword Using Non-Temporal Hint
MOVQMove Doubleword/Move Quadword
MOVQMove Quadword
MOVQ2DQMove Quadword from MMX Technology to XMM Register
MOVSMove Data from String to String
MOVSBMove Data from String to String
MOVSDMove Data from String to String
MOVSDMove Scalar Double-Precision Floating-Point Value
MOVSHDUPMove Packed Single-FP High and Duplicate
MOVSLDUPMove Packed Single-FP Low and Duplicate
MOVSQMove Data from String to String
MOVSSMove Scalar Single-Precision Floating-Point Values
MOVSWMove Data from String to String
MOVSXMove with Sign-Extension
MOVSXDMove with Sign-Extension
MOVUPDMove Unaligned Packed Double-Precision Floating-Point Values
MOVUPSMove Unaligned Packed Single-Precision Floating-Point Values
MOVZXMove with Zero-Extend
MPSADBWCompute Multiple Packed Sums of Absolute Difference
MULUnsigned Multiply
MULPDMultiply Packed Double-Precision Floating-Point Values
MULPSMultiply Packed Single-Precision Floating-Point Values
MULSDMultiply Scalar Double-Precision Floating-Point Values
MULSSMultiply Scalar Single-Precision Floating-Point Values
MWAITMonitor Wait
MULXUnsigned Multiply Without Affecting Flags
MWAITMonitor Wait
NEGTwo's Complement Negation
NOPNo Operation
NOTOne's Complement Negation
ORLogical Inclusive OR
ORPDBitwise Logical OR of Double-Precision Floating-Point Values
ORPSBitwise Logical OR of Single-Precision Floating-Point Values
OUTOutput to Port
OUTSOutput String to Port
OUTSBOutput String to Port
OUTSDOutput String to Port
OUTSWOutput String to Port
PABSBPacked Absolute Value
PABSDPacked Absolute Value
PABSWPacked Absolute Value
PACKSSDWPack with Signed Saturation
PACKSSWBPack with Signed Saturation
PACKUSDWPack with Unsigned Saturation
PACKUSWBPack with Unsigned Saturation
PADDBAdd Packed Integers
PADDDAdd Packed Integers
PADDQAdd Packed Quadword Integers
PADDSBAdd Packed Signed Integers with Signed Saturation
PADDSWAdd Packed Signed Integers with Signed Saturation
PADDUSBAdd Packed Unsigned Integers with Unsigned Saturation
PADDUSWAdd Packed Unsigned Integers with Unsigned Saturation
PADDWAdd Packed Integers
PALIGNRPacked Align Right
PANDLogical AND
PANDNLogical AND NOT
PAUSESpin Loop Hint
PAVGBAverage Packed Integers
PAVGWAverage Packed Integers
PBLENDVBVariable Blend Packed Bytes
PBLENDWBlend Packed Words
PCLMULQDQCarry-Less Multiplication Quadword
PCMPEQBCompare Packed Data for Equal
PCMPEQDCompare Packed Data for Equal
PCMPEQQCompare Packed Qword Data for Equal
PCMPEQWCompare Packed Data for Equal
PCMPESTRIPacked Compare Explicit Length Strings, Return Index
PCMPESTRMPacked Compare Explicit Length Strings, Return Mask
PCMPGTBCompare Packed Signed Integers for Greater Than
PCMPGTDCompare Packed Signed Integers for Greater Than
PCMPGTQCompare Packed Data for Greater Than
PCMPGTWCompare Packed Signed Integers for Greater Than
PCMPISTRIPacked Compare Implicit Length Strings, Return Index
PCMPISTRMPacked Compare Implicit Length Strings, Return Mask
PDEPParallel Bits Deposit
PEXTParallel Bits Extract
PEXTRBExtract Byte/Dword/Qword
PEXTRDExtract Byte/Dword/Qword
PEXTRQExtract Byte/Dword/Qword
PEXTRWExtract Word
PHADDDPacked Horizontal Add
PHADDSWPacked Horizontal Add and Saturate
PHADDWPacked Horizontal Add
PHMINPOSUWPacked Horizontal Word Minimum
PHSUBDPacked Horizontal Subtract
PHSUBSWPacked Horizontal Subtract and Saturate
PHSUBWPacked Horizontal Subtract
PINSRBInsert Byte/Dword/Qword
PINSRDInsert Byte/Dword/Qword
PINSRQInsert Byte/Dword/Qword
PINSRWInsert Word
PMADDUBSWMultiply and Add Packed Signed and Unsigned Bytes
PMADDWDMultiply and Add Packed Integers
PMAXSBMaximum of Packed Signed Byte Integers
PMAXSDMaximum of Packed Signed Dword Integers
PMAXSWMaximum of Packed Signed Word Integers
PMAXUBMaximum of Packed Unsigned Byte Integers
PMAXUDMaximum of Packed Unsigned Dword Integers
PMAXUWMaximum of Packed Word Integers
PMINSBMinimum of Packed Signed Byte Integers
PMINSDMinimum of Packed Dword Integers
PMINSWMinimum of Packed Signed Word Integers
PMINUBMinimum of Packed Unsigned Byte Integers
PMINUDMinimum of Packed Dword Integers
PMINUWMinimum of Packed Word Integers
PMOVMSKBMove Byte Mask
PMOVSXPacked Move with Sign Extend
PMOVZXPacked Move with Zero Extend
PMULDQMultiply Packed Signed Dword Integers
PMULHRSWPacked Multiply High with Round and Scale
PMULHUWMultiply Packed Unsigned Integers and Store High Result
PMULHWMultiply Packed Signed Integers and Store High Result
PMULLDMultiply Packed Signed Dword Integers and Store Low Result
PMULLWMultiply Packed Signed Integers and Store Low Result
PMULUDQMultiply Packed Unsigned Doubleword Integers
POPPop a Value from the Stack
POPAPop All General-Purpose Registers
POPADPop All General-Purpose Registers
POPCNTReturn the Count of Number of Bits Set to 1
POPFPop Stack into EFLAGS Register
POPFDPop Stack into EFLAGS Register
POPFQPop Stack into EFLAGS Register
PORBitwise Logical OR
PREFETCHWPrefetch Data into Caches in Anticipation of a Write
PREFETCHWT1Prefetch Vector Data Into Caches with Intent to Write and T1 Hint
PREFETCHhPrefetch Data Into Caches
PSADBWCompute Sum of Absolute Differences
PSHUFBPacked Shuffle Bytes
PSHUFDShuffle Packed Doublewords
PSHUFHWShuffle Packed High Words
PSHUFLWShuffle Packed Low Words
PSHUFWShuffle Packed Words
PSIGNBPacked SIGN
PSIGNDPacked SIGN
PSIGNWPacked SIGN
PSLLDShift Packed Data Left Logical
PSLLDQShift Double Quadword Left Logical
PSLLQShift Packed Data Left Logical
PSLLWShift Packed Data Left Logical
PSRADShift Packed Data Right Arithmetic
PSRAWShift Packed Data Right Arithmetic
PSRLDShift Packed Data Right Logical
PSRLDQShift Double Quadword Right Logical
PSRLQShift Packed Data Right Logical
PSRLWShift Packed Data Right Logical
PSUBBSubtract Packed Integers
PSUBDSubtract Packed Integers
PSUBQSubtract Packed Quadword Integers
PSUBSBSubtract Packed Signed Integers with Signed Saturation
PSUBSWSubtract Packed Signed Integers with Signed Saturation
PSUBUSBSubtract Packed Unsigned Integers with Unsigned Saturation
PSUBUSWSubtract Packed Unsigned Integers with Unsigned Saturation
PSUBWSubtract Packed Integers
PTESTLogical Compare
PUNPCKHBWUnpack High Data
PUNPCKHDQUnpack High Data
PUNPCKHQDQUnpack High Data
PUNPCKHWDUnpack High Data
PUNPCKLBWUnpack Low Data
PUNPCKLDQUnpack Low Data
PUNPCKLQDQUnpack Low Data
PUNPCKLWDUnpack Low Data
PUSHPush Word, Doubleword or Quadword Onto the Stack
PUSHAPush All General-Purpose Registers
PUSHADPush All General-Purpose Registers
PUSHFPush EFLAGS Register onto the Stack
PUSHFDPush EFLAGS Register onto the Stack
PXORLogical Exclusive OR
RCL—Rotate
RCPPSCompute Reciprocals of Packed Single-Precision Floating-Point Values
RCPSSCompute Reciprocal of Scalar Single-Precision Floating-Point Values
RCR—Rotate
RDFSBASERead FS/GS Segment Base
RDGSBASERead FS/GS Segment Base
RDMSRRead from Model Specific Register
RDPMCRead Performance-Monitoring Counters
RDRANDRead Random Number
RDSEEDRead Random SEED
RDTSCRead Time-Stamp Counter
RDTSCPRead Time-Stamp Counter and Processor ID
REPRepeat String Operation Prefix
REPERepeat String Operation Prefix
REPNERepeat String Operation Prefix
REPNZRepeat String Operation Prefix
REPZRepeat String Operation Prefix
RETReturn from Procedure
ROL—Rotate
ROR—Rotate
RORXRotate Right Logical Without Affecting Flags
ROUNDPDRound Packed Double Precision Floating-Point Values
ROUNDPSRound Packed Single Precision Floating-Point Values
ROUNDSDRound Scalar Double Precision Floating-Point Values
ROUNDSSRound Scalar Single Precision Floating-Point Values
RSMResume from System Management Mode
RSQRTPSCompute Reciprocals of Square Roots of Packed Single-Precision Floating-Point Values
RSQRTSSCompute Reciprocal of Square Root of Scalar Single-Precision Floating-Point Value
SAHFStore AH into Flags
SALShift
SARShift
SARXShift Without Affecting Flags
SBBInteger Subtraction with Borrow
SCASScan String
SCASBScan String
SCASDScan String
SCASWScan String
SETccSet Byte on Condition
SFENCEStore Fence
SGDTStore Global Descriptor Table Register
SHLShift
SHLDDouble Precision Shift Left
SHLXShift Without Affecting Flags
SHRShift
SHRDDouble Precision Shift Right
SHRXShift Without Affecting Flags
SHUFPDShuffle Packed Double-Precision Floating-Point Values
SHUFPSShuffle Packed Single-Precision Floating-Point Values
SIDTStore Interrupt Descriptor Table Register
SLDTStore Local Descriptor Table Register
SMSWStore Machine Status Word
SQRTPDCompute Square Roots of Packed Double-Precision Floating-Point Values
SQRTPSCompute Square Roots of Packed Single-Precision Floating-Point Values
SQRTSDCompute Square Root of Scalar Double-Precision Floating-Point Value
SQRTSSCompute Square Root of Scalar Single-Precision Floating-Point Value
STACSet AC Flag in EFLAGS Register
STCSet Carry Flag
STDSet Direction Flag
STISet Interrupt Flag
STMXCSRStore MXCSR Register State
STOSStore String
STOSBStore String
STOSDStore String
STOSQStore String
STOSWStore String
STRStore Task Register
SUBSubtract
SUBPDSubtract Packed Double-Precision Floating-Point Values
SUBPSSubtract Packed Single-Precision Floating-Point Values
SUBSDSubtract Scalar Double-Precision Floating-Point Values
SUBSSSubtract Scalar Single-Precision Floating-Point Values
SWAPGSSwap GS Base Register
SYSCALLFast System Call
SYSENTERFast System Call
SYSEXITFast Return from Fast System Call
SYSRETReturn From Fast System Call
TESTLogical Compare
TZCNTCount the Number of Trailing Zero Bits
UCOMISDUnordered Compare Scalar Double-Precision Floating-Point Values and Set EFLAGS
UCOMISSUnordered Compare Scalar Single-Precision Floating-Point Values and Set EFLAGS
UD2Undefined Instruction
UNPCKHPDUnpack and Interleave High Packed Double-Precision Floating-Point Values
UNPCKHPSUnpack and Interleave High Packed Single-Precision Floating-Point Values
UNPCKLPDUnpack and Interleave Low Packed Double-Precision Floating-Point Values
UNPCKLPSUnpack and Interleave Low Packed Single-Precision Floating-Point Values
VBROADCASTBroadcast Floating-Point Data
VCVTPH2PSConvert 16-bit FP Values to Single-Precision FP Values
VCVTPS2PHConvert Single-Precision FP value to 16-bit FP value
VERRVerify a Segment for Reading or Writing
VERWVerify a Segment for Reading or Writing
VEXTRACTF128Extract Packed Floating-Point Values
VEXTRACTI128Extract packed Integer Values
VFMADD132PDFused Multiply-Add of Packed Double-Precision Floating-Point Values
VFMADD132PSFused Multiply-Add of Packed Single-Precision Floating-Point Values
VFMADD132SDFused Multiply-Add of Scalar Double-Precision Floating-Point Values
VFMADD132SSFused Multiply-Add of Scalar Single-Precision Floating-Point Values
VFMADD213PDFused Multiply-Add of Packed Double-Precision Floating-Point Values
VFMADD213PSFused Multiply-Add of Packed Single-Precision Floating-Point Values
VFMADD213SDFused Multiply-Add of Scalar Double-Precision Floating-Point Values
VFMADD213SSFused Multiply-Add of Scalar Single-Precision Floating-Point Values
VFMADD231PDFused Multiply-Add of Packed Double-Precision Floating-Point Values
VFMADD231PSFused Multiply-Add of Packed Single-Precision Floating-Point Values
VFMADD231SDFused Multiply-Add of Scalar Double-Precision Floating-Point Values
VFMADD231SSFused Multiply-Add of Scalar Single-Precision Floating-Point Values
VFMADDSUB132PDFused Multiply-Alternating Add/Subtract of Packed Double-Precision Floating-Point Values
VFMADDSUB132PSFused Multiply-Alternating Add/Subtract of Packed Single-Precision Floating-Point Values
VFMADDSUB213PDFused Multiply-Alternating Add/Subtract of Packed Double-Precision Floating-Point Values
VFMADDSUB213PSFused Multiply-Alternating Add/Subtract of Packed Single-Precision Floating-Point Values
VFMADDSUB231PDFused Multiply-Alternating Add/Subtract of Packed Double-Precision Floating-Point Values
VFMADDSUB231PSFused Multiply-Alternating Add/Subtract of Packed Single-Precision Floating-Point Values
VFMSUB132PDFused Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFMSUB132PSFused Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFMSUB132SDFused Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFMSUB132SSFused Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VFMSUB213PDFused Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFMSUB213PSFused Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFMSUB213SDFused Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFMSUB213SSFused Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VFMSUB231PDFused Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFMSUB231PSFused Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFMSUB231SDFused Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFMSUB231SSFused Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VFMSUBADD132PDFused Multiply-Alternating Subtract/Add of Packed Double-Precision Floating-Point Values
VFMSUBADD132PSFused Multiply-Alternating Subtract/Add of Packed Single-Precision Floating-Point Values
VFMSUBADD213PDFused Multiply-Alternating Subtract/Add of Packed Double-Precision Floating-Point Values
VFMSUBADD213PSFused Multiply-Alternating Subtract/Add of Packed Single-Precision Floating-Point Values
VFMSUBADD231PDFused Multiply-Alternating Subtract/Add of Packed Double-Precision Floating-Point Values
VFMSUBADD231PSFused Multiply-Alternating Subtract/Add of Packed Single-Precision Floating-Point Values
VFNMADD132PDFused Negative Multiply-Add of Packed Double-Precision Floating-Point Values
VFNMADD132PSFused Negative Multiply-Add of Packed Single-Precision Floating-Point Values
VFNMADD132SDFused Negative Multiply-Add of Scalar Double-Precision Floating-Point Values
VFNMADD132SSFused Negative Multiply-Add of Scalar Single-Precision Floating-Point Values
VFNMADD213PDFused Negative Multiply-Add of Packed Double-Precision Floating-Point Values
VFNMADD213PSFused Negative Multiply-Add of Packed Single-Precision Floating-Point Values
VFNMADD213SDFused Negative Multiply-Add of Scalar Double-Precision Floating-Point Values
VFNMADD213SSFused Negative Multiply-Add of Scalar Single-Precision Floating-Point Values
VFNMADD231PDFused Negative Multiply-Add of Packed Double-Precision Floating-Point Values
VFNMADD231PSFused Negative Multiply-Add of Packed Single-Precision Floating-Point Values
VFNMADD231SDFused Negative Multiply-Add of Scalar Double-Precision Floating-Point Values
VFNMADD231SSFused Negative Multiply-Add of Scalar Single-Precision Floating-Point Values
VFNMSUB132PDFused Negative Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFNMSUB132PSFused Negative Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFNMSUB132SDFused Negative Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFNMSUB132SSFused Negative Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VFNMSUB213PDFused Negative Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFNMSUB213PSFused Negative Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFNMSUB213SDFused Negative Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFNMSUB213SSFused Negative Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VFNMSUB231PDFused Negative Multiply-Subtract of Packed Double-Precision Floating-Point Values
VFNMSUB231PSFused Negative Multiply-Subtract of Packed Single-Precision Floating-Point Values
VFNMSUB231SDFused Negative Multiply-Subtract of Scalar Double-Precision Floating-Point Values
VFNMSUB231SSFused Negative Multiply-Subtract of Scalar Single-Precision Floating-Point Values
VGATHERDPDGather Packed DP FP Values Using Signed Dword/Qword Indices
VGATHERDPSGather Packed SP FP values Using Signed Dword/Qword Indices
VGATHERQPDGather Packed DP FP Values Using Signed Dword/Qword Indices
VGATHERQPSGather Packed SP FP values Using Signed Dword/Qword Indices
VINSERTF128Insert Packed Floating-Point Values
VINSERTI128Insert Packed Integer Values
VMASKMOVConditional SIMD Packed Loads and Stores
VPBLENDDBlend Packed Dwords
VPBROADCASTBroadcast Integer Data
VPERM2F128Permute Floating-Point Values
VPERM2I128Permute Integer Values
VPERMDFull Doublewords Element Permutation
VPERMILPDPermute Double-Precision Floating-Point Values
VPERMILPSPermute Single-Precision Floating-Point Values
VPERMPDPermute Double-Precision Floating-Point Elements
VPERMPSPermute Single-Precision Floating-Point Elements
VPERMQQwords Element Permutation
VPGATHERDDGather Packed Dword Values Using Signed Dword/Qword Indices
VPGATHERDQGather Packed Qword Values Using Signed Dword/Qword Indices
VPGATHERQDGather Packed Dword Values Using Signed Dword/Qword Indices
VPGATHERQQGather Packed Qword Values Using Signed Dword/Qword Indices
VPMASKMOVConditional SIMD Integer Packed Loads and Stores
VPSLLVDVariable Bit Shift Left Logical
VPSLLVQVariable Bit Shift Left Logical
VPSRAVDVariable Bit Shift Right Arithmetic
VPSRLVDVariable Bit Shift Right Logical
VPSRLVQVariable Bit Shift Right Logical
VTESTPDPacked Bit Test
VTESTPSPacked Bit Test
VZEROALLZero All YMM Registers
VZEROUPPERZero Upper Bits of YMM Registers
WAITWait
WBINVDWrite Back and Invalidate Cache
WRFSBASEWrite FS/GS Segment Base
WRGSBASEWrite FS/GS Segment Base
WRMSRWrite to Model Specific Register
XABORTTransactional Abort
XACQUIREHardware Lock Elision Prefix Hints
XADDExchange and Add
XBEGINTransactional Begin
XCHGExchange Register/Memory with Register
XENDTransactional End
XGETBVGet Value of Extended Control Register
XLATTable Look-up Translation
XLATBTable Look-up Translation
XORLogical Exclusive OR
XORPDBitwise Logical XOR for Double-Precision Floating-Point Values
XORPSBitwise Logical XOR for Single-Precision Floating-Point Values
XRELEASEHardware Lock Elision Prefix Hints
XRSTORRestore Processor Extended States
XRSTORSRestore Processor Extended States Supervisor
XSAVESave Processor Extended States
XSAVECSave Processor Extended States with Compaction
XSAVEOPTSave Processor Extended States Optimized
XSAVESSave Processor Extended States Supervisor
XSETBVSet Extended Control Register
XTESTTest If In Transactional Execution




http://www.felixcloutier.com/x86/





반응형
ENTER numbytes, nestinglevel

numbytes 는 변수로 사용하고자 하는 바이트 수치
nestinglevel 은 { 를 중첩해서 써 내려갈 때의 중첩 수치


Enter명령은 nestingLevel 이 0 일때 아래처럼 매칭이 되는데


일반적 방법

ENTER 명령어 사용

push ebp

mov ebp,esp

sub esp,4

enter 4,0


nestingLevel 에 수치가 주어 지게 되면 이전 , 이전전... ebp 들을 저장하여 이전에 사용했던 변수들에 접근 하도록허용해준다

enter 로 들어 가서 할당한다음 leave 로 할당한 메모리를 해제 하는 처리를 해야함


if 먼저 아래처럼 asm 코드를 작성 한다고 했을 때


_asm {


enter 4, 0 0)

enter 4, 1 1)


enter 4, 2 2)


enter 4, 3 3)


enter 4, 4 4)


enter 4, 5 5)


}




먼저 아래처럼 asm 코드를 작성 한다고 했을 때 아래 처럼 실제 메모리 주소에 이전 ebp 값들이 어떻게 쌓이는지 확인 할 수가 있으며 이 값들로 한 함수 내에서 아래와 같은 괄호로 묶은 지역 변수들을 참조 할 수 있는 형태를 구성 할 수 있다


void stackFrameTestFunc()

{

int a=0;

{

int b=0;

{

int c=0;

a=3;

b=4;

}

}

}



}


먼저 이전 스택영역으로 되돌아 가기전에 enter 명령어가 수행 되면 push ebp 가

기본 수행 된 다음 이전 ebp 를 넣는 처리를 하게 된다



왼쪽 굵은 글자 0x00000000 는 실제 메모리 주소를 말한다

오른쪽 주소는 해당 메모리 주소에 들어가있는 값


 

5)

0X0078F794

0X0078F798  0078F7AC   //현재 ebp

0X0078F79C  0078F7C4 //이전 ebp

0X0078F7A0  0078F7D8 //이전전 ebp

0X0078F7A4  0078F7E8 //이전전전 ebp

0X0078F7A8  0078F7F4   //이전전전전 ebp

0X0078F7AC  0078F7C4   //이전 ebp                        enter 4, 5 5)

4)

0X0078F7B0  

0X0078F7B4  0078F7C4 //현재 ebp

0X0078F7B8  0078F7D8 //이전 ebp

0X0078F7BC  0078F7E8 //이전전 ebp

0X0078F7C0  0078F7F4 //이전전전 ebp

0X0078F7C4  0078F7D8 //이전 ebp                        enter 4, 4 4)


3)

0X0078F7C8

0X0078F7CC  0078F7D8 //현재 ebp

0X0078F7D0  0078F7E8 //이전 ebp

0X0078F7D4  0078F7F4 //이전전 ebp

0X0078F7D8  0078F7E8 //이전 ebp                        enter 4, 3 3)

2)

0X0078F7DC

0X0078F7E0  0078F7E8 //현재 ebp

0X0078F7E4  0078F7F4 //이전 ebp

0X0078F7E8  0078F7F4 //이전 ebp                        enter 4, 2 2)

1)

0X0078F7EC

0X0078F7F0  0078F7F4 //현재 ebp

0X0078F7F4  0078F7FC   //이전 ebp                        enter 4, 1 1)


0)

0X0078F7F8  

0X0078F7FC  0078F8CC //이전 ebp                        enter 4, 0 0)

 










반응형
다운 받은 파일을 Microsoft Visual Studio 14.0\Common7\IDE 경로 아래다가 복사해줍니다.

usertype.dat


아래는 _asm 코드가 하이라이트 된 화면 예시




다른 설정을 하지 않았다면 이 경로 C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE 에다가 복붙
 


 

 

VS에서 도구 -> 옵션 -> 텍스트 편집기 -> 파일 확장명을 클릭한후
 
확장명에 asm을 적고 편집기에서 C++을 설정을 해줍니다.
 
확인후 VS를 재시작합니다.

 
 


http://m.todayhumor.co.kr/view.php?table=total&no=10627412








반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
_asm {
        mov ebx, [ebp - 4h]    
        mov dword ptr[ebp - 4h], 10
        mov eax, [ebp - 4]
        mov ecx, ebp
                           //lea 에서 [] 은 한번 더 거처가는게 아니고 그냥 그 안에 있는 것들의 연산 결과 값이며 + 연산등을 쓸 수가 있다
        //lea eax, ecx        //lea 는 [] 이 와야만 한다 , 그냥 쓰면 이건 없는 명령어
        lea eax, [ecx + 4]    //[]를 쓰면 이 안에 사칙 연산을 쓸 수가 있게 되고 연산된 결과를 복사한다
        //mov edx, ecx + 4    //[] 없이 + 연산자 사용 하지 못함
        mov edx, ecx
        
        mov edx, [ecx]        //mov 일때 [] 는 배열 기호 [] 처럼 동작함, ecx 값을 주소로하여 ecx 주소번지에 대한 값을 가져온다
        mov edx, [ecx+4]      //mov 일때 [] 는 배열 기호 [] 처럼 동작함, ecx 값을 주소로하여 ecx 주소번지에 대한 값을 가져온다
        lea eax, dword ptr[ebp - 4]
        mov edx, dword ptr[ebp - 4]
        
    }
cs


반응형

[스택 프레임 전체 흐름]



[어셈블리 수준에서의 설명]

//원래 소스 코드
void Swap(int *parm_a, int *parm_b)
{
    int temp = 0;
    // temp 변수를 이용하여 parm_a와 parm_b의 포인터 값을 바꾼다.
    temp = *parm_a;
    *parm_a = *parm_b;
    *parm_b = temp;
}
void main()
{
    int a = 5, b = 7;
    
    // 변수 a와 b의 값을 바꾼다.
    Swap(&a, &b);
    a += 3;
    b += 4;
}
 
 
 
//어셈 코드
void Swap(int *parm_a, int *parm_b)
{
00FA16A0  push        ebp          //main의 스택 베이스 포인터를 저장한다, swap 함수가 끝나면 다시 main 함수의 스택주소 
                                   // 구간으로 이동하기 위함 여기 까지 하면 EIP, 이전 EBP 가 스택에 싸여 있게 되고
00FA16A1  mov         ebp,esp      //ebp 를 현재 함수의 스택 주소 구간으로 변경하기 위해서 현재 스택포인터 값을 베이스 포인터 값으로 바꿔준다
00FA16A3  sub         esp,0CCh  
00FA16A9  push        ebx          //edx,esi,edi 빽업
00FA16AA  push        esi                       
00FA16AB  push        edi  
00FA16AC  lea         edi,[ebp-0CCh]  
00FA16B2  mov         ecx,33h  
00FA16B7  mov         eax,0CCCCCCCCh          // 변수 공간으로 사용할 해당 구간을  CCCCCCCC 값으로 초기화 해준다
00FA16BC  rep stos    dword ptr es:[edi]      //
    int temp = 0;
00FA16BE  mov         dword ptr [temp],0  
    temp = *parm_a;
00FA16C5  mov         eax,dword ptr [parm_a]  
00FA16C8  mov         ecx,dword ptr [eax]  
00FA16CA  mov         dword ptr [temp],ecx  
    *parm_a = *parm_b;
00FA16CD  mov         eax,dword ptr [parm_a]  
00FA16D0  mov         ecx,dword ptr [parm_b]  
00FA16D3  mov         edx,dword ptr [ecx]  
00FA16D5  mov         dword ptr [eax],edx  
    *parm_b = temp;
00FA16D7  mov         eax,dword ptr [parm_b]  
    *parm_b = temp;
00FA16DA  mov         ecx,dword ptr [temp]  
00FA16DD  mov         dword ptr [eax],ecx  
}
00FA16DF  pop         edi           //함수가 끝때날 edi,esi,edx 를 pop한다
00FA16E0  pop         esi  
00FA16E1  pop         ebx  
00FA16E2  mov         esp,ebp       //스택포인터를 main 의 스택 포인터 구간으로 되돌려주어 main 함수를 계속 수행해나갈 준비를 한다
00FA16E4  pop         ebp           //swap 함수가 끝났음으로 swap 에 대한 스택공간이 필요 없됐음으로 swap 에 대한 pop ebp을 수행
//pop 명령어는 ebp 에 현재 스택 상단의 내용을 ebp 에 넣고 스택을 줄인다는 것인데, 이것은
//이전 main 함수의 스택 포인터 기준 영역으로 되돌아 간다는 의미가 된다
00FA16E5  ret           //이 함수가 콜 되면서 저장해 놓았던 이전 EIP 즉 main 의 다음 실행 주소로 복귀한다(해당 번지로 점프 하는 효과가 발생)
.......
void main()
{
00FA1700  push        ebp  
00FA1701  mov         ebp,esp  
00FA1703  sub         esp,0DCh  
00FA1709  push        ebx  
00FA170A  push        esi  
00FA170B  push        edi  
00FA170C  lea         edi,[ebp-0DCh]  
00FA1712  mov         ecx,37h  
00FA1717  mov         eax,0CCCCCCCCh  
00FA171C  rep stos    dword ptr es:[edi]  
00FA171E  mov         eax,dword ptr [__security_cookie (0FA8004h)]  
00FA1723  xor         eax,ebp  
00FA1725  mov         dword ptr [ebp-4],eax          
//메모리 할당은 작은 주소 순으로 주소가 배열되며 지역변수는 ebp 주소를 기준으로 상대적으로 변수를 할당/사용한다
    int a = 5, b = 7;
00FA1728  mov         dword ptr [a],5  
00FA172F  mov         dword ptr [b],7  
    
    Swap(&a, &b);                                    
00FA1736  lea         eax,[b]                          //swap 에 담길 인자를 스택에 넣는다
00FA1739  push        eax  
00FA173A  lea         ecx,[a]  
00FA173D  push        ecx  
00FA173E  call        Swap (0FA10F5h)                  // swap 을 call 하면서 다음 실행 주소 EIP:00FA1743  를 스택에 push 한다
00FA1743  add         esp,8  
    a += 3;
00FA1746  mov         eax,dword ptr [a]  
    a += 3;
00FA1749  add         eax,3  
00FA174C  mov         dword ptr [a],eax  
    b += 4;
00FA174F  mov         eax,dword ptr [b]  
00FA1752  add         eax,4  
00FA1755  mov         dword ptr [b],eax  
}
00FA1758  xor         eax,eax  
00FA175A  push        edx  
00FA175B  mov         ecx,ebp  
00FA175D  push        eax  
00FA175E  lea         edx,ds:[0FA178Ch]  
00FA1764  call        @_RTC_CheckStackVars@8 (0FA1253h)  
00FA1769  pop         eax  
00FA176A  pop         edx  
00FA176B  pop         edi  
00FA176C  pop         esi  
00FA176D  pop         ebx 


반응형

x86 Instruction Set Reference

LOOP/LOOPcc

Loop According to ECX Counter

-Loop 명령어를 만나게 되면 자ecx 값이 자동 감소 되고 ecx 값이 0 이 아니라면 해당 번지로 점프한다
0이면 점프 하지 않고 loop 다음 구문을 실행한다( c언어에서 for 문을 떠올리면 됨)
여기서 점프를 한다는건 일반적으로 반복 수행을 위해 loop 명령어 위쪽으로 점프한다는 것을 의미함

-ECX 외에 and 가 붙는 것들의 이해는 cmp 로 두개의 값을 비교하여 같으면 Z=1 이 세팅이 되는데 반복문의 조건문에 두개의 조건이 있다고 가정 할때 ECX 의 값과 어떤 값을 비교하는 연산이 and 로 있는 경우를 생각해 볼 수 있다
1.cmp 로 비교하여 z 값 세팅
2.이후 loopcc 로 점프할지 말지 결정
주의 loop 의 경우 점프 loop 다음 실행할 번지와 점프 뛸 곳까지의 명령어 1바이트를 벗어난 위치로 점프 할 수 없다
점프 하려면 jmp 로 그에 대한 내용은 http://codetronik.tistory.com/5 를 참고

OpcodeMnemonicDescription
E2 cbLOOP rel8Decrement count; jump short if count != 0.
E1 cbLOOPE rel8Decrement count; jump short if count != 0 and ZF=1.
E1 cbLOOPZ rel8Decrement count; jump short if count != 0 and ZF=1.
E0 cbLOOPNE rel8Decrement count; jump short if count != 0 and ZF=0.
E0 cbLOOPNZ rel8Decrement count; jump short if count != 0 and ZF=0.
Description

Performs a loop operation using the ECX or CX register as a counter. Each time the LOOP instruction is executed, the count register is decremented, then checked for 0. If the count is 0, the loop is terminated and program execution continues with the instruction following the LOOP instruction. If the count is not zero, a near jump is performed to the destination (target) operand, which is presumably the instruction at the beginning of the loop. If the address-size attribute is 32 bits, the ECX register is used as the count register; otherwise the CX register is used.

The target instruction is specified with a relative offset (a signed offset relative to the current value of the instruction pointer in the EIP register). This offset is generally specified as a label in assembly code, but at the machine code level, it is encoded as a signed, 8-bit immediate value, which is added to the instruction pointer. Offsets of -128 to +127 are allowed with this instruction.

Some forms of the loop instruction (LOOPcc) also accept the ZF flag as a condition for terminating the loop before the count reaches zero. With these forms of the instruction, a condition code (cc) is associated with each instruction to indicate the condition being tested for. Here, the LOOPcc instruction itself does not affect the state of the ZF flag; the ZF flag is changed by other instructions in the loop.

Operation
if(AddressSize == 32) Count = ECX;
else Count = CX; //AddressSize == 16

Count = Count - 1;

switch(Instruction) {
	case LOOPE:
	case LOOPZ:
		if(ZF == 1 && Count != 0) BranchCond = 1;
		else BranchCond = 0;
		break;
	case LOOPNE:
	case LOOPNZ:
		if(ZF == 0 && Count != 0) BranchCond = 1;
		else BranchCond = 0;
		break;
	default: //LOOP
		if(Count != 0) BranchCond = 1;
		else BranchCond = 0;
		break;
}
if(BranchCond == 1) {
	EIP = EIP + SignExtend(Destination);
	if(OperandSize == 16) EIP = EIP & 0xFFFF;
	else /*OperandSize == 32*/ if(EIP < CS.Base || EIP < CS.Limit) Exception(GP);
}
else ResumeExecution(); //Terminate loop and continue program execution at EIP
Flags affected

None.

Protected Mode Exceptions
#GP(0)If the offset being jumped to is beyond the limits of the CS segment.
Real-Address Mode Exceptions
#GPIf the offset being jumped to is beyond the limits of the CS segment or is outside of the effective address space from 0 to FFFFH. This condition can occur if a 32-bit address size override prefix is used.
Virtual-8086 Mode Exceptions
Same exceptions as in Real Address Mode
InstructionLatencyThroughputExecution Unit
CPUID0F3n/0F2n/069n0F3n/0F2n/069n0F2n
LOOP81.5ALU

http://x86.renejeschke.de/html/file_module_x86_id_161.html


반응형

상태 레지스터 또는 플래그 레지스터는 마이크로프로세서에서 다양한 산술 연산 결과의 상태를 알려주는 플래그 비트들이 모인 레지스터이다.

주로, 조건문과 같은 실행 순서의 분기에 사용된다.


상태 레지스터 플래그

상태 레지스터에는 다음과 같은 플래그들이 있다.

플래그 기호이름의미
Z제로 플래그연산 결과가 0일 경우에 참이 된다.
C캐리 플래그부호 없는 숫자의 연산 결과가 비트 범위를 넘어섰을 때 참이 된다.
A보조 캐리 플래그연산 결과 하위 니블(4bits)에서 비트 범위를 넘어섰을 때 참이 된다. 이진화 십진법(BCD) 연산에 사용된다.
V / O / W오버플로 플래그부호 있는 숫자의 연산 결과가 비트 범위를 넘어섰을 때 참이 된다.
N / S네거티브 플래그, 사인 플래그연산 결과가 음수일 때 참이 된다.
I / E인터럽트 플래그이 플래그가 참일 경우에만 인터럽트 요구를 받아들인다. 일반적으로 관리자 모드에서만 값을 변경 할 수 있다.
P패리티 플래그연산 결과에서 1로된 비트의 수가 짝수일 경우 참이 된다.
D디렉션 플래그문자열 조작에서 참일 경우 주소 레지스터 값이 자동으로 감소하고, 거짓일 경우 자동으로 증가한다.
D / T디버그 플래그, 트랩 플래그참일 경우 한 명령이 실행할 때마다 인터럽트가 발생한다. 디버깅에 사용된다.



https://ko.wikipedia.org/wiki/%EC%83%81%ED%83%9C_%EB%A0%88%EC%A7%80%EC%8A%A4%ED%84%B0

반응형


점프 할때의 플래그들 정리

비슷한 의미 별로 그룹화 시켜놓은것들, 필요 할 때 참고삼아


Getting the sense for jumps and flags has long been a troublesome area for me, especially since the Intel assembler book shows 32 of these, all with similar-sounding names. Looking more closely I found that many of the instructions were synonyms for each other, and in practice the whole gamut is not needed, and in the process found that my copy of Intel's 80386 Programmer's Reference Manual gave an incorrect description for one of the instructions.

So I have grouped these functionally, with all instruction synonyms in the same row.

InstructionDescriptionsigned-nessFlagsshort 
jump 
opcodes
near 
jump 
opcodes
JOJump if overflow OF = 1700F 80
JNOJump if not overflow OF = 0710F 81
JSJump if sign SF = 1780F 88
JNSJump if not sign SF = 0790F 89
JE 
JZ
Jump if equal 
Jump if zero
 ZF = 1740F 84
JNE 
JNZ
Jump if not equal 
Jump if not zero
 ZF = 0750F 85
JB 
JNAE 
JC
Jump if below 
Jump if not above or equal 
Jump if carry
unsignedCF = 1720F 82
JNB 
JAE 
JNC
Jump if not below 
Jump if above or equal 
Jump if not carry
unsignedCF = 0730F 83
JBE 
JNA
Jump if below or equal 
Jump if not above
unsignedCF = 1 or ZF = 1760F 86
JA 
JNBE
Jump if above 
Jump if not below or equal
unsignedCF = 0 and ZF = 0770F 87
JL 
JNGE
Jump if less 
Jump if not greater or equal
signedSF <> OF7C0F 8C
JGE 
JNL
Jump if greater or equal 
Jump if not less
signedSF = OF7D0F 8D
JLE 
JNG
Jump if less or equal 
Jump if not greater
signedZF = 1 or SF <> OF7E0F 8E
JG 
JNLE
Jump if greater 
Jump if not less or equal
signedZF = 0 and SF = OF7F0F 8F
JP 
JPE
Jump if parity 
Jump if parity even
 PF = 17A0F 8A
JNP 
JPO
Jump if not parity 
Jump if parity odd
 PF = 07B0F 8B
JCXZ 
JECXZ
Jump if %CX register is 0 
Jump if %ECX register is 0
 %CX = 0 
%ECX = 0
E3 

Processor Flags

The x86 processors have a large set of flags that represent the state of the processor, and the conditional jump instructions can key off of them in combination.

CF - carry flag(c에서는 CY)
Set on high-order bit carry or borrow; cleared otherwise
PF - parity flag(c에서는 PE)
Set if low-order eight bits of result contain an even number of "1" bits; cleared otherwise
ZF - zero flags(c에서는 ZR)
Set if result is zero; cleared otherwise
SF - sign flag(c에서는 PL이던디)
Set equal to high-order bit of result (0 if positive 1 if negative)
OF - overflow flag(c에서는 OV)
Set if result is too large a positive number or too small a negative number (excluding sign bit) to fit in destination operand; cleared otherwise



http://unixwiz.net/techtips/x86-jumps.html


반응형

mov eax,0                    //mov 명령어는 ZR 플래그를 조작하는 명령어가 아님

cmp eax,0 //두개의 값이 같으면 Z(ZR) 에 1을 세팅함

je          main //ZR값이 1 이면 점프 , jz 도 ZR 이 1 이면 점프,  jz==je 이 둘은 같은 동작을 한다


jz 는 eax 값이 증가 했다가 감소 해서 0 이 되면 가 1이 된다는 관점

je 는 cmp 로 두개를 비교하여 같으면 Z 가 1 이 된다는 관점


jne = jump not equal 로 Z가 0 일때 점프 한다

jze 가 0 일 때 점프



cmp A, B

JA  : 앞에 것이 크면 점프 (Above)

JB  : 앞에 것이 작으면 점프(Below)


C : Carry 비트(더하기, 자리 올림)가 1이 됨 1111 + 1    또는 자리내림(빼기(1-2=-1))  일때 C 가 1이 됨


cmp 연산에서 cmp a,b 는 a-b 연산을 하는대 이때 C 비트가 변경 된다





[부호가 없는 데이터 비교, 제일 앞의 비트또한 숫자로 처리한다]

JA 의 경우 C가 0이고 ZR 이 0 일 때 점프 한다 

cmp 는 A-B 연산을 하는데 두 값이 같다면 A-B=0 , A>B 의 경우 결과는 양수이고 A 보다 

결과가 작음으로 자리 올림은 발생 하지 않으며 ZR 은 두 값이 같지 않음으로 0 이 된다


JB 의 경우 C 가 1일때 점프 한다 

ZR 은 0 이든 1이든 상관 없는데 그 이유는 A-B 결과가 음수가 되면서 이로 인해 자리내림으로 C 가 1이 되어서 

이것으로 점프를 할지 말지 구분하면 됨


[부호가 없는 데이터 비교, 제일 앞의 비트를 부호로 처리한다]

JG  

JL


JA, JG 가 같은 맥락인데 어떤 명령어를 사용 하느냐에 따라서 비트는 같지만 비트를 해석하는 방식이 달라진다




JNA == JBE





jc : carry 플래그 값만 보고도 점프가 가능한데(CY)

jo : overflow bit 가 1 일때 (OV)

js : sign 비트가 1 일때 (PL)


pl : 연산 값이 음수인경우 1 , 양수면  0

ov : char s=127

s+=1 == -128 이 되는데 이때 부호 비트까지 연산이 되어버리는 경우 ov 에 1이 세팅 됨
 




(c에서는 AC 가 보조 캐리비트)

 cmp edx,eax 했을 때 cmp 한 연산 결과의 하위 4bit 에 대해 올림이 발생하면 그때 1이 됨

   [BCD : 2진수 4자리를 묶어 10진수 한자리로 표현 하는 법]

           16진수 표현 시 10=a~ 15=f 로 표현 되는데  이렇게 표현 하는 방식을 말함

그리하여 4bit까지 체크 하기 위한 비트가 AC 보조 캐리 비트다, 즉 15가 넘어 가게 될 경우 AC=1 이 된다(f에 대한 자리 올림)

ex) mov eax , 15

inc eax



CF - carry flag(c에서는 CY)
Set on high-order bit carry or borrow; cleared otherwise
PF - parity flag(c에서는 PE, 연산될 결과에서 하위 8bit에 대해 인텔은 홀 수 비트 개수를 유지하기 위해 여기에 1 또는 0 을 채운다
                                   cmp edx,eax 했을 때 cmp 한 연산 결과의 하위 8bit 에 대해 체크)
Set if low-order eight bits of result contain an even number of "1" bits; cleared otherwise

ZF - zero flags(c에서는 ZR)
Set if result is zero; cleared otherwise
SF - sign flag(c에서는 PL이던디)
Set equal to high-order bit of result (0 if positive 1 if negative)
OF - overflow flag(c에서는 OV)
Set if result is too large a positive number or too small a negative number (excluding sign bit) to fit in destination operand; cleared otherwise



반응형



[어셈블리어 기초] CMP JMP CALL RET NOP  


 

 

 

① CMP

비교합니다.

 

 CMP 연산 결과

 ZF

 CF

 dest  < source

 0

 1

 dest  > source

 0

 0

 dest == source

 1

 0

CMP reg, reg

CMP mem, reg

CMP reg, mem

CMP reg, imm

CMP mem, imm

#include <stdio.h>

int main( int argc, char* argv[] )
{
 int nValue = 5;

 __asm
 {
  CMP nValue, 0x05  //dest, source 비교
 }

 printf( "%d\n", nValue );
 

return 0;
}

5와 5를 비교하면 같으므로 ZF = 1, CF = 0 이 나옵니다.

 

 

② JMP

지정된 위치로 이동합니다. C에서 goto문이랑 비슷합니다.

JMP label

JMP reg16

JMP mem16

JMP mem32

#include <stdio.h>

int main( int argc, char* argv[] )
{
 int nValue = 5;

 __asm
 {
  JMP L1
  MOV nValue, 0x0A            //생략한다.

 

 L1:
  MOV nValue, 0x01
 }

 printf( "%d\n", nValue );

return 0;
}

결과





L1으로 이동하므로 MOV nValue, 0x0A는 실행되지 않습니다.

 

 

③ 조건 점프 명령

조건이 있는 점프 명령어들이 있습니다.

 

 조건 점프 명령

 산술, 논리 연산 

 JA

 CMP dest  > source

 JB

 CMP dest  < source

 JE

 CMP dest == source

 JNE

 CMP dest  != source

 JZ

 TEST EAX, EAX (EAX = 0)

 JNZ

 TEST EAX, EAX (EAX = 1)

 

#include <stdio.h>

int main( int argc, char* argv[] )
{
 int nValue = 5;
 char *pszResult = NULL;

 __asm
 {
  CMP nValue, 0x05

  JA DestBig                //nValue가 클 때
  JB DestSmall             //nValue가 작을 때

  JE DestSame             //nValue가 같을 
 }

switch(1)
{
case 1 : DestBig: pszResult = "nValue가 더 큽니다"; break;
case 2 : DestSmall: pszResult = "nValue가 더 작습니다"; break;
case 3 : DestSame: pszResult = "nValue 와 같습니다"; break;
}

puts(pszResult);


return 0;
}

결과

 

 

 명령어

 의미

 부등호

 플래그 조건

 JA

 jump if (unsigned) above

 >

 CF = 0 and ZF = 0

 JAE

 jump if (unsigned) above or eual

 >=

 CF = 0 or ZF = 1

 JB

 jump if (unsigned) below

 <

 CF = 1

 JBE

 jump if (unsigned) below or equal

 <=

 CF = 1 or ZF = 1

 JC

 jump if carry flag set

 

 CF = 1

 JCXZ

 jump if CX is 0

 

 CX = 0

 JE

 jump if equal

 ==

 ZF = 1

 JECXZ

 jump if ECX is 0

 

 ECX = 0

 JG

 jump if (signed) greater

 >

 ZF = 0 and SF == OF

 JZ

 jump if zero

 ==

 ZF = 1

 

 

④ CALL

함수를 콜합니다.

#include <stdio.h>

int Sum(void);

int main( int argc, char* argv[] )
{
 int nResult = 0;

 printf( "계산 전 : %d\n", nResult );

 __asm
 {
  CALL Sum
  MOV nResult, EAX
 }

 printf( "계산 후 : %d\n", nResult );

return 0;
}

int Sum(void)
{
 int nValue1 = 1, 
  nValue2 =2;

 printf( "sum 함수 call\n" );

return nValue1 + nValue2;
}

결과

반환 값은 EAX에 대입됩니다.

 

 

⑤ RET

ESP 레지스터가 가르키는 값을 EIP 레지스터에 저장

RET imm8

#include <stdio.h>

int Sum(void);

int main( int argc, char* argv[] )
{
 __asm
 {
  RET
 }

return 0;
}

 

 

⑥ NOP

아무 동작도 수행하지 않는 명령어입니다.

#include <stdio.h>

int main( int argc, char* argv[] )
{
 __asm
 {
  NOP
  NOP
  NOP
  NOP
 }

return 0;
}

NOP을 이용한 버퍼오버플로우때 공부했었죠.

 

 

 

출처 : I2Sec 

http://blog.naver.com/shw20319/20138513661


반응형

+ Recent posts