Disassemble Help Library

This documentation contain descriptions of the functions, which exports from the native 64-bit library dsmhelp.dll.
Нomepage http://dsmhelp.narod.ru/.

Functions.

Name | Short description.
InitInstr | getting a special handle.
ReinitInstr | setting an address, base and decoding mode.
SetCPointer | setting a current pointer to the instruction.
Assemble | assembling.
AssembleEx | assembling, and retrieving other not optimal opcodes.
Disassemble | disassembling and getting mnemonic.
FreeInstr | close a special handle, retrieved by the InitInstr.
InstrDasm | disassembling.
JoinMnemonic | joins a mnemonic.
InstrEF | retrieving information about instruction affects to the rFLAGS.
LastInstrLength | retrieves a length of the last dis/assembled opcode.
DsmVersion | version info.

Structures.

Instruction
Features
EF
x87c
moRanges
moRange

Macros.

altm
enum

Examples.

dsmdemo.exe - disassembling (asmlist.txt is always full dissasebly text).
asmdasm.exe - assembling and info about effects on the flags.
dwowtest.exe - is a 32-bit application that works in the compatibility mode under win64.
main include file dsmhelp.inc, in the /include/ directory.

5 December 2010.
Any warranties are disclaimed. Free for non-comertional use. Feedback dsmhep@yandex.ru


InitInstr

Allocates memory blocks from a process heap and initialize them as  Instruction structure.

InitInstr PROTO CodePtr:PVOID,AlterBase:ULONG64,Mode:BYTE,CodeSize:ULONG64

  • CodePtr - a pointer to the first opcode.
  • AlterBase - a virtual address, in simplest case this can be equal to the CodePtr.
  • Mode - en/coding mode.

    Allows 3 values.

    LONG_MODE      equ 0 - 64-bit code.
    LEGACY_MODE32 equ 1 - 32-bit code.
    LEGACY_MODE16 equ 2 - 16-bit code.

  • CodeSize - size of the code in bytes, which pointed with CodePtr.

    Return Value: rax is a pointer to  Instruction structure, which ready for use.


ReinitInstr

Reinitialize an Instruction structure.

ReinitInstr PROTO hInstr:HINSTR,CodePtr:PVOID,AlterBase:ULONG64,Mode:BYTE,CodeSize:ULONG64

  • hInstr - a pointer to  Instruction structure.
  • CodePtr - a new pointer to the first opcode.
  • AlterBase - a new virtual address.
  • Mode - en/coding mode.

    Allows 3 values.

    LONG_MODE equ 0 - 64-bit code.
    LEGACY_MODE32 equ 1 - 32-bit code.
    LEGACY_MODE16 equ 2 - 16-bit code.

  • CodeSize - size of the code, which pointed with CodePtr.

    Return Value: nothing meaningful.


SetCPointer

Changes current pointer to the next instruction.

SetCPointer PROTO hInstr:HINSTR,CodePtr:PVOID

  • hInstr - a pointer to the Instruction structure.
  • CodePtr - a new pointer to the instruction.

    Return Value: if the function succeeds, rax is equal to 0, in other case you must define size of the code block, RemnCode field of the Instruction structure.


Assemble

Assembles a mnemonic.

Assemble PROTO hInstr:HINSTR,Mnemonic:LPSTR

  • hInstr - a pointer to the Instruction structure, which can be obtained with InitInstr.
  • Mnemonic - a pointer to the text of mnemonic. A first byte that equal to 0 or 13 will be interprets as end of mnemonic.

    Return Value: eax is a length of assembled opcode. eax contain 0, if mnemonic was be incorrect and -1 if size of the mnemonic too large.

    Note: Supported location counter $. fword is always a 6 bytes and pword is always 4 bytes, independently from en/coding mode. Register TPR is alias to cr8, uses only on the AMD`s processors.


AssembleEx

Assemble a single mnemonic.

AssembleEx PROTO hInstr:HINSTR,Mnemonic:LPSTR,AlterOpc:BYTE

  • hInstr - a pointer to the  Instruction structure, which can be obtained by the  InitInstr.
  • Mnemonic - specifies the mnemonic to assemble. A first byte that equal 0 or 13 is limit string.
  • AlterOpc - a number of the alternate opcode from 1 till 7(usually till 3), must be 0, if needed a shortest opcode.

    Return Value: eax is equal to the length of the opcode. If the fuction fails, eax is equal to 0. If eax is equal to -1 then Mnemonic is too long.

    Note: Supported location counter $. fword is always a 6 bytes and pword is always 4 bytes, independently from en/coding mode. Register TPR is alias to cr8, uses only on the AMD`s processors.


Disassemble

Disassemble a current opcode.

