Commit Graph

2694 Commits

Author SHA1 Message Date
Szabolcs Nagy e6403887cc fix exp10l.c to include float.h
the previous commit was a no op in exp10l because LDBL_* macros
were implicitly 0 (the preprocessor does not warn about undefined
symbols).
2014-09-08 16:24:17 +02:00
Szabolcs Nagy 0c32c2635e prune math code on archs with binary64 long double
__polevll, __p1evll and exp10l were provided on archs when long double
is the same as double. The first two were completely unused and exp10l
can be a wrapper around exp10.
2014-09-08 15:51:42 +02:00
Szabolcs Nagy 976bb28fa0 add new F_OFD_* macros to fcntl.h (open file description locks)
open file description locks are inherited across fork and only auto
dropped after the last fd of the file description is closed, they can be
used to synchronize between threads that open separate file descriptions
for the same file.

new in linux 3.15 commit 0d3f7a2dd2f5cf9642982515e020c1aee2cf7af6
2014-09-08 15:35:26 +02:00
Rich Felker 23614b0fcb add C11 thread creation and related thread functions
based on patch by Jens Gustedt.

the main difficulty here is handling the difference between start
function signatures and thread return types for C11 threads versus
POSIX threads. pointers to void are assumed to be able to represent
faithfully all values of int. the function pointer for the thread
start function is cast to an incorrect type for passing through
pthread_create, but is cast back to its correct type before calling so
that the behavior of the call is well-defined.

changes to the existing threads implementation were kept minimal to
reduce the risk of regressions, and duplication of code that carries
implementation-specific assumptions was avoided for ease and safety of
future maintenance.
2014-09-07 10:28:08 -04:00
Jens Gustedt 14397cec2c add C11 condition variable functions
Because of the clear separation for private pthread_cond_t these
interfaces are quite simple and direct.
2014-09-06 22:27:45 -04:00
Jens Gustedt 8b0472932c add C11 mutex functions 2014-09-06 22:07:22 -04:00
Jens Gustedt e16f70f452 add C11 thread functions operating on tss_t and once_flag
These all have POSIX equivalents, but aside from tss_get, they all
have minor changes to the signature or return value and thus need to
exist as separate functions.
2014-09-06 21:38:04 -04:00
Rich Felker b7cf71a190 add threads.h and needed per-arch types for mtx_t and cnd_t
based on patch by Jens Gustedt.

mtx_t and cnd_t are defined in such a way that they are formally
"compatible types" with pthread_mutex_t and pthread_cond_t,
respectively, when accessed from a different translation unit. this
makes it possible to implement the C11 functions using the pthread
functions (which will dereference them with the pthread types) without
having to use the same types, which would necessitate either namespace
violations (exposing pthread type names in threads.h) or incompatible
changes to the C++ name mangling ABI for the pthread types.

for the rest of the types, things are much simpler; using identical
types is possible without any namespace considerations.
2014-09-06 20:44:30 -04:00
Jens Gustedt df7d0dfb9c use weak symbols for the POSIX functions that will be used by C threads
The intent of this is to avoid name space pollution of the C threads
implementation.

