musl
3 years agos390x: derive float_t from compiler or default to float
Marius Hillenbrand [Tue, 1 Dec 2020 14:36:34 +0000 (15:36 +0100)]
s390x: derive float_t from compiler or default to float

float_t should represent the type that is used to evaluate float
expressions internally. On s390x, float_t is currently set to double.
In contrast, the isa supports single-precision float operations and
compilers by default evaluate float in single precision, which
violates the C standard (sections 5.2.4.2.2 and 7.12 in C11/C17, to be
precise). With -fexcess-precision=standard, gcc evaluates float in
double precision, which aligns with the standard yet at the cost of
added conversion instructions.

gcc-11 will drop the special case to retrofit double precision
behavior for -fexcess-precision=standard so that __FLT_EVAL_METHOD__
will be 0 on s390x in any scenario.

To improve standards compliance and compatibility with future compiler
direction, this patch changes the definition of float_t to be derived
from the compiler's __FLT_EVAL_METHOD__.

3 years agoimplement reallocarray
Ariadne Conill [Sat, 1 Aug 2020 14:26:35 +0000 (08:26 -0600)]
implement reallocarray

reallocarray is an extension introduced by OpenBSD, which introduces
calloc overflow checking to realloc.

glibc 2.28 introduced support for this function behind _GNU_SOURCE,
while glibc 2.29 allows its usage in _DEFAULT_SOURCE.

3 years agoimplement realpath directly instead of using procfs readlink
Rich Felker [Mon, 30 Nov 2020 17:14:47 +0000 (12:14 -0500)]
implement realpath directly instead of using procfs readlink

inability to use realpath in chroot/container without procfs access
and at early boot prior to mount of /proc has been an ongoing issue,
and it turns out realpath was one of the last remaining interfaces
that needed procfs for its core functionality. during investigation
while reimplementing, it was determined that there were also serious
problems with the procfs-based implementation. most seriously it was
unsafe on pre-O_PATH kernels, and unlike other places where O_PATH was
used, the unsafety was hard or impossible to fix because O_NOFOLLOW
can't be used (since the whole purpose was to follow symlinks).

the new implementation is a direct one, performing readlink on each
path component to resolve it. an explicit stack, as opposed to
recursion, is used to represent the remaining components to be
processed. the stack starts out holding just the input string, and
reading a link pushes the link contents onto the stack.

unlike many other implementations, this one does not call getcwd
initially for relative pathnames. instead it accumulates initial ..
components to be applied to the working directory if the result is
still a relative path. this avoids calling getcwd (which may fail) at
all when symlink traversal will eventually yield an absolute path. it
also doesn't use any form of stat operation; instead it arranges for
readlink to tell it when a non-directory is used in a context where a
directory is needed. this minimizes the number of syscalls needed,
avoids accessing inodes when the directory table suffices, and reduces
the amount of code pulled in for static linking.

3 years agofix mallocng regression in malloc_usable_size with null argument
Dominic Chen [Wed, 25 Nov 2020 07:53:16 +0000 (02:53 -0500)]
fix mallocng regression in malloc_usable_size with null argument

commit d1507646975cbf6c3e511ba07b193f27f032d108 added support for null
argument in oldmalloc and was overlooked when switching to mallocng.

3 years agoconfigure: do not use obsolescent form of test -a|o
Issam E. Maghni [Mon, 2 Nov 2020 22:16:41 +0000 (17:16 -0500)]
configure: do not use obsolescent form of test -a|o

The -a and -o operators are obsolescent and not in baseline POSIX.

3 years agofix segfault in lutimes when tv argument is NULL
Érico Rolim [Thu, 12 Nov 2020 20:52:23 +0000 (17:52 -0300)]
fix segfault in lutimes when tv argument is NULL

calling lutimes with tv=0 is valid if the application wants to set the
timestamps to the current time. this commit makes it so the timespec
struct is populated with values from tv only if tv != 0 and calls
utimensat with times=0 if tv == 0.

3 years agonetinet/in.h: add IP_RECVERR_4884 from linux v5.9
Szabolcs Nagy [Sun, 25 Oct 2020 16:42:41 +0000 (16:42 +0000)]
netinet/in.h: add IP_RECVERR_4884 from linux v5.9

see

  linux commit eba75c587e811d3249c8bd50d22bb2266ccd3c0f
  icmp: support rfc 4884

3 years agosys/fanotify.h: add new FAN_* macros from linux v5.9
Szabolcs Nagy [Sun, 25 Oct 2020 16:25:34 +0000 (16:25 +0000)]
sys/fanotify.h: add new FAN_* macros from linux v5.9

Update fanotify.h, see

  linux commit 929943b38daf817f2e6d303ea04401651fc3bc05
  fanotify: add support for FAN_REPORT_NAME

  linux commit 83b7a59896dd24015a34b7f00027f0ff3747972f
  fanotify: add basic support for FAN_REPORT_DIR_FID

  linux commit 08b95c338e0c5a96e47f4ca314ea1e7580ecb5d7
  fanotify: remove event FAN_DIR_MODIFY

FAN_DIR_MODIFY that was new in v5.7 is now removed from linux uapi,
but kept in musl, so we don't break api, linux cannot reuse the
value anyway.

3 years agobits/syscall.h: add __NR_close_range from linux v5.9
Szabolcs Nagy [Sat, 24 Oct 2020 10:15:43 +0000 (10:15 +0000)]
bits/syscall.h: add __NR_close_range from linux v5.9

see

  linux commit 9b4feb630e8e9801603f3cab3a36369e3c1cf88d
  arch: wire-up close_range()

  linux commit 278a5fbaed89dacd04e9d052f4594ffd0e0585de
  open: add close_range()

3 years agoadd missing personality values
William Woodruff [Wed, 18 Nov 2020 15:59:31 +0000 (10:59 -0500)]
add missing personality values

Adds two missing personality(2) personas: UNAME26 and FDPIC_FUNCPTRS.

FDPIC_FUNCPTRS was also missing its corresponding PER_LINUX_FDPIC
value.

3 years agoarm fabs and sqrt: support single-precision-only fpu variants
Jinliang Li [Fri, 20 Nov 2020 10:45:03 +0000 (18:45 +0800)]
arm fabs and sqrt: support single-precision-only fpu variants

3 years agofix typo in INSTALL
Érico Rolim [Thu, 26 Nov 2020 13:46:03 +0000 (10:46 -0300)]
fix typo in INSTALL

"big-engian" should be "big-endian".

3 years agowork around linux bug in readlink syscall with zero buffer size
Rich Felker [Tue, 24 Nov 2020 00:44:19 +0000 (19:44 -0500)]
work around linux bug in readlink syscall with zero buffer size

linux fails with EINVAL when a zero buffer size is passed to the
syscall. this is non-conforming because POSIX already defines EINVAL
with a significantly different meaning: the target is not a symlink.

since the request is semantically valid, patch it up by using a dummy
buffer of length one, and truncating the return value to zero if it
succeeds.

3 years agoparse v3 or future-unknown zoneinfo file versions as v2+
Rich Felker [Sun, 22 Nov 2020 22:26:36 +0000 (17:26 -0500)]
parse v3 or future-unknown zoneinfo file versions as v2+

the v1 zoneinfo format with 32-bit time is deprecated. previously, the
v2 parsing code was only used if an exact match for '2' was found in
the version field of the header. this was already incorrect for v3
files (trivial differences from v2 that arguably didn't merit a new
version number anyway) but also failed to be future-proof.

