Search code examples
c++assemblymasm

How to get the Process Environment Block (PEB) address using assembler (x64 OS)?


I'm trying to get PEB address of the current process with assembler.

the cpp file:

#include <iostream>
//#include <windows.h>

extern "C" int* __ptr64 Get_Ldr_Addr();

int main(int argc, char **argv)
{
    std::cout << "asm     " << Get_Ldr_Addr() << "\n";
    //std::cout <<"peb     "<< GetModuleHandle(0) << "\n";

    return 0;
}

the asm file:

.code

Get_Ldr_Addr proc
    push rax
    mov rax, GS:[30h]
    mov rax, [rax + 60h]
    pop rax
    ret
Get_Ldr_Addr endp

end

But I get different addresses from the GetModuleHandle(0) and the Get_Ldr_Addr()!

what is the problem? doesn't is suppose to be the same?

Q: If the function is external, it will check the PEB of the process that called it or of the function's dll (it suppose to be a dll)?

Tnx


Solution

  • Just two comments.

    No need to push/pop rax because it's a scratch or volatile register on Windows, see the caller/callee saved registers. In particular, rax will hold the return value for your function.

    It often helps to step through the machine code when you call GetModuleHandle() and compare it with your own assembly code. You'll probably encounter something like this implementation.