Disassemble PROTO hInstr:HINSTR,Mnemonic:LPSTR,MnemLen:PULONG,dwFlags:DWORD

  • hInstr -  a pointer to the  Instruction structure, which can be obtained by the  InitInstr .
  • Mnemonic - a pointer to the buffer with at least 256 bytes.
  • MnemLen - a pointer to the dword for saving length of the Mnemonic string. It`s optional parameter and can be NULL. Mnemonic is always a null-terminaited string.
  • dwFlags - the flags which specifies layout of the Mnemonic string.

    The following flags are used.
    OFFSETS_COL equ 1 shl 0 - a hex-ascii address will be precede Mnemonic.
    HEX_COL      equ 1 shl 1 - a hex-ascii opcode will be precede Mnemonic.
    RIP_ADDRS   equ 1 shl 2 - the addresses with the rip-addressing will be have layout  [$+/-disp32][length_of_the_opcode ].
    REL_ADDRS   equ 1 shl 3 - the relative addresses will be have layout $+/-xxxxxxxxh .
    CR_LF       equ 1 shl 4 - Mnemonic will be ends by 3 bytes 13,10,0.
    NOT_TABBED   equ 1 shl 5 - avoid using the TAB(9) chars.
    Some useful combinations.
    STD_MNEM    equ CR_LF or OFFSETS_COL or HEX_COL
    RIP_REL     equ RIP_ADDRS or REL_ADDRS or     CR_LF
    STD_CLEAR_MNEM equ NOT_TABBED

    Return Value: rax is equal to zero. If instruction fails rax have is non-zero value. Although fails not means impossibility to disassemble to the next opcode. If Mnemonic is empty null-string or  MnemLen=0 then you must stop disassembling.


FreeInstr

Frees a memory block within Instruction structure.

FreeInstr PROTO hInstr:HINSTR

  • hInstr - a poiter to the Instruction structure to be freed.

    Return Value: nothing.


InstrDasm

Disassembles a binary opcode and save results in the Instruction structure.

InstrDasm PROTO hInstr:HINSTR

  • hInstr - a pointer to the  Instruction structure, which can be obtained with  InitInstr.

    Return Value: eax contain an error code. If eax is equal to 0 then no errors was be.


JoinMnemonic

Combines a full memonic string.

JoinMnemonic PROTO hInstr:HINSTR,Mnemonic:LPSTR,MnemLen:PULONG,dwFlags:DWORD

  • hInstr -  a pointer to the  Instruction structure, which can be obtained with  InitInstr.
  • Mnemonic - a pointer to the buffer with at least 256 bytes.
  • MnemLen - a pointer to the DWORD for saving length of the Mnemonic string. It`s optional parameter and can be NULL. Mnemonic is always a null-terminaited string.
  • dwFlags - the flags which specifies layout of the Mnemonic string.

    The following flags are used.
    OFFSETS_COL equ 1 shl 0 - a hex-ascii address will be precede Mnemonic.
    HEX_COL      equ 1 shl 1 - a hex-ascii opcode will be precede Mnemonic.
    RIP_ADDRS   equ 1 shl 2 - the addresses with the rip-addressing will be have layout  [$+/-disp32][length_of_the_opcode ].
    REL_ADDRS   equ 1 shl 3 - the relative addresses will be have layout $+/-xxxxxxxxh .
    CR_LF       equ 1 shl 4 - Mnemonic will be terminated with 3 bytes 13,10,0.
    NOT_TABBED   equ 1 shl 5 - avoid using the TAB(9) chars.
    Some useful combinations.
    STD_MNEM    equ CR_LF or OFFSETS_COL or HEX_COL
    RIP_REL     equ RIP_ADDRS or REL_ADDRS or     CR_LF
    STD_CLEAR_MNEM equ NOT_TABBED

    Return Value: rax is equal to zero. If instruction fails rax have is non-zero value. Although fails not means impossibility to disassemble to the next opcode. If Mnemonic is empty null-string or  MnemLen=0 then you must stop disassembling.


InstrEF

Retrieves a pointer to the EF structure, which contain information about instruction`s effects on the rFLAGS register.

InstrEF PROTO hInstr:HINSTR

  • hInstr - a pointer to  Instruction  structure.

    Return Value: rax contains pointer to the  EF structure. If fails, rax is equal to 0.


LastInstrLength

Retrieves a length of the last dis/assembled opcode.

LastInstrLength PROTO hInstr:HINSTR

  • hInstr - a pointer to the  Instruction structure.

    Return Value: opcode`s length in the al register .


DsmVersion

Retrieves the version number of the dsmhelp.dll.

DsmVersion PROTO

Return Value: ah - the major version and al - minor version.


Instruction

Instruction struc
    MajorVersa    BYTE ? ;out + 0h
    MinorVersa    BYTE ?
    OpcNum        BYTE ?
    OpcTotal      BYTE ?
    DsmCtrl       DWORD ?
    CodePtr       PVOID ? ;in/out + 08h
    NextPtr       PVOID ? ;in/out + 10h
    AlterBase     QWORD ? ;in/out + 18h
    MnemOperType  LPSTR ? ;out + 20h
    Mnemonic      LPSTR ? ;out + 28h
    Oper1Mnemonic LPSTR ? ;+ 30h
    Oper2Mnemonic LPSTR ? ;+ 38h
    Oper3Mnemonic LPSTR ? ;+ 40h
    Oper4Mnemonic LPSTR ? ;+ 48h
    Oper5Mnemonic LPSTR ? ;+ 50h
    RemnCode      ULONG64 ? ;in/out ;+ 58h
    ModrmOffsets  pmoRanges ? ;+ 60h
    Mode          BYTE ? ;in + 68h
    IsHeapStr     BYTE ? ;+ 69h
    FullOpcode    BYTE FULL_OPCSIZE dup(?) ;+ 6Ah
    ;Legacy prefixes
    SegOver BYTE ? ;out + 8Ah
    RepPfx  BYTE ? ;out + 8Bh
    PfxCnt  BYTE ? ;out + 8Ch
    ;REX prefix
     union
        RexPfx BYTE ? ;out + 8Dh
        XopRex BYTE ?
        VexRex BYTE ?
    ends
    union
        XopSec BYTE ? ;+ 8Eh
        VexSec BYTE ?
     ends
    InstrLen BYTE ? ;out + 8Fh
     ;ModRM
    mode BYTE ? ;out + 90h
    reg  BYTE ? ;out + 91h
    rmem BYTE ? ;out + 92h
    ;SIB
    Scale BYTE ? ;out + 93h
    Index BYTE ? ;out + 94h
    Base  BYTE ? ;out + 95h
    ModRmAddress    BYTE 32 dup(?) ;+ 96h
    DefaultOperSize BYTE ? ;out +0B6h
    DefaultAddrSize BYTE ? ;out +0B7h
    iFlags          PVOID ? ;out +0B8h
    x87Condition    x87c <> ;out +0C0h
    mOffset         DWORD ? ;out +0C8h
    iMxcsr          DWORD ? ;out +0CCh
    DataSegMnem     DWORD ? ;out +0D0h
    Status          DWORD ? ;out +0D4h
    AddrBias        DWORD ? ;out +0D8h
    Opflags         DWORD ? ;out +0DCh
    OpFeatures      Features <> ;out +0E0h
    union
        RipOffset   BYTE 38 dup(?) ;out +0EAh
        JAddrOffset BYTE 38 dup(?)
    ends