3 years agoexplicitly prefer 64-bit/v2 zoneinfo tables
Rich Felker [Sun, 22 Nov 2020 22:00:01 +0000 (17:00 -0500)]
explicitly prefer 64-bit/v2 zoneinfo tables

since commit 38143339646a4ccce8afe298c34467767c899f51, the condition
sizeof(time_t) > 4 is always true, so there is no functional change
being made here. but semantically, the 64-bit tables should always be
preferred now, because upstream zic (zoneinfo compiler) has quietly
switched to emitting empty 32-bit tables by default, and the resulting
backwards-incompatible zoneinfo files will be encountered in the wild.

3 years agofix regression in pthread_exit
Rich Felker [Fri, 20 Nov 2020 15:43:20 +0000 (10:43 -0500)]
fix regression in pthread_exit

commit d26e0774a59bb7245b205bc8e7d8b35cc2037095 moved the detach state
transition at exit before the thread list lock was taken. this
inadvertently allowed pthread_join to race to take the thread list
lock first, and proceed with unmapping of the exiting thread's memory.

we could fix this by just revering the offending commit and instead
performing __vm_wait unconditionally before taking the thread list
lock, but that may be costly. instead, bring back the old DT_EXITING
vs DT_EXITED state distinction that was removed in commit
8f11e6127fe93093f81a52b15bb1537edc3fc8af, and don't transition to
DT_EXITED (a value of 0, which is what pthread_join waits for) until
after the lock has been taken.

3 years agorewrite wcsnrtombs to fix buffer overflow and other bugs
Rich Felker [Thu, 19 Nov 2020 22:12:43 +0000 (17:12 -0500)]
rewrite wcsnrtombs to fix buffer overflow and other bugs

the original wcsnrtombs implementation, which has been largely
untouched since 0.5.0, attempted to build input-length-limiting
conversion on top of wcsrtombs, which only limits output length. as
best I recall, this choice was made out of a mix of disdain over
having yet another variant function to implement (added in POSIX 2008;
not standard C) and preference not to switch things around and
implement the wcsrtombs in terms of the more general new function,
probably over namespace issues. the strategy employed was to impose
output limits that would ensure the input limit wasn't exceeded, then
finish up the tail character-at-a-time. unfortunately, none of that
worked correctly.

first, the logic in the wcsrtombs loop was wrong in that it could
easily get stuck making no forward progress, by imposing an output
limit too small to convert even one character.

the character-at-a-time loop that followed was even worse. it made no
effort to ensure that the converted multibyte character would fit in
the remaining output space, only that there was a nonzero amount of
output space remaining. it also employed an incorrect interpretation
of wcrtomb's interface contract for converting the null character,
thereby failing to act on end of input, and remaining space accounting
was subject to unsigned wrap-around. together these errors allow
unbounded overflow of the destination buffer, controlled by input
length limit and input wchar_t string contents.

given the extent to which this function was broken, it's plausible
that most applications that would have been rendered exploitable were
sufficiently broken not to be usable in the first place. however, it's
also plausible that common (especially ASCII-only) inputs succeeded in
the wcsrtombs loop, which mostly worked, while leaving the wildly
erroneous code in the second loop exposed to particular non-ASCII
inputs.

CVE-2020-28928 has been assigned for this issue.

3 years agoprotect destruction of process-shared mutexes against robust list races
Rich Felker [Thu, 19 Nov 2020 21:20:45 +0000 (16:20 -0500)]
protect destruction of process-shared mutexes against robust list races

after a non-normal-type process-shared mutex is unlocked, it's
immediately available to another thread to lock, unlock, and destroy,
but the first unlocking thread may still have a pointer to it in its
robust_list pending slot. this means, on async process termination,
the kernel may attempt to access and modify the memory that used to
contain the mutex -- memory that may have been reused for some other
purpose after the mutex was destroyed.

setting up for this kind of race to occur is difficult to begin with,
requiring dynamic use of shared memory maps, and actually hitting the
race is very difficult even with a suitable setup. so this is mostly a
theoretical fix, but in any case the cost is very low.

3 years agopthread_exit: don't __vm_wait under thread list lock
Rich Felker [Thu, 19 Nov 2020 21:09:16 +0000 (16:09 -0500)]
pthread_exit: don't __vm_wait under thread list lock

the __vm_wait operation can delay forward progress arbitrarily long if
a thread holding the lock is interrupted by a signal. in a worst case
this can deadlock. any critical section holding the thread list lock
must respect lock ordering contracts and must not take any lock which
is not AS-safe.

to fix, move the determination of thread joinable/detached state to
take place before the killlock and thread list lock are taken. this
requires reverting the atomic state transition if we determine that
the exiting thread is the last thread and must call exit, but that's
easy to do since it's a single-threaded context with application
signals blocked.

3 years agolift child restrictions after multi-threaded fork
Rich Felker [Wed, 11 Nov 2020 18:37:33 +0000 (13:37 -0500)]
lift child restrictions after multi-threaded fork

as the outcome of Austin Group tracker issue #62, future editions of
POSIX have dropped the requirement that fork be AS-safe. this allows
but does not require implementations to synchronize fork with internal
locks and give forked children of multithreaded parents a partly or
fully unrestricted execution environment where they can continue to
use the standard library (per POSIX, they can only portably use
AS-safe functions).

up until recently, taking this allowance did not seem desirable.
however, commit 8ed2bd8bfcb4ea6448afb55a941f4b5b2b0398c0 exposed the
extent to which applications and libraries are depending on the
ability to use malloc and other non-AS-safe interfaces in MT-forked
children, by converting latent very-low-probability catastrophic state
corruption into predictable deadlock. dealing with the fallout has
been a huge burden for users/distros.

while it looks like most of the non-portable usage in applications
could be fixed given sufficient effort, at least some of it seems to
occur in language runtimes which are exposing the ability to run
unrestricted code in the child as part of the contract with the
programmer. any attempt at fixing such contracts is not just a
technical problem but a social one, and is probably not tractable.

this patch extends the fork function to take locks for all libc
singletons in the parent, and release or reset those locks in the
child, so that when the underlying fork operation takes place, the
state protected by these locks is consistent and ready for the child
to use. locking is skipped in the case where the parent is
single-threaded so as not to interfere with legacy AS-safety property
of fork in single-threaded programs. lock order is mostly arbitrary,
but the malloc locks (including bump allocator in case it's used) must
be taken after the locks on any subsystems that might use malloc, and
non-AS-safe locks cannot be taken while the thread list lock is held,
imposing a requirement that it be taken last.

3 years agoconvert malloc use under libc-internal locks to use internal allocator
Rich Felker [Wed, 11 Nov 2020 18:08:42 +0000 (13:08 -0500)]
convert malloc use under libc-internal locks to use internal allocator

this change lifts undocumented restrictions on calls by replacement
mallocs to libc functions that might take these locks, and sets the
stage for lifting restrictions on the child execution environment
after multithreaded fork.

care is taken to #define macros to replace all four functions (malloc,
calloc, realloc, free) even if not all of them will be used, using an
undefined symbol name for the ones intended not to be used so that any
inadvertent future use will be caught at compile time rather than
directed to the wrong implementation.

3 years agogive libc access to its own malloc even if public malloc is interposed
Rich Felker [Wed, 11 Nov 2020 05:22:34 +0000 (00:22 -0500)]
give libc access to its own malloc even if public malloc is interposed

