[sanitizer_common][Darwin] Fix TLS base and size on arm64 (#242018)

On arm64 Darwin, GetThreadStackAndTls() returns an empty TLS range, so
LSan
never scans a thread's TSD. Memory that is only referenced from a live
thread's TSD is then reported as leaked, for example
pthread_setspecific()
values or the continuation cache libdispatch keeps in a worker thread.

There are two bugs. TlsBaseAddr() reads TPIDRRO_EL0 and then does
`segbase &= 0x07ul`, which keeps the low 3 bits instead of clearing
them.
TlsSize() returns 0 on arm64, so the bad base was never used. The mask
was
added in 443820179a.

Up to xnu-7195 (macOS 11), xnu's `_os_tsd_get_base()` also cleared the
low
3 bits of TPIDRRO_EL0, which held the CPU number. Since xnu-8019 (macOS
12)
it uses the register as is. The TSD array is 16-byte aligned, so
clearing
the bits is correct on both.

TlsSize() now returns the size of the TSD array on arm64. The slot count
is
`_INTERNAL_POSIX_THREAD_KEYS_END` from libpthread's
src/types_internal.h:
768 on macOS (512 external + 256 internal keys) and 512 on iOS-like
devices
(256 + 256). It has not changed since macOS 11. `tsd` is the last member
of
`struct pthread_s`, so the range does not go past the struct.

ASan and TSan also use this range. ASan clears its shadow when a thread
starts and ends, and TSan marks it as written when a thread starts. With
this patch they do that on arm64 too, as on x86_64.

Testing: on Apple platforms TestThreadInfo now creates every pthread key
it
can and checks that the range holds each one's slot. On arm64 it also
checks
that the range is exactly the TSD: its first slot holds pthread_self()
and
its last slot is a key's. It fails on macOS arm64 without this patch.
With
the LSan lit tests enabled locally for arm64, many_tls_keys_pthread.cpp
and
many_tls_keys_thread.cpp now pass, standalone and with ASan. No new
failures
in check-asan, check-tsan and check-sanitizer.

Assisted-by: Claude
GitOrigin-RevId: 4a3ac30a53ba0417941cab04f51c6ce8a8a67feb
2 files changed