typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; typedef unsigned long long u64; typedef char s8; typedef short s16; typedef long s32; typedef long long s64; #define TLS __declspec(thread) #define OP1(op, b1) struct op##_t : b1 { using b1::operator(); }; op##_t op; #define OP2(op, b1, b2) struct op##_t : b1, b2 { \ using b1::operator(); using b2::operator(); }; op##_t op; namespace X86 { TLS u8 *x86Ptr; void Write8(u8 b) { *x86Ptr++ = b; } void Write16(u16 w) { *(u16*)x86Ptr = w; x86Ptr += 2; } void Write32(u32 dw) { *(u32*)x86Ptr = dw; x86Ptr += 4; } void Write64(u64 qw) { *(u64*)x86Ptr = qw; x86Ptr += 8; } // Left to right opcode helper for readability template void WriteOp() { if (opcode >> 24) Write32(opcode); else { if (opcode >> 16) Write8((opcode >> 16) & 0xffU); if (opcode >> 8) Write8((opcode >> 8) & 0xffU); Write8(opcode & 0xffU); } } template struct Naked { void operator()() { WriteOp(); } }; template struct Imm8 { void operator()(u8 ib) { WriteOp(); Write8(ib); } }; template struct Imm8S { void operator()(s8 ib) { WriteOp(); Write8((u8)ib); } }; template struct Imm16 { void operator()(u16 iw) { if (op8 && iw < 0x100) { WriteOp(); Write8((u8)iw); } else { WriteOp(); Write16(iw); } } }; template struct Imm16S { void operator()(s16 iw) { if (op8 && iw < 0x80 && iw >= -0x80) { WriteOp(); Write8((u8)iw); } else { WriteOp(); Write16((u16)iw); } } }; template struct Imm32 { void operator()(u32 id) { if (op8 && id < 0x100) { WriteOp(); Write8((u8)id); } else if (op16 && id < 0x10000) { WriteOp(); Write16((u16)id); } else { WriteOp(); Write32(id); } } }; template struct Imm32S { void operator()(s32 id) { if (op8 && id < 0x80 && id >= -0x80) { WriteOp(); Write8((u8)id); } else if (op16 && id < 0x8000 && id >= -0x8000) { WriteOp(); Write16((u16)id); } else { WriteOp(); Write32((u32)id); } } }; namespace X86_32 { OP1(AAA, Naked<0x37>); OP2(AAD, Naked<0xD50A>, Imm8<0xD5>); }; namespace X86_3264 { OP2(RET, Naked<0xC3>, Imm16<0xC2>); OP2(RETF, Naked<0xCB>, Imm16<0xCA>); }; }; using namespace X86; using namespace X86::X86_3264; using namespace X86::X86_32; #include int main() { u8* buf = static_cast(malloc(0x40000)); x86Ptr = buf; RET(); AAA(); AAD(); AAD(16); AAD(-16); RET(); RET(16); RETF(); RETF(16); ((void(*)())buf)(); return 0; }