Search code examples
cwinapistackallocationntdll

C - Stack allocation using only ntdll


Is there an API call or any another similar way, that uses only ntdll.dll, to allocate memory on the stack?

I know alloca() does that, but I can't use it because I can use only function from ntdll.dll.

Thanks!


Solution

  • alloca is partially intrinsic function, implemented by compiler. but internally it call _alloca_probe_16 (for x86) or __chkstk(x64) for move guard page down on stack. implementation of this functions exist in alloca16.obj and chkstk.objwhich can be found in VC subfolder (where exacly depended from VC version) - you can add this obj for link process or even first convert it to lib. also in latest WDK libs - exist ntdllp.lib (not confuse with ntdll.lib) - it also containing all need for implementation ( ntdll.dll export _chkstk (for x86) and __chkstk (for x64))


    again in more details:

    when you write in src code

    alloca(cb) CL compiler generate in x86

    mov eax,cb
    call _alloca_probe_16 ; do actual stack allocation and probe
    

    and in x64 version

    mov         ecx,eax 
    add         rcx,0Fh 
    cmp         rcx,rax 
    ja          @@0
    mov         rcx,0FFFFFFFFFFFFFF0h 
    @@0:
    and         rcx,0FFFFFFFFFFFFFFF0h 
    mov         rax,rcx 
    call        __chkstk ; probe only
    sub         rsp,rax ; actual stack allocation
    

    so _alloca_probe_16 and/or __chkstk must be implemented somewhere or you got link error - unresolved external symbol.

    in latest WDK builds exist ntdllp.lib (note about p - not ntdll.lib) which containing this implementation. in this case your PE will be import __chkstk or _alloca_probe from ntdll.dll (this functions exported how minimum from XP - both this functions is point to same code, simply alias)

    another solution - in VC folders can be found alloca16.obj and chkstk.obj - you can use this obj as link input (or merge alloca16.obj + chkstk.obj in single lib file). in this case your PE will be nothing import.