Rich Felker [Sun, 5 May 2019 15:10:42 +0000 (11:10 -0400)]
fix build regression on mips n32 due to typo in new inline syscall
commit
1bcdaeee6e659f1d856717c9aa562a068f2f3bd4 introduced the
regression.
Rich Felker [Sun, 5 May 2019 14:52:41 +0000 (10:52 -0400)]
fix passing of 64-bit syscall arguments on microblaze
this has been wrong since the beginning of the microblaze port: the
syscall ABI for microblaze does not align 64-bit arguments on even
register boundaries. commit
788d5e24ca19c6291cebd8d1ad5b5ed6abf42665
exposed the problem by introducing references to a nonexistent
__syscall7. the ABI is not documented well anywhere, but I was able to
confirm against both strace source and glibc source that microblaze is
not using the alignment.
per the syscall(2) man page, posix_fadvise, ftruncate, pread, pwrite,
readahead, sync_file_range, and truncate were all affected and either
did not work at all, or only worked by chance, e.g. when the affected
argument slots were all zero.
Rich Felker [Tue, 23 Apr 2019 16:57:16 +0000 (12:57 -0400)]
fix regression in s390x SO_PEERSEC definition
analogous to commit
efda534b212f713fe2b92a62b06e45f656b763ce for
powerpc. commit
587f5a53bc3a68d80b239ba515d583df690a96df moved the
definition of SO_PEERSEC to bits/socket.h for archs where the SO_*
macros differ.
Rich Felker [Sat, 20 Apr 2019 22:53:00 +0000 (18:53 -0400)]
make new math code compatible with unused variable warning/error
commit
b50d315fd23f0fbc4c11e2583801dd123d933745 introduced
fp_force_eval implemented by default with a dead store to a volatile
variable. unfortunately introduces warnings with -Wunused-variable and
breaks the ability to use -Werror with the default warning options set
by configure when warnings are enabled.
we could just call fp_barrier instead, but that results in a spurious
load after the store due to volatile semantics.
the fix committed here avoids the load. it will still produce warnings
without -Wno-unused-but-set-variable, but that's part of our default
warning profile, and there are already other locations in the source
where an unused variable warning will occur without it.
Szabolcs Nagy [Sat, 1 Dec 2018 01:09:01 +0000 (01:09 +0000)]
math: new pow
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
The underflow exception is signaled if the result is in the subnormal
range even if the result is exact.
code size change: +3421 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
pow rthruput: 102.96 ns/call 33.38 ns/call 3.08x
pow latency: 144.37 ns/call 54.75 ns/call 2.64x
-O3:
pow rthruput: 98.91 ns/call 32.79 ns/call 3.02x
pow latency: 138.74 ns/call 53.78 ns/call 2.58x
Szabolcs Nagy [Fri, 30 Nov 2018 21:39:47 +0000 (21:39 +0000)]
math: new exp and exp2
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
TOINT_INTRINSICS and EXP_USE_TOINT_NARROW cases are unused.
The underflow exception is signaled if the result is in the subnormal
range even if the result is exact (e.g. exp2(-1023.0)).
code size change: -1672 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
exp rthruput: 12.73 ns/call 6.68 ns/call 1.91x
exp latency: 45.78 ns/call 21.79 ns/call 2.1x
exp2 rthruput: 6.35 ns/call 5.26 ns/call 1.21x
exp2 latency: 26.00 ns/call 16.58 ns/call 1.57x
-O3:
exp rthruput: 12.75 ns/call 6.73 ns/call 1.89x
exp latency: 45.91 ns/call 21.80 ns/call 2.11x
exp2 rthruput: 6.47 ns/call 5.40 ns/call 1.2x
exp2 latency: 26.03 ns/call 16.54 ns/call 1.57x
Szabolcs Nagy [Sat, 1 Dec 2018 00:53:54 +0000 (00:53 +0000)]
math: new log2
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
code size change: +2458 bytes (+1524 bytes with fma).
benchmark on x86_64 before, after, speedup:
-Os:
log2 rthruput: 16.08 ns/call 10.49 ns/call 1.53x
log2 latency: 44.54 ns/call 25.55 ns/call 1.74x
-O3:
log2 rthruput: 15.92 ns/call 10.11 ns/call 1.58x
log2 latency: 44.66 ns/call 26.16 ns/call 1.71x
Szabolcs Nagy [Sat, 1 Dec 2018 00:40:47 +0000 (00:40 +0000)]
math: new log
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
Assume __FP_FAST_FMA implies __builtin_fma is inlined as a single
instruction.
code size change: +4588 bytes (+2540 bytes with fma).
benchmark on x86_64 before, after, speedup:
-Os:
log rthruput: 12.61 ns/call 7.95 ns/call 1.59x
log latency: 41.64 ns/call 23.38 ns/call 1.78x
-O3:
log rthruput: 12.51 ns/call 7.75 ns/call 1.61x
log latency: 41.82 ns/call 23.55 ns/call 1.78x
Szabolcs Nagy [Sun, 22 Oct 2017 18:32:47 +0000 (18:32 +0000)]
math: new powf
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
POWF_SCALE != 1.0 case only matters if TOINT_INTRINSICS is set, which
is currently not supported for any target.
SNaN is not supported, it would require an issignalingf
implementation.
code size change: -816 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
powf rthruput: 95.14 ns/call 20.04 ns/call 4.75x
powf latency: 137.00 ns/call 34.98 ns/call 3.92x
-O3:
powf rthruput: 92.48 ns/call 13.67 ns/call 6.77x
powf latency: 131.11 ns/call 35.15 ns/call 3.73x
Szabolcs Nagy [Sun, 22 Oct 2017 18:06:00 +0000 (18:06 +0000)]
math: new exp2f and expf
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
In expf TOINT_INTRINSICS is kept, but is unused, it would require support
for __builtin_round and __builtin_lround as single instruction.
code size change: +94 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
expf rthruput: 9.19 ns/call 8.11 ns/call 1.13x
expf latency: 34.19 ns/call 18.77 ns/call 1.82x
exp2f rthruput: 5.59 ns/call 6.52 ns/call 0.86x
exp2f latency: 17.93 ns/call 16.70 ns/call 1.07x
-O3:
expf rthruput: 9.12 ns/call 4.92 ns/call 1.85x
expf latency: 34.44 ns/call 18.99 ns/call 1.81x
exp2f rthruput: 5.58 ns/call 4.49 ns/call 1.24x
exp2f latency: 17.95 ns/call 16.94 ns/call 1.06x
Szabolcs Nagy [Sun, 22 Oct 2017 17:39:36 +0000 (17:39 +0000)]
math: new log2f
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc
code size change: +177 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
log2f rthruput: 11.38 ns/call 5.99 ns/call 1.9x
log2f latency: 35.01 ns/call 22.57 ns/call 1.55x
-O3:
log2f rthruput: 10.82 ns/call 5.58 ns/call 1.94x
log2f latency: 35.13 ns/call 21.04 ns/call 1.67x
Szabolcs Nagy [Sun, 22 Oct 2017 14:19:20 +0000 (14:19 +0000)]
math: new logf
from https://github.com/ARM-software/optimized-routines,
commit
04884bd04eac4b251da4026900010ea7d8850edc,
with minor changes to better fit into musl.
code size change: +289 bytes.
benchmark on x86_64 before, after, speedup:
-Os:
logf rthruput: 8.40 ns/call 6.14 ns/call 1.37x
logf latency: 31.79 ns/call 24.33 ns/call 1.31x
-O3:
logf rthruput: 8.43 ns/call 5.58 ns/call 1.51x
logf latency: 32.04 ns/call 20.88 ns/call 1.53x
Szabolcs Nagy [Sun, 2 Dec 2018 18:53:37 +0000 (18:53 +0000)]
math: add configuration macros
Musl currently aims to support non-nearest rounding mode and does not
support SNaNs. These macros allow marking relevant code paths in case
these decisions are changed later (they also help documenting the
corner cases involved).
Szabolcs Nagy [Thu, 29 Nov 2018 23:33:40 +0000 (23:33 +0000)]
math: add macros for static branch prediction hints
These don't have an effectw with -Os so not useful with default settings
other than documenting the expectation.
With --enable-optimize=internal,malloc,string,math the libc.so code size
increases by 18K on x86_64 and performance varies in -2% .. +10%.
Szabolcs Nagy [Fri, 30 Nov 2018 21:15:23 +0000 (21:15 +0000)]
math: add double precision error handling functions
Szabolcs Nagy [Sun, 22 Oct 2017 13:51:35 +0000 (13:51 +0000)]
math: add single precision error handling functions
These are supposed to be used in tail call positions when handling
special cases in new code. (fp exceptions may be raised "naturally"
by the common code path if special casing is more effort.)
This implements the error handling apis used in
https://github.com/ARM-software/optimized-routines
without errno setting.
Szabolcs Nagy [Sat, 1 Dec 2018 23:52:34 +0000 (23:52 +0000)]
math: add eval_as_float and eval_as_double
Previously type casts or assignments were used for handling excess
precision, which assumed standard C99 semantics, but since it's a
rarely needed obscure detail, it's better to use explicit helper
functions to document where we rely on this. It also helps if the
code is used outside of the libc in non-C99 compilation mode: with the
default excess precision handling of gcc, explicit inline asm barriers
are needed for narrowing on FLT_EVAL_METHOD!=0 targets.
I plan to use this in new code with the existing style that uses
double_t and float_t as much as possible.
One ugliness is that it is required for almost every return statement
since that does not drop excess precision (the standard changed this
in C11 annex F, but that does not help in non-standard compilation
modes or with old compilers).
Szabolcs Nagy [Mon, 26 Nov 2018 23:30:00 +0000 (23:30 +0000)]
math: add fp_arch.h with fp_barrier and fp_force_eval
C99 has ways to support fenv access, but compilers don't implement it
and assume nearest rounding mode and no fp status flag access. (gcc has
-frounding-math and then it does not assume nearest rounding mode, but
it still assumes the compiled code itself does not change the mode.
Even if the C99 mechanism was implemented it is not ideal: it requires
all code in the library to be compiled with FENV_ACCESS "on" to make it
usable in non-nearest rounding mode, but that limits optimizations more
than necessary.)
The math functions should give reasonable results in all rounding modes
(but the quality may be degraded in non-nearest rounding modes) and the
fp status flag settings should follow the spec, so fenv side-effects are
important and code transformations that break them should be prevented.
Unfortunately compilers don't give any help with this, the best we can
do is to add fp barriers to the code using volatile local variables
(they create a stack frame and undesirable memory accesses to it) or
inline asm (gcc specific, requires target specific fp reg constraints,
often creates unnecessary reg moves and multiple barriers are needed to
express that an operation has side-effects) or extern call (only useful
in tail-call position to avoid stack-frame creation and does not work
with lto).
We assume that in a math function if an operation depends on the input
and the output depends on it, then the operation will be evaluated at
runtime when the function is called, producing all the expected fenv
side-effects (this is not true in case of lto and in case the operation
is evaluated with excess precision that is not rounded away). So fp
barriers are needed (1) to prevent the move of an operation within a
function (in case it may be moved from an unevaluated code path into an
evaluated one or if it may be moved across a fenv access), (2) force the
evaluation of an operation for its side-effect when it has no input
dependency (may be constant folded) or (3) when its output is unused. I
belive that fp_barrier and fp_force_eval can take care of these and they
should not be needed in hot code paths.
Szabolcs Nagy [Thu, 29 Nov 2018 22:25:38 +0000 (22:25 +0000)]
math: remove sun copyright from libm.h
Nothing is left from the original fdlibm header nor from the bsd
modifications to it other than some internal api declarations.
Comments are dropped that may be copyrightable content.
Szabolcs Nagy [Sat, 21 Oct 2017 21:09:02 +0000 (21:09 +0000)]
math: add asuint, asuint64, asfloat and asdouble
Code generation for SET_HIGH_WORD slightly changes, but it only affects
pow, otherwise the generated code is unchanged.
Szabolcs Nagy [Thu, 29 Nov 2018 22:09:53 +0000 (22:09 +0000)]
math: move complex math out of libm.h
This makes it easier to build musl math code with a compiler that
does not support complex types (tcc) and in general more sensible
factorization of the internal headers.
Szabolcs Nagy [Tue, 16 Oct 2018 22:20:39 +0000 (22:20 +0000)]
define FP_FAST_FMA* when fma* can be inlined
FP_FAST_FMA can be defined if "the fma function generally executes about
as fast as, or faster than, a multiply and an add of double operands",
which can only be true if the fma call is inlined as an instruction.
gcc sets __FP_FAST_FMA if __builtin_fma is inlined as an instruction,
but that does not mean an fma call will be inlined (e.g. it is defined
with -fno-builtin-fma), other compilers (clang) don't even have such
macro, but this is the closest we can get.
(even if the libc fma implementation is a single instruction, the extern
call overhead is already too big when the macro is used to decide between
x*y+z and fma(x,y,z) so it cannot be based on libc only, defining the
macro unconditionally on targets which have fma in the base isa is also
incorrect: the compiler might not inline fma anyway.)
this solution works with gcc unless fma inlining is explicitly turned off.
A. Wilcox [Wed, 13 Mar 2019 16:16:11 +0000 (11:16 -0500)]
fcntl.h: define O_TTY_INIT to 0
POSIX: "[If] either O_TTY_INIT is set in oflag or O_TTY_INIT has the
value zero, open() shall set any non-standard termios structure
terminal parameters to a state that provides conforming behavior."
The Linux kernel tty drivers always perform initialisation on their
devices to set known good termios values during the open(2) call. This
means that setting O_TTY_INIT to zero is conforming.
Rich Felker [Thu, 11 Apr 2019 00:11:19 +0000 (20:11 -0400)]
remove external __syscall function and last remaining users
the weak version of __syscall_cp_c was using a tail call to __syscall
to avoid duplicating the 6-argument syscall code inline in small
static-linked programs, but now that __syscall no longer exists, the
inline expansion is no longer duplication.
the syscall.h machinery suppported up to 7 syscall arguments, only via
an external __syscall function, but we presently have no syscall call
points that actually make use of that many, and the kernel only
defines 7-argument calling conventions for arm, powerpc (32-bit), and
sh. if it turns out we need them in the future, they can easily be
added.
Rich Felker [Wed, 10 Apr 2019 23:51:47 +0000 (19:51 -0400)]
implement inline 5- and 6-argument syscalls for mipsn32 and mips64
n32 and n64 ABIs add new argument registers vs o32, so that passing on
the stack is not necessary, so it's not clear why the 5- and
6-argument versions were special-cased to begin with; it seems to have
been pattern-copying from arch/mips (o32).
i've treated the new argument registers like the first 4 in terms of
clobber status (non-clobbered). hopefully this is correct.
Rich Felker [Wed, 10 Apr 2019 23:45:17 +0000 (19:45 -0400)]
cleanup mips64 syscall_arch functions
Rich Felker [Wed, 10 Apr 2019 23:23:15 +0000 (19:23 -0400)]
implement inline 5- and 6-argument syscalls for mips
the OABI passes these on the stack, using the convention that their
position on the stack is as if the first four arguments (in registers)
also had stack slots. originally this was deemed too awkward to do
inline, falling back to external __syscall, but it's not that bad and
now that external __syscall is being removed, it's necessary.
Rich Felker [Wed, 10 Apr 2019 22:34:38 +0000 (18:34 -0400)]
use inline syscalls for powerpc (32-bit)
the inline syscall code is copied directly from powerpc64. the extent
of register clobber specifiers may be excessive on both; if that turns
out to be the case it can be fixed later.
Rich Felker [Wed, 10 Apr 2019 22:07:51 +0000 (18:07 -0400)]
remove cruft for supposedly-buggy clang from or1k & microblaze syscall_arch
it was never demonstrated to me that this workaround was needed, and
seems likely that, if there ever was any clang version for which it
was needed, it's old enough to be unusably buggy in other ways. if it
turns out some compilers actually can't do the register allocation
right, we'll need to replace this with inline shuffling code, since
the external __syscall dependency is being removed.
Rich Felker [Wed, 10 Apr 2019 21:10:36 +0000 (17:10 -0400)]
overhaul i386 syscall mechanism not to depend on external asm source
this is the first part of a series of patches intended to make
__syscall fully self-contained in the object file produced using
syscall.h, which will make it possible for crt1 code to perform
syscalls.
the (confusingly named) i386 __vsyscall mechanism, which this commit
removes, was introduced before the presence of a valid thread pointer
was mandatory; back then the thread pointer was setup lazily only if
threads were used. the intent was to be able to perform syscalls using
the kernel's fast entry point in the VDSO, which can use the sysenter
(Intel) or syscall (AMD) instruction instead of int $128, but without
inlining an access to the __syscall global at the point of each
syscall, which would incur a significant size cost from PIC setup
everywhere. the mechanism also shuffled registers/calling convention
around to avoid spills of call-saved registers, and to avoid
allocating ebx or ebp via asm constraints, since there are plenty of
broken-but-supported compiler versions which are incapable of
allocating ebx with -fPIC or ebp with -fno-omit-frame-pointer.
the new mechanism preserves the properties of avoiding spills and
avoiding allocation of ebx/ebp in constraints, but does it inline,
using some fairly simple register shuffling, and uses a field of the
thread structure rather than global data for the vdso-provided syscall
code address.
for now, the external __syscall function is refactored not to use the
old __vsyscall so it can be kept, but the intent is to remove it too.
Rich Felker [Wed, 10 Apr 2019 00:39:21 +0000 (20:39 -0400)]
release 1.1.22
Rich Felker [Tue, 9 Apr 2019 21:51:54 +0000 (17:51 -0400)]
in membarrier fallback, allow for possibility that sigaction fails
this is a workaround to avoid a crashing regression on qemu-user when
dynamic TLS is installed at dlopen time. the sigaction syscall should
not be able to fail, but it does fail for implementation-internal
signals under qemu user-level emulation if the host libc qemu is
running under reserves the same signals for implementation-internal
use, since qemu makes no provision to redirect/emulate them. after
sigaction fails, the subsequent tkill would terminate the process
abnormally as the default action.
no provision to account for membarrier failing is made in the dynamic
linker code that installs new TLS. at the formal level, the missing
barrier in this case is incorrect, and perhaps we should fail the
dlopen operation, but in practice all the archs we support (and
probably all real-world archs except alpha, which isn't yet supported)
should give the right behavior with no barrier at all as a consequence
of consume-order properties.
in the long term, this workaround should be supplemented or replaced
by something better -- a different fallback approach to ensuring
memory consistency, or dynamic allocation of implementation-internal
signals. the latter is appealing in that it would allow cancellation
to work under qemu-user too, and would even allow many levels of
nested emulation.
Ilya Matveychikov [Sat, 9 Feb 2019 14:56:17 +0000 (18:56 +0400)]
fix the use of syscall result in dl_mmap
Bobby Bingham [Fri, 5 Apr 2019 17:26:17 +0000 (12:26 -0500)]
fix signature of function accepted by makecontext
This parameter was incorrectly declared to be a pointer to a function
accepting zero parameters. The intent of makecontext is that it is
possible to pass integer parameters to the function, so this should
have been a pointer to a function accepting an unspecified set of
parameters.
Dan Gohman [Wed, 3 Apr 2019 12:48:50 +0000 (05:48 -0700)]
fix unintended global symbols in atanl.c
Mark atanhi, atanlo, and aT in atanl.c as static, as they're not
intended to be part of the public API.
These are already static in the LDBL_MANT_DIG == 64 code, so this
patch is just making the LDBL_MANT_DIG == 113 code do the same thing.
Frediano Ziglio [Tue, 26 Mar 2019 09:36:47 +0000 (09:36 +0000)]
use __strchrnul instead of strchr and strlen in execvpe
The result is the same but takes less code.
Note that __execvpe calls getenv which calls __strchrnul so even
using static output the size of the executable won't grow.
Ray [Wed, 13 Mar 2019 10:12:17 +0000 (10:12 +0000)]
delete a redundant if in dynamic linker ctor execution loop
Rich Felker [Mon, 1 Apr 2019 22:51:50 +0000 (18:51 -0400)]
fix harmless-by-chance typo in priority inheritance mutex code
commit
54ca677983d47529bab8752315ac1a2b49888870 inadvertently
introduced bitwise and where logical and was intended. since the
right-hand operand is always 0 or -1 whenever the left-hand operand is
nonzero, the behavior happened to be equivalent.
Rich Felker [Sun, 31 Mar 2019 22:03:27 +0000 (18:03 -0400)]
implement priority inheritance mutexes
priority inheritance is a feature to mitigate priority inversion
situations, where a execution of a medium-priority thread can
unboundedly block forward progress of a high-priority thread when a
lock it needs is held by a low-priority thread.
the natural way to do priority inheritance would be with a simple
futex flag to donate the calling thread's priority to a target thread
while it waits on the futex. unfortunately, linux does not offer such
an interface, but instead insists on implementing the whole locking
protocol in kernelspace with special futex commands that exist solely
for the purpose of doing PI mutexes. this would require the entire
"trylock" logic to be duplicated in the timedlock code path for PI
mutexes, since, once the previous lock holder releases the lock and
the futex call returns, the lock is already held by the caller.
obviously such code duplication is undesirable.
instead, I've made the PI timedlock success path set the mutex lock
count to -1, which can be thought of as "not yet complete", since a
lock count of 0 is "locked, with no recursive references". a simple
branch in a non-hot path of pthread_mutex_trylock can then see and act
on this state, skipping past the code that would check and take the
lock to the same code path that runs after the lock is obtained for a
non-PI mutex.
because we're forced to let the kernel perform the actual lock and
unlock operations whenever the mutex is contended, we have to patch
things up when it does the wrong thing:
1. the lock operation is not aware of whether the mutex is
error-checking, so it will always fail with EDEADLK rather than
deadlocking.
2. the lock operation is not aware of whether the mutex is robust, so
it will successfully obtain mutexes in the owner-died state even if
they're non-robust, whereas this operation should deadlock.
3. the unlock operation always sets the lock value to zero, whereas
for robust mutexes, we want to set it to a special value indicating
that the mutex obtained after its owner died was unlocked without
marking it consistent, so that future operations all fail with
ENOTRECOVERABLE.
the first of these is easy to solve, just by performing a futex wait
on a dummy futex address to simulate deadlock or ETIMEDOUT as
appropriate. but problems 2 and 3 interact in a nasty way. to solve
problem 2, we need to back out the spurious success. but if waiters
are present -- which we can't just ignore, because even if we don't
want to wake them, the calling thread is incorrectly inheriting their
priorities -- this requires using the kernel's unlock operation, which
will zero the lock value, thereby losing the "owner died with lock
held" state.
to solve these problems, we overload the mutex's waiters field, which
is unused for PI mutexes since they don't call the normal futex wait
functions, as an indicator that the PI mutex is permanently
non-lockable. originally I wanted to use the count field, but there is
one code path that needs to access this flag without synchronization:
trylock's CAS failure path needs to be able to decide whether to fail
with EBUSY or ENOTRECOVERABLE, the waiters field is already treated as
a relaxed-order atomic in our memory model, so this works out nicely.
Rich Felker [Fri, 29 Mar 2019 19:49:14 +0000 (15:49 -0400)]
clean up access to mutex type in pthread_mutex_trylock
there was no point in masking off the pshared bit when first loading
the type, since every subsequent access involves a mask anyway. not
masking it may avoid a subsequent load to check the pshared flag, and
it's just simpler.
Drew DeVault [Thu, 21 Mar 2019 15:32:39 +0000 (11:32 -0400)]
support archs with no renameat syscall, only renameat2
Drew DeVault [Thu, 21 Mar 2019 15:32:38 +0000 (11:32 -0400)]
support archs with no mlock syscall, only mlock2
Rich Felker [Thu, 21 Mar 2019 17:58:12 +0000 (13:58 -0400)]
fix data race choosing next key slot in pthread_key_create
commit
84d061d5a31c9c773e29e1e2b1ffe8cb9557bc58 wrongly moved the
access to the global next_key outside of the scope of the lock. the
error manifested as spurious failure to find an available key slot
under concurrent calls to pthread_key_create, since the stopping
condition could be met after only a small number of slots were
examined.
Rich Felker [Fri, 15 Mar 2019 00:52:18 +0000 (20:52 -0400)]
fix crash/out-of-bound read in sscanf
commit
d6c855caa88ddb1ab6e24e23a14b1e7baf4ba9c7 caused this
"regression", though the behavior was undefined before, overlooking
that f->shend=0 was being used as a sentinel for "EOF" status (actual
EOF or hitting the scanf field width) of the stream helper (shgetc)
functions.
obviously the shgetc macro could be adjusted to check for a null
pointer in addition to the != comparison, but it's the hot path, and
adding extra code/branches to it begins to defeat the purpose.
so instead of setting shend to a null pointer to block further reads,
which no longer works, set it to the current position (rpos). this
makes the shgetc macro work with no change, but it breaks shunget,
which can no longer look at the value of shend to determine whether to
back up. Szabolcs Nagy suggested a solution which I'm using here:
setting shlim to a negative value is inexpensive to test at shunget
time, and automatically re-trips the cnt>=shlim stop condition in
__shgetc no matter what the original limit was.
Rich Felker [Thu, 14 Mar 2019 03:23:26 +0000 (23:23 -0400)]
fix namespace violation in dependencies of mtx_lock
commit
2de29bc994029b903a366b8a4a9f8c3c3ee2be90 left behind one
reference to pthread_mutex_trylock. fixing this also improves code
generation due to the namespace-safe version being hidde.
Szabolcs Nagy [Thu, 7 Mar 2019 21:58:12 +0000 (21:58 +0000)]
aarch64: add HWCAP_ definitions from linux v5.0
HWCAP_SB - speculation barrier instruction available added in linux
commit
bd4fb6d270bc423a9a4098108784f7f9254c4e6d
HWCAP_PACA, HWCAP_PACG - pointer authentication instructions available
(address and generic) added in linux commit
7503197562567b57ec14feb3a9d5400ebc56812f
Szabolcs Nagy [Thu, 7 Mar 2019 21:53:48 +0000 (21:53 +0000)]
sys/prctl.h: add PR_PAC_RESET_KEYS from linux v5.0
aarch64 pointer authentication code related prctl that allows
reinitializing the key for the thread, added in linux commit
ba830885656414101b2f8ca88786524d4bb5e8c1
Szabolcs Nagy [Thu, 7 Mar 2019 21:43:45 +0000 (21:43 +0000)]
elf.h: add NT_ definitions from linux v5.0
NT_MIPS_MSA for ptrace access to mips simd arch reg set, added in linux
commit
3cd640832894b85b5929d5bda74505452c800421
NT_ARM_PAC_MASK for ptrace access to pointer auth code mask, added in
commit
ec6e822d1a22d0eef1d1fa260dff751dba9a4258
Szabolcs Nagy [Thu, 7 Mar 2019 21:29:40 +0000 (21:29 +0000)]
elf.h: update with C-SKY definitions
C-SKY support was added to binutils 2.32 in commit
b8891f8d622a31306062065813fc278d8a94fe21
the elf.h change was added to glibc 2.29 in commit
4975f0c3d0131fdf697be0b1631c265e5fd39088
Szabolcs Nagy [Thu, 7 Mar 2019 21:07:45 +0000 (21:07 +0000)]
aarch64, or1k: add kexec_file_load syscall number from linux v5.0
added in linux commit
4e21565b7fd4d9045765f697887e74a704135fe2
Szabolcs Nagy [Wed, 6 Mar 2019 22:30:30 +0000 (22:30 +0000)]
netinet/tcp.h: add TCP_NLA_SRTT from linux v5.0
smoothed RTT for SCM_TIMESTAMPING_OPT_STATS control messages.
added in linux commit
e8bd8fca6773ef49390269bd467bf940a0841ccf
Szabolcs Nagy [Wed, 6 Mar 2019 22:24:05 +0000 (22:24 +0000)]
netinet/udp.h: add UDP_GRO from linux v5.0
sockopt to enable gro for udp.
added in linux commit
e20cf8d3f1f763ad28a9cb3b41305b8a8a42653e
Szabolcs Nagy [Sun, 24 Feb 2019 17:54:33 +0000 (17:54 +0000)]
powerpc: add PTRACE_SYSEMU from linux v4.20
added in linux commit
5521eb4bca2db733952f068c37bdf3cd656ad23c
Szabolcs Nagy [Sun, 24 Feb 2019 17:27:39 +0000 (17:27 +0000)]
aarch64: add HWCAP_SSBS from linux v4.20
for armv8.5 speculative store bypass PSTATE bit support,
added in linux commit
d71be2b6c0e19180b5f80a6d42039cc074a693a2
Szabolcs Nagy [Wed, 23 Jan 2019 21:18:55 +0000 (21:18 +0000)]
bits/ioctl.h: add TIOC{G,S}ISO7816 from linux v4.20
ISO7816 smart cards ioctls.
linux commit
ad8c0eaa0a418ae8ef3f9217638bb86439399eac
the actual kernel definitions are
#define TIOCGISO7816 _IOR('T', 0x42, struct serial_iso7816)
#define TIOCSISO7816 _IOWR('T', 0x43, struct serial_iso7816)
where struct serial_iso7816 is defined in linux/serial.h as
struct serial_iso7816 {
__u32 flags;
__u32 tg;
__u32 sc_fi;
__u32 sc_di;
__u32 clk;
__u32 reserved[5];
};
Szabolcs Nagy [Wed, 23 Jan 2019 20:50:55 +0000 (20:50 +0000)]
sys/prctl.h: add PR_SPEC_INDIRECT_BRANCH from linux v4.20
prctls to allow per task control of indirect branch speculation on x86.
added in linux commit
9137bb27e60e554dab694eafa4cca241fa3a694f
Szabolcs Nagy [Wed, 23 Jan 2019 20:41:29 +0000 (20:41 +0000)]
netinet/in.h add IPV6_MULTICAST_ALL from linux v4.20
ipv6 analogue of IP_MULTICAST_ALL sockopt.
added in linux commit
15033f0457dca569b284bef0c8d3ad55fb37eacb
Szabolcs Nagy [Tue, 22 Jan 2019 23:01:37 +0000 (23:01 +0000)]
add PACKET_IGNORE_OUTGOING sockopt from linux v4.20
new in linux commit
fa788d986a3aac5069378ed04697bd06f83d3488
Szabolcs Nagy [Sat, 10 Nov 2018 21:00:06 +0000 (21:00 +0000)]
sys/mman.h: add new hugetlb mmap flags from linux v4.19
aarch64 supports 32MB and 512MB hugetlb page sizes too.
added in linux commit
20916d4636a9b3c1bf562b305f91d126771edaf9
Szabolcs Nagy [Sat, 10 Nov 2018 20:52:43 +0000 (20:52 +0000)]
arm: add io_pgetevents syscall number from v4.19
wired up in linux commit
73aeb2cbcdc9be391b3d32a55319a59ce425426f
Szabolcs Nagy [Sat, 10 Nov 2018 20:48:50 +0000 (20:48 +0000)]
aarch64, or1k: define rseq syscall number following linux v4.19
added in linux commit
db7a2d1809a5b6b08d138ff68837f805fc073351
Szabolcs Nagy [Sat, 10 Nov 2018 20:37:46 +0000 (20:37 +0000)]
elf.h: add new mips core dump note values from linux v4.19
NT_MIPS_FP_MODE is new in linux commit
1ae22a0e35636efceab83728ba30b013df761592
NT_MIPS_DSP is new in linux commit
44109c60176ae73924a42a6bef64ef151aba9095
Szabolcs Nagy [Wed, 6 Mar 2019 22:03:42 +0000 (22:03 +0000)]
netinet/udp.h: add UDP_ENCAP_RXRPC from linux v4.19
used for optimizing the rxrpc protocol
added in linux commit
5271953cad31b97dea80f848c16e96ad66401199
Szabolcs Nagy [Sat, 10 Nov 2018 20:04:50 +0000 (20:04 +0000)]
netinet/tcp.h: add tcp_info fields from linux v4.19
new fields for RFC 4898 tcp stats in linux
tcpi_bytes_sent added in commit
ba113c3aa79a7f941ac162d05a3620bdc985c58d
tcpi_bytes_retrans added in commit
fb31c9b9f6c85b1bad569ecedbde78d9e37cd87b
tcpi_dsack_dups added in commit
7e10b6554ff2ce7f86d5d3eec3af5db8db482caa
tcpi_reord_seen added in commit
7ec65372ca534217b53fd208500cf7aac223a383
The new fields change the size of a public struct and thus an ABI break,
but this is how the getsockopt TCP_INFO api is designed: the tcp_info
type must only be used with a length parameter in extern interfaces.
Szabolcs Nagy [Sat, 10 Nov 2018 19:25:28 +0000 (19:25 +0000)]
sys/inotify.h: add IN_MASK_CREATE from linux v4.19
inotify_add_watch flag to prevent modifying existing watch descriptors,
when used on an already watched inode it fails with EEXIST.
added in linux commit
4d97f7d53da7dc830dbf416a3d2a6778d267ae68
Szabolcs Nagy [Sat, 10 Nov 2018 18:29:58 +0000 (18:29 +0000)]
sys/socket.h: add SO_TXTIME from linux v4.19
added in linux commit
80b14dee2bea128928537d61c333f24cb8cbb62f
Ryan Fairfax [Thu, 7 Mar 2019 21:20:54 +0000 (13:20 -0800)]
handle labels with 8-bit byte values in dn_skipname
The original logic considered each byte until it either found a 0
value or a value >= 192. This means if a string segment contained any
byte >= 192 it was interepretted as a compressed segment marker even
if it wasn't in a position where it should be interpretted as such.
The fix is to adjust dn_skipname to increment by each segments size
rather than look at each character. This avoids misinterpretting
string segment characters by not considering those bytes.
Jonathan Neuschäfer [Wed, 20 Feb 2019 18:07:12 +0000 (19:07 +0100)]
fix POSIX_FADV_DONTNEED/_NOREUSE on s390x
On s390x, POSIX_FADV_DONTNEED and POSIX_FADV_NOREUSE have different
values than on all other architectures that Linux supports.
Handle this difference by wrapping their definitions in
include/fcntl.h in #ifdef, so that arch/s390x/bits/fcntl.h can
override them.
Rich Felker [Wed, 13 Mar 2019 14:38:12 +0000 (10:38 -0400)]
expose TSVTX unconditionally in tar.h
as noted in Austin Group issue #1236, the XSI shading for TSVTX is
misplaced in the html version of the standard; it was only supposed to
be on the description text. the intent was that the definition always
be visible, which is reflected in the pdf version of the standard.
this reverts commits
d93c0740d86aaf7043e79b942a6c0b3f576af4c8 and
729fef0a9358e2f6f1cd8c75a1a0f7ee48b08c95.
A. Wilcox [Tue, 12 Mar 2019 20:31:22 +0000 (15:31 -0500)]
setvbuf: return failure if mode is invalid
POSIX requires setvbuf to return non-zero if `mode` is not one of _IONBF,
_IOLBF, or _IOFBF.
Rich Felker [Tue, 12 Mar 2019 19:24:00 +0000 (15:24 -0400)]
make FILE a complete type for pre-C11 standard profiles
C11 removed the requirement that FILE be a complete type, which was
deemed erroneous, as part of the changes introduced by N1439 regarding
completeness of types (see footnote 6 for specific mention of FILE).
however the current version of POSIX is still based on C99 and
incorporates the old requirement that FILE be a complete type.
expose an arbitrary, useless complete type definition because the
actual object used to represent FILE streams cannot be public/ABI.
thanks to commit
13d1afa46f8098df290008c681816c9eb89ffbdb, we now have
a framework for suppressing the public complete-type definition of FILE
when stdio.h is included internally, so that a different internal
definition can be provided. this is perfectly well-defined, since the
same struct tag can refer to different types in different translation
units. it would be a problem if the implementation were accessing the
application's FILE objects or vice versa, but either would be
undefined behavior.
Rich Felker [Sun, 10 Mar 2019 17:16:59 +0000 (13:16 -0400)]
fix invalid-/double-/use-after-free in new dlopen ctor execution
this affected the error path where dlopen successfully found and
loaded the requested dso and all its dependencies, but failed to
resolve one or more relocations, causing the operation to fail after
storage for the ctor queue was allocated.
commit
188759bbee057aa94db2bbb7cf7f5855f3b9ab53 wrongly put the free
for the ctor_queue array in the error path inside a loop over each
loaded dso that needed to be backed-out, rather than just doing it
once. in addition, the exit path also observed the ctor_queue pointer
still being nonzero, and would attempt to call ctors on the backed-out
dsos unless the double-free crashed the process first.
Rich Felker [Tue, 5 Mar 2019 16:02:15 +0000 (11:02 -0500)]
don't reject unknown/future flags in sigaltstack, allow SS_AUTODISARM
historically, and likely accidentally, sigaltstack was specified to
fail with EINVAL if any flag bit other than SS_DISABLE was set. the
resolution of Austin Group issue 1187 fixes this so that the
requirement is only to fail for SS_ONSTACK (which cannot be set) or
"invalid" flags.
Linux fails on the kernel side for invalid flags, but historically
accepts SS_ONSTACK as a no-op, so it needs to be rejected in userspace
still.
with this change, the Linux-specific SS_AUTODISARM, provided since
commit
9680e1d03a794b0e0d5815c749478228ed40a36d but unusable due to
rejection at runtime, is now usable.
Rich Felker [Sun, 3 Mar 2019 18:24:23 +0000 (13:24 -0500)]
avoid malloc of ctor queue for programs with no external deps
together with the previous two commits, this completes restoration of
the property that dynamic-linked apps with no external deps and no tls
have no failure paths before entry.
Rich Felker [Sun, 3 Mar 2019 17:42:34 +0000 (12:42 -0500)]
avoid malloc of deps arrays for ldso and vdso
neither has or can have any dependencies, but since commit
403555690775f7c8806372644f543518e6664e3b, gratuitous zero-length deps
arrays were being allocated for them. use a dummy array instead.
Rich Felker [Sun, 3 Mar 2019 17:12:59 +0000 (12:12 -0500)]
avoid malloc of deps array for programs with no external deps
traditionally, we've provided a guarantee that dynamic-linked
applications with no external dependencies (nothing but libc) and no
thread-local storage have no failure paths before the entry point.
normally, thanks to reclaim_gaps, such a malloc will not require a
syscall anyway, but if segment alignment is unlucky, it might. use a
builtin array for this common special case.
Rich Felker [Sun, 3 Mar 2019 14:57:19 +0000 (09:57 -0500)]
fix malloc misuse for startup ctor queue, breakage on fdpic archs
in the case where malloc is being replaced, it's not valid to call
malloc between final relocations and main app's crt1 entry point; on
fdpic archs the main app's entry point will not yet have performed the
self-fixups necessary to call its code.
to fix, reorder queue_ctors before final relocations. an alternative
solution would be doing the allocation from __libc_start_init, after
the entry point but before any ctors run. this is less desirable,
since it would leave a call to malloc that might be provided by the
application happening at startup when doing so can be easily avoided.
Rich Felker [Sat, 2 Mar 2019 03:47:29 +0000 (22:47 -0500)]
synchronize shared library dtor exec against concurrent loads/ctors
previously, going way back, there was simply no synchronization here.
a call to exit concurrent with ctor execution from dlopen could cause
a dtor to execute concurrently with its corresponding ctor, or could
cause dtors for newly-constructed libraries to be skipped.
introduce a shutting_down state that blocks further ctor execution,
producing the quiescence the dtor execution loop needs to ensure any
kind of consistency, and that blocks further calls to dlopen so that a
call into dlopen from a dtor cannot deadlock.
better approaches to some of this may be possible, but the changes
here at least make things safe.
Rich Felker [Sat, 2 Mar 2019 02:06:23 +0000 (21:06 -0500)]
overhaul shared library ctor execution for dependency order, concurrency
previously, shared library constructors at program start and dlopen
time were executed in reverse load order. some libraries, however,
rely on a depth-first dependency order, which most other dynamic
linker implementations provide. this is a much more reasonable, less
arbitrary order, and it turns out to have much better properties with
regard to how slow-running ctors affect multi-threaded programs, and
how recursive dlopen behaves.
this commit builds on previous work tracking direct dependencies of
each dso (commit
403555690775f7c8806372644f543518e6664e3b), and
performs a topological sort on the dependency graph at load time while
the main ldso lock is held and before success is committed, producing
a queue of constructors needed by the newly-loaded dso (or main
application). in the case of circular dependencies, the dependency
chain is simply broken at points where it becomes circular.
when the ctor queue is run, the init_fini_lock is held only for
iteration purposes; it's released during execution of each ctor, so
that arbitrarily-long-running application code no longer runs with a
lock held in the caller. this prevents a dlopen with slow ctors in one
thread from arbitrarily delaying other threads that call dlopen.
fully-independent ctors can run concurrently; when multiple threads
call dlopen with a shared dependency, one will end up executing the
ctor while the other waits on a condvar for it to finish.
another corner case improved by these changes is recursive dlopen
(call from a ctor). previously, recursive calls to dlopen could cause
a ctor for a library to be executed before the ctor for its
dependency, even when there was no relation between the calling
library and the library it was loading, simply due to the naive
reverse-load-order traversal. now, we can guarantee that recursive
dlopen in non-circular-dependency usage preserves the desired ctor
execution order properties, and that even in circular usage, at worst
the libraries whose ctors call dlopen will fail to have completed
construction when ctors that depend on them run.
init_fini_lock is changed to a normal, non-recursive mutex, since it
is no longer held while calling back into application code.
Rich Felker [Fri, 1 Mar 2019 20:09:16 +0000 (15:09 -0500)]
record preloaded libraries as direct pseudo-dependencies of main app
this makes calling dlsym on the main app more consistent with the
global symbol table (load order), and is a prerequisite for
dependency-order ctor execution to work correctly with LD_PRELOAD.
Rich Felker [Fri, 1 Mar 2019 19:37:52 +0000 (14:37 -0500)]
fix unsafety of new ldso dep tracking in presence of malloc replacement
commit
403555690775f7c8806372644f543518e6664e3b introduced runtime
realloc of an array that may have been allocated before symbols were
resolved outside of libc, which is invalid if the allocator has been
replaced. track this condition and manually copy if needed.
Rich Felker [Tue, 26 Feb 2019 23:05:19 +0000 (18:05 -0500)]
fix and overhaul dlsym depedency order, always record direct deps
dlsym with an explicit handle is specified to use "dependency order",
a breadth-first search rooted at the argument. this has always been
implemented by iterating a flattened dependency list built at dlopen
time. however, the logic for building this list was completely wrong
except in trivial cases; it simply used the list of libraries loaded
since a given library, and their direct dependencies, as that
library's dependencies, which could result in misordering, wrongful
omission of deep dependencies from the search, and wrongful inclusion
of unrelated libraries in the search.
further, libraries did not have any recorded list of resolved
dependencies until they were explicitly dlopened, meaning that
DT_NEEDED entries had to be resolved again whenever a library
participated as a dependency of more than one dlopened library.
with this overhaul, the resolved direct dependency list of each
library is always recorded when it is first loaded, and can be
extended to a full flattened breadth-first search list if dlopen is
called on the library. the extension is performed using the direct
dependency list as a queue and appending copies of the direct
dependency list of each dependency in the queue, excluding duplicates,
until the end of the queue is reached. the direct deps remain
available for future use as the initial subarray of the full deps
array.
first-load logic in dlopen is updated to match these changes, and
clarified.
Rich Felker [Wed, 27 Feb 2019 17:02:49 +0000 (12:02 -0500)]
fix crash/misbehavior from oob read in new dynamic tls installation
code introduced in commit
9d44b6460ab603487dab4d916342d9ba4467e6b9
wrongly attempted to read past the end of the currently-installed dtv
to determine if a dso provides new, not-already-installed tls. this
logic was probably leftover from an earlier draft of the code that
wrongly installed the new dtv before populating it.
it would work if we instead queried the new, not-yet-installed dtv,
but instead, replace the incorrect check with a simple range check
against old_cnt. this also catches modules that have no tls at all
with a single condition.
Rich Felker [Mon, 25 Feb 2019 07:09:36 +0000 (02:09 -0500)]
fix crash in new dynamic tls installation when last dep lacks tls
code introduced in commit
9d44b6460ab603487dab4d916342d9ba4467e6b9
wrongly assumed the dso list tail was the right place to find new dtv
storage. however, this is only true if the last-loaded dependency has
tls. the correct place to get it is the dso corresponding to the tls
module list tail. introduce a container_of macro to get it, and use
it.
ultimately, dynamic tls allocation should be refactored so that this
is not an issue. there is no reason to be allocating new dtv space at
each load_library; instead it could happen after all new libraries
have been loaded but before they are committed. such changes may be
made later, but this commit fixes the present regression.
Rich Felker [Fri, 22 Feb 2019 07:56:10 +0000 (02:56 -0500)]
add membarrier syscall wrapper, refactor dynamic tls install to use it
the motivation for this change is twofold. first, it gets the fallback
logic out of the dynamic linker, improving code readability and
organization. second, it provides application code that wants to use
the membarrier syscall, which depends on preregistration of intent
before the process becomes multithreaded unless unbounded latency is
acceptable, with a symbol that, when linked, ensures that this
registration happens.
Rich Felker [Fri, 22 Feb 2019 07:29:21 +0000 (02:29 -0500)]
make thread list lock a recursive lock
this is a prerequisite for factoring the membarrier fallback code into
a function that can be called from a context with the thread list
already locked or independently.
Rich Felker [Fri, 22 Feb 2019 07:24:33 +0000 (02:24 -0500)]
fix loop logic cruft in dynamic tls installation
commit
9d44b6460ab603487dab4d916342d9ba4467e6b9 inadvertently
contained leftover logic from a previous approach to the fallback
signaling loop. it had no adverse effect, since j was always nonzero
if the loop body was reachable, but it makes no sense to be there with
the current approach to avoid signaling self.
Rich Felker [Wed, 20 Feb 2019 22:58:21 +0000 (17:58 -0500)]
fix spurious undefined behavior in getaddrinfo
addressing &out[k].sa was arguably undefined, despite &out[k] being
defined the slot one past the end of an array, since the member access
.sa is intervening between the [] operator and the & operator.
Rich Felker [Wed, 20 Feb 2019 22:51:22 +0000 (17:51 -0500)]
fix invalid free of partial addrinfo list with multiple services
the backindex stored by getaddrinfo to allow freeaddrinfo to perform
partial-free wrongly used the address result index, rather than the
output slot index, and thus was only valid when they were equal
(nservs==1).
patch based on report with proposed fix by Markus Wichmann.
Rich Felker [Mon, 18 Feb 2019 04:22:27 +0000 (23:22 -0500)]
install dynamic tls synchronously at dlopen, streamline access
previously, dynamic loading of new libraries with thread-local storage
allocated the storage needed for all existing threads at load-time,
precluding late failure that can't be handled, but left installation
in existing threads to take place lazily on first access. this imposed
an additional memory access and branch on every dynamic tls access,
and imposed a requirement, which was not actually met, that the
dynamic tlsdesc asm functions preserve all call-clobbered registers
before calling C code to to install new dynamic tls on first access.
the x86[_64] versions of this code wrongly omitted saving and
restoring of fpu/vector registers, assuming the compiler would not
generate anything using them in the called C code. the arm and aarch64
versions saved known existing registers, but failed to be future-proof
against expansion of the register file.
now that we track live threads in a list, it's possible to install the
new dynamic tls for each thread at dlopen time. for the most part,
synchronization is not needed, because if a thread has not
synchronized with completion of the dlopen, there is no way it can
meaningfully request access to a slot past the end of the old dtv,
which remains valid for accessing slots which already existed.
however, it is necessary to ensure that, if a thread sees its new dtv
pointer, it sees correct pointers in each of the slots that existed
prior to the dlopen. my understanding is that, on most real-world
coherency architectures including all the ones we presently support, a
built-in consume order guarantees this; however, don't rely on that.
instead, the SYS_membarrier syscall is used to ensure that all threads
see the stores to the slots of their new dtv prior to the installation
of the new dtv. if it is not supported, the same is implemented in
userspace via signals, using the same mechanism as __synccall.
the __tls_get_addr function, variants, and dynamic tlsdesc asm
functions are all updated to remove the fallback paths for claiming
new dynamic tls, and are now all branch-free.
Rich Felker [Mon, 18 Feb 2019 02:46:14 +0000 (21:46 -0500)]
fix data race between new pthread_key_delete and dtor execution
access to clear the entry in each thread's tsd array for the key being
deleted was not synchronized with __pthread_tsd_run_dtors. I probably
made this mistake from a mistaken belief that the thread list lock was
held during the latter, which of course is not possible since it
executes application code in a still-live-thread context.
while we're at it, expand the interval during which signals are
blocked to cover taking the write lock on key_lock, so that a signal
at an inopportune time doesn't block forward progress of readers.
Rich Felker [Sat, 16 Feb 2019 16:44:07 +0000 (11:44 -0500)]
introduce namespace-safe rwlock aliases; use in pthread_key_create
commit
84d061d5a31c9c773e29e1e2b1ffe8cb9557bc58 inadvertently
introduced namespace violations by using the pthread-namespace rwlock
functions in pthread_key_create, which is in turn used for C11 tss.
fix that and possible future uses of rwlocks elsewhere.
Rich Felker [Sat, 16 Feb 2019 15:13:31 +0000 (10:13 -0500)]
rewrite pthread_key_delete to use global thread list
with the availability of the thread list, there is no need to mark tsd
key slots dirty and clean them up only when a free slot can't be
found. instead, directly iterate threads and clear any value
associated with the key being deleted.
no synchronization is necessary for the clearing, since there is no
way the slot can be accessed without having synchronized with the
creation of a new key occupying the same slot, which is already
sequenced after and synchronized with the deletion of the old key.
Rich Felker [Sat, 16 Feb 2019 14:13:45 +0000 (09:13 -0500)]
rewrite __synccall in terms of global thread list
the __synccall mechanism provides stop-the-world synchronous execution
of a callback in all threads of the process. it is used to implement
multi-threaded setuid/setgid operations, since Linux lacks them at the
kernel level, and for some other less-critical purposes.
this change eliminates dependency on /proc/self/task to determine the
set of live threads, which in addition to being an unwanted dependency
and a potential point of resource-exhaustion failure, turned out to be
inaccurate. test cases provided by Alexey Izbyshev showed that it
could fail to reflect newly created threads. due to how the
presignaling phase worked, this usually yielded a deadlock if hit, but
in the worst case it could also result in threads being silently
missed (allowed to continue running without executing the callback).
Rich Felker [Sat, 16 Feb 2019 03:29:01 +0000 (22:29 -0500)]
track all live threads in an AS-safe, fully-consistent linked list
the hard problem here is unlinking threads from a list when they exit
without creating a window of inconsistency where the kernel task for a
thread still exists and is still executing instructions in userspace,
but is not reflected in the list. the magic solution here is getting
rid of per-thread exit futex addresses (set_tid_address), and instead
using the exit futex to unlock the global thread list.
since pthread_join can no longer see the thread enter a detach_state
of EXITED (which depended on the exit futex address pointing to the
detach_state), it must now observe the unlocking of the thread list
lock before it can unmap the joined thread and return. it doesn't
actually have to take the lock. for this, a __tl_sync primitive is
offered, with a signature that will allow it to be enhanced for quick
return even under contention on the lock, if needed. for now, the
exiting thread always performs a futex wake on its detach_state. a
future change could optimize this out except when there is already a
joiner waiting.
initial/dynamic variants of detached state no longer need to be
tracked separately, since the futex address is always set to the
global list lock, not a thread-local address that could become invalid
on detached thread exit. all detached threads, however, must perform a
second sigprocmask syscall to block implementation-internal signals,
since locking the thread list with them already blocked is not
permissible.
the arch-independent C version of __unmapself no longer needs to take
a lock or setup its own futex address to release the lock, since it
must necessarily be called with the thread list lock already held,
guaranteeing exclusive access to the temporary stack.
changes to libc.threads_minus_1 no longer need to be atomic, since
they are guarded by the thread list lock. it is largely vestigial at
this point, and can be replaced with a cheaper boolean indicating
whether the process is multithreaded at some point in the future.
Rich Felker [Sat, 16 Feb 2019 00:58:09 +0000 (19:58 -0500)]
always block signals for starting new threads, refactor start args
whether signals need to be blocked at thread start, and whether
unblocking is necessary in the entry point function, has historically
depended on intricacies of the cancellation design and on whether
there are scheduling operations to perform on the new thread before
its successful creation can be committed. future changes to track an
AS-safe list of live threads will require signals to be blocked
whenever changes are made to the list, so ...
prior to commits
b8742f32602add243ee2ce74d804015463726899 and
40bae2d32fd6f3ffea437fa745ad38a1fe77b27e, a signal mask for the entry
function to restore was part of the pthread structure. it was removed
to trim down the size of the structure, which both saved a small
amount of stack space and improved code generation on archs where
small immediate displacements are less costly than arbitrary ones, by
limiting the range of offsets between the base of the thread
structure, its members, and the thread pointer. these commits moved
the saved mask to a special structure used only when special
scheduling was needed, in which case the pthread_create caller and new
thread had to synchronize with each other and could use this memory to
pass a mask.
this commit partially reverts the above two commits, but instead of
putting the mask back in the pthread structure, it moves all "start
argument" members out of the pthread structure, trimming it down
further, and puts them in a separate structure passed on the new
thread's stack. the code path for explicit scheduling of the new
thread is also changed to synchronize with the calling thread in such
a way to avoid spurious futex wakes.
Rich Felker [Fri, 15 Feb 2019 20:23:11 +0000 (15:23 -0500)]
for SIGEV_THREAD timer threads, replace signal handler with sigwaitinfo
this eliminates some ugly hacks that were repurposing the start
function and start argument fields in the pthread structure for timer
use, and the need to longjmp out of a signal handler.
Rich Felker [Fri, 15 Feb 2019 19:20:49 +0000 (14:20 -0500)]
defer free of thread-local dlerror buffers from inconsistent context
__dl_thread_cleanup is called from the context of an exiting thread
that is not in a consistent state valid for calling application code.
since commit
c9f415d7ea2dace5bf77f6518b6afc36bb7a5732, it's possible
(and supported usage) for the allocator to have been replaced by the
application, so __dl_thread_cleanup can no longer call free. instead,
reuse the message buffer as a linked-list pointer, and queue it to be
freed the next time any dynamic linker error message is generated.
Rich Felker [Wed, 13 Feb 2019 23:48:04 +0000 (18:48 -0500)]
fix behavior of gets when input line contains a null byte
the way gets was implemented in terms of fgets, it used the location
of the null termination to determine where to find and remove the
newline, if any. an embedded null byte prevented this from working.
this also fixes a one-byte buffer overflow, whereby when gets read an
N-byte line (not counting newline), it would store two null
terminators for a total of N+2 bytes. it's unlikely that anyone would
care that a function whose use is pretty much inherently a buffer
overflow writes too much, but it could break the only possible correct
uses of this function, in conjunction with input of known format from
a trusted/same-privilege-domain source, where the buffer length may
have been selected to exactly match a line length contract.
there seems to be no correct way to implement gets in terms of a
single call to fgets or scanf, and using multiple calls would require
explicit locking, so we might as well just write the logic out
explicitly character-at-a-time. this isn't fast, but nobody cares if a
catastrophically unsafe function that's so bad it was removed from the
C language is fast.
Rich Felker [Wed, 13 Feb 2019 00:56:49 +0000 (19:56 -0500)]
redesign robust mutex states to eliminate data races on type field
in order to implement ENOTRECOVERABLE, the implementation has
traditionally used a bit of the mutex type field to indicate that it's
recovered after EOWNERDEAD and will go into ENOTRECOVERABLE state if
pthread_mutex_consistent is not called before unlocking. while it's
only the thread that holds the lock that needs access to this
information (except possibly for the sake of pthread_mutex_consistent
choosing between EINVAL and EPERM for erroneous calls), the change to
the type field is formally a data race with all other threads that
perform any operation on the mutex. no individual bits race, and no
write races are possible, so things are "okay" in some sense, but it's
still not good.
this patch moves the recovery/consistency state to the mutex
owner/lock field which is rightfully mutable. bit 30, the same bit the
kernel uses with a zero owner to indicate that the previous owner died
holding the lock, is now used with a nonzero owner to indicate that
the mutex is held but has not yet been marked consistent. note that
the kernel ABI also reserves bit 29 not to appear in any tid, so the
sentinel value we use for ENOTRECOVERABLE, 0x7fffffff, does not clash
with any tid plus bit 30.