Instruction ends

HINSTR TYPEDEF PTR Instruction
FULL_OPCSIZE equ 32

  • MajorVersa    - reserved for a major version.
  • MinorVersa    - reserved for a minor version.
  • OpcNum         - opcode`s number in the list of the mnemonic opcodes. Enumerating begins from 1.
  • OpcTotal      - a whole quantity of the opcodes that regards to mnemonic, after assembling.
  • DsmCtrl       - reserved.
  • CodePtr       - a pointer to the current opcode.
  • NextPtr       - a pointer to the next opcode.
  • AlterBase     - a virtual address of the next opcode. From this base will be counts relative and rip-addresses.
  • MnemOperType  - a pointer to the short string that defines default operands type, for example "dword ptr".
  • Mnemonic      - a pointer to the mnemonic (sometimes together with prefixes lock,rep/n/e).
  • Oper1Mnemonic,Oper2Mnemonic,Oper3Mnemonic,Oper4Mnemonic,Oper5Mnemonic - pointers to the corresponding operands mnemonis.
  • RemnCode      - remainder of the memory buffer. After re/initialization by InitInstr or ReinitInstr , this one contain value of the CodeSize argument.
  • ModrmOffsets   - a pointer to  moRanges structure.
  • Mode          - en/coding mode.

    The following values are using.

    LONG_MODE      equ 0 - 64-bit code.
    LEGACY_MODE32 equ 1 - 32-bit code.
    LEGACY_MODE16 equ 2 - 16-bit code.

  • IsHeapStr     - contains flags, that marks aditional memory blocks for mnemonics as allocated from a process heap. FreeInstr function use this flags and by default calls API HeapFree for Mnemonic,Oper1Mnemonic,Oper2Mnemonic,Oper3Mnemonic,Oper4Mnemonic,Oper5Mnemonic and ModrmOffsets.

    The following flags are using.

    MNEM_HEAP   equ 1 shl 0
    OPER1_HEAP  equ 1 shl 1
    OPER2_HEAP  equ 1 shl 2
    OPER3_HEAP  equ 1 shl 3
    OPER4_HEAP  equ 1 shl 4
    OPER5_HEAP  equ 1 shl 5
    MO_RANGES   equ 1 shl 6
  • FullOpcode     - 32-byte buffer. After dis/assembling contains a copy of the last opcode.
  • SegOver       - an immediate value of the last segment prefix or 0 if opcode has no segment prefixes.
  • RepPfx        - an immediate value of the rep\n\e (0F3h\0F2h) prefix or 0 if opcode has no one such prefixes.
  • PfxCnt        - whole quantity of the prefixes. It`s number from 0 till 14.
  • RexPfx        - an immediate value of the potent REX prefix or 0. Potent REX is always precede main part of the opcode, unless REX treats as a null prefix. It was be tested on the one Athlon processor.
  • XopRex        - a first byte value of the XOP prefix, shifted by 3 bits to left with rol instruction.
  • VexRex        - a first byte value of the VEX prefix, shifted by 3 bits to left with rol instruction.
  • XopSec        - a second byte value of the XOP prefix.
  • VexSec        - a second byte value of the VEX prefix.
  • InstrLen      - length of the last dis/assembled opcode.
  • mode          - represents bit-field from ModRM-byte.
  • reg           - represents bit-field from ModRM-byte.
  • rmem          - represents bit-field from ModRM-byte.
  • Scale         - represents bit-field from SIB-byte.
  • Index         - represents bit-field from SIB-byte.
  • Base          - represents bit-field from SIB-byte.
  • ModRmAddress  - a short string that contain mnemonic of the MODRM address. It`s have no mean if mode equal to 11b.
  • DefaultOperSize - a default operand width in bits, depends from Mode field, VEX/XOP/REX and 66h prefixes. Can have one of the following values 16/32/64.
  • DefaultAddrSize  - a default address width in bits, depends from Mode field and 67h prefix. Can have one of the following values 16/32/64.
  • iFlags        - a pointer to the  EF structure. It`s equal to 0 if dis/assembled instruction have no effects on rFLAGS register.
  • x87Condition   - a x87c structure that contain information about instruction`s effects on the FPU-flags C0,C1,C2,C3.
  • mOffset        - 1,2 or 4 bytes bias that follows after ModRM or SIB bytes.
  • iMxcsr        - a mask of the modifiable flags of the mxcsr.
  • DataSegMnem   - a short mnemonic of the last segment prefix, just for 64-bit code it`s can be equal to zero.
  • Status        - status of the dis/assembling. Equal to 0 if has nothing fails.

    MaxInstrLen           equ 15
    The following flags are useing.
    VERBOSE_PFX           equ MaxInstrLen +1 - a presenting prefixes that make an instruction`s length more then 15.
    INVALID_INSTRUCTION   equ MaxInstrLen +2 - unknown instruction or reserved to the future opcode.
    INVALID_OPERAND       equ MaxInstrLen +3 - not allowed operand, for example prefetch eax.
    OPCODE_OUT_RANGE      equ MaxInstrLen+4 - opcode may be is correct, but RemnCode field didn`t allow read this one wholely.
    If Assemble/Ex has fails.
    UNKNOWN_MNEMONIC      equ MaxInstrLen +5 - unknown or unexisting mnemonic.
    ASM_DUMP              equ MaxInstrLen +6 - a dump string was be assembled. For example this short string can be assembled  db 2Ch,77h .
    NOT_ALLOWED_LOCK      equ MaxInstrLen +7 - wrong use of lock prefix.
    NOT_ALLOWED_REP       equ MaxInstrLen +8 - wrong use of rep prefix.
    NOT_ALLOWED_REPXX     equ MaxInstrLen +9 - wrong use of repe or repne prefixes.
    TOO_LONG_STR          equ MaxInstrLen +10 - length of the mnemonic string too long for to be processed.
    TOO_MANY_ARGS         equ MaxInstrLen +11 - instruction have more than 5 operands.
    INSUFFICIENT_BUFFER   equ MaxInstrLen +12 - a buffer has not enough size. See description of FullOpcode field.

  • AddrBias - 1,2 or 4 bytes bias of the relative address.
  • Opflags - a flags set.

    The following flags are using.

    OPER66OVER            equ 1 shl  0 - presenting at least one prefix 66h.
    ADDR67OVER            equ 1 shl  1 - presenting at least one prefix 67h.
    LOCK_PFX              equ 1 shl  2 - presenting at least one prefix 0F0h.
    MODRM                 equ 1 shl  3 - presenting of the ModRM.
    SIB_BYTE              equ 1 shl  4 - sib-byte is present.
    MOFFSET               equ 1 shl  5 - presenting 1,2 or 4-byte bias in mOffset field.
    RIP_ADDR              equ 1 shl  6 - RIP-addressing.
    ERASE_SECOND_N        equ 1 shl  7 - presenting wait prefix for a few FPU instructions.
    JADDR16_BUT_NOT_LM16  equ 1 shl  8 - 16-bit relative address in the not 16-bit code.
    MOD11_OPCODE          equ 1 shl  9 - mode field can specify an opcode, if equal to 11b.
    JADDR                  equ 1 shl 11 - AddrBias have a meaningful value.
    OPER2_MEM              equ 1 shl 12 - a second operand is a memory pointer.
    REG_OPCODE            equ 1 shl 13 - reg field is a part of the main opcode.
    RMEM_OPCODE           equ 1 shl 14 - rmem field is a part of the main opcode..
    F2F366_OPCODE         equ 1 shl 15 - last prefix 0F3h,66h or 0F2h can modify an opcode.
    F2F3_OPCODE           equ 1 shl 16 - last prefix 0F3h or 0F2h can modify an opcode, but not 66h.
    FLAG_0F               equ 1 shl 18 - main opcode begins with a byte 0Fh.
    OPSZ_NOT_INFERRS      equ 1 shl 19 - qualifier type of the memory operands cannot be ommited.
    CS_D_NA                equ 1 shl 20 - DefaultOperSize depends only from Mode field.
    FLAG_38               equ 1 shl 21 - main opcode begins with 2 bytes 0Fh,38h.
    FLAG_3A               equ 1 shl 22 - main opcode begins with 2 bytes 0Fh,3Ah.
    CPL3_ALLOWED          equ 1 shl 23 - an instruction can be executed with CPL= 3.
    VEX_PFX                equ 1 shl 24 - presenting of the VEX prefix.
    XOP_PFX               equ 1 shl 25 - presenting of the XOP prefix.
    M256_INT               equ 1 shl 26 - presenting a 256-bit vector that contain integer elements.
    L_MBZ                  equ 1 shl 27 - means that the VEX.L must be cleared.
    OPER3_MEM              equ 1 shl 28 - third operand is a memory pointer.
    OPER4_MEM              equ 1 shl 29 - fourth operand is a memory pointer.
    SVEX_PFX              equ 1 shl 30 - presenting a short VEX prefix, which have only 2 bytes.

  • OpFeatures     - see description of the  Features structure.
  • RipOffset     - short string with a mnemonic of the rip-pointer operand, which represented as absolute offset.
  • JAddrOffset   - short string with a mnemonic of the relative address, which represented as absolute address.