This has two sides to it. First we have to provide symbols that wouldn't
pollute the name space for the C threads implementation. Second we have
to clean up some internal uses of POSIX functions such that they don't
implicitly drag in such symbols.
2014-09-06 18:11:24 -04:00
Rich Felker 6eb19505bc add C11 timespec_get function, with associated time.h changes for C11
based on patch by Jens Gustedt for inclusion with C11 threads
implementation, but committed separately since it's independent of
threads.
2014-09-06 12:58:09 -04:00
Rich Felker 86876dbec5 fix non-static dummy function that slipped in with locale implementation 2014-09-06 08:40:20 -04:00
Szabolcs Nagy 7ff804269b fix macros for LFS *64_t types in sys/stat.h, sys/types.h, glob.h
there is no blksize64_t (blksize_t is always long) but there are
fsblkcnt64_t and fsfilcnt64_t types in sys/stat.h and sys/types.h.
and glob.h missed glob64_t.
2014-09-05 16:03:07 -04:00
Szabolcs Nagy 36c30c4ddd add missing legacy LFS *64 symbol aliases
versionsort64, aio*64 and lio*64 symbols were missing, they are
only needed for glibc ABI compatibility, on the source level
dirent.h and aio.h already redirect them.
2014-09-05 16:02:22 -04:00
Szabolcs Nagy 546f6b322b fix memory leak in regexec when input contains illegal sequence 2014-09-05 15:12:34 -04:00
Rich Felker 3bed89aa74 fix off-by-one in bounds check in fpathconf
this error resulted in an out-of-bounds read, as opposed to a reported
error, when calling the function with an argument one greater than the
max valid index.
2014-09-05 14:01:13 -04:00
Rich Felker 633183b5d1 fix potential read past end of buffer in getnameinfo service name lookup
if the loop stopped due to reaching the end of the string, the
subsequent increment could possibly move the position one past the end
of the buffer. no further writes happen, the reads cannot fault anyway
unless the stack completely lacks any zero bytes, and reading junk
should not yield an incorrect result from the function either.
nonetheless the code was wrong and needs to be fixed.
2014-09-05 13:52:20 -04:00
Rich Felker 4ec2d25a6a remove incorrect and useless check in network service name lookup code
the condition was probably intended to be !*p rather than !p, but
neither is needed here. the subsequent code naturally handles the case
where it's already at end of string.
2014-09-05 13:49:47 -04:00
Rich Felker 4674809bdf fix case mapping for U+00DF (ß)
U+00DF ('ß') has had an uppercase form (U+1E9E) available since
Unicode 5.1, but Unicode lacks the case mappings for it due to
stability policy. when I added support for the new character in commit
1a63a9fc30, I omitted the mapping in the
lowercase-to-uppercase direction. this choice was not based on any
actual information, only assumptions.

this commit adds bidirectional case mappings between U+00DF and
U+1E9E, and removes the special-case hack that allowed U+00DF to be
identified as lowecase despite lacking a mapping. aside from strong
evidence that this is the "right" behavior for real-world usage of
these characters, several factors informed this decision:

- the other "potentially correct" mapping, to "SS", is not
  representable in the C case-mapping system anyway.

- leaving one letter in lowercase form when transforming a string to
  uppercase is obviously wrong.

- having a character which is nominally lowercase but which is fixed
  under case mapping violates reasonable invariants.
2014-09-05 03:28:00 -04:00
Rich Felker fff5469303 make non-waiting paths of sem_[timed]wait and pthread_join cancelable
per POSIX these functions are both cancellation points, so they must
act on any cancellation request which is pending prior to the call.
previously, only the code path where actual waiting took place could
act on cancellation.
2014-09-05 03:22:52 -04:00
Rich Felker 80e6485455 remove an extra layer of buffer copying in getnameinfo reverse dns
the outer getnameinfo function already has a properly-sized temporary
buffer for storing the reverse dns (ptr) result. there is no reason
for the callback to use a secondary buffer and copy it on success, and
doing so potentially expanded the impact of the dn_expand bug that was
fixed in commit 49d2c8c6bc.

this change reduces the code size by a small amount, and also reduces
the run-time stack space requirements by about 256 bytes.
2014-09-05 02:50:38 -04:00
Rich Felker 6e2bb7acf4 fix multiple stdio functions' behavior on zero-length operations
previously, fgets, fputs, fread, and fwrite completely omitted locking
and access to the FILE object when their arguments yielded a zero
length read or write operation independent of the FILE state. this
optimization was invalid; it wrongly skipped marking the stream as
byte-oriented (a C conformance bug) and exposed observably missing
synchronization (a POSIX conformance bug) where one of these functions
could wrongly complete despite another thread provably holding the
lock.
2014-09-04 22:21:17 -04:00
Rich Felker 402611c3ba suppress null termination when fgets reads EOF with no data
the C standard requires that "the contents of the array remain
unchanged" in this case.

this patch also changes the behavior on read errors, but in that case
"the array contents are indeterminate", so the application cannot
inspect them anyway.
2014-09-04 21:37:13 -04:00
Szabolcs Nagy 49d2c8c6bc fix dn_expand empty name handling and offsets to 0
Empty name was rejected in dn_expand since commit
56b57f37a4
which is a regression as reported by Natanael Copa.

