从FS寄存器获取当前线程ID
int GetThreadId()
{
int ithread = 0;
_asm{
xor esi , esi
mov eax, fs:[esi+18h]
mov ecx, [eax+ 20h]
mov eax, [eax+ 24h]
mov dword ptr[ithread], eax
}
return ithread;
}
从FS寄存器获取当前进程ID
int GetProcessId()
{
int iProcess = 0;
_asm{
xor esi , esi
mov eax, fs:[esi+18h]
mov ecx, [eax+ 20h]
mov eax, [eax+ 24h]
mov dword ptr[iProcess ], ecx
}
return iProcess ;
}
原理:
1.fs:18h 地址指向线程环境块_TEB
打开windbg可以证明:
0:028> dd fs:18h L1
0053:00000018 7eeb8000
0:028> !teb
TEB at 7eeb8000
ExceptionList: 1f8ff15c
StackBase: 1f900000
StackLimit: 1f8fc000
SubSystemTib: 00000000
FiberData: 00001e00
ArbitraryUserPointer: 00000000
Self: 7eeb8000
EnvironmentPointer: 00000000
ClientId: 00001a30 . 00001408
RpcHandle: 00000000
Tls Storage: 133d2718
PEB Address: 7efde000
LastErrorValue: 0
LastStatusValue: c0000302
Count Owned Locks: 0
HardErrorMode: 0
2. 在_TEB中找到线程ID和进程ID
0:028> dt ntdll!_TEB
+0x000 NtTib : _NT_TIB
+0x01c EnvironmentPointer : Ptr32 Void
+0x020 ClientId : _CLIENT_ID
0:028> dt ntdll!_CLIENT_ID
+0x000 UniqueProcess : Ptr32 Void >进程ID
+0x004 UniqueThread : Ptr32 Void >线程ID
当然从TEB又可以找到_PEB的地址,从_PEB里面可以获取到更多的信息。暂且搁笔~~
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)