Features

Features struc
    Note        BYTE ?
    exNote      BYTE ?
    MnemOrd     WORD ?
    FirstOper   BYTE ?
    SecondOper  BYTE ?
    ThirdOper   BYTE ?
    FourthOper  BYTE ?
    FifthOper   BYTE ?
    iSet        BYTE ?
Features ends

  • Note - peculiar opcode characteristic.

    Can have one of the following values.

    NullNoteCode  equ 0 - has no characteristic.
    UD64           equ 1 - undefined opcode in the 64-bit mode.
    UD16_32       equ 2 - opcode is defined only in the 64-bit mode.
    DIFF64_OPC     equ 3 - opcode has a differ means in the 64-bit and legacy/compatibility modes.
    WaitPfx       equ 4 - presenting a wait prefix for a few FPU instructions or it`s wait/fwait immediatly.
    MNEM16_DIFF   equ 6 - other mnemonic when Instruction .DefaultOperSize is equal to 16.
    MNEM16_DFUD64 equ 7 - same as MNEM16_DIFF and UD64, but together.
    MNEM_DIF      equ 11 - Instruction .DefaultOperSize specify a mnemonic.
    MNEM67_DIF    equ 12 - Instruction .DefaultAddrSize specify a mnemonic.
    AvxNoF2F3     equ 16
    AvxF2F3       equ 17
    wm_ch         equ 19 - VEX.W bit specify a mnemonic.
    modmsd        equ 20 - mode field specify a mnemonic.
    WMBZ          equ 21 - VEX.W bit must be cleared.
    sg_opc        equ 22 - a instruction with no ModRM byte vzeroupper or vzeroall.
    wm_chf        equ 23 - a FMA3 instruction.
  • exNote - second byte that contain an additional opcode characteristic.

    The following values are using.

    NullNoteCode equ 0 - has no characteristic.
    no32op       equ 1 - in the 64-bit mode instruction can have 16 or 64-bit operand size, but not 32-bit.
    j32no        equ 2 - in the 64 bit mode instruction can have 16 or 64-bit address as operand, but not 32-bit.
    framel       equ 3 - it`s for frame instructions enter,leave and retn.
    op_lock       equ 4 - an opcode can have prefix lock (0F0h), if Instruction.mode!= 11b.
    op_rep        equ 5 - an instruction can have prefix rep (0F3h).
    rep_n_e       equ 6 - an instruction can have anyone prefix repe/repne (0F3h/0F2h).
    CSdNA        equ 7 - Instruction .DefaultOperSize field not depends from the CS.D bit of a segment descriptor.
    m1l_avx      equ 8 - VEX.L bit must be toggled to 1.
    xop2op       equ 9 - AVX instruction that have 3 vector operands.
    xop3op        equ 10 - AVX instruction have 3 vector operands and VEX.W-bit specify their sequence.
    xop4op       equ 11 - AVX instruction have 4 vector operands and VEX.W-bit specify their sequence.
    nrev3op      equ 12 - AVX instruction that have 3 vector operands.
    nrev4op      equ 13 - AVX instruction that have 4 vector operands.
  • MnemOrd - a number of the mnemonic in the list of the mnemonics. All numbers enumerated in the include file include/dsmhelp.inc .

  • Next five byte fields FirstOper/SecondOper/ThirdOper/FourthOper/FifthOper is a types of operands. Equality to 0 means that the operand is absent. Full list of the used values you may see  here .
  • iSet - specify an instruction group.

    The following values are using. (Here used macro  enum for constant enumeration.)
    curr_id=1
    enum      ibasic, icmpxchgxb,    icmovcc,i3dprefetch,   iclflush,     imovbe,     icrc32,  iprefetch
    enum   ilongmode, ipclmulqdq,       iaes, ixsaverstr, i64sysctrl,       itsc,    irdtscp,   irdwrmsr
    enum isyscallret, ienterexit,       isvm,   isysctrl,  iisysctrl,       isse, issemmxext, issemmxbsc
    enum     issemmx,  issebasic,ifxsaverstr,      isse2,   isse2mmx, ibasicsse2,isse2mmxext, isse2basic
    enum       isse3,   isse3mmx,   isse3fpu,     issse3,issse3mmxex,     isse4a,     isse41,  isse41bsc
    enum      isse42,       immx,    immxx87,  immxbasic,       ix87, ix87cmovcc,    ix87mmx,     i3dnow
    enum   i3dnowx87,  i3dnowext,       ivmx,      ifma4,       ixop,       iavx,    iaesavx,      iavx3
    enum       ivcvt,     ivcvtu,     ivcvtp,    ivcvtfu,    iaclmul

    Super group | Group | Architecture | Description
    Basic ibasic - simple instructions.
    icmpxchgxb - cmpxchg/8b/16b.
    icmovcc - conditional data moving.
    i3dprefetch | AMD64 | instruction prefetch or prefetchw.
    icflush - clflush.
    imovbe | Intel64 | movbe.
    icrc32 | Intel64 | crc32.
    iprefetch - instructions prefetch\nta\t0\t1\t2.
    ilongmode - simple instructions just for LONG MODE.
    New instructions,
    CPUID         		ipclmulqdq Intel64 pclmulqdq.
    iaes | Intel64 | special instruction for encoding.
    ixsaverstr - saving/restoring of the media register state.
    System i64sysctrl - simple system instructions for the LONG MODE.
    itsc - rdtsc.
    irdtscp - rdtscp.
    irdwrmsr - instructions rdmsr and wrmsr.
    isyscallret - instructions syscall and sysret, only for flat memory model.
    ienterexit - instructions sysenter and sysexit.
    isvm | AMD64 | virtualization SVM.
    isysctrl - simple for system control.
    iisysctrl | Intel64 | simple for system control.
    SSE isse - 128-bit media instructions.
    issemmxext - 64-bit media instructions.
    issemmxbsc - 64-bit media instructions, which can use GPR as operand.
    issemmx - 128-bit media instructions, which can use 64-bit media registers as operand.
    issebasic - 128-bit media instructions, which can use GPR as operand.
    ifxsaverstr - saving/restoring of the media register state.
    SSE2 isse2 - 128-bit media instructions.
    isse2mmx - 128-bit media instructions, which can use 64-bit media registers as operand.
    ibasicsse2 - instructions lfence, mfence and movnti.
    isse2mmxext - 64-bit media instructions.
    isse2basic - 128-bit media instructions, which can use GPR as operand.
    SSE3 isse3 - 128-bit media instructions.
    isse3mmx - 128-bit media instructions, which can use 64-bit media registers as operand.
    isse3fpu - fisttp.
    SSSE3 | issse3 | Intel64 | 128-bit media instructions.
    issse3mmxex | Intel64 | 128-bit media instructions, which can use 64-bit media registers as operand.
    SSE4A | isse4a | AMD64 | 128-bit media instructions.
    SSE4.1 | isse41 | Intel64 | 128-bit media instructions.
    isse41bsc | Intel64 | 128-bit media instructions, which can use GPR as operand.
    SSE4.2 | isse42 | Intel64 | 128-bit media instructions.
    MMX immx - 64-bit media instructions.
    immxx87 - emms.
    immxbasic - 64-bit media instructions, which can use GPR as operand.
    FPU ix87 - fpu-instructions.
    ix87cmovcc - conditional data moving.
    ix87mmx - instructions saving/restoring of the fpu-registers, in which later appears 64-bit media registers.
    3DNOW | i3dnow | AMD64 | 64-bit media instructions.
    i3dnowx87 | AMD64 | femms.
    i3dnowext | AMD64 | additional 3DNOW instructions.
    VMX | ivmx | Intel64 | virtualization of the VMX.
    XOP and FMA4 (SSE5A after revision) | ixop | AMD64 | 128 and 256-bit media instructions.
    ifma4 | AMD64
    AVX iavx - 128 and 256-bit media instructions.
    iaesavx | Intel64
    iavx3 | Intel64
    ivcvt -
    ivcvtu -
    ivcvtp -
    ivcvtfu -
    iaclmul | Intel64