Furthermore if an offset pointer in a compressed name
pointed to a terminating 0 byte (instead of a label)
the returned name was not null terminated.
2014-09-04 20:13:10 -04:00
Szabolcs Nagy 70729de075 add static_assert and hide noreturn, alignas, alignof from C++
add static_assert and protect the other new C11 keyword macros
with #ifndef __cplusplus so they don't conflict with C++ keywords.
2014-08-27 02:55:54 -04:00
Szabolcs Nagy 18dde00713 add C11 floating-point characteristic macros to float.h
C11 introduced *_DECIMAL_DIG and *_HAS_SUBNORM macros.
2014-08-27 02:54:01 -04:00
Rich Felker 8d998a7b3b add malloc_usable_size function and non-stub malloc.h
this function is needed for some important practical applications of
ABI compatibility, and may be useful for supporting some non-portable
software at the source level too.

I was hesitant to add a function which imposes any constraints on
malloc internals; however, it turns out that any malloc implementation
which has realloc must already have an efficient way to determine the
size of existing allocations, so no additional constraint is imposed.

for now, some internal malloc definitions are duplicated in the new
source file. if/when malloc is refactored to put them in a shared
internal header file, these could be removed.

since malloc_usable_size is conventionally declared in malloc.h, the
empty stub version of this file was no longer suitable. it's updated
to provide the standard allocator functions, nonstandard ones (even if
stdlib.h would not expose them based on the feature test macros in
effect), and any malloc-extension functions provided (currently, only
malloc_usable_size).
2014-08-25 22:47:27 -04:00
Rich Felker f5fb20b0e9 refrain from spinning on locks when there is already a waiter
if there is already a waiter for a lock, spinning on the lock is
essentially an attempt to steal it from whichever waiter would obtain
it via any priority rules in place, and is therefore undesirable. in
the current implementation, there is always an inherent race window at
unlock during which a newly-arriving thread may steal the lock from
the existing waiters, but we should aim to keep this window minimal
rather than enlarging it.
2014-08-25 20:24:07 -04:00
Rich Felker 97a7512b68 spin before waiting on futex in mutex and rwlock lock operations 2014-08-25 20:16:26 -04:00
Rich Felker 2ff714c613 spin in sem_[timed]wait before performing futex wait
empirically, this increases the maximum rate of wait/post operations
between two threads by 20-150 times on machines I tested, including
x86 and arm. conceptually, it makes sense to do some spinning because
semaphores are intended to be usable as a notification mechanism
between threads, not just as locks, and low-latency notification is a
valuable property to have.
2014-08-25 16:38:25 -04:00
Rich Felker 8b3d7d0d35 fix build error on arm due to new a_spin code
this was broken by commit ea818ea834.
2014-08-25 16:37:13 -04:00
Rich Felker b8a9c90e4f sanitize number of spins in userspace before futex wait
the previous spin limit of 10000 was utterly unreasonable.
empirically, it could consume up to 200000 cycles, whereas a failed
futex wait (EAGAIN) typically takes 1000 cycles or less, and even a
true wait/wake round seems much less expensive.

the new counts (100 for general wait, 200 in barrier) were simply
chosen to be in the range of what's reasonable without having adverse
effects on casual micro-benchmark tests I have been running. they may
still be too high, from a standpoint of not wasting cpu cycles, but at
least they're a lot better than before. rigorous testing across
different archs and cpu models should be performed at some point to
determine whether further adjustments should be made.
2014-08-25 15:58:19 -04:00
Rich Felker ea818ea834 add working a_spin() atomic for non-x86 targets
conceptually, a_spin needs to be at least a compiler barrier, so the
compiler will not optimize out loops (and the load on each iteration)
while spinning. it should also be a memory barrier, or the spinning
thread might keep spinning without noticing stores from other threads,
thus delaying for longer than it should.

ideally, an optimal a_spin implementation that avoids unnecessary
cache/memory contention should be chosen for each arch, but for now,
the easiest thing is to perform a useless a_cas on the calling
thread's stack.
2014-08-25 15:43:40 -04:00
Rich Felker 5345c9b884 fix false ownership of stdio FILEs due to tid reuse
this is analogous commit fffc5cda10
which fixed the corresponding issue for mutexes.

