Xyzzel
Xyzzel

Reputation: 115

Inline __asm code for getting the address of TIB (fs:[0x18])

I'd like to get the TIB of a process and afterwards get its PEB and so forth. I'm failing to do so because I'm having some issues with the __readfsdword(0x18) function, so I'd like to do it with __asm inline code, if possible. The program is compiled for x86, so I think it means that the TIB will be located at offset 0x18 from the FS register. On x64 it should be on gs:[0x30].

How would I implement this inline assembly idea?

Edit

NtCurrentTeb() and __readfsdword gave different return addresses so I wanted to get as low-level as possible to figure out which one was malfunctioning. The reason why __readfsdword wasn't working is because I think the libraries weren't compatible with each other, so I replaced them with the updated versions and now it's working properly.

Upvotes: 0

Views: 3068

Answers (1)

Anders
Anders

Reputation: 101736

__readfsdword/__readgsqword are compiler intrinsic functions that will generate more optimized code, there is no reason to use inline assembly. Inline assembly is not even supported by Microsoft's compilers for 64-bit targets.

#include <intrin.h>

__declspec(naked) void* __stdcall GetTEB()
{
    __asm mov eax, dword ptr fs:[0x18] ;
    __asm ret ;
}

...

void *teb;
__asm push eax ;
__asm mov eax, dword ptr fs:[0x18] ;
__asm mov teb, eax ;
__asm pop eax ;
printf("%p == %p == %p\n", GetTEB(), teb, __readfsdword(0x18));

And as suggested in the comments, NtCurrentTeb() is provided by the Windows SDK. It most likely just uses __readfsdword.

Upvotes: 3

Related Questions