allowing the application to replace malloc (since commit
c9f415d7ea2dace5bf77f6518b6afc36bb7a5732) has brought multiple
headaches where it's used from various critical sections in libc
components. for example:

- the thread-local message buffers allocated for dlerror can't be
  freed at thread exit time because application code would then run in
  the context of a non-existant thread. this was handled in commit
  aa5a9d15e09851f7b4a1668e9dbde0f6234abada by queuing them for free
  later.

- the dynamic linker has to be careful not to pass memory allocated at
  early startup time (necessarily using its own malloc) to realloc or
  free after redoing relocations with the application and all
  libraries present. bugs in this area were fixed several times, at
  least in commits 0c5c8f5da6e36fe4ab704bee0cd981837859e23f and
  2f1f51ae7b2d78247568e7fdb8462f3c19e469a4 and possibly others.

- by calling the allocator from contexts where libc-internal locks are
  held, we impose undocumented requirements on alternate malloc
  implementations not to call into any libc function that might
  attempt to take these locks; if they do, deadlock results.

- work to make fork of a multithreaded parent give the child an
  unrestricted execution environment is blocked by lock order issues
  as long as the application-provided allocator can be called with
  libc-internal locks held.

these problems are all fixed by giving libc internals access to the
original, non-replaced allocator, for use where needed. it can't be
used everywhere, as some interfaces like str[n]dup, open_[w]memstream,
getline/getdelim, etc. are required to provide the called memory
obtained as if by (the public) malloc. and there are a number of libc
interfaces that are "pure library" code, not part of some internal
singleton, and where using the application's choice of malloc
implementation is preferable -- things like glob, regex, etc.

one might expect there to be significant cost to static-linked
programs, pulling in two malloc implementations, one of them
mostly-unused, if malloc is replaced. however, in almost all of the
places where malloc is used internally, care has been taken already
not to pull in realloc/free (i.e. to link with just the bump
allocator). this size optimization carries over automatically.

the newly-exposed internal allocator functions are obtained by
renaming the actual definitions, then adding new wrappers around them
with the public names. technically __libc_realloc and __libc_free
could be aliases rather than needing a layer of wrapper, but this
would almost surely break certain instrumentation (valgrind) and the
size and performance difference is negligible. __libc_calloc needs to
be handled specially since calloc is designed to work with either the
internal or the replaced malloc.

as a bonus, this change also eliminates the longstanding ugly
dependency of the static bump allocator on order of object files in
libc.a, by making it so there's only one definition of the malloc
function and having it in the same source file as the bump allocator.

3 years agodrop use of getdelim/stdio in dynamic linker
Rich Felker [Wed, 11 Nov 2020 00:32:09 +0000 (19:32 -0500)]
drop use of getdelim/stdio in dynamic linker

the only place stdio was used here was for reading the ldso path file,
taking advantage of getdelim to automatically allocate and resize the
buffer. the motivation for use here was that, with shared libraries,
stdio is already available anyway and free to use. this has long been
a nuisance to users because getdelim's use of realloc here triggered a
valgrind bug, but removing it doesn't really fix that; on some archs
even calling the valgrind-interposed malloc at this point will crash.

the actual motivation for this change is moving towards getting rid of
use of application-provided malloc in parts of libc where it would be
called with libc-internal locks held, leading to the possibility of
deadlock if the malloc implementation doesn't follow unwritten rules
about which libc functions are safe for it to call. since getdelim is
required to produce a pointer as if by malloc (i.e. that can be passed
to reallor or free), it necessarily must use the public malloc.

instead of performing a realloc loop as the path file is read, first
query its size with fstat and allocate only once. this produces
slightly different truncation behavior when racing with writes to a
file, but neither behavior is or could be made safe anyway; on a live
system, ldso path files should be replaced by atomic rename only. the
change should also reduce memory waste.

3 years agodlerror: don't gratuitously hold freebuf_queue lock while freeing
Rich Felker [Tue, 10 Nov 2020 19:29:05 +0000 (14:29 -0500)]
dlerror: don't gratuitously hold freebuf_queue lock while freeing

thread-local buffers allocated for dlerror need to be queued for free
at a later time when the owning thread exits, since malloc may be
replaced by application code and the exiting context is not valid to
call application code from. the code to process queue of pending
frees, introduced in commit aa5a9d15e09851f7b4a1668e9dbde0f6234abada,
gratuitously held the lock for the entire duration of queue
processing, updating the global queue pointer after each free, despite
there being no logical requirement that all frees finish before
another thread can access the queue.

instead, immediately claim the whole queue for freeing and release the
lock, then walk the list and perform frees without the lock held. the
change is unlikely to make any meaningful difference to performance,
but it eliminates one point where the allocator is called under an
internal lock. since the allocator may be application-provided, such
calls are undesirable because they allow application code to impede
forward progress of libc functions in other threads arbitrarily long,
and to induce deadlock if it calls a libc function that requires the
same lock.

the change also eliminates a lock ordering consideration that's an
impediment upcoming work with multithreaded fork.

3 years agofix vector types in aarch64 register file structures
Rich Felker [Tue, 3 Nov 2020 04:25:12 +0000 (23:25 -0500)]
fix vector types in aarch64 register file structures

the ABI type for the vector registers in fpregset_t, struct
fpsimd_context, and struct user_fpsimd_struct is __uint128_t, which
was presumably originally not used because it's a nonstandard type,
but its existence is mandated by the aarch64 psABI. use of the wrong
type here broke software using these structures, and encouraged
incorrect fixes with casts rather than reinterpretation of
representation.

3 years agofix erroneous pthread_cond_wait mutex waiter count logic due to typo
Rich Felker [Fri, 30 Oct 2020 20:50:08 +0000 (16:50 -0400)]
fix erroneous pthread_cond_wait mutex waiter count logic due to typo

introduced in commit 27b2fc9d6db956359727a66c262f1e69995660aa.

3 years agofix missing-wake regression in pthread_cond_wait
Rich Felker [Fri, 30 Oct 2020 15:21:06 +0000 (11:21 -0400)]
fix missing-wake regression in pthread_cond_wait

the reasoning in commit 2d0bbe6c788938d1332609c014eeebc1dff966ac was
not entirely correct. while it's true that setting the waiters flag
ensures that the next unlock will perform a wake, it's possible that
the wake is consumed by a mutex waiter that has no relationship with
the condvar wait queue being processed, which then takes the mutex.
when that thread subsequently unlocks, it sees no waiters, and leaves
the rest of the condvar queue stuck.

bring back the waiter count adjustment, but skip it for PI mutexes,
for which a successful lock-after-waiting always sets the waiters bit.
if future changes are made to bring this same waiters-bit contract to
all lock types, this can be reverted.

3 years agoadd support for SIGEV_THREAD_ID timers
James Y Knight [Mon, 1 Jul 2019 01:55:20 +0000 (21:55 -0400)]
add support for SIGEV_THREAD_ID timers

This is like SIGEV_SIGNAL, but targeted to a particular thread's
tid, rather than the process.

3 years agofix sem_close unmapping of still-referenced semaphore
Rich Felker [Wed, 28 Oct 2020 20:13:45 +0000 (16:13 -0400)]
fix sem_close unmapping of still-referenced semaphore

sem_open is required to return the same sem_t pointer for all
references to the same named semaphore when it's opened more than once
in the same process. thus we keep a table of all the mapped semaphores
and their reference counts. the code path for sem_close checked the
reference count, but then proceeded to unmap the semaphore regardless
of whether the count had reached zero.

