在 OS X pthreads 实现 ( http://www.opensource.apple.com/source/Libc/Libc-825.26/pthreads/thread_setup.c?txt ) 中,它们在线程堆栈上提供了一个伪造的返回地址(第 140 行):
ts->rip = (uintptr_t) routine;
/*
** We need to simulate a 16-byte aligned stack frame as if we had
** executed a call instruction. The stack should already be aligned
** before it comes to us and we don't need to push any arguments,
** so we shouldn't need to change it.
*/
ts->rdi = (uintptr_t) thread; /* argument to function */
*--sp = 0; /* fake return address */
ts->rsp = (uintptr_t) sp; /* set stack pointer */
我不明白当线程正在执行的函数调用“ret”并从堆栈中弹出返回地址时,这如何不会因非法指令/段错误而崩溃。谁能解释一下如何预防/处理这种情况?
最佳答案
在不查看其余代码的情况下,我只能大胆猜测。我的直觉告诉我,被调用的线程过程(用户提供的 start_routine
参数)应该永远返回到调用函数。
想一想:如果新线程确实返回,那么您将有两个线程在相同的原始代码路径上运行。我想象实际调用的线程函数是一个调用用户提供的start_routine
的包装器。当 start_routine
返回时,包装器然后调用 pthread_exit
。
(main thread)
v
pthread_create
v
thread_setup (sets up stack), and spawns new thread
v |
return to main thread |
|
|
v
wrapper_function
v
user-supplied start_routine
| (returns)
v
wrapper_function calls
v
pthread_exit
同样,这只是一个猜测,但重点是,新线程永远不应该返回到调用 pthread_create
的代码。包装器的目的是确保调用pthread_exit
。
我必须看看它们作为例程
传递给thread_setup
的内容。
我的感受被以下事实所证实:you don't have to call pthread_exit
.
关于macos - Mac OS X pthreads 假返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16350187/