macos - Mac OS X pthreads 假返回地址

标签 macos pthreads mach

在 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/

相关文章:

macos -/usr/include 中的 mach 头文件和 SDK 中的 mach 头文件有什么区别?

macos - cocoa:以退格键作为等效键的菜单栏项

objective-c - MacOS:UDP/TCP 数据包之间出现奇怪的延迟

c - 为什么在以下代码中将结构传递给线程会导致段错误?

c - 第一个线程未使用给定参数运行

iOS UI 测试链接器错误

objective-c - 即使我显式释放它,循环中的 NSMutableArray 也会泄漏内存

java - gradle:在远程计算机上执行时找不到命令

C - ncurses 和两个并发线程

kernel - Mac OS X 内核扩展 CPU 选择