EF

EF struc
    ID		BYTE ?	;21
    VIP		BYTE ?	;20
    VIF		BYTE ?	;19
    AC		BYTE ?	;18
    VM		BYTE ?	;17
    RF		BYTE ?	;16
    NT		BYTE ?	;14
    IOPL            BYTE ?	;13-12
    _OF		BYTE ?	;11
    _DF		BYTE ?	;10
    _IF		BYTE ?	;9
    TF		BYTE ?	;8
    SF		BYTE ?	;7
    ZF		BYTE ?	;6
    AF		BYTE ?	;4
    PF		BYTE ?	;2
    CF		BYTE ?	;0
EF ends

Structure contains bytes that represents a corresponding them flags of the rFLAGS register.
Each byte can have one of the following values.
NA   equ  0 - not changes.
_0   equ  1 - toggle to 0.
_1   equ  2 - sets to 1.
U     equ  3 - has unpredictible value.
_Mod equ  4 - toggles by a strict rule.
TMod equ  5 - tests and toggles by a someone strict rule.
_Pop equ  6 - toggles by the instruction popf/d/q or iret/d/q.
TPop equ  7 - tests and toggles by the instruction popf/d/q or iret/d/q.
Tst  equ  8 - tests.
lAH  equ  9 - loads from the register ah.
VMS0 equ 10 - must be cleared with a VMX instruction.
VMIN equ 11 - toggled to 1, if VMfailInvalid.
VMEN equ 12 - toggled to 1, if VMfailValid.