the robust list can't be used here because the locks do not share a
common layout with mutexes. at some point it may make sense to simply
incorporate a mutex object into the FILE structure and use it, but
that would be a much more invasive change, and it doesn't mesh well
with the current design that uses a simpler code path for internal
locking and pulls in the recursive-mutex-like code when the flockfile
API is used explicitly.
2014-08-23 23:35:10 -04:00
Rich Felker b8ca9eb530 fix fallback checks for kernels without private futex support
for unknown syscall commands, the kernel produces ENOSYS, not EINVAL.
2014-08-22 23:49:54 -04:00
Rich Felker a6293285e9 fix use of uninitialized memory with application-provided thread stacks
the subsequent code in pthread_create and the code which copies TLS
initialization images to the new thread's TLS space assume that the
memory provided to them is zero-initialized, which is true when it's
obtained by pthread_create using mmap. however, when the caller
provides a stack using pthread_attr_setstack, pthread_create cannot
make any assumptions about the contents. simply zero-filling the
relevant memory in this case is the simplest and safest fix.
2014-08-22 14:05:10 -04:00
Rich Felker 321f4fa906 add max_align_t definition for C11 and C++11
unfortunately this needs to be able to vary by arch, because of a huge
mess GCC made: the GCC definition, which became the ABI, depends on
quirks in GCC's definition of __alignof__, which does not match the
formal alignment of the type.

GCC's __alignof__ unexpectedly exposes the an implementation detail,
its "preferred alignment" for the type, rather than the formal/ABI
alignment of the type, which it only actually uses in structures. on
most archs the two values are the same, but on some (at least i386)
the preferred alignment is greater than the ABI alignment.

I considered using _Alignas(8) unconditionally, but on at least one
arch (or1k), the alignment of max_align_t with GCC's definition is
only 4 (even the "preferred alignment" for these types is only 4).
2014-08-20 17:20:14 -04:00
Rich Felker 4992ace942 further simplify and optimize new cond var
the main idea of the changes made is to have waiters wait directly on
the "barrier" lock that was used to prevent them from making forward
progress too early rather than first waiting on the atomic state value
and then attempting to lock the barrier.

in addition, adjustments to the mutex waiter count are optimized.
previously, each waking waiter decremented the count (unless it was
the first) then immediately incremented it again for the next waiter
(unless it was the last). this was a roundabout was of achieving the
equivalent of incrementing it once for the first waiter and
decrementing it once for the last.
2014-08-18 14:36:56 -04:00
Rich Felker 2c4b510bae simplify and improve new cond var implementation
previously, wake order could be unpredictable: if a waiter happened to
leave its futex wait on the state early, e.g. due to EAGAIN while
restarting after a signal handler, it could acquire the mutex out of
turn. handling this required ugly O(n) list walking in the unwait
function and accounting to remove waiters that already woke from the
list.

with the new changes, the "barrier" locks in each waiter node are only
unlocked in turn. in addition to simplifying the code, this seems to
improve performance slightly, probably by reducing the number of
accesses threads make to each other's stacks.

as an additional benefit, unrecoverable mutex re-locking errors
(mainly ENOTRECOVERABLE for robust mutexes) no longer need to be
handled with deadlock; they can be reported to the caller, since the
unlocking sequence makes it unnecessary to rely on the mutex to
synchronize access to the waiter list.
2014-08-18 01:26:16 -04:00
Rich Felker 37195db8ec redesign cond var implementation to fix multiple issues
the immediate issue that was reported by Jens Gustedt and needed to be
fixed was corruption of the cv/mutex waiter states when switching to
using a new mutex with the cv after all waiters were unblocked but
before they finished returning from the wait function.

self-synchronized destruction was also handled poorly and may have had
race conditions. and the use of sequence numbers for waking waiters
admitted a theoretical missed-wakeup if the sequence number wrapped
through the full 32-bit space.

the new implementation is largely documented in the comments in the
source. the basic principle is to use linked lists initially attached
to the cv object, but detachable on signal/broadcast, made up of nodes
residing in automatic storage (stack) on the threads that are waiting.
this eliminates the need for waiters to access the cv object after
they are signaled, and allows us to limit wakeup to one waiter at a
time during broadcasts even when futex requeue cannot be used.