add an immediate unlock-and-return for the nonzero refcnt case so the
property of performing the munmap syscall after releasing the lock can
be preserved.

3 years agorefactor setxid return path to use __syscall_ret
Rich Felker [Tue, 27 Oct 2020 05:12:56 +0000 (01:12 -0400)]
refactor setxid return path to use __syscall_ret

this avoids some spurious negation and duplicated errno logic, and
brings the code in line with the newly-added multithreaded setgroups.

3 years agoldso: notify the debugger when we're doing a dlopen
rcombs [Sat, 24 Oct 2020 19:31:14 +0000 (14:31 -0500)]
ldso: notify the debugger when we're doing a dlopen

Otherwise lldb doesn't notice the new library and stack traces
containing it get cut off unhelpfully.

3 years agofix setgroups behavior in multithreaded process
Rich Felker [Tue, 27 Oct 2020 04:59:54 +0000 (00:59 -0400)]
fix setgroups behavior in multithreaded process

this function is outside the scope of the standards, but logically
should behave like the set*id functions whose effects are
process-global.

3 years agoavoid __synccall for setrlimit on kernels with prlimit syscall
Rich Felker [Tue, 27 Oct 2020 04:45:59 +0000 (00:45 -0400)]
avoid __synccall for setrlimit on kernels with prlimit syscall

resource limits have been process-wide since linux 2.6.10, and the
prlimit syscall was added in 2.6.36, so prlimit can be assumed to set
the resource limits correctly for the whole process.

3 years agofix reintroduction of errno clobbering by atfork handlers
Rich Felker [Mon, 26 Oct 2020 22:06:18 +0000 (18:06 -0400)]
fix reintroduction of errno clobbering by atfork handlers

commit bd153422f28634bb6e53f13f80beb8289d405267 reintroduced the bug
fixed in c21051e90cd27a0b26be0ac66950b7396a156ba1 by refactoring the
__syscall_ret into _Fork where it once again runs before the atfork
handlers are called. since _Fork is a public interface that sets
errno, this can't be fixed the way it was fixed last time without
making new internal interfaces. instead, just save errno, and restore
it only on error to ensure that a value of 0 is never restored.

3 years agofix pthread_cond_wait paired with with priority-inheritance mutex
Rich Felker [Mon, 26 Oct 2020 19:56:25 +0000 (15:56 -0400)]
fix pthread_cond_wait paired with with priority-inheritance mutex

pthread_cond_wait arranged for requeued waiters to wake when the mutex
is unlocked by temporarily adjusting the mutex's waiter count. commit
54ca677983d47529bab8752315ac1a2b49888870 broke this when introducing
PI mutexes by repurposing the waiter count field of the mutex
structure. since then, for PI mutexes, the waiter count adjustment was
misinterpreted by the mutex locking code as indicating that the mutex
is non a non-recoverable state.

it would be possible to special-case PI mutexes here, but instead just
drop all adjustment of the waiters count, and instead use the lock
word waiters bit for all mutex types. since the mutex is either held
by the caller or in unrecoverable state at the time the bit is set, it
will necessarily still be set at the time of any subsequent valid
unlock operation, and this will produce the desired effect of waking
the next waiter.

if waiter counts are entirely dropped at some point in the future this
code should still work without modification.

3 years agolift sigaction abort locking to fix posix_spawn child deadlock
Rich Felker [Sat, 24 Oct 2020 17:34:29 +0000 (13:34 -0400)]
lift sigaction abort locking to fix posix_spawn child deadlock

commit 25ea9f712c30c32957de493d4711ee39d0bbb024 introduced a deadlock
to the posix_spawn child whereby, if abort was called in the parent
and ended up taking the abort lock to terminate the process, the
__libc_sigaction calls in the child would wait forever to obtain a
lock that would not be released. this could be fixed by having abort
set the abort lock as the exit futex address, but it's cleaner to just
remove the SIGABRT special handling from the internal __libc_sigaction
and lift it to the public sigaction function.

nothing but the posix_spawn child calls __libc_sigaction on SIGABRT,
and since commit b7bc966522d73e1dc420b5ee6fc7a2e78099a08c the abort
lock is held at the time of __clone, which precludes the child
inheriting a kernel-level signal disposition inconsistent with the
disposition on the abstract machine. this means it's fine to inspect
and modify the disposition in the child without a lock.

3 years agoupdate crypt_blowfish to support $2b$ prefix
Julien Ramseier [Sun, 18 Oct 2020 16:15:06 +0000 (12:15 -0400)]
update crypt_blowfish to support $2b$ prefix

