Batch -> Assembly Concept
I’ve been reading ebooks and stuff on how C++ is converted to assembly language; it has given me ideas on how to come up with assembly code for batch file operations. Let’s take a some common batch code and see what they look like in assembly.
First of all, I would like to discuss declaring a variable. I’m thinking that declaring a variable just means to allocate space within the file for that variable and terminating it with a null byte:
set msg=hello world = db "hello world",00
Accessing that variable and modifying it’s contents would mean to use the BX register as a pointer to that variable and the AX register to modify it:
mov bx,variable mov al,byte [bx] ;modify al register mov byte [bx],al
The above would place the byte found at address of variable pointed to by BX into AL, modify that byte, then place it back into that address. This may be repeated with the incrementation of BX until the whole value of the variable is set to one’s desire.
Here’s batch code where we declare a number variable and increment it:
set number=0 set /a number+=1
This could be translated to, in assembly:
push ax push bx mov bx,number mov ax,word [bx] add ax,1 mov word [bx],ax pop ax pop bx number db 00,00,00
In the assembly code, we first save the contents of registers ax and bx to the stack. Then we place the address of the number variable to bx to use as a pointer when placing the value found at that address into ax. After that we add 1 to the value of ax and place that new value back at that address which bx is pointing to. We then end by restoring the ax and bx registers by popping them off the stack.
How about an IF statement?
if %number% LSS 0 ( REM more code )
Here’s that same statement in assembly:
push ax push bx mov bx,number mov ax,word [bx] cmp ax,0 jge label pop ax pop bx ;Yes label: ;No pop ax pop bx number db 00,00,00
Here we again saved ax and bx. Then we moved the address of the number variable to bx and moved the value pointed to by bx into ax. From here we can just use the cmp instruction to compare the value of ax to 0 and perform one of the conditional jump instructions to check if it’s less than or greater than. In this case we used ‘jge’; so if it’s greater than or equal to, then it will skip past the conditional code to the line labeled with label:. In the end, we again restored the ax and bx values from the stack.
Now in both of those examples I provided 2 bytes space for the number variables (Terminated with 0). So the numbers could go up to 65535. But converting those byte values to their ascii number representations to print it to the console is another story.
Well that was just one of my theories on how we could convert batch to assembly. Hopefully, we will have a real batch file compiler in the future.