Hacky ways to retrieve data from thread local storage

170 Views Asked by At

I've learned something about thread local storage(TLS). From my point of view, this is a totally black box - you give it a key, and it gives you the thread local data back. No idea what the key is like and where these local data is saved.

Recently I've found some hacky ways to retrieve TLS data, but couldn't figure out how they work.

  1. In project async-profiler(at src/vmStructs.cpp line:347), pthread key is an int, why? I read the source code about pthread manipulation of Hotspot JVM and didn't find any clue. Hotspot doesn't specify the type of pthread key (and I don't think it can either). And why we could guarantee to find the pthread key with just a simple integer loop? Not sure this is a TLS question or a Hotspot question. :( enter image description here

  2. pthread_tis an address of pthread. I think it points to some OS thread instance that we may not parse it directly. But, according to Phoenix87's answer, we could regard pthread_t as an address of pthread_t list in which we could find TID(the return of gettid()) with a simple loop (a simple loop, again). You could find it in Austin (at src/linux/py_proc.h line: 613). How does it work? enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

Both of these make assumptions about the pthread implementation they are working on.

Such assumptions are not warranted in general, and are almost guaranteed to break with a different implementation.

Don't write code like that unless absolutely necessary, and if you do write code like that, please clearly state exactly which implementation(s) and which versions you support.