[PATCH 1/3] Linux: Add the pthread_gettid_np function

Adhemerval Zanella Netto adhemerval.zanella@linaro.org
Tue Mar 11 13:13:30 GMT 2025



On 11/03/25 09:58, enh wrote:
> On Tue, Mar 11, 2025 at 8:54 AM enh <enh@google.com> wrote:
>>
>> On Tue, Mar 11, 2025 at 7:06 AM Florian Weimer <fweimer@redhat.com> wrote:
>>>
>>> There is no good match for this function in other libcs.
>>> Bionic has pthread_gettid without error checking (and without the
>>> _np suffix), but with the same prototype.  Other systems use
>>> a pointer argument for the value.
>>
>> you must have been looking at an 11+ year old version of bionic :-)
>>
>> no LP64 version of Android has pthread_gettid() (though ILP32 will do
>> until it's removed, for app compat), and every version of Android
>> since at least 2014's "L"/api level 21 has pthread_gettid_np().
>>
>> i'm not sure what error checking you think is missing?
> 
> ah, that's probably also an artifact of looking at an ancient
> implementation: i just looked and the historical __pthread_gettid()
> [note the leading underscores, which i'd forgotten about] did indeed
> just cast the pthread_t to the internal thread type and dereference it
> ... though it seems like your implementation does the same? (i know
> glibc has thread caching which bionic doesn't, but i assumed you had
> some cache eviction policy

The thread stack cache does not really prevent corner cases issues
where user would pass an invalid pthread_t to pthread_gettid_np.
Best case the thread stack is still in the cache, but depending of
the cache size and thread creation pattern blindly accessing 
the tid field will just access invalid memory.

So the question is whether we implement something similar to bionic,
and take the dl_stack_cache_lock to check if the pthread_t is 
within dl_stack_cache/dl_stack_user.  This will make the implementation
no async-signal-safe, but at least it would remove the potential UB.
We don't do this for other pthread functions, like pthread_join, but
if the idea is to use pthread_gettid to query the pthread_t lifetime
it would make sense to follow bionic here.


More information about the Libc-alpha mailing list