x87c

x87c struc
    C0	BYTE ?
    C1	BYTE ?
    C2	BYTE ?
    C3	BYTE ?
    dC0	BYTE ?
    dC1	BYTE ?
    dC2	BYTE ?
    dC3	BYTE ?
x87c ends
  • C0,C1,C2,C3 - each of this 4 bytes, which represents appropriate conditional flags from an FPU`s state-register, contain an affecting-code of the current instruction.

    Can be one of the following values.

    NA equ 0 - not affecting.
    _0 equ 1 - clears.
    _1 equ 2 - toggles to 1.
    U equ 3 - unpredictable value.
    _Mod equ 4 - changes with a certain rules.
  • dC0,dC1,dC2,dC3 - these 4 bytes may contain a rule-code for the changes or 0.

    Can be one of the following values.
    Rules | Value | Description.
    lmem equ 1 - Loads from memory.
    _rng equ 2 | 0 | Source operand was in range.
    1 | Source operand was out of range.
    _ovs equ 3 | 0 | No stack overflow.
    1 | x87 stack overflow, if an x87 register stack fault was detected.
    v0q equ 4 | 0 | x87 stack underflow, if an x87 register stack fault was detected.
    - Set equal to the value of bit 0 of the quotient, if there was no fault.
    v1q equ 5 - Set equal to the value of bit 1 of the quotient.
    v2q equ 6 - Set equal to the value of bit 2 of the quotient.
    fpri equ 7 | 0 | FPREM generated the partial remainder.
    1 | The source operands differed by more than a factor of 2^64, so the result is incomplete.
    rnup equ 8 | 0 | x87 stack underflow, if an x87 register stack fault was detected.
    0 | Result was rounded down, if a precision exception was detected.
    1 | Result was rounded up, if a precision exception was detected.
    fexm equ 9 - C3 C2 C1 C0
    0  0  0  0  +unsupported format
    0  0  0  1  +NaN
    0  0  1  0  –unsupported format
    0  0  1  1  –NaN
    0  1  0  0  +normal
    0  1  0  1  +infinity
    0  1  1  0  –normal
    0  1  1  1  –infinity
    1  0  0  0  +0
    1  0  0  1  +empty
    1  0  1  0  –0
    1  0  1  1  –empty
    1  1  0  0  +denormal
    1  1  1  0  –denormal
    _ous equ 10 | 0 | x87 stack underflow, if an x87 register stack fault was detected.
    1 | x87 stack overflow, if an x87 register stack fault was detected.
    cmp0 equ 11 - C3 C2 C1 C0
    0  0  0  0  ST(0) > source.
    0  0  0  1  ST(0) < source.
    1  0  0  0  ST(0) = source.
    1  1  0  1  Operands were unordered.
    ex00 equ 12 | 0 | No precision exception occurred.
    0 | x87 stack underflow, if an x87 register stack fault was detected.
    0 | Result was rounded down, if a precision exception was detected.
    1 | Result was rounded up, if a precision exception was detected.
    ex01 equ 13 | 1 | x87 stack overflow, if an x87 register stack fault was detected.
    0 | If no other flags are set.
    ex02 equ 14 | 0 | x87 stack underflow, if an x87 register stack fault was detected.
    1 | x87 stack overflow, if an x87 register stack fault was detected.
    0 | No x87 stack fault.
    ex03 equ 15 | 0 | x87 stack underflow, if an x87 register stack fault was detected.
    1 | x87 stack overflow, if an x87 register stack fault was detected.
    0 | Result was rounded down, if a precision exception was detected.
    1 | Result was rounded up, if a precision exception was detected.


moRanges

moRanges struc
    CntRange   ULONG ?
    rng        moRange ?
moRanges ends

pmoRanges TYPEDEF PTR moRanges

  • CntRange - the number of the subranges of the virtual memory, within preferred RIP-addressing.
  • rng - array of the subranges.

    Note: in the LONG_MODE, instructions which uses modrm for the addressing, can address at least to the 6 Gb virtual memory independent from rip. Below you can see the ranges of this virtual address space.
    No | Range modrm=00xxx100b,sib=25h | Prefix 67h
    1. |  0000000000000000h..000000007FFFFFFFh | allowed
    2. |          80000000h..0FFFFFFFFh | necessary
    3. | 0FFFFFFFF80000000h..0FFFFFFFFFFFFFFFFh | not allowed

    Pointer from the  Instruction  structure ModrmOffsets points to the moRanges structure which contains subranges from first and second ranges, after this one follows other moRanges structure, which contains subranges from third range with the signed limits.

    By default first moRanges contain one subrange 400000h..0FFFFFFFFh, and followed is empty. You can define not more than a 2 additional ranges.


moRange

moRange struc
    HighAddr	DWORD ?
    LowAddr		DWORD ?
moRange ends

  • HighAddr - the highest address.
  • LowAddr - the lowest address.


altm

altm MACRO Consts:VARARG
    EXITM <>
ENDM

Pseudo-macro, in masm this one do nothing. This macro allows alternate opcode at assembling. Fo example altm(0) xor edx,edx  assembles as  31h,0D2h,and  altm(1) xor edx,edx  assembles as  33h,0D2h. By a second number for 64-bit code can be sets forced rip-addressing or forced MODRM-offset. For example altm(0,1) xor edx,[0] always with rip-addressing or fails and altm(0,2) xor edx,[0] always with MODRM-offset or fails. This macro can be ommited with  AssembleEx  function, but always uses with the  Assemble.


enum

enum MACRO Consts:VARARG
%   FOR parm,<Consts>
   %   parm equ curr_id
       curr_id=curr_id+1
    ENDM
ENDM

Macro for enumerating of the macro-constants. curr_id is a numeric macro-variable, that must be defined before using this macro. enum can be very useful if at developing needs regular changes, values of the macro-constants.


About

О проэкте.

Дизассемблерная библиотека для архитектуры x86-64.

Обратная связь dsmhelp@yandex.ru


History

История.

Версия 0.4   30 Mая 2010 года.

Первая версия, которую я разместил в сети.

Версия 0.5   5 Июня 2010 года.

Исправлено большое количество мелких ошибок и неточностей.
Появилась возможность использовать 32-битные аддресса в 16-битном коде. Для операндов это modrm,sib-байты плюс смещение.
В инструкциях push и pop у сегментных регистров теперь можно переопределять размер.
push word ptr es занимает 2 байта в стэке.
pop dword ptr es - освобождает 4 байта в стэке, dword ptr нельзя писать для LONG_MODE, только word ptr.
Добавил функцию InstrEF для получения информации о модифицируемых флагах.

Версия 0.6   8 Aвгуста 2010 года.

В форме вызова функций почти нет изминений, в то время как основные структуры Instruction и Features пришлось очень сильно перекроить, в их описании появилось много нового. Также появились три новых структуры x87c,moRanges и moRange. Таблицы опкодов стали гораздо более информативными, появилась поддержка инстркукций специфичных только для Intel64. При выводе листинга теперь не всегда указывается размерность операндов. Например вместо mov byte ptr [edx],cl теперь mov [edx],cl. Если операнд является непосредственной константой то при вычислении теперь могут выполняться сложения и вычитания. Например mov al,2+3. Появилиcь дополнительные мнемоники для cmppd,cmpps,cmpsd и cmpss, альтернативные варианты с 2-мя операндами такие как cmpeqpd. Для enter,leave и retn, теперь есть варианты указывающие на наличие префикса 66h, enterw\enterd,leavew\leaved и retnw\retnd.

Версия 0.7   29 Aвгуста 2010 года.

Эта версия отличается от 0.6-ой главным образом большим количеством уже исправленных ошибок в ассемблерной части. Все инструкции без исключения были перепроверены. Теперь перед ассемблированием проводится более тщательная проверка синтаксиса. В структуре Instruction появилось два новых поля, OpcNum и OpcTotal. Добавлена функция AssembleEx для получения альтернативных опкодов одной инструкции. Добавлены 3 дополнительные мнемониники для инструкций wait,fxsave,fxrstor - это соответственно fwait,fxsave64 и fxrstor64. Изменено количество типов данных для структуры Features, и некоторые из них теперь уже подробно описаны.

Версия 0.8   3 Oктября 2010 года.

Исправил ошибку связаную с неправильной обработкой избыточных REX префиксов. Исправлена ошибка с nop`aми, опкоды 0F_19..0F_1F, теперь двух-операндные nop Ev,Gv и nop Gv,Ev. Добавил новые мнемоники для pclmulqdq, двух-операндные варианты подробно описаные в интеловском мануале. Также менее значимые retfw,retfd,retfq и call64,jmp64(предназначены для архитектуры AMD64). Самое существенное изминение это наличие поддержки всех без исключения AVX инструкций, в том числе FMA3 и амдешные SSE5 после ревизии XOP и FMA4. При добавлении были большие трудности потому-что формат этих новых инструкций сильно отличается от остальных и в плане получения информации об этих инструкциях, вполне возможны ошибки. Но ассемблироваться\дизассемблироваться т.е. с получением опкода или наоборот мнемоники проблем не должно быть. Есть существенные изминения в структуре Instruction, в основном связанные с правильным выравниванием полей.