Merge changes from Solar Designer's crypt_blowfish v1.3. This makes
crypt_blowfish fully compatible with OpenBSD's bcrypt by adding
support for the $2b$ prefix (which behaves the same as
crypt_blowfish's $2y$).

3 years agoremove unused weak definition of __tl_sync in membarrier.c
Rich Felker [Thu, 15 Oct 2020 00:31:23 +0000 (20:31 -0400)]
remove unused weak definition of __tl_sync in membarrier.c

3 years agomove aio implementation details to a proper internal header
Rich Felker [Mon, 28 Sep 2020 22:47:13 +0000 (18:47 -0400)]
move aio implementation details to a proper internal header

also fix the lack of declaration (and thus hidden visibility) in
__stdio_close's use of __aio_close.

3 years agoremove long-unused struct __timer from pthread_impl.h
Rich Felker [Wed, 14 Oct 2020 23:36:03 +0000 (19:36 -0400)]
remove long-unused struct __timer from pthread_impl.h

commit 3990c5c6a40440cdb14746ac080d0ecf8d5d6733 removed the last
reference.

3 years agodrop use of pthread_once in timer_create
Rich Felker [Wed, 14 Oct 2020 23:07:27 +0000 (19:07 -0400)]
drop use of pthread_once in timer_create

this makes the code slightly smaller and eliminates timer_create from
relevance to possible future changes to multithreaded fork.

the barrier of a_store isn't technically needed here, but a_store is
used anyway for internal consistency of the memory model.

3 years agoremove unused SIGTIMER handler in timer_create
Rich Felker [Wed, 14 Oct 2020 23:04:19 +0000 (19:04 -0400)]
remove unused SIGTIMER handler in timer_create

this was leftover from when the actual SIGEV_THREAD timer logic was in
the signal handler. commit 5b74eed3b301e2227385f3bf26d3bb7c2d822cf8
replaced that with use of sigwaitinfo, with the actual signal left
blocked, so the no-op signal handler was no longer serving any
purpose.

the signal disposition reset to SIG_DFL is still needed, however, in
case we inherited SIG_IGN from a foreign-libc process.

3 years agoremove incorrect fflush from assert failure handler
Rich Felker [Wed, 14 Oct 2020 14:55:55 +0000 (10:55 -0400)]
remove incorrect fflush from assert failure handler

assert is not specified to flush open stdio streams, and doing so can
block indefinitely waiting for a lock already held or an output
operation to a file that can't accept more output until an
unsatisfiable condition is met.

3 years agofix getgrouplist when nscd reports an empty list
Rich Felker [Sun, 11 Oct 2020 00:04:18 +0000 (20:04 -0400)]
fix getgrouplist when nscd reports an empty list

commit 500c6886c654fd45e4926990fee2c61d816be197 broke this by fixing
the behavior of fread to conform to the C standard; getgroupslist was
assuming the old behavior, that a request to read 1 member of length 0
would return 1, not 0.

3 years agofix posix_spawn interaction with fork and abort by taking lock
Rich Felker [Thu, 1 Oct 2020 18:53:12 +0000 (14:53 -0400)]
fix posix_spawn interaction with fork and abort by taking lock

this change prevents the child created concurrently with abort from
seeing the SIGABRT disposition change from SIG_IGN to SIG_DFL (other
changes are not visible anyway) and prevents leaking the write end of
the child pipe to children created by fork in another thread, which
may block return of posix_spawn indefinitely if the forked child does
not exit or exec.

along with other changes, this suggests that __abort_lock should
perhaps eventually be renamed to reflect that it's becoming a broader
lock on related "process lifetime" state.

3 years agofix unintended observability of SIGABRT disposition reset via sigaction
Rich Felker [Thu, 1 Oct 2020 16:18:18 +0000 (12:18 -0400)]
fix unintended observability of SIGABRT disposition reset via sigaction

the existing abort locking logic in sigaction only accounted for
attempts to change the disposition, not attempts to observe the change
made by abort.

unfortunately the change is still observable in at least one other
place: inheritance of signal dispositions across exec and posix_spawn.
fixing these is a separate task and it's not even clear whether a
complete fix is possible.

3 years agoimplement _Fork and refactor fork using it
Rich Felker [Wed, 30 Sep 2020 17:32:59 +0000 (13:32 -0400)]
implement _Fork and refactor fork using it

the _Fork interface is defined for future issue of POSIX as the
outcome of Austin Group issue 62, which drops the AS-safety
requirement for fork, and provides an AS-safe replacement that does
not run the registered atfork handlers.

3 years agorename fork source file
Rich Felker [Wed, 30 Sep 2020 17:24:28 +0000 (13:24 -0400)]
rename fork source file

this is in preparation for implementing _Fork from POSIX-future,
factored as a separate commit to improve readability of history.

3 years agoldso: use pthread_t rather than kernel tid to track ctor visitor
Rich Felker [Tue, 29 Sep 2020 23:16:19 +0000 (19:16 -0400)]
ldso: use pthread_t rather than kernel tid to track ctor visitor

commit 188759bbee057aa94db2bbb7cf7f5855f3b9ab53 documented the intent
to allow recursive dlopen based on tracking ctor_visitor, but used a
kernel tid rather than the pthread_t to identify the caller. as a
result, it would not behave as intended under fork by a ctor, where
the child tid would not match.

3 years agofix stale lock when allocation of ctor queue fails during dlopen
Rich Felker [Tue, 29 Sep 2020 22:42:05 +0000 (18:42 -0400)]
fix stale lock when allocation of ctor queue fails during dlopen

queue_ctors should not be called with the init_fini_lock held, since
it may longjmp out on allocation failure. this introduces a minor
TOCTOU race with p->constructed, but one already exists further down
anyway, and by design it's okay to run through the queue more than
once anyway. the only reason we bother to check p->constructed at all
is to avoid spurious failure of dlopen when the library is already
fully loaded and constructed.

3 years agodrop use of pthread_once in mutexattr kernel support tests
Rich Felker [Tue, 29 Sep 2020 18:02:06 +0000 (14:02 -0400)]
drop use of pthread_once in mutexattr kernel support tests

this makes the code slightly smaller and eliminates these functions
from relevance to possible future changes to multithreaded fork.

the barrier of a_store isn't technically needed here, but a_store is
used anyway for internal consistency of the memory model.

3 years agofix missing synchronization of fork with abort
Rich Felker [Mon, 28 Sep 2020 23:32:34 +0000 (19:32 -0400)]
fix missing synchronization of fork with abort

if the multithreaded parent forked while another thread was calling
sigaction for SIGABRT or calling abort, the child could inherit a lock
state in which future calls to abort will deadlock, or in which the
disposition for SIGABRT has already been reset to SIG_DFL. this is
nonconforming since abort is AS-safe and permitted to be called
concurrently with fork or in the MT-forked child.

3 years agomove __abort_lock to its own file and drop pointless weak_alias trick
Rich Felker [Mon, 28 Sep 2020 23:30:19 +0000 (19:30 -0400)]
move __abort_lock to its own file and drop pointless weak_alias trick

the dummy definition of __abort_lock in sigaction.c was performing
exactly the same role that putting the lock in its own source file
could and should have been used to achieve.

while we're moving it, give it a proper declaration.

3 years agofix fork of processes with active async io contexts
Rich Felker [Mon, 28 Sep 2020 22:38:27 +0000 (18:38 -0400)]
fix fork of processes with active async io contexts

previously, if a file descriptor had aio operations pending in the
parent before fork, attempting to close it in the child would attempt
to cancel a thread belonging to the parent. this could deadlock, fail,
or crash the whole process of the cancellation signal handler was not
yet installed in the parent. in addition, further use of aio from the
child could malfunction or deadlock.

POSIX specifies that async io operations are not inherited by the
child on fork, so clear the entire aio fd map in the child, and take
the aio map lock (with signals blocked) across the fork so that the
lock is kept in a consistent state.

3 years agoavoid set*id/setrlimit misbehavior and hang in vforked/cloned child
Rich Felker [Thu, 17 Sep 2020 19:09:46 +0000 (15:09 -0400)]
avoid set*id/setrlimit misbehavior and hang in vforked/cloned child

taking the deprecated/dropped vfork spec strictly, doing pretty much
anything but execve in the child is wrong and undefined. however,
these are commonly needed operations to setup the child state before
exec, and historical implementations tolerated them.

for single-threaded parents, these operations already worked as
expected in the vforked child. however, due to the need for __synccall
to synchronize id/resource limit changes among all threads, calling
these functions in the vforked child of a multithreaded parent caused
a misdirected broadcast signaling of all threads in the parent. these
signals could kill the parent entirely if the synccall signal handler
had never been installed in the parent, or could be ignored if it had,
or could signal/kill one or more utterly wrong processes if the parent
already terminated (due to vfork semantics, only possible via fatal
signal) and the parent tids were recycled. in any case, the expected
number of semaphore posts would never happen, so the child would
permanently hang (with all signals blocked) waiting for them.

to mitigate this, and also make the normal usage case work as
intended, treat the condition where the caller's actual tid does not
match the tid in its thread structure as single-threaded, and bypass
the entire synccall broadcast operation.

3 years agouse new SYS_faccessat2 syscall to implement faccessat with flags
Rich Felker [Thu, 10 Sep 2020 01:55:11 +0000 (21:55 -0400)]
use new SYS_faccessat2 syscall to implement faccessat with flags

commit 0a05eace163cee9b08571d2ff9d90f5e82d9c228 implemented AT_EACCESS
for faccessat with a horrible hack, creating a child process to change
switch uid/gid and perform the access probe without making potentially
irreversible changes to the caller's credentials. this was due to the
syscall lacking a flags argument.

linux 5.8 introduced a new syscall, SYS_faccessat2, fixing this
deficiency. use it if any flags are passed, and fallback to the old
strategy on ENOSYS. continue using the old syscall when there are no
flags.

3 years agonetinet/if_ether.h: add ETH_P_MRP from linux v5.8
Szabolcs Nagy [Wed, 9 Sep 2020 07:33:47 +0000 (07:33 +0000)]
netinet/if_ether.h: add ETH_P_MRP from linux v5.8

Ethernet protocol number for media redundancy protocol, see

  linux commit 4714d13791f831d253852c8b5d657270becb8b2a
  bridge: uapi: mrp: Add mrp attributes.

3 years agoelf.h: add .note.gnu.property related definitions
Szabolcs Nagy [Wed, 9 Sep 2020 07:25:52 +0000 (07:25 +0000)]
elf.h: add .note.gnu.property related definitions

On x86 and aarch64 GNU properties may be used to mark ELF objects.

3 years agobits/syscall.h: add __NR_faccessat2 from linux v5.8
Szabolcs Nagy [Tue, 28 Jul 2020 21:17:13 +0000 (21:17 +0000)]
bits/syscall.h: add __NR_faccessat2 from linux v5.8

the linux faccessat syscall lacks a flag argument that is necessary
to implement the posix api, see

  linux commit c8ffd8bcdd28296a198f237cc595148a8d4adfbe
  vfs: add faccessat2 syscall

3 years agonetinet/tcp.h: update to linux v5.7
Szabolcs Nagy [Mon, 13 Jul 2020 19:59:41 +0000 (19:59 +0000)]
netinet/tcp.h: update to linux v5.7

add TCP_NLA_BYTES_NOTSENT and new tcp_zerocopy_receive fields, see

  linux commit c8856c051454909e5059df4e81c77b9c366c5515
  tcp-zerocopy: Return inq along with tcp receive zerocopy.

  linux commit 33946518d493cdf10aedb4a483f1aa41948a3dab
  tcp-zerocopy: Return sk_err (if set) along with tcp receive zerocopy.

  linux commit e08ab0b377a1489760533424437c5f4be7f484a4
  tcp: add bytes not sent to SCM_TIMESTAMPING_OPT_STATS

3 years agosys/mman.h: add MREMAP_DONTUNMAP from linux v5.7
Szabolcs Nagy [Mon, 13 Jul 2020 19:43:44 +0000 (19:43 +0000)]
sys/mman.h: add MREMAP_DONTUNMAP from linux v5.7

it remaps anon mappings without unmapping the original. chromeos plans
to use it with userfaultfd, see:

  linux commit e346b3813067d4b17383f975f197a9aa28a3b077
  mm/mremap: add MREMAP_DONTUNMAP to mremap()

3 years agosys/fanotify.h: update to linux v5.7
Szabolcs Nagy [Mon, 13 Jul 2020 19:38:27 +0000 (19:38 +0000)]
sys/fanotify.h: update to linux v5.7

see

  linux commit 9e2ba2c34f1922ca1e0c7d31b30ace5842c2e7d1
  fanotify: send FAN_DIR_MODIFY event flavor with dir inode and name

  linux commit 44d705b0370b1d581f46ff23e5d33e8b5ff8ec58
  fanotify: report name info for FAN_DIR_MODIFY event

3 years agoaarch64: add new HWCAP2_ macros from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:57:46 +0000 (20:57 +0000)]
aarch64: add new HWCAP2_ macros from linux v5.6

