Addresses of Thread Local Storage Variables

故事扮演 提交于 2019-11-30 21:53:50

For x86 at least, TLS is performed using segment registers. The default segment register %ds is implicit in instructions that address memory. When accessing TLS, a thread uses another segment register - %gs for i386 and %fs for x86-64 - which is saved/restored when a thread is scheduled, just as other registers are in a context switch.

So a process-wide variable might be accessed with something like:

mov (ADDR) -> REG ; load memory `myVar` to REG.

which is implicitly:

mov %DS:(ADDR) -> REG

For TLS, the compiler generates:

mov %FS:(ADDR) -> REG ; load thread-local address `myVar` to REG.

In effect, even if the address of the variable appears to be the same in different threads, e.g.,

fprintf(stdout, "%p\n", & myVar); /* in separate threads... */

the fact each thread is using a different value for the segment register, means that they map to different regions of physical memory. If you were to pass an address from one thread to another, you couldn't access the memory it represents in the first thread - a different segment register value is in effect in the second thread.

The same scheme is used by Windows (it may interchange the roles of %fs and %gs - not sure), and OS X. As for other architectures, there's an in-depth technical guide to TLS for the ELF ABI. It's missing a discussion of the ARM architecture, and has details on IA-64 and Alpha, so it's showing its age.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!