Simple demo of directly importing WinAPI from source without extern. Probe starts from kernel32.dll.
This demo attempts to import MessageBoxA from user32.dll. Demo is not for beginners.
;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
; Demo: Importing library directly
; nasm -f win64 demo.asm
; golink demo.obj
;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
;Tested on Win10 only
global start
STARTING equ 0x10000
section .bss
AddrLoadLib resq 1
AddrExitProcess resq 1
AddrGetProc resq 1
AddrFreeLib resq 1
BaseKernel resq 1
imgExport resq 1
AddrOfNames resq 1
AddrOfFunctions resq 1
NumOfFunctions resq 1
section .data
msg db 'MessageBox from user32.dll',0
title db 'by dreamCoder',0
_ExitProcess db 'ExitProcess',0
_GetProcAddress db 'GetProcAddress',0
_LoadLibrary db 'LoadLibraryA',0
_FreeLibrary db 'FreeLibrary',0
_user32 db 'user32.dll',0
_MessageBoxA db 'MessageBoxA',0
align 16
section .text
start:
mov rsi,[rsp]
and rsi,-STARTING
more: mov ax,word[rsi]
cmp ax,'MZ'
je good
sub rsi,STARTING
jmp more
good: mov [BaseKernel],rsi
mov ebx,dword[rsi+3ch]
add rsi,rbx
add rsi,4*6
add rsi,112
mov ebx,[rsi]
mov rax,[BaseKernel]
add rax,rbx
mov [imgExport],rax
mov ebx,[rax+4*6]
mov [NumOfFunctions],rbx
add rax,4*8
mov [AddrOfNames],rax
mov ebx,[rax]
mov rax,[BaseKernel]
mov ebx,[rsi]
add rax,rbx
add rax,4*7
mov [AddrOfFunctions],rax
mov rbx,_GetProcAddress
call GetAddress
mov [AddrGetProc],rax
mov rbx,_LoadLibrary
call GetAddress
mov [AddrLoadLib],rax
mov rbx,_ExitProcess
call GetAddress
mov [AddrExitProcess],rax
mov rbx,_FreeLibrary
call GetAddress
mov [AddrFreeLib],rax
;alignment + shadow space
sub rsp,40
;Load user32.dll
mov rcx,_user32
call [AddrLoadLib]
mov r15,rax
;MessageBoxA address
mov rdx,_MessageBoxA
mov rcx,rax
call [AddrGetProc]
;Run MessageBoxA
mov rcx,0
mov rdx,msg
mov r8,title
mov r9,0
call rax
;Run FreeLibrary
mov rcx,r15
call [AddrFreeLib]
add rsp,40
;Run ExitProcess
mov rcx,0
call [AddrExitProcess]
;In RBX: pointer to function string
;Ret : RAX = Address of function
GetAddress:
mov rax,[AddrOfNames]
mov edx,[rax]
mov rax,[BaseKernel]
add rax,rdx
mov rcx,[NumOfFunctions]
mov rbx,[rbx]
xor esi,esi
Str: mov edx,[rax]
add rdx,[BaseKernel]
mov rcx,[rdx]
cmp rbx,rcx
je Addr
add rax,4
add rsi,1
sub rcx,1
jnz Str
Addr: mov rax,[imgExport]
add rax,4*7
mov ebx,[rax]
mov rax,[BaseKernel]
add rax,rbx
mov ecx,[rax+rsi*4]
mov rax,[BaseKernel]
add rax,rcx
ret