BaseThreadStart代码分析
第一部分:
在调用CreateThead创建线程的时候,操作系统会为新线程创建线程内核对想象,
线程内核对象包含了线程的上下文(是一个C O N T E X T结构)以及一些其他属性和统计信息,
注意线程是在上下文中运行的,上下文包含了堆栈指针寄存器SP,指令指针寄存器IP,和一些其他的CPU寄存器。
在线程创建的时候,系统会把CreateThread传递进来的线程运行函数和参数一次压栈,
同时会把一个为称为BaseThreadStart的未文档化(和未输出)的函数的地址放入IP寄存器中,
当线程初始化完成并处于可以运行状态时,BaseThreadStart函数就会被执行,
当新线程执行BaseThreadStart函数时,将会出现下列情况:
• 在线程函数中建立一个结构化异常处理(S E H)帧,这样,在线程执行时产生的任何异常情
况都会得到系统的某种默认处理(关于结构化异常处理的详细说明参见第2 3、2 4和2 5章)。
• 系统调用线程函数,并将你传递给CreateThead函数的pvParam参数传递给它。
• 当线程函数返回时, BaseThreadStart调用ExitThread,并将线程函数的返回值传递给它。
该线程内核对象的使用计数被递减,线程停止执行。
• 如果线程产生一个没有处理的异常条件,由BaseThreadStart函数建立的S E H帧将负责处理
该异常条件。通常情况下,这意味着向用户显示一个消息框,并且在用户撤消该消息框时,
BaseThreadStart调用ExitThread,以终止整个进程的运行,而不只是终止线程的运行。
第二部分:
第二部分A:位置
base/win32/client/support.c
第二部分B:代码
VOID
BaseThreadStart(
IN LPTHREAD_START_ROUTINE lpStartAddress,
IN LPVOID lpParameter
)
/*++
Routine Description:
This function is called to start a Win32 thread. Its purpose
is to call the thread, and if the thread returns, to terminate
the thread and delete its stack.
Arguments:
lpStartAddress - Supplies the starting address of the new thread. The
address is logically a procedure that never returns and that
accepts a single 32-bit pointer argument.
lpParameter - Supplies a single parameter value passed to the thread.
Return Value:
None.
--*/
{
try {
//
// test for fiber start or new thread
//
//
// WARNING WARNING DO NOT CHANGE INIT OF NtTib.Version. There is
// external code depending on this initialization !
//
if ( NtCurrentTeb()->NtTib.Version == OS2_VERSION ) {
if ( !BaseRunningInServerProcess ) {
CsrNewThread();
}
}
ExitThread((lpStartAddress)(lpParameter));
}
except(UnhandledExceptionFilter( GetExceptionInformation() )) {
if ( !BaseRunningInServerProcess ) {
ExitProcess(GetExceptionCode());
}
else {
ExitThread(GetExceptionCode());
}
}
}
第三部分:
NTSTATUS
CsrNewThread (
VOID
)
/*++
Routine Description:
This function is called by each new thread (except the first thread in
a process). Its function is to call the subsystem to notify it that
a new thread is starting.
Arguments:
None.
Return Value:
Status Code from either client or server
--*/
{
return NtRegisterThreadTerminatePort (CsrPortHandle);
}