performance is also greatly improved, roughly double some tests.

basically nothing is changed in the process-shared cond var case,
where this implementation does not work, since processes do not have
access to one another's local storage.
2014-08-17 22:09:47 -04:00
Rich Felker 4220d298ef fix possible failure-to-wake deadlock with robust mutexes
when the kernel is responsible for waking waiters on a robust mutex
whose owner died, it does not have a waiters count available and must
rely entirely on the waiter bit of the lock value.

normally, this bit is only set by newly arriving waiters, so it will
be clear if no new waiters arrived after the current owner obtained
the lock, even if there are other waiters present. leaving it clear is
desirable because it allows timed-lock operations to remove themselves
as waiters and avoid causing unnecessary futex wake syscalls. however,
for process-shared robust mutexes, we need to set the bit whenever
there are existing waiters so that the kernel will know to wake them.

for non-process-shared robust mutexes, the wake happens in userspace
and can look at the waiters count, so the bit does not need to be set
in the non-process-shared case.
2014-08-17 02:05:14 -04:00
Rich Felker de7e99c585 make pointers used in robust list volatile
when manipulating the robust list, the order of stores matters,
because the code may be asynchronously interrupted by a fatal signal
and the kernel will then access the robust list in what is essentially
an async-signal context.

previously, aliasing considerations made it seem unlikely that a
compiler could reorder the stores, but proving that they could not be
reordered incorrectly would have been extremely difficult. instead
I've opted to make all the pointers used as part of the robust list,
including those in the robust list head and in the individual mutexes,
volatile.

in addition, the format of the robust list has been changed to point
back to the head at the end, rather than ending with a null pointer.
this is to match the documented kernel robust list ABI. the null
pointer, which was previously used, only worked because faults during
access terminate the robust list processing.
2014-08-17 00:46:26 -04:00
Rich Felker d338b506e3 fix robust mutex unrecoverable status, and related clean-up
a robust mutex should not enter the unrecoverable status until it's
unlocked without marking it consistent. previously, flag 8 in the type
was used as an indication of unrecoverable, but only honored after
successful locking; this resulted in a race window where the
unrecoverable mutex could appear to a second thread as locked/busy
again while the first thread was in the process of observing it as
unrecoverable.

now, flag 8 is used to mean that the mutex is in the process of being
recovered, but not yet marked consistent. the flag only takes effect
in pthread_mutex_unlock, where it causes the value 0x40000000 (owner
dead flag, with old owner tid 0, an otherwise impossible state) to be
stored in the lock. subsequent lock attempts will interpret this state
as unrecoverable.
2014-08-16 19:52:04 -04:00
Rich Felker fffc5cda10 fix false ownership of mutexes due to tid reuse, using robust list
per the resolution of Austin Group issue 755, the POSIX requirement
that ownership be enforced for recursive and error-checking mutexes
does not allow a random new thread to acquire ownership of an orphaned
mutex just because it happened to be assigned the same tid as the
original owner that exited with the mutex locked.

one possible fix for this issue would be to disallow the kernel thread
to terminate when it exited with mutexes held, permanently reserving
the tid against reuse. however, this does not solve the problem for
process-shared mutexes where lifetime cannot be controlled, so it was
not used.

the alternate approach I've taken is to reuse the robust mutex system
for non-robust recursive and error-checking mutexes. when a thread
exits, the kernel (or the new userspace robust-list code added in
commit b092f1c5fa) will set the
owner-died bit for these orphaned mutexes, but since the mutex-type is
not robust, pthread_mutex_trylock will not allow a new owner to
acquire them. instead, they remain in a state of being permanently
locked, as desired.
2014-08-16 19:15:19 -04:00
Rich Felker 25d12fc0fc optimize locking against vm changes for mmap/munmap
the whole point of this locking is to prevent munmap, or mmap with
MAP_FIXED, from deallocating virtual addresses, or changing the
backing a given virtual address refers to, during certain race windows
involving self-synchronized unmapping or destruction of pthread
synchronization objects. there is no need for exclusion in the other
direction, so it suffices to take the lock momentarily and release it
before making the syscall, rather than holding it across the syscall.
2014-08-16 02:41:45 -04:00
Rich Felker b092f1c5fa enable private futex for process-local robust mutexes
the kernel always uses non-private wake when walking the robust list
when a thread or process exits, so it's not able to wake waiters
listening with the private futex flag. this problem is solved by doing
the equivalent in userspace as the last step of pthread_exit.