Версия 0.9   5 Декабря 2010 года.

Основная часть осталась без существенных изминений. Было исправлено несколько досадных мелких ошибок, связаных с не правильным ассемблированием инструкций с rip-аддрессацией. Добавил обработку псевдо-макроса altm(), для возможности в ручную определять опкод при ассемблировании инструкций. Сделал библиотеку переходник dsmwow64.dll посредством которой 32-битные приложения работающие в режиме совместимости теперь могут использовать все функции. Начал писать отладчик, сделал к нему простую подсветку синтаксиса, но готов он будет не раньше весны.

Обратная связь  dsmhelp@yandex.ru


Opcode-Syntax Notation

A Far pointer is encoded in the instruction.
C Control register specified by the ModRM reg field.
D Debug register specified by the ModRM reg field.
E General purpose register or memory operand specified by the ModRM byte. Memory addresses
can be computed from a segment register, SIB byte, and/or displacement.
F rFLAGS register.
G General purpose register specified by the ModRM reg field.
I Immediate value.
J The instruction includes a relative offset that is added to the rIP.
M A memory operand specified by the ModRM byte.
O The offset of an operand is encoded in the instruction. There is no ModRM byte in the
instruction. Complex addressing using the SIB byte cannot be done.
P 64-bit MMX register specified by the ModRM reg field.
PR 64-bit MMX register specified by the ModRM r/m field. The ModRM mod field must be 11b.
Q 64-bit MMX-register or memory operand specified by the ModRM byte. Memory addresses can
be computed from a segment register, SIB byte, and/or displacement.
R General purpose register specified by the ModRM r/m field. The ModRM mod field must be 11b.
S Segment register specified by the ModRM reg field.
V 128-bit XMM register specified by the ModRM reg field.
VR 128-bit XMM register specified by the ModRM r/m field. The ModRM mod field must be 11b.
W A 128-bit XMM register or memory operand specified by the ModRM byte. Memory addresses
can be computed from a segment register, SIB byte, and/or displacement.
X A memory operand addressed by the DS.rSI registers. Used in string instructions.
Y A memory operand addressed by the ES.rDI registers. Used in string instructions.

