Combining Strings of Machine Code
Next stage
This does the same as above but with two helper functions to simplify coding.
'------------------------------------------------------------------------
' How to create strings of machine code during run time and execute them.
'------------------------------------------------------------------------
' Version 2
' with helper functions
' 28 May 2007
' Charles E V Pegge
' (Using FreeBasic)
'------------------------------------------------------------------------
' pass location of code and location of data space to this function:
function caller( byval p as byte pointer, byval q as byte pointer) as long
asm '
mov esi,[q] ' location of work space into index register esi
mov eax,[p] ' location of code into eax register
call eax ' call to the afdress contained in eax
mov [function],eax ' assume eax contains something meaningful and return it
end asm '
end function
'------------------------------------------------------------------------
'pass the hexadecimal text string to this function and obtain a binary string:
function hexconvert(byref s as string) as string
dim as long i=1
dim as long j=1
dim as long l
s=ltrim$(s)
dim t as string
t=string$(len(s)/2,chr$(0)) ' estimate max length
l=len(s)
do
if i>l then exit do
mid$(t,j)=chr$(val("&h"+mid$(s,i,2)))
i+=2: j+=1
' skip space for next hex code
do
if asc(s,i)>32 then exit do
i+=1
if i>l then exit do
loop
loop
function=left$(t,j-1)
end function
'-------------------------------------
' Combining strings of machine code:
DIM AS STRING w = string$( 8192,chr$(0) ) ' indexed work space for the code
DIM s AS STRING ' string for the executable code
DIM AS STRING push_regs = hexconvert("51 52 53") ' pushes registers ecx edx ebx onto the stack
DIM AS STRING pop_regs = hexconvert("5b 5a 59") ' pops registers ebx edx ecx from the stack
DIM AS STRING new_frame = hexconvert("83 c6 40") ' add 64 to index register esi
DIM AS STRING old_frame = hexconvert("83 ee 40") ' subtract 64 from index register esi
DIM AS STRING rets = chr$(&hc3) ' standard return
' use these to test the strings above:
DIM AS STRING movAXSI = hexconvert("8b c6") ' move esi to eax
DIM AS STRING subAXSI = hexconvert("2b c6") ' subtract esi from eax
s=push_regs + movAXSI + new_frame + subAXSI + old_frame + pop_regs + rets
'-------------------------------------
a=caller(strptr(s),strptr(w))
print "Answer: ";hex$(a)
'-------------------------------------
end