care is taken to remove mutexes from the robust list before unlocking
them so that the kernel will not attempt to access them again,
possibly after another thread locks them. this removal code can treat
the list as singly-linked, since no further code which would add or
remove items is able to run at this point. moreover, the pending
pointer is not needed since the mutexes being unlocked are all
process-local; in the case of asynchronous process termination, they
all cease to exist.

since a process-local robust mutex cannot come into existence without
a call to pthread_mutexattr_setrobust in the same process, the code
for userspace robust list processing is put in that source file, and
a weak alias to a dummy function is used to avoid pulling in this
bloat as part of pthread_exit in static-linked programs.
2014-08-16 02:28:34 -04:00
Rich Felker bc09d58c04 make futex operations use private-futex mode when possible
private-futex uses the virtual address of the futex int directly as
the hash key rather than requiring the kernel to resolve the address
to an underlying backing for the mapping in which it lies. for certain
usage patterns it improves performance significantly.

in many places, the code using futex __wake and __wait operations was
already passing a correct fixed zero or nonzero flag for the priv
argument, so no change was needed at the site of the call, only in the
__wake and __wait functions themselves. in other places, especially
where the process-shared attribute for a synchronization object was
not previously tracked, additional new code is needed. for mutexes,
the only place to store the flag is in the type field, so additional
bit masking logic is needed for accessing the type.

for non-process-shared condition variable broadcasts, the futex
requeue operation is unable to requeue from a private futex to a
process-shared one in the mutex structure, so requeue is simply
disabled in this case by waking all waiters.

for robust mutexes, the kernel always performs a non-private wake when
the owner dies. in order not to introduce a behavioral regression in
non-process-shared robust mutexes (when the owning thread dies), they
are simply forced to be treated as process-shared for now, giving
correct behavior at the expense of performance. this can be fixed by
adding explicit code to pthread_exit to do the right thing for
non-shared robust mutexes in userspace rather than relying on the
kernel to do it, and will be fixed in this way later.

since not all supported kernels have private futex support, the new
code detects EINVAL from the futex syscall and falls back to making
the call without the private flag. no attempt to cache the result is
made; caching it and using the cached value efficiently is somewhat
difficult, and not worth the complexity when the benefits would be
seen only on ancient kernels which have numerous other limitations and
bugs anyway.
2014-08-15 23:54:52 -04:00
Szabolcs Nagy d86af2a080 fix #ifdef inside a macro argument list in __init_tls.c
C99 6.10.3p11 disallows such constructs
so use an #ifdef outside of the argument list of __syscall
2014-08-13 17:07:44 +02:00
Szabolcs Nagy d146d4dc11 fix CPU_EQUAL macro in sched.h 2014-08-13 16:55:56 +02:00
Szabolcs Nagy b04971d91a add inline isspace in ctype.h as an optimization
isspace can be a bottleneck in a simple parser, inlining it
gives slightly smaller and faster code

src/locale/pleval.o already had this optimization, the size
change for other libc functions for i386 is

src/internal/intscan.o     2134    2118   -16
src/locale/dcngettext.o    1562    1552   -10
src/network/res_msend.o    1961    1940   -21
src/network/lookup_name.o  2627    2608   -19
src/network/getnameinfo.o  1814    1811    -3
src/network/lookup_serv.o   643     624   -19
src/stdio/vfscanf.o        2675    2663   -12
src/stdlib/atoll.o          117     107   -10
src/stdlib/atoi.o            95      91    -4
src/stdlib/atol.o            95      91    -4
src/time/strptime.o        1515    1503   -12
(TOTALS)                 432451  432321  -130
2014-08-13 16:47:51 +02:00
Rich Felker 4fe57cad70 add dlerror message for static-linked dlsym failure 2014-08-08 00:53:27 -04:00