a Two 16-bit or 32-bit memory operands, depending on the effective operand size. Used in the
BOUND instruction.
b A byte, irrespective of the effective operand size.
d A doubleword (32 bits), irrespective of the effective operand size.
dq A double-quadword (128 bits), irrespective of the effective operand size.
p A 32-bit or 48-bit far pointer, depending on the effective operand size.
pd A 128-bit double-precision floating-point vector operand (packed double).
pi A 64-bit MMX operand (packed integer).
ps A 128-bit single-precision floating-point vector operand (packed single).
q A quadword, irrespective of the effective operand size.
s A 6-byte or 10-byte pseudo-descriptor.
sd A scalar double-precision floating-point operand (scalar double).
si A scalar doubleword (32-bit) integer operand (scalar integer).
ss A scalar single-precision floating-point operand (scalar single).
v A word, doubleword, or quadword, depending on the effective operand size.
w A word, irrespective of the effective operand size.
z A word if the effective operand size is 16 bits, or a doubleword if the effective operand size is 32
or 64 bits.
/n A ModRM-byte reg field or SIB-byte base field that contains a value (n) between zero (binary
000) and 7 (binary 111).

curr_id=1

enum      m2z,       Ub,      Ib,       Iz,       Ubm,       Sb,           Uw,          _CL
enum       Iv
enum      Ib8
enum      Ub8
enum      Ubt
enum Vctb
enum Vctd
enum Vctp
enum Wcts
enum Mcts
enum     Ccts,    Gprd,     WD_Q,       VPD,      WPD,     E32d,          WSS,         M32d
enum      VRX,     EDQ,      WSD,       WDY,     VDFM,     G32d,         MBRQ,         MWRQ
enum       Eb,      Ew,       Ed,       Ub4
enum       Ev,     _Eq,     Ed_q,        Gb,       Gw,       Gd,           Gv,           Gz
enum     Gd_q,     Vps,      Vss,       Vsd,     iVpb,     iVpw,         iVpd,         iVpq
enum      Yps,     Ypd,      Yss,       Ysd,     iYpb,     iYpw,         iYpd,         iYpq
enum     vVps,    vVpd,     vVss,      vVsd,    viVpb,    viVpw,        viVpd,        viVpq
enum     vYps,    vYpd,     vYss,      vYsd,    viYpb,    viYpw,        viYpd,        viYpq
enum     VRps,    VRpd,      VRq,      VRdq,     iWpb,     iWpw,         iWpd,         iWpq
enum     mYps,    mYpd,     mYss,      mYsd,    imYpb,    imYpw,        imYpd,        imYpq
enum     bVps,    bVpd,     bVss,      bVsd,    biVpb,    biVpw,        biVpd,        biVpq
enum     bYps,    bYpd,     bYss,      bYsd,    biYpb,    biYpw,        biYpd,        biYpq
enum     YRdq
enum      Vpd,      Vq,      Vdq,      Vd_q,   Vdq_sd,   Vdq_ss,          Wps,          Wpd
enum      Wss,     Wsd,       Ww,        Wd,       Wq,      Wdq,           Pd,           Pq
enum     Pd_q,      Qd,       Qq,       PRq, mem80dec,  m32real,      m64real,    mem80real
enum   m16int,  m32int,   m64int,       m16,      Mss,      Msd,          Mps,          Mpd
enum        M,      Ma,        Mp,       Mb,     Wd_q
enum       Mw,      Md,       Mq,        Mv,       Ms,      Mdq,       Mq_Mdq,Mq_VRqDifMnem
enum     Md_q,      Rv,     Rd_q,     Mw_Rv,    Mw_Rd,    Mb_Rd,      Mb_Rd_q,           Sw
enum     Cd_q,    Dd_q,      st0,       st1,      st2,      st3,          st4,          st5
enum      st6,     st7, env14_28, env98_108, UnkModRM,       Ob,           Ov,           Ap
enum      _Jb,      Yb,       Xb,        Yz,       Xz,       Yv,           Xv,       rAX_r8
enum   rCX_r9, rDX_r10,  rBX_r11,   rSP_r12,  rBP_r13,  rSI_r14,      rDI_r15,       AL_r8b
enum   CL_r9b, DL_r10b,  BL_r11b,   AH_r12b,  CH_r13b,  DH_r14b,      BH_r15b,         _rAX
enum     _eAX,    _eCX,     _eDX,      _eBX,     _eSP,     _eBP,         _eSI,         _eDI
enum      _AL,     _AX,      _DX,       _ES,      _CS,      _SS,          _DS,          _FS
enum      _GS,     One,       xb,       _Jz

MIN_MODRM equ Eb
MAX_MODRM equ UnkModRM

Ib  - byte with the sign extension, which can be replaced by WORD or DWORD Iz.
Iz  - WORD or DWORD with the sign extension.
Uw  - WORD with no sign.
Ub   - signed or unsigned byte.
Ubm   - unsigned byte, which can change instruction`s mnemonic, for example cmppd,cmpps.
Sb   - byte for the logical shifts.
Uw   - unsigned word.
_CL - register cl.
Iv  - WORD, DWORD or QWORD for the move instructions  mov rEG,Imm  within opcodes 0B8h..0BFh.
M2Z - a number from 1 till 15 for the vpermil2pd and vpermil2ps instructions.
YRdq - 32-byte vector within integer numbers, specified by the rmem field of the ModRM byte.
Ms - pointer to the 6 or 10-byte pseudo descriptor.
UnkModRM - equal Ev, but used for the nops instructions within opcodes 0F_19..0F_1F.