Simply JIT

Share your advanced PureBasic knowledge/code with the community.
rodego
User
User
Posts: 10
Joined: Thu Nov 08, 2007 7:39 pm

Simply JIT

Post by rodego »

Code: Select all

; Load libs and get function pointers
OpenLibrary(0,"User32.dll")
OpenLibrary(1,"Kernel32.dll")
func.i=GetFunction(0,"MessageBoxA")
func2.i=GetFunction(1,"ExitProcess")

; Allocate strings
#StringBufferSize=200
Title.i=AllocateMemory(#StringBufferSize)
PokeS(Title,"Some caption")
Text.i=AllocateMemory(#StringBufferSize)
PokeS(Text,"Hello world!")

; Allocate JIT section
ExSize=?EndEx-?Ex
*mem=AllocateMemory(ExSize)
CopyMemory(?Ex,*mem,ExSize)
ending.i=?ReturnDot

Debug "Jit pointer "+Str(*mem)

; Call JIT code
NewMode=#PAGE_EXECUTE_READ
VirtualProtect_(*mem,ExSize,NewMode,@OldMode)
!jmp [p_mem]

; Here we return after JIT code execution
ReturnDot:
Debug "Return to main application"
End

; Generic code
Ex:

; MessageBox
!PUSH 0
!PUSH [v_Title]
!PUSH [v_Text]
!PUSH 0
!CALL [v_func]

; ExitProcess == End in PureBasic
;!PUSH 0
;!CALL [v_func2]

; Return to next line after JIT code call
!jmp [v_ending]
EndEx:
I just copy the generated code FASM (PureBasic inline assembler).

Warning! Work on Win32, but on Win64 is falling. Have any idea what went wrong?

P.S. Sorry for my english)