All pastes #1384022 Raw Edit

Miscellany

public cpp v1 · immutable
#1384022 ·published 2009-04-06 19:43 UTC
rendered paste body
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<u32 opcode> 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<u32 opcode> struct Naked	{		void operator()()		{			WriteOp<opcode>();		}	};	template<u32 opcode> struct Imm8	{		void operator()(u8 ib)		{			WriteOp<opcode>();			Write8(ib);		}	};	template<u32 opcode> struct Imm8S	{		void operator()(s8 ib)		{			WriteOp<opcode>();			Write8((u8)ib);		}	};	template<u32 op16, u32 op8 = 0> struct Imm16	{		void operator()(u16 iw)		{			if (op8 && iw < 0x100) {				WriteOp<op8>();				Write8((u8)iw);			} else {				WriteOp<op16>();				Write16(iw);			}		}	};	template<u32 op16, u32 op8 = 0> struct Imm16S	{		void operator()(s16 iw)		{			if (op8 && iw < 0x80 && iw >= -0x80) {				WriteOp<op8>();				Write8((u8)iw);			} else {				WriteOp<op16>();				Write16((u16)iw);			}		}	};	template<u32 op32, u32 op16 = 0, u32 op8 = 0> struct Imm32	{		void operator()(u32 id)		{			if (op8 && id < 0x100) {				WriteOp<op8>();				Write8((u8)id);			} else if (op16 && id < 0x10000) {				WriteOp<op16>();				Write16((u16)id);			} else {				WriteOp<op32>();				Write32(id);			}		}	};	template<u32 op32, u32 op16 = 0, u32 op8 = 0> struct Imm32S	{		void operator()(s32 id)		{			if (op8 && id < 0x80 && id >= -0x80) {				WriteOp<op8>();				Write8((u8)id);			} else if (op16 && id < 0x8000 && id >= -0x8000) {				WriteOp<op16>();				Write16((u16)id);			} else {				WriteOp<op32>();				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 <stdlib.h>int main(){	u8* buf = static_cast<u8*>(malloc(0x40000));	x86Ptr = buf;	RET();	AAA();	AAD();	AAD(16);	AAD(-16);		RET();	RET(16);	RETF();	RETF(16);	((void(*)())buf)();	return 0;}