added in

  linux commit 1a50ec0b3b2e9a83f1b1245ea37a853aac2f741c
  arm64: Implement archrandom.h for ARMv8.5-RNG

  linux commit d4209d8b717311d114b5d47ba7f8249fd44e97c2
  arm64: cpufeature: Export matrix and other features to userspace

3 years agoaarch64: add HWCAP2_ macros from linux v5.3
Szabolcs Nagy [Tue, 31 Mar 2020 20:57:46 +0000 (20:57 +0000)]
aarch64: add HWCAP2_ macros from linux v5.3

these were missed before, added in

  linux commit 1201937491822b61641c1878ebcd16a93aed4540
  arm64: Expose ARMv8.5 CondM capability to userspace

  linux commit ca9503fc9e9812aa6258e55d44edb03eb30fc46f
  arm64: Expose FRINT capabilities to userspace

3 years agosched.h: add CLONE_NEWTIME from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:42:14 +0000 (20:42 +0000)]
sched.h: add CLONE_NEWTIME from linux v5.6

reuses a bit from CSIGNAL so it can only be used with unshare
and clone3, added in

  linux commit 769071ac9f20b6a447410c7eaa55d1a5233ef40c
  ns: Introduce Time Namespace

3 years agosys/random.h: add GRND_INSECURE from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:37:23 +0000 (20:37 +0000)]
sys/random.h: add GRND_INSECURE from linux v5.6

added in

  linux commit 75551dbf112c992bc6c99a972990b3f272247e23
  random: add GRND_INSECURE to return best-effort non-cryptographic bytes

3 years agosys/prctl.h: add PR_{SET,GET}_IO_FLUSHER from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:26:53 +0000 (20:26 +0000)]
sys/prctl.h: add PR_{SET,GET}_IO_FLUSHER from linux v5.6

needed for storage drivers with userspace component that may
run in the IO path, see

  linux commit 8d19f1c8e1937baf74e1962aae9f90fa3aeab463
  prctl: PR_{G,S}ET_IO_FLUSHER to support controlling memory reclaim

3 years agonetinet/udp.h: add TCP_ENCAP_ESPINTCP from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:19:26 +0000 (20:19 +0000)]
netinet/udp.h: add TCP_ENCAP_ESPINTCP from linux v5.6

The use of TCP_ in udp.h is not known, fortunately udp.h is not
specified by posix so there are no strict namespace rules, added in

  linux commit e27cca96cd68fa2c6814c90f9a1cfd36bb68c593
  xfrm: add espintcp (RFC 8229)

3 years agonetinet/tcp.h: update for linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 20:07:33 +0000 (20:07 +0000)]
netinet/tcp.h: update for linux v5.6

TCP_NLA_TIMEOUT_REHASH queries timeout-triggered rehash attempts,
tcpm_ifindex limits the scope of TCP_MD5SIG* sockopt to a device.

see

  linux commit 32efcc06d2a15fa87585614d12d6c2308cc2d3f3
  tcp: export count for rehash attempts

  linux commit 6b102db50cdde3ba2f78631ed21222edf3a5fb51
  net: Add device index to tcp_md5sig

3 years agonetinet/in.h: add IPPROTO_ macros from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 19:57:53 +0000 (19:57 +0000)]
netinet/in.h: add IPPROTO_ macros from linux v5.6

add IPPROTO_ETHERNET and IPPROTO_MPTCP, see

  linux commit 2677625387056136e256c743e3285b4fe3da87bb
  seg6: fix SRv6 L2 tunnels to use IANA-assigned protocol number

  linux commit faf391c3826cd29feae02078ca2022d2f912f7cc
  tcp: Define IPPROTO_MPTCP

3 years agoadd pidfd_getfd and openat2 syscall numbers from linux v5.6
Szabolcs Nagy [Tue, 31 Mar 2020 18:32:51 +0000 (18:32 +0000)]
add pidfd_getfd and openat2 syscall numbers from linux v5.6

also added clone3 on sh and m68k, on sh it's still missing (not
yet wired up), but reserved so safe to add.

see

  linux commit fddb5d430ad9fa91b49b1d34d0202ffe2fa0e179
  open: introduce openat2(2) syscall

  linux commit 9a2cef09c801de54feecd912303ace5c27237f12
  arch: wire up pidfd_getfd syscall

  linux commit 8649c322f75c96e7ced2fec201e123b2b073bf09
  pid: Implement pidfd_getfd syscall

  linux commit e8bb2a2a1d51511e6b3f7e08125d52ec73c11139
  m68k: Wire up clone3() syscall

3 years agonetinet/tcp.h: update tcp_info for linux v5.5
Szabolcs Nagy [Sat, 15 Feb 2020 09:42:37 +0000 (09:42 +0000)]
netinet/tcp.h: update tcp_info for linux v5.5

see

  linux commit 480274787d7e3458bc5a7cfbbbe07033984ad711
  tcp: add TCP_INFO status for failed client TFO

3 years agouse generic bits/fcntl.h for x86_64 and riscv64
Rich Felker [Thu, 3 Sep 2020 22:02:55 +0000 (18:02 -0400)]
use generic bits/fcntl.h for x86_64 and riscv64

these were only using a custom version because they needed the
"non-64" variants of the file locking command macros.

3 years agomake generic bits/fcntl.h shareable with 64-bit archs
Rich Felker [Thu, 3 Sep 2020 21:58:17 +0000 (17:58 -0400)]
make generic bits/fcntl.h shareable with 64-bit archs

the fcntl file locking command macro values in the existing generic
bits/fcntl.h were the "64" variants, requiring 64-bit archs that use
the "plain" variants to have their own bits/fcntl.h, even if they
otherwise use the common definitions for everything.

since commit 7cc79d10afd43811a486fd5e9fcdf8e45ac599e0 exposed
__LONG_MAX to all bits headers, we can now make the generic one common
between 32- and 64-bit archs.

3 years agofix missing O_LARGEFILE values on x86_64, x32, and mips64
Rich Felker [Thu, 3 Sep 2020 21:37:11 +0000 (17:37 -0400)]
fix missing O_LARGEFILE values on x86_64, x32, and mips64

prior to commit 685e40bb09f5f24a2af54ea09c97328808f76990, x86_64 was
correctly passing O_LARGEFILE to SYS_open; it was removed (defined to
0 in the public header, and changed to use the public definition) as
part of that change, probably out of a mistaken belief that it's not
needed.

however, on a mixed system with 32-bit and 64-bit binaries, it's
important that all files be opened with O_LARGEFILE, even if the
opening process is 64-bit, in case a descriptor is passed to a 32-bit
process. otherwise, attempts to access past 2GB in the 32-bit process
could produce EOVERFLOW.

most 64-bit archs added later got this right alread, except for
mips64. x32 was also affected. there are now fixed.

3 years agofix missing newline in herror output
Rich Felker [Thu, 3 Sep 2020 21:30:22 +0000 (17:30 -0400)]
fix missing newline in herror output

3 years agofix i386 __set_thread_area fallback
Rich Felker [Mon, 31 Aug 2020 01:37:12 +0000 (21:37 -0400)]
fix i386 __set_thread_area fallback

this code is only needed for pre-2.6 kernels, which are not actually
supported anyway, and was never tested. the fallback path using
SYS_modify_ldt failed to clear the upper bits of %eax (all ones due to
SYS_set_thread_area's return value being an error) before modifying
%al to attempt a new syscall.

3 years agorestore h_errno ABI compatibility with ancient binaries
Rich Felker [Mon, 31 Aug 2020 01:30:37 +0000 (21:30 -0400)]
restore h_errno ABI compatibility with ancient binaries

prior to commit e68c51ac46a9f273927aef8dcebc89912ab19ece, h_errno was
actually an external data object not a macro. bring back the symbol,
and use it as the storage for the main thread's h_errno.

technically this still doesn't provide full compatibility if the
application was multithreaded, but at the time there were no res_*
functions (and they did not set h_errno anyway), so any use of h_errno
would have been via thread-unsafe functions. thus a solution that just
fixes single-threaded applications seems acceptable.

3 years agoclean up overinclusion in files using TIOCGWINSZ
Rich Felker [Sun, 30 Aug 2020 20:49:48 +0000 (16:49 -0400)]
clean up overinclusion in files using TIOCGWINSZ

now that struct winsize is available via sys/ioctl.h once again,
including termios.h is not needed.

3 years agofix regression with applications that expect struct winsize in ioctl.h
Rich Felker [Sun, 30 Aug 2020 20:47:40 +0000 (16:47 -0400)]
fix regression with applications that expect struct winsize in ioctl.h

putting the (simple) definition in alltypes.h seems like the best
solution here. making sys/ioctl.h implicitly include termios.h is
probably excess namespace pollution.

3 years agoconfigure: enable warnings by default
Rich Felker [Fri, 28 Aug 2020 00:43:47 +0000 (20:43 -0400)]
configure: enable warnings by default

now that -Wall is not used and we control which warnings are enabled,
it makes sense to have the wanted ones on by default. hopefully this
will also discourage manually adding -Wall to CFLAGS and making
incorrect changes or bug reports based on the compiler's output.

3 years agoconfigure: use additive warnings instead of subtracting from -Wall
Rich Felker [Fri, 28 Aug 2020 00:39:41 +0000 (20:39 -0400)]
configure: use additive warnings instead of subtracting from -Wall

-Wall varies too much by compiler and version. rather than trying to
track all the unwanted style warnings that need to be subtracted, just
enable wanted warnings.

also, move -Wno-pointer-to-int-cast outside --enable-warnings
conditional so that it always applies, since it's turning off a
nuisance warning that's on-by-default with most compilers.

3 years agoconfigure: add further -Werror=... options to detected CFLAGS
Rich Felker [Thu, 27 Aug 2020 22:50:02 +0000 (18:50 -0400)]
configure: add further -Werror=... options to detected CFLAGS

these four warning options were overlooked previously, likely because
they're not part of GCC's -Wall. they all detect constraint violations
(invalid C at the source level) and should always be on in -Werror
form.

3 years agoremove redundant pthread struct members repeated for layout purposes
Rich Felker [Tue, 25 Aug 2020 02:45:51 +0000 (22:45 -0400)]
remove redundant pthread struct members repeated for layout purposes

dtv_copy, canary2, and canary_at_end existed solely to match multiple
ABI and asm-accessed layouts simultaneously. now that pthread_arch.h
can be included before struct __pthread is defined, the struct layout
can depend on macros defined by pthread_arch.h.

3 years agodeduplicate __pthread_self thread pointer adjustment out of each arch
Rich Felker [Tue, 25 Aug 2020 02:23:08 +0000 (22:23 -0400)]
deduplicate __pthread_self thread pointer adjustment out of each arch

the adjustment made is entirely a function of TLS_ABOVE_TP and
TP_OFFSET. aside from avoiding repetition of the TP_OFFSET value and
arithmetic, this change makes pthread_arch.h independent of the
definition of struct __pthread from pthread_impl.h. this in turn will
allow inclusion of pthread_arch.h to be moved to the top of
pthread_impl.h so that it can influence the definition of the
structure.

previously, arch files were very inconsistent about the type used for
the thread pointer. this change unifies the new __get_tp interface to
always use uintptr_t, which is the most correct when performing
arithmetic that may involve addresses outside the actual pointed-to
object (due to TP_OFFSET).

3 years agodeduplicate TP_ADJ logic out of each arch, replace with TP_OFFSET
Rich Felker [Tue, 25 Aug 2020 02:04:52 +0000 (22:04 -0400)]
deduplicate TP_ADJ logic out of each arch, replace with TP_OFFSET

the only part of TP_ADJ that was not uniquely determined by
TLS_ABOVE_TP was the 0x7000 adjustment used mainly on mips and powerpc
variants.

3 years agoreport res_query failures, including nxdomain/nodata, via h_errno
Rich Felker [Tue, 25 Aug 2020 01:56:48 +0000 (21:56 -0400)]
report res_query failures, including nxdomain/nodata, via h_errno

while it's not clearly documented anywhere, this is the historical
behavior which some applications expect. applications which need to
see the response packet in these cases, for example to distinguish
between nonexistence in a secure vs insecure zone, must already use
res_mkquery with res_send in order to be portable, since most if not
all other implementations of res_query don't provide it.

3 years agomake h_errno thread-local
Rich Felker [Tue, 25 Aug 2020 01:38:49 +0000 (21:38 -0400)]
make h_errno thread-local

the framework to do this always existed but it was deemed unnecessary
because the only [ex-]standard functions using h_errno were not
thread-safe anyway. however, some of the nonstandard res_* functions
are also supposed to set h_errno to indicate the cause of error, and
were unable to do so because it was not thread-safe. this change is a
prerequisite for fixing them.

3 years agoadd tcgetwinsize and tcsetwinsize functions, move struct winsize
Rich Felker [Mon, 24 Aug 2020 16:29:30 +0000 (12:29 -0400)]
add tcgetwinsize and tcsetwinsize functions, move struct winsize

these have been adopted for future issue of POSIX as the outcome of
Austin Group issue 1151, and are simply functions performing the roles
of the historical ioctls. since struct winsize is being standardized
along with them, its definition is moved to the appropriate header.

there is some chance this will break source files that expect struct
winsize to be defined by sys/ioctl.h without including termios.h. if
this happens, further changes will be needed to have sys/ioctl.h
expose it too.

3 years agofix MUSL_LOCPATH search
Rich Felker [Sat, 22 Aug 2020 17:51:32 +0000 (13:51 -0400)]
fix MUSL_LOCPATH search

all path elements but the last had the final byte truncated.

3 years agoadd gettid function
Rich Felker [Tue, 18 Aug 2020 00:12:53 +0000 (20:12 -0400)]
add gettid function

this is a prerequisite for addition of other interfaces that use
kernel tids, including futex and SIGEV_THREAD_ID.

there is some ambiguity as to whether the semantic return type should
be int or pid_t. either way, futex API imposes a contract that the
values fit in int (excluding some upper reserved bits). glibc used
pid_t, so in the interest of not having gratuitous mismatch (the
underlying types are the same anyway), pid_t is used here as well.

while conceptually this is a syscall, the copy stored in the thread
structure is always valid in all contexts where it's valid to call
libc functions, so it's used to avoid the syscall.

3 years agoaarch64: fix setjmp return value
Szabolcs Nagy [Wed, 12 Aug 2020 21:00:26 +0000 (21:00 +0000)]
aarch64: fix setjmp return value

longjmp should set the return value of setjmp, but 64bit
registers were used for the 0 check while the type is int.

use the code that gcc generates for return val ? val : 1;

3 years agosetjmp: optimize longjmp prologues
Alexander Monakov [Wed, 12 Aug 2020 11:34:30 +0000 (14:34 +0300)]
setjmp: optimize longjmp prologues

Use a branchless sequence that is one byte shorter on 64-bit, same size
on 32-bit. Thanks to Pete Cawley for suggesting this variant.

3 years agosetjmp: optimize x86 longjmp epilogues
Alexander Monakov [Tue, 11 Aug 2020 18:11:16 +0000 (21:11 +0300)]
setjmp: optimize x86 longjmp epilogues

3 years agosetjmp: avoid useless REX-prefix on xor %eax, %eax
Alexander Monakov [Tue, 11 Aug 2020 18:11:15 +0000 (21:11 +0300)]
setjmp: avoid useless REX-prefix on xor %eax, %eax

3 years agosetjmp: fix x86-64 longjmp argument adjustment
Alexander Monakov [Tue, 11 Aug 2020 18:11:14 +0000 (21:11 +0300)]
setjmp: fix x86-64 longjmp argument adjustment

longjmp 'val' argument is an int, but the assembly is referencing 64-bit
registers as if the argument was a long, or the caller was responsible
for extending the argument. Though the psABI is not clear on this, the
interpretation in GCC is that high bits may be arbitrary and the callee
is responsible for sign/zero-extending the value as needed (likewise for
return values: callers must anticipate that high bits may be garbage).

Therefore testing %rax is a functional bug: setjmp would wrongly return
zero if longjmp was called with val==0, but high bits of %rsi happened
to be non-zero.

Rewrite the prologue to refer to 32-bit registers. In passing, change
'test' to use %rsi, as there's no advantage to using %rax and the new
form is cheaper on processors that do not perform move elimination.

3 years agoprefer new socket syscalls, fallback to SYS_socketcall only if needed
Rich Felker [Sun, 9 Aug 2020 00:59:26 +0000 (20:59 -0400)]
prefer new socket syscalls, fallback to SYS_socketcall only if needed

a number of users performing seccomp filtering have requested use of
the new individual syscall numbers for socket syscalls, rather than
the legacy multiplexed socketcall, since the latter has the arguments
all in memory where they can't participate in filter decisions.

previously, some archs used the multiplexed socketcall if it was
historically all that was available, while other archs used the
separate syscalls. the intent was that the latter set only include
archs that have "always" had separate socket syscalls, at least going
back to linux 2.6.0. however, at least powerpc, powerpc64, and sh were
wrongly included in this set, and thus socket operations completely
failed on old kernels for these archs.

with the changes made here, the separate syscalls are always
preferred, but fallback code is compiled for archs that also define
SYS_socketcall. two such archs, mips (plain o32) and microblaze,
define SYS_socketcall despite never having needed it, so it's now
undefined by their versions of syscall_arch.h to prevent inclusion of
useless fallback code.

some archs, where the separate syscalls were only added after the
addition of SYS_accept4, lack SYS_accept. because socket calls are
always made with zeros in the unused argument positions, it suffices
to just use SYS_accept4 to provide a definition of SYS_accept, and
this is done to make happy the macro machinery that concatenates the
socket call name onto __SC_ and SYS_.

3 years agomath: new software sqrtl
Szabolcs Nagy [Sun, 14 Jun 2020 13:41:21 +0000 (13:41 +0000)]
math: new software sqrtl

same approach as in sqrt.

sqrtl was broken on aarch64, riscv64 and s390x targets because
of missing quad precision support and on m68k-sf because of
missing ld80 sqrtl.

this implementation is written for quad precision and then
edited to make it work for both m68k and x86 style ld80 formats
too, but it is not expected to be optimal for them.

note: using fp instructions for the initial estimate when such
instructions are available (e.g. double prec sqrt or rsqrt) is
avoided because of fenv correctness.

3 years agomath: add __math_invalidl
Szabolcs Nagy [Mon, 29 Jun 2020 17:14:42 +0000 (17:14 +0000)]
math: add __math_invalidl

for targets where long double is different from double.

3 years agomath: new software sqrtf
Szabolcs Nagy [Fri, 12 Jun 2020 17:34:28 +0000 (17:34 +0000)]
math: new software sqrtf

same method as in sqrt, this was tested on all inputs against
an sqrtf instruction. (the only difference found was that x86
sqrtf does not signal the x86 specific input-denormal exception
on negative subnormal inputs while the software sqrtf does,
this is fine as it was designed for ieee754 exceptions only.)

there is known faster method:
"Computing Floating-Point Square Roots via Bivariate Polynomial Evaluation"
that computes sqrtf directly via pipelined polynomial evaluation
which allows more parallelism, but the design does not generalize
easily to higher precisions.