//汇编转机器码
import win.ui;
import process
import fsys;
	
/*DSG{{*/
var winform = win.form(parent=...; text="汇编转机器码";right=481;bottom=388 )
winform.add( 
button={ bottom=206;text="生成机器码";left=298;top=176;z=1;right=423;cls="button" };
editAsm={ vscroll=1;text="edit";left=15;multiline=1;top=9;bottom=170;z=2;right=465;hscroll=1;edge=1;cls="edit" };
btnSample={ bottom=206;right=278;left=153;top=176;z=4;text="执行机器码 范例";cls="button" };
editByteCode={ vscroll=1;text="";left=14;multiline=1;top=214;bottom=374;z=3;right=464;hscroll=1;edge=1;cls="edit" }
)
/*}}*/

winform.editAsm.text = /*
push ebp 
mov ebp,esp 
sub esp,0C0h 
push ebx       
push esi 
push edi
mov esi,[ebp+8]   
xor eax,eax    
cpuid       
mov [esi],ebx   
mov [esi+4],edx   
mov [esi+8],ecx  
pop edi 
pop esi 
pop ebx
mov esp, ebp; 
pop ebp
ret 
*/ 

asm2bin = function(str){
	string.save("/.asm/temp.asm",'[BITS 32]\n' + str ) 
	var prcs = process("/.asm/nasm.exe" , " temp.asm -o temp.bin" ,{flags =  0x1/*_STARTF_USESHOWWINDOW*/} );
	thread.wait(prcs.thandle)
	
	var asm = string.load("/.asm/temp.bin");
	if(#str){ 
		asm = string.replace(asm,".",
			function(x){ 
				return string.format("\x%02X",x[1] );
				
			}
		);
		return string.format("	'%s', //%s",asm, str);
	}	 
}

winform.button.oncommand = function(id,event){
	winform.button.text = "正在编译"
	winform.button.disabled = true;
	winform.editByteCode.text = "请稍候......"
	
	var tAsmCode = string.split( winform.editAsm.text,'\n');
	for(i=1;#tAsmCode;1){
		var code = string.trim(tAsmCode[i] )
		if(#code){
			tAsmCode[i] = asm2bin( code )  
			if(! #tAsmCode[i] ){
				winform.editByteCode.text = "编译失败,错误的汇编语法!"
				winform.button.text = "生成机器码"
				winform.button.disabled = false;
				return;
			}
		}
	}
	
	var template = /***
import process 
var prcs = process();//打开目标进程，可在参数中指定程序路径

//写入机器码,并返回函数对象
func = prcs.asmCdecl(
	"void()",//请指定函数原型
	$ASM_CODE$
)
***/
	var str = string.replace(template,"@$ASM_CODE$",string.trim( string.join(tAsmCode,'\r\n') ) );
	winform.editByteCode.text = str;
	
	winform.button.text = "生成机器码"
	winform.button.disabled = false;
}

winform.btnSample.oncommand = function(id,event){
	var code = /*** 
import process 
var prcs = process();//打开目标进程，可在参数中指定程序路径

//写入机器码,并返回函数对象
getCpuId = prcs.asmCdecl(
	"void(struct &cpuid)",//函数原型
	'\x55', //push ebp
	'\x89\xE5', //mov ebp,esp
	'\x81\xEC\xC0\x00\x00\x00', //sub esp,0C0h
	'\x53', //push ebx
	'\x56', //push esi
	'\x57', //push edi
	'\x8B\x75\x08', //mov esi,[ebp+8]
	'\x31\xC0', //xor eax,eax
	'\x0F\xA2', //cpuid
	'\x89\x1E', //mov [esi],ebx
	'\x89\x56\x04', //mov [esi+4],edx
	'\x89\x4E\x08', //mov [esi+8],ecx
	'\x5F', //pop edi
	'\x5E', //pop esi
	'\x5B', //pop ebx
	'\x89\xEC', //mov esp, ebp;
	'\x5D', //pop ebp
	'\xC3', //ret 
)

//调用函数
var cpuid = getCpuId( { BYTE name[20] } )

//输出结果
io.open()
io.print( cpuid.name )
***/

	string.save("/.asm/getCpuId_asm.aau", code)
	process.execute("/.asm/getCpuId_asm.aau");
	
}

winform.show() 
win.loopMessage();
return winform;
