musl
8 years agoadd sh fdpic subarch variants
Rich Felker [Sat, 12 Sep 2015 03:22:19 +0000 (03:22 +0000)]
add sh fdpic subarch variants

with this commit it should be possible to produce a working
static-linked fdpic libc and application binaries for sh.

the changes in reloc.h are largely unused at this point since dynamic
linking is not supported, but the CRTJMP macro is used one place
outside of dynamic linking, in __unmapself.

8 years agoadd fdpic version of entry point code for sh
Rich Felker [Sat, 12 Sep 2015 03:18:08 +0000 (03:18 +0000)]
add fdpic version of entry point code for sh

this version of the entry point is only suitable for static linking in
ET_EXEC form. neither dynamic linking nor pie is supported yet. at
some point in the future the fdpic and non-fdpic versions of this code
may be unified but for now it's easiest to work with them separately.

8 years agoprovide arch-generic fdpic self-relocation code for crt1 to use
Rich Felker [Sat, 12 Sep 2015 03:10:44 +0000 (03:10 +0000)]
provide arch-generic fdpic self-relocation code for crt1 to use

this file is intended to be included by crt_arch.h on fdpic-based
targets and needs to be called from the entry point asm.

8 years agomake sh clone asm fdpic-compatible
Rich Felker [Sat, 12 Sep 2015 02:55:28 +0000 (02:55 +0000)]
make sh clone asm fdpic-compatible

clone calls back to a function pointer provided by the caller, which
will actually be a pointer to a function descriptor on fdpic. the
obvious solution is to have a separate version of clone for fdpic, but
I have taken a simpler approach to go around the problem. instead of
calling the pointed-to function from asm, a direct call is made to an
internal C function which then calls the pointed-to function. this
lets the C compiler generate the appropriate calling convention for an
indirect call with no need for ABI-specific assembly.

8 years agomake sh crti/crtn init/fini fragments setup proper stack frame
Rich Felker [Sat, 12 Sep 2015 02:50:28 +0000 (02:50 +0000)]
make sh crti/crtn init/fini fragments setup proper stack frame

for fdpic support is is essential that the got pointer be saved at a
known, ABI-dictated offset from the frame pointer, since there is no
way to recover it once it's lost.

8 years agoadd sh relocation types needed for fdpic to elf.h
Rich Felker [Sat, 12 Sep 2015 02:49:02 +0000 (02:49 +0000)]
add sh relocation types needed for fdpic to elf.h

8 years agofix uninitialized scopeid in lookups from hosts file and ip literals
Timo Teräs [Fri, 11 Sep 2015 06:15:06 +0000 (06:15 +0000)]
fix uninitialized scopeid in lookups from hosts file and ip literals

8 years agofix missing earlyclobber flag in i386 a_ctz_64 asm
Rich Felker [Wed, 9 Sep 2015 07:18:28 +0000 (07:18 +0000)]
fix missing earlyclobber flag in i386 a_ctz_64 asm

this error was only found by reading the code, but it seems to have
been causing gcc to produce wrong code in malloc: the same register
was used for the output and the high word of the input. in principle
this could have caused an infinite loop searching for an available
bin, but in practice most x86 models seem to implement the "undefined"
result of the bsf instruction as "unchanged".

8 years agoremove unused (and invalid) C version of sigsetjmp
Rich Felker [Wed, 9 Sep 2015 06:59:45 +0000 (06:59 +0000)]
remove unused (and invalid) C version of sigsetjmp

originally, the comment in this code was correct and it would likely
work if the compiler generated a tail call to setjmp. however, commit
583e55122e767b1586286a0d9c35e2a4027998ab redesigned sigsetjmp and
siglongjmp such that the old C implementation (which was not intended
to be used) is not even conceptually correct. remove it in the
interest of avoiding confusion when porting to new archs.

8 years agofix breakage in nl_langinfo from previous commit
Rich Felker [Wed, 9 Sep 2015 06:04:42 +0000 (06:04 +0000)]
fix breakage in nl_langinfo from previous commit

8 years agomake nl_langinfo(CODESET) always return "UTF-8"
Rich Felker [Wed, 9 Sep 2015 05:13:33 +0000 (05:13 +0000)]
make nl_langinfo(CODESET) always return "UTF-8"

this restores the original behavior prior to the addition of the
byte-based C locale and fixes what is effectively a regression in
musl's property of always providing working UTF-8 support.

commit 1507ebf837334e9e07cfab1ca1c2e88449069a80 introduced the codeset
name "UTF-8-CODE-UNITS" for the byte-based C locale to represent that
the semantic content is UTF-8 but that it is being processed as code
units (bytes) rather than whole multibyte characters. however, many
programs assume that the codeset name is usable with iconv and/or
comes from a set of standard/widely-used names known to the
application. such programs are likely to produce warnings or errors,
run with reduced functionality, or mangle character data when run
explicitly in the C locale.

the standard places basically no requirements for the string returned
by nl_langinfo(CODESET) and how it interacts with other interfaces, so
returning "UTF-8" is permissible. moreover, it seems like the right
thing to do, since the identity of the character encoding as "UTF-8"
is independent of whether it is being processed as bytes of characters
by the standard library functions.

8 years agofix fclose of permanent (stdin/out/err) streams
Rich Felker [Wed, 9 Sep 2015 04:31:07 +0000 (04:31 +0000)]
fix fclose of permanent (stdin/out/err) streams

this fixes a bug reported by Nuno Gonçalves. previously, calling
fclose on stdin or stdout resulted in deadlock at exit time, since
__stdio_exit attempts to lock these streams to flush/seek them, and
has no easy way of knowing that they were closed.

conceptually, leaving a FILE stream locked on fclose is valid since,
in the abstract machine, it ceases to exist. but to satisfy the
implementation-internal assumption in __stdio_exit that it can access
these streams unconditionally, we need to unlock them.

it's also necessary that fclose leaves permanent streams in a state
where __stdio_exit will not attempt any further operations on them.
fortunately, the call to fflush already yields this property.

8 years agoimplement arm eabi mem* functions
Timo Teräs [Sun, 30 Aug 2015 15:58:26 +0000 (18:58 +0300)]
implement arm eabi mem* functions

these functions are part of the ARM EABI, meaning compilers may
generate references to them. known versions of gcc do not use them,
but llvm does. they are not provided by libgcc, and the de facto
standard seems to be that libc provides them.

8 years agoremove use of buggy .SECONDARY special target in makefile
Rich Felker [Sun, 30 Aug 2015 18:44:58 +0000 (18:44 +0000)]
remove use of buggy .SECONDARY special target in makefile

this functionality is affected by GNU make bug #30653, "intermediate
files incorrectly pruned in parallel builds". on affected versions of
make, parallel builds attempt to compile source files before
alltypes.h is generated.

as noted with commit a91ebdcfac6804714a1fe39f4375e2b4ebab085b, which
added the use of .SECONDARY, suppression of removal of "intermediate"
files does not seem to be needed at present. if it is needed in the
future, it should be achievable by explicitly mentioning their names
as targets or prerequisites.

8 years agorelease 1.1.11
Rich Felker [Sun, 30 Aug 2015 04:15:56 +0000 (04:15 +0000)]
release 1.1.11

8 years agofix makefile suppression of intermediate file removal
Rich Felker [Thu, 27 Aug 2015 19:58:20 +0000 (19:58 +0000)]
fix makefile suppression of intermediate file removal

at one point, GNU make was removing crt/*.o after producing the copies
in lib/ due to an arcane misfeature for handling "intermediate" files.
the circumstances that caused this are no longer present in our
makefile, but the previous workaround using .PRECIOUS was wrong and
could result in corrupt/partial files being left behind during an
interrupted build. using .SECONDARY is the correct, documented fix
that will prevent deletion of "intermediate" files from ever
resurfacing.

8 years agoBuild process uses script to add CFI directives to x86 asm
Alex Dowad [Fri, 10 Jul 2015 13:03:24 +0000 (15:03 +0200)]
Build process uses script to add CFI directives to x86 asm

Some functions implemented in asm need to use EBP for purposes other
than acting as a frame pointer. (Notably, it is used for the 6th
argument to syscalls with 6 arguments.) Without frame pointers, GDB
can only show backtraces if it gets CFI information from a
.debug_frame or .eh_frame ELF section.

Rather than littering our asm with ugly .cfi directives, use an awk
script to insert them in the right places during the build process, so
GDB can keep track of where the current stack frame is relative to the
stack pointer. This means GDB can produce beautiful stack traces at
any given point when single-stepping through asm functions.

Additionally, when registers are saved on the stack and later
overwritten, emit ..cfi directives so GDB will know where they were
saved relative to the stack pointer. This way, when you look back up
the stack from within an asm function, you can still reliably print
the values of local variables in the caller.

If this awk script were to understand every possible wild and crazy
contortion that an asm programmer can do with the stack and registers,
and always emit the exact ..cfi directives needed for GDB to know what
the register values were in the preceding stack frame, it would
necessarily be as complex as a full x86 emulator. That way lies
madness.

Hence, we assume that the stack pointer will _only_ ever be adjusted
using push/pop or else add/sub with a constant. We do not attempt to
detect every possible way that a register value could be saved for
later use, just the simple and common ways.

Thanks to Szabolcs Nagy for suggesting numerous improvements to this
code.

8 years agogetsubopt: don't include leading = in value string
Steven Barth [Tue, 18 Aug 2015 09:06:04 +0000 (11:06 +0200)]
getsubopt: don't include leading = in value string

getsubopt incorrectly returns the delimiting = in the value string,
this patch fixes it by increasing the pointer position by one.

Signed-off-by: Steven Barth <cyrus@openwrt.org>
8 years agomitigate performance regression in libc-internal locks on x86_64
Rich Felker [Sun, 16 Aug 2015 18:15:18 +0000 (18:15 +0000)]
mitigate performance regression in libc-internal locks on x86_64

commit 3c43c0761e1725fd5f89a9c028cbf43250abb913 fixed missing
synchronization in the atomic store operation for i386 and x86_64, but
opted to use mfence for the barrier on x86_64 where it's always
available. however, in practice mfence is significantly slower than
the barrier approach used on i386 (a nop-like lock orl operation).
this commit changes x86_64 (and x32) to use the faster barrier.

8 years agomatch historical behavior for tm_gmtoff member of struct tm
Natanael Copa [Thu, 13 Aug 2015 15:28:39 +0000 (17:28 +0200)]
match historical behavior for tm_gmtoff member of struct tm

tm_gmtoff is a nonstandard field, but on historical systems which have
this field, it stores the offset of the local time zone from GMT or
UTC. this is the opposite of the POSIX extern long timezone object and
the offsets used in POSIX-form TZ strings, which represent the offset
from local time to UTC. previously we were storing these negated
offsets in tm_gmtoff too.

programs which only used this field indirectly via strftime were not
affected since strftime performed the negation for presentation.
however, some programs and libraries accesse tm_gmtoff directly and
were obtaining negated time zone offsets.

8 years agoaarch64: fix 64-bit syscall argument passing
Szabolcs Nagy [Tue, 11 Aug 2015 20:55:18 +0000 (20:55 +0000)]
aarch64: fix 64-bit syscall argument passing

On 32bit systems long long arguments are passed in a special way
to some syscalls; this accidentally got copied to the AArch64 port.

The following interfaces were broken: fallocate, fanotify, ftruncate,
posix_fadvise, posix_fallocate, pread, pwrite, readahead,
sync_file_range, truncate.

8 years agofix failure of tempnam to null-terminate result
Rich Felker [Sun, 9 Aug 2015 22:51:09 +0000 (22:51 +0000)]
fix failure of tempnam to null-terminate result

tempnam uses an uninitialized buffer which is filled using memcpy and
__randname. It is therefore necessary to explicitly null-terminate it.

based on patch by Felix Janda.

8 years agomitigate blow-up of heap size under malloc/free contention
Rich Felker [Fri, 7 Aug 2015 19:19:49 +0000 (19:19 +0000)]
mitigate blow-up of heap size under malloc/free contention

during calls to free, any free chunks adjacent to the chunk being
freed are momentarily held in allocated state for the purpose of
merging, possibly leaving little or no available free memory for other
threads to allocate. under this condition, other threads will attempt
to expand the heap rather than waiting to use memory that will soon be
available. the race window where this happens is normally very small,
but became huge when free chooses to use madvise to release unused
physical memory, causing unbounded heap size growth.

this patch drastically shrinks the race window for unwanted heap
expansion by performing madvise with the bin lock held and marking the
bin non-empty in the binmask before making the expensive madvise
syscall. testing by Timo Teräs has shown this approach to be a
suitable mitigation.

more invasive changes to the synchronization between malloc and free
would be needed to completely eliminate the problem. it's not clear
whether such changes would improve or worsen typical-case performance,
or whether this would be a worthwhile direction to take malloc
development.

8 years agofix missing synchronization in atomic store on i386 and x86_64
Rich Felker [Tue, 28 Jul 2015 18:40:18 +0000 (18:40 +0000)]
fix missing synchronization in atomic store on i386 and x86_64

despite being strongly ordered, the x86 memory model does not preclude
reordering of loads across earlier stores. while a plain store
suffices as a release barrier, we actually need a full barrier, since
users of a_store subsequently load a waiter count to determine whether
to issue a futex wait, and using a stale count will result in soft
(fail-to-wake) deadlocks. these deadlocks were observed in malloc and
possible with stdio locks and other libc-internal locking.

on i386, an atomic operation on the caller's stack is used as the
barrier rather than performing the store itself using xchg; this
avoids the need to read the cache line on which the store is being
performed. mfence is used on x86_64 where it's always available, and
could be used on i386 with the appropriate cpu model checks if it's
shown to perform better.

8 years agofix undefined left-shift of negative values in utf-8 state table
Rich Felker [Sat, 25 Jul 2015 03:15:45 +0000 (03:15 +0000)]
fix undefined left-shift of negative values in utf-8 state table

8 years agofix atexit when it is called from an atexit handler
Rich Felker [Fri, 24 Jul 2015 21:15:49 +0000 (21:15 +0000)]
fix atexit when it is called from an atexit handler

The old code accepted atexit handlers after exit, but did not run them
reliably. C11 seems to explicitly allow atexit to fail (and report
such failure) in this case, but this situation can easily come up in
C++ if a destructor has a local static object with a destructor so it
should be handled.

Note that the memory usage can grow linearly with the overall number
of registered atexit handlers instead of with the worst case list
length. (This only matters if atexit handlers keep registering atexit
handlers which should not happen in practice).

Commit message/rationale based on text by Szabolcs Nagy.

8 years agosocket.h: cleanup/reorder mips and powerpc bits/socket.h
Roman Yeryomin [Thu, 2 Jul 2015 09:29:00 +0000 (12:29 +0300)]
socket.h: cleanup/reorder mips and powerpc bits/socket.h

....to be somewhat consistent and easily comparable with asm/socket.h

Signed-off-by: Roman Yeryomin <roman@ubnt.com>
8 years agosocket.h: fix SO_* for mips
Roman Yeryomin [Thu, 2 Jul 2015 09:28:41 +0000 (12:28 +0300)]
socket.h: fix SO_* for mips

Signed-off-by: Roman Yeryomin <roman@ubnt.com>
8 years agomips: fix mcontext_t register array field name
Felix Fietkau [Tue, 21 Jul 2015 13:01:25 +0000 (15:01 +0200)]
mips: fix mcontext_t register array field name

glibc and uclibc use gregs instead of regs

Signed-off-by: Felix Fietkau <nbd@openwrt.org>
8 years agohandle loss of syslog socket connection
Rich Felker [Thu, 9 Jul 2015 18:36:02 +0000 (18:36 +0000)]
handle loss of syslog socket connection

when traditional syslogd implementations are restarted, the old server
socket ceases to exist and a new unix socket with the same pathname is
created. when this happens, the default destination address associated
with the client socket via connect is no longer valid, and attempts to
send produce errors. this happens despite the socket being datagram
type, and is in contrast to the behavior that would be seen with an IP
datagram (UDP) socket.

in order to avoid a situation where the application is unable to send
further syslog messages without calling closelog, this patch makes
syslog attempt to reconnect the socket when send returns an error
indicating a lost connection.

additionally, initial failure to connect the socket no longer results
in the socket being closed. this ensures that an application which
calls openlog to reserve the socket file descriptor will not run into
a situation where transient connection failure (e.g. due to syslogd
restart) prevents fd reservation. however, applications which may be
unable to connect the socket later (e.g. due to chroot, restricted
permissions, seccomp, etc.) will still fail to log if the syslog
socket cannot be connected at openlog time or if it has to be
reconnected later.

8 years agofix incorrect void return type for syncfs function
Rich Felker [Thu, 9 Jul 2015 17:07:35 +0000 (17:07 +0000)]
fix incorrect void return type for syncfs function

being nonstandard, the closest thing to a specification for this
function is its man page, which documents it as returning int. it can
fail with EBADF if the file descriptor passed is invalid.

8 years agofix negated return value of ns_skiprr, breakage in related functions
Rich Felker [Wed, 8 Jul 2015 02:46:45 +0000 (02:46 +0000)]
fix negated return value of ns_skiprr, breakage in related functions

due to a reversed pointer difference computation, ns_skiprr always
returned a negative value, which functions using it would interpret as
an error.

patch by Yu Lu.

8 years agoadd musl-clang, a wrapper for system clang installs
Shiz [Sun, 28 Jun 2015 21:08:21 +0000 (23:08 +0200)]
add musl-clang, a wrapper for system clang installs

musl-clang allows the user to compile musl-powered programs using their
already existent clang install, without the need of a special cross compiler.
it achieves this by wrapping around both the system clang install and the
linker and passing them special flags to re-target musl at runtime.
it does only affect invocations done through the special musl-clang wrapper
script, so that the user setup remains fully intact otherwise.

the clang wrapper consists of the compiler frontend wrapper script,
musl-clang, and the linker wrapper script, ld.musl-clang.
musl-clang makes sure clang invokes ld.musl-clang to link objects; neither
script needs to be in PATH for the wrapper to work.

8 years agobuild: fix musl-targeting toolchain test
Shiz [Sun, 28 Jun 2015 21:08:20 +0000 (23:08 +0200)]
build: fix musl-targeting toolchain test

the old test was broken in that it would never fail on a toolchains built
without dynamic linking support, leading to the wrapper script possibly being
installed on compilers that do not support it. in addition, the new test is
portable across compilers: the old test only worked on GCC.

the new test works by testing whether the toolchain libc defines __GLIBC__:
most non-musl Linux libc's do define this for compatibility even when they
are not glibc, so this is a safe bet to check for musl. in addition, the
compiler runtime would need to have a somewhat glibc-compatible ABI in the
first place, so any non-glibc compatible libc's compiler runtime might not
work. it is safer to disable these cases by default and have the user enable
the wrappers manually there using --enable-wrapper if they certain it works.

8 years agobuild: overhaul wrapper script system for multiple wrapper support
Shiz [Sun, 28 Jun 2015 21:08:19 +0000 (23:08 +0200)]
build: overhaul wrapper script system for multiple wrapper support

this overhauls part of the build system in order to support multiple
toolchain wrapper scripts, as opposed to solely the musl-gcc wrapper as
before. it thereby replaces --enable-gcc-wrapper with --enable-wrapper=...,
which has the options 'auto' (the default, detect whether to use wrappers),
'all' (build and install all wrappers), 'no' (don't build any) and finally
the options named after the individual compiler scripts (currently only
'gcc' is available) to build and install only that wrapper.
the old --enable-gcc-wrapper is removed from --help, but still available.

it also modifies the wrappers to use the C compiler specified to the build
system as 'inner' compiler, when applicable. as wrapper detection works by
probing this compiler, it may not work with any other.

8 years agotreat empty TZ environment variable as GMT rather than default
Rich Felker [Mon, 6 Jul 2015 22:13:11 +0000 (22:13 +0000)]
treat empty TZ environment variable as GMT rather than default

this improves compatibility with the behavior of other systems and
with some applications which set an empty TZ var to disable use of
local time by mktime, etc.

8 years agodynlink.c: pass gnu-hash table pointer to gnu_lookup
Alexander Monakov [Sat, 27 Jun 2015 23:48:33 +0000 (02:48 +0300)]
dynlink.c: pass gnu-hash table pointer to gnu_lookup

The callers need to check the value of the pointer anyway, so make
them pass the pointer to gnu_lookup instead of reloading it there.

Reorder gnu_lookup arguments so that always-used ones are listed
first. GCC can choose a calling convention with arguments in registers
(e.g. up to 3 arguments in eax, ecx, edx on x86), but cannot reorder
the arguments for static functions.

8 years agodynlink.c: slim down gnu_lookup
Alexander Monakov [Sat, 27 Jun 2015 23:48:32 +0000 (02:48 +0300)]
dynlink.c: slim down gnu_lookup

Do not reference dso->syms and dso->strings until point of use.
Check 'h1 == (h2|1)', the simplest condition, before the others.

8 years agodynlink.c: use bloom filter in gnu hash lookup
Alexander Monakov [Sat, 27 Jun 2015 23:48:31 +0000 (02:48 +0300)]
dynlink.c: use bloom filter in gnu hash lookup

Introduce gnu_lookup_filtered and use it to speed up symbol lookups in
find_sym (do_dlsym is left as is, based on an expectation that
frequently dlsym queries will use a dlopen handle rather than
RTLD_NEXT or RTLD_DEFAULT, and will not need to look at more than one
DSO).

8 years agodynlink.c: use a faster expression in gnu_hash
Alexander Monakov [Sat, 27 Jun 2015 23:48:30 +0000 (02:48 +0300)]
dynlink.c: use a faster expression in gnu_hash

With -Os, GCC uses a multiply rather than a shift and addition for 'h*33'.
Use a more efficient expression explicitely.

8 years agofix local-dynamic model TLS on mips and powerpc
Rich Felker [Thu, 25 Jun 2015 22:22:00 +0000 (22:22 +0000)]
fix local-dynamic model TLS on mips and powerpc

the TLS ABI spec for mips, powerpc, and some other (presently
unsupported) RISC archs has the return value of __tls_get_addr offset
by +0x8000 and the result of DTPOFF relocations offset by -0x8000. I
had previously assumed this part of the ABI was actually just an
implementation detail, since the adjustments cancel out. however, when
the local dynamic model is used for accessing TLS that's known to be
in the same DSO, either of the following may happen:

1. the -0x8000 offset may already be applied to the argument structure
passed to __tls_get_addr at ld time, without any opportunity for
runtime relocations.

2. __tls_get_addr may be used with a zero offset argument to obtain a
base address for the module's TLS, to which the caller then applies
immediate offsets for individual objects accessed using the local
dynamic model. since the immediate offsets have the -0x8000 adjustment
applied to them, the base address they use needs to include the
+0x8000 offset.

it would be possible, but more complex, to store the pointers in the
dtv[] array with the +0x8000 offset pre-applied, to avoid the runtime
cost of adding 0x8000 on each call to __tls_get_addr. this change
could be made later if measurements show that it would help.

8 years agomake dynamic linker work around MAP_FAILED mmap failure on nommu kernels
Rich Felker [Tue, 23 Jun 2015 04:03:42 +0000 (04:03 +0000)]
make dynamic linker work around MAP_FAILED mmap failure on nommu kernels

previously, loading of additional libraries beyond libc/ldso did not
work on nommu kernels, nor did loading programs via invocation of the
dynamic linker as a command.

8 years agoreimplement strverscmp to fix corner cases
Rich Felker [Tue, 23 Jun 2015 00:12:25 +0000 (00:12 +0000)]
reimplement strverscmp to fix corner cases

this interface is non-standardized and is a GNU invention, and as
such, our implementation should match the behavior of the GNU
function. one peculiarity the old implementation got wrong was the
handling of all-zero digit sequences: they are supposed to compare
greater than digit sequences of which they are a proper prefix, as in
009 < 00.

in addition, high bytes were treated with char signedness rather than
as unsigned. this was wrong regardless of what the GNU function does
since the resulting order relation varied by arch.

the new strverscmp implementation makes explicit the cases where the
order differs from what strcmp would produce, of which there are only
two.

8 years agofix regression/typo that disabled __simple_malloc when calloc is used
Rich Felker [Mon, 22 Jun 2015 20:33:28 +0000 (20:33 +0000)]
fix regression/typo that disabled __simple_malloc when calloc is used

commit ba819787ee93ceae94efd274f7849e317c1bff58 introduced this
regression. since the __malloc0 weak alias was not properly provided
by __simple_malloc, use of calloc forced the full malloc to be linked.

8 years agofix calloc when __simple_malloc implementation is used
Rich Felker [Mon, 22 Jun 2015 18:50:09 +0000 (18:50 +0000)]
fix calloc when __simple_malloc implementation is used

previously, calloc's implementation encoded assumptions about the
implementation of malloc, accessing a size_t word just prior to the
allocated memory to determine if it was obtained by mmap to optimize
out the zero-filling. when __simple_malloc is used (static linking a
program with no realloc/free), it doesn't matter if the result of this
check is wrong, since all allocations are zero-initialized anyway. but
the access could be invalid if it crosses a page boundary or if the
pointer is not sufficiently aligned, which can happen for very small
allocations.

this patch fixes the issue by moving the zero-fill logic into malloc.c
with the full malloc, as a new function named __malloc0, which is
provided by a weak alias to __simple_malloc (which always gives
zero-filled memory) when the full malloc is not in use.

8 years agoprovide __stack_chk_fail_local in libc.a
Rich Felker [Sat, 20 Jun 2015 03:01:07 +0000 (03:01 +0000)]
provide __stack_chk_fail_local in libc.a

this symbol is needed only on archs where the PLT call ABI is klunky,
and only for position-independent code compiled with stack protector.
thus references usually only appear in shared libraries or PIE
executables, but they can also appear when linking statically if some
of the object files being linked were built as PIC/PIE.

normally libssp_nonshared.a from the compiler toolchain should provide
__stack_chk_fail_local, but reportedly it appears prior to -lc in the
link order, thus failing to satisfy references from libc itself (which
arise only if libc.a was built as PIC/PIE with stack protector
enabled).

8 years agowork around mips detached thread exit breakage due to kernel regression
Rich Felker [Sat, 20 Jun 2015 02:54:30 +0000 (02:54 +0000)]
work around mips detached thread exit breakage due to kernel regression

linux kernel commit 46e12c07b3b9603c60fc1d421ff18618241cb081 caused
the mips syscall mechanism to fail with EFAULT when the userspace
stack pointer is invalid, breaking __unmapself used for detached
thread exit. the workaround is to set $sp to a known-valid, readable
address, and the simplest one to obtain is the address of the current
function, which is available (per o32 calling convention) in $25.

8 years agoignore ENOSYS error from mprotect in pthread_create and dynamic linker
Rich Felker [Wed, 17 Jun 2015 17:21:46 +0000 (17:21 +0000)]
ignore ENOSYS error from mprotect in pthread_create and dynamic linker

this error simply indicated a system without memory protection (NOMMU)
and should not cause failure in the caller.

8 years agoswitch to using trap number 31 for syscalls on sh
Rich Felker [Tue, 16 Jun 2015 15:25:02 +0000 (15:25 +0000)]
switch to using trap number 31 for syscalls on sh

nominally the low bits of the trap number on sh are the number of
syscall arguments, but they have never been used by the kernel, and
some code making syscalls does not even know the number of arguments
and needs to pass an arbitrary high number anyway.

sh3/sh4 traditionally used the trap range 16-31 for syscalls, but part
of this range overlapped with hardware exceptions/interrupts on sh2
hardware, so an incompatible range 32-47 was chosen for sh2.

using trap number 31 everywhere, since it's in the existing sh3/sh4
range and does not conflict with sh2 hardware, is a proposed
unification of the kernel syscall convention that will allow binaries
to be shared between sh2 and sh3/sh4. if this is not accepted into the
kernel, we can refit the sh2 target with runtime selection mechanisms
for the trap number, but doing so would be invasive and would entail
non-trivial overhead.

8 years agoswitch sh port's __unmapself to generic version when running on sh2/nommu
Rich Felker [Tue, 16 Jun 2015 14:55:06 +0000 (14:55 +0000)]
switch sh port's __unmapself to generic version when running on sh2/nommu

due to the way the interrupt and syscall trap mechanism works,
userspace on sh2 must never set the stack pointer to an invalid value.
thus, the approach used on most archs, where __unmapself executes with
no stack for the interval between SYS_munmap and SYS_exit, is not
viable on sh2.

in order not to pessimize sh3/sh4, the sh asm version of __unmapself
is not removed. instead it's renamed and redirected through code that
calls either the generic (safe) __unmapself or the sh3/sh4 asm,
depending on compile-time and run-time conditions.

8 years agoadd support for sh2 interrupt-masking-based atomics to sh port
Rich Felker [Tue, 16 Jun 2015 14:28:30 +0000 (14:28 +0000)]
add support for sh2 interrupt-masking-based atomics to sh port

the sh2 target is being considered an ISA subset of sh3/sh4, in the
sense that binaries built for sh2 are intended to be usable on later
cpu models/kernels with mmu support. so rather than hard-coding
sh2-specific atomics, the runtime atomic selection mechanisms that was
already in place has been extended to add sh2 atomics.

at this time, the sh2 atomics are not SMP-compatible; since the ISA
lacks actual atomic operations, the new code instead masks interrupts
for the duration of the atomic operation, producing an atomic result
on single-core. this is only possible because the kernel/hardware does
not impose protections against userspace doing so. additional changes
will be needed to support future SMP systems.

care has been taken to avoid producing significant additional code
size in the case where it's known at compile-time that the target is
not sh2 and does not need sh2-specific code.

8 years agorefactor stdio open file list handling, move it out of global libc struct
Rich Felker [Tue, 16 Jun 2015 07:11:19 +0000 (07:11 +0000)]
refactor stdio open file list handling, move it out of global libc struct

functions which open in-memory FILE stream variants all shared a tail
with __fdopen, adding the FILE structure to stdio's open file list.
replacing this common tail with a function call reduces code size and
duplication of logic. the list is also partially encapsulated now.

function signatures were chosen to facilitate tail call optimization
and reduce the need for additional accessor functions.

with these changes, static linked programs that do not use stdio no
longer have an open file list at all.

8 years agobyte-based C locale, phase 3: make MB_CUR_MAX variable to activate code
Rich Felker [Tue, 16 Jun 2015 06:18:00 +0000 (06:18 +0000)]
byte-based C locale, phase 3: make MB_CUR_MAX variable to activate code

this patch activates the new byte-based C locale (high bytes treated
as abstract code unit "characters" rather than decoded as multibyte
characters) by making the value of MB_CUR_MAX depend on the active
locale. for the C locale, the LC_CTYPE category pointer is null,
yielding a value of 1. all other locales yield a value of 4.

8 years agobyte-based C locale, phase 2: stdio and iconv (multibyte callers)
Rich Felker [Tue, 16 Jun 2015 05:35:31 +0000 (05:35 +0000)]
byte-based C locale, phase 2: stdio and iconv (multibyte callers)

this patch adjusts libc components which use the multibyte functions
internally, and which depend on them operating in a particular
encoding, to make the appropriate locale changes before calling them
and restore the calling thread's locale afterwards. activating the
byte-based C locale without these changes would cause regressions in
stdio and iconv.

in the case of iconv, the current implementation was simply using the
multibyte functions as UTF-8 conversions. setting a multibyte UTF-8
locale for the duration of the iconv operation allows the code to
continue working.

in the case of stdio, POSIX requires that FILE streams have an
encoding rule bound at the time of setting wide orientation. as long
as all locales, including the C locale, used the same encoding,
treating high bytes as UTF-8, there was no need to store an encoding
rule as part of the stream's state.

a new locale field in the FILE structure points to the locale that
should be made active during fgetwc/fputwc/ungetwc on the stream. it
cannot point to the locale active at the time the stream becomes
oriented, because this locale could be mutable (the global locale) or
could be destroyed (locale_t objects produced by newlocale) before the
stream is closed. instead, a pointer to the static C or C.UTF-8 locale
object added in commit commit aeeac9ca5490d7d90fe061ab72da446c01ddf746
is used. this is valid since categories other than LC_CTYPE will not
affect these functions.

8 years agobyte-based C locale, phase 1: multibyte character handling functions
Rich Felker [Tue, 16 Jun 2015 04:44:17 +0000 (04:44 +0000)]
byte-based C locale, phase 1: multibyte character handling functions

this patch makes the functions which work directly on multibyte
characters treat the high bytes as individual abstract code units
rather than as multibyte sequences when MB_CUR_MAX is 1. since
MB_CUR_MAX is presently defined as a constant 4, all of the new code
added is dead code, and optimizing compilers' code generation should
not be affected at all. a future commit will activate the new code.

as abstract code units, bytes 0x80 to 0xff are represented by wchar_t
values 0xdf80 to 0xdfff, at the end of the surrogates range. this
ensures that they will never be misinterpreted as Unicode characters,
and that all wctype functions return false for these "characters"
without needing locale-specific logic. a high range outside of Unicode
such as 0x7fffff80 to 0x7fffffff was also considered, but since C11's
char16_t also needs to be able to represent conversions of these
bytes, the surrogate range was the natural choice.

8 years agofix btowc corner case
Rich Felker [Tue, 16 Jun 2015 04:21:38 +0000 (04:21 +0000)]
fix btowc corner case

btowc is required to interpret its argument by conversion to unsigned
char, unless the argument is equal to EOF. since the conversion to
produces a non-character value anyway, we can just unconditionally
convert, for now.

8 years agoarm: add vdso support
Szabolcs Nagy [Wed, 3 Jun 2015 09:32:14 +0000 (10:32 +0100)]
arm: add vdso support

vdso will be available on arm in linux v4.2, the user-space code
for it is in kernel commit 8512287a8165592466cb9cb347ba94892e9c56a5

8 years agorefactor malloc's expand_heap to share with __simple_malloc
Rich Felker [Sun, 14 Jun 2015 01:59:02 +0000 (01:59 +0000)]
refactor malloc's expand_heap to share with __simple_malloc

this extends the brk/stack collision protection added to full malloc
in commit 276904c2f6bde3a31a24ebfa201482601d18b4f9 to also protect the
__simple_malloc function used in static-linked programs that don't
reference the free function.

it also extends support for using mmap when brk fails, which full
malloc got in commit 5446303328adf4b4e36d9fba21848e6feb55fab4, to
__simple_malloc.

since __simple_malloc may expand the heap by arbitrarily large
increments, the stack collision detection is enhanced to detect
interval overlap rather than just proximity of a single address to the
stack. code size is increased a bit, but this is partly offset by the
sharing of code between the two malloc implementations, which due to
linking semantics, both get linked in a program that needs the full
malloc with realloc/free support.

8 years agoremove cancellation points in stdio
Rich Felker [Sat, 13 Jun 2015 20:53:02 +0000 (20:53 +0000)]
remove cancellation points in stdio

commit 58165923890865a6ac042fafce13f440ee986fd9 added these optional
cancellation points on the basis that cancellable stdio could be
useful, to unblock threads stuck on stdio operations that will never
complete. however, the only way to ensure that cancellation can
achieve this is to violate the rules for side effects when
cancellation is acted upon, discarding knowledge of any partial data
transfer already completed. our implementation exhibited this behavior
and was thus non-conforming.

in addition to improving correctness, removing these cancellation
points moderately reduces code size, and should significantly improve
performance on i386, where sysenter/syscall instructions can be used
instead of "int $128" for non-cancellable syscalls.

8 years agofix idiom for setting stdio stream orientation to wide
Rich Felker [Sat, 13 Jun 2015 05:17:16 +0000 (05:17 +0000)]
fix idiom for setting stdio stream orientation to wide

the old idiom, f->mode |= f->mode+1, was adapted from the idiom for
setting byte orientation, f->mode |= f->mode-1, but the adaptation was
incorrect. unless the stream was alreasdy set byte-oriented, this code
incremented f->mode each time it was executed, which would eventually
lead to overflow. it could be fixed by changing it to f->mode |= 1,
but upcoming changes will require slightly more work at the time of
wide orientation, so it makes sense to just call fwide. as an
optimization in the single-character functions, fwide is only called
if the stream is not already wide-oriented.

8 years agoadd printing of null %s arguments as "(null)" in wide printf
Rich Felker [Sat, 13 Jun 2015 04:42:38 +0000 (04:42 +0000)]
add printing of null %s arguments as "(null)" in wide printf

this is undefined, but supported in our implementation of the normal
printf, so for consistency the wide variant should support it too.

8 years agoadd %m support to wide printf
Rich Felker [Sat, 13 Jun 2015 04:37:27 +0000 (04:37 +0000)]
add %m support to wide printf

8 years agoadd sh asm for vfork
Rich Felker [Thu, 11 Jun 2015 05:01:04 +0000 (05:01 +0000)]
add sh asm for vfork

8 years agoimplement arch-generic version of __unmapself
Rich Felker [Wed, 10 Jun 2015 02:27:40 +0000 (02:27 +0000)]
implement arch-generic version of __unmapself

this can be used to put off writing an asm version of __unmapself for
new archs, or as a permanent solution on archs where it's not
practical or even possible to run momentarily with no stack.

the concept here is simple: the caller takes a lock on a global shared
stack and uses it to make the munmap and exit syscalls. the only trick
is unlocking, which must be done after the thread exits, and this is
achieved by using the set_tid_address syscall to have the kernel zero
and futex-wake the lock word as part of the exit syscall.

8 years agoin malloc, refuse to use brk if it grows into stack
Rich Felker [Tue, 9 Jun 2015 20:30:35 +0000 (20:30 +0000)]
in malloc, refuse to use brk if it grows into stack

the linux/nommu fdpic ELF loader sets up the brk range to overlap
entirely with the main thread's stack (but growing from opposite
ends), so that the resulting failure mode for malloc is not to return
a null pointer but to start returning pointers to memory that overlaps
with the caller's stack. needless to say this extremely dangerous and
makes brk unusable.

since it's non-trivial to detect execution environments that might be
affected by this kernel bug, and since the severity of the bug makes
any sort of detection that might yield false-negatives unsafe, we
instead check the proximity of the brk to the stack pointer each time
the brk is to be expanded. both the main thread's stack (where the
real known risk lies) and the calling thread's stack are checked. an
arbitrary gap distance of 8 MB is imposed, chosen to be larger than
linux default main-thread stack reservation sizes and larger than any
reasonable stack configuration on nommu.

the effeciveness of this patch relies on an assumption that the amount
by which the brk is being grown is smaller than the gap limit, which
is always true for malloc's use of brk. reliance on this assumption is
why the check is being done in malloc-specific code and not in __brk.

8 years agofix spurious errors from pwd/grp functions when nscd backend is absent
Rich Felker [Tue, 9 Jun 2015 20:09:27 +0000 (20:09 +0000)]
fix spurious errors from pwd/grp functions when nscd backend is absent

for several pwd/grp functions, the only way the caller can distinguish
between a successful negative result ("no such user/group") and an
internal error is by clearing errno before the call and checking errno
afterwards. the nscd backend support code correctly simulated a
not-found response on systems where such a backend is not running, but
failed to restore errno.

this commit also fixed an outdated/incorrect comment.

8 years agofix regression in pre-v7 arm on kernels with kuser helper removed
Rich Felker [Sun, 7 Jun 2015 20:55:23 +0000 (20:55 +0000)]
fix regression in pre-v7 arm on kernels with kuser helper removed

the arm atomics/TLS runtime selection code is called from
__set_thread_area and depends on having libc.auxv and __hwcap
available. commit 71f099cb7db821c51d8f39dfac622c61e54d794c moved the
first call to __set_thread_area to the top of dynamic linking stage 3,
before this data is made available, causing the runtime detection code
to always see __hwcap as zero and thereby select the atomics/TLS
implementations based on kuser helper.

upcoming work on superh will use similar runtime detection.

ideally this early-init code should be cleanly refactored and shared
between the dynamic linker and static-linked startup.

8 years agoadd multiple inclusion guard to locale_impl.h
Rich Felker [Sun, 7 Jun 2015 03:09:16 +0000 (03:09 +0000)]
add multiple inclusion guard to locale_impl.h

8 years agoremove redefinition of MB_CUR_MAX in locale_impl.h
Rich Felker [Sun, 7 Jun 2015 02:59:49 +0000 (02:59 +0000)]
remove redefinition of MB_CUR_MAX in locale_impl.h

unless/until the byte-based C locale is implemented, defining
MB_CUR_MAX to 1 in the C locale is wrong. no internal code currently
uses the MB_CUR_MAX macro, but having it defined inconsistently is
error-prone. applications get the value from stdlib.h and were
unaffected.

8 years agomake static C and C.UTF-8 locales available outside of newlocale
Rich Felker [Sat, 6 Jun 2015 18:53:02 +0000 (18:53 +0000)]
make static C and C.UTF-8 locales available outside of newlocale

8 years agoremove another invalid skip of locking in ungetwc
Rich Felker [Sat, 6 Jun 2015 18:20:30 +0000 (18:20 +0000)]
remove another invalid skip of locking in ungetwc

8 years agoadd macro version of ctype.h isascii function
Rich Felker [Sat, 6 Jun 2015 18:16:22 +0000 (18:16 +0000)]
add macro version of ctype.h isascii function

presumably internal code (ungetwc and fputwc) was written assuming a
macro implementation existed; otherwise use of isascii is just a
pessimization.

8 years agoremove invalid skip of locking in ungetwc
Rich Felker [Sat, 6 Jun 2015 18:11:17 +0000 (18:11 +0000)]
remove invalid skip of locking in ungetwc

aside from being invalid, the early check only optimized the error
case, and likely pessimized the common case by separating the
two branches on isascii(c) at opposite ends of the function.

8 years agofix uselocale((locale_t)0) not to modify locale
Timo Teräs [Fri, 5 Jun 2015 07:39:42 +0000 (10:39 +0300)]
fix uselocale((locale_t)0) not to modify locale

commit 68630b55c0c7219fe9df70dc28ffbf9efc8021d8 made the new locale to
be assigned unconditonally resulting in crashes later on.

9 years agorelease 1.1.10
Rich Felker [Thu, 4 Jun 2015 20:08:24 +0000 (16:08 -0400)]
release 1.1.10

9 years agofix dynamic linker regression processing R_*_NONE type relocations
Rich Felker [Thu, 4 Jun 2015 15:45:17 +0000 (11:45 -0400)]
fix dynamic linker regression processing R_*_NONE type relocations

commit f3ddd173806fd5c60b3f034528ca24542aecc5b9 inadvertently removed
the early check for "none" type relocations, causing the address
dso->base+0 to be dereferenced to obtain an addend. shared libraries,
(including libc.so) and PIE executables were unaffected, since their
base addresses are the actual address of their mappings and are
readable. non-PIE main executables, however, have a base address of 0
because their load addresses are absolute and not offset at load time.

in practice none-type relocations do not arise with toolchains that
are in use except on mips, and on mips it's moderately rare for a
non-PIE executable to have a relocation table, since the mips-specific
got processing serves in its place for most purposes.

9 years agoadd additional Makefile dependency rules for rcrt1.o PIE start file
Rich Felker [Wed, 3 Jun 2015 06:00:44 +0000 (02:00 -0400)]
add additional Makefile dependency rules for rcrt1.o PIE start file

9 years agofix failure of ungetc and ungetwc to work on files in eof status
Rich Felker [Fri, 29 May 2015 03:08:12 +0000 (23:08 -0400)]
fix failure of ungetc and ungetwc to work on files in eof status

these functions were written to handle clearing eof status, but failed
to account for the __toread function's handling of eof. with this
patch applied, __toread still returns EOF when the file is in eof
status, so that read operations will fail, but it also sets up valid
buffer pointers for read mode, which are set to the end of the buffer
rather than the beginning in order to make the whole buffer available
to ungetc/ungetwc.

minor changes to __uflow were needed since it's now possible to have
non-zero buffer pointers while in eof status. as made, these changes
remove a 'fast path' bypassing the function call to __toread, which
could be reintroduced with slightly different logic, but since
ordinary files have a syscall in f->read, optimizing the code path
does not seem worthwhile.

the __stdio_read function is also updated not to zero the read buffer
pointers on eof/error. while not necessary for correctness, this
change avoids the overhead of calling __toread in ungetc after
reaching eof, and it also reduces code size and increases consistency
with the fmemopen read operation which does not zero the pointers.

9 years agoadd missing legacy LFS64 macros in sys/resource.h
Rich Felker [Thu, 28 May 2015 19:37:23 +0000 (15:37 -0400)]
add missing legacy LFS64 macros in sys/resource.h

based on patch by Felix Janda, with RLIM64_SAVED_CUR and
RLIM64_SAVED_MAX added for completeness.

9 years agoconfigure: work around compilers that merely warn for unknown options
Shiz [Thu, 28 May 2015 03:52:22 +0000 (05:52 +0200)]
configure: work around compilers that merely warn for unknown options

some compilers (such as clang) accept unknown options without error,
but then print warnings on each invocation, cluttering the build
output and burying meaningful warnings. this patch makes configure's
tryflag and tryldflag functions use additional options to turn the
unknown-option warnings into errors, if available, but only at check
time. these options are not output in config.mak to avoid the risk of
spurious build breakage; if they work, they will have already done
their job at configure time.

9 years agoimplement fail-safe static locales for newlocale
Rich Felker [Wed, 27 May 2015 19:54:47 +0000 (15:54 -0400)]
implement fail-safe static locales for newlocale

this frees applications which need to make temporary use of the C
locale (via uselocale) from the possibility that newlocale might fail.

the C.UTF-8 locale is also provided as a static locale. presently they
behave the same, but this may change in the future.

9 years agorename internal locale file handling locale maps
Rich Felker [Wed, 27 May 2015 07:32:46 +0000 (03:32 -0400)]
rename internal locale file handling locale maps

since the __setlocalecat function was removed, the filename
__setlocalecat.c no longer made sense.

9 years agooverhaul locale internals to treat categories roughly uniformly
Rich Felker [Wed, 27 May 2015 07:22:52 +0000 (03:22 -0400)]
overhaul locale internals to treat categories roughly uniformly

previously, LC_MESSAGES was treated specially as the only category
which could be set to a locale name without a definition file, in
order to facilitate gettext message translations when no libc locale
was available. LC_NUMERIC was completely un-settable, and LC_CTYPE
stored a flag intended to be used for a possible future byte-based C
locale, instead of storing a __locale_map pointer like the other
categories use.

this patch changes all categories to be represented by pointers to
__locale_map structures, and allows locale names without definition
files to be treated as valid locales with trivial definition when used
in any category. outwardly visible functional changes should be minor,
limited mainly to the strings read back from setlocale and the way
gettext handles translations in categories other than LC_MESSAGES.

various internal refactoring has also been performed, and improvements
in const correctness have been made.

9 years agoreplace atomics with locks in locale-setting code
Rich Felker [Wed, 27 May 2015 04:22:43 +0000 (00:22 -0400)]
replace atomics with locks in locale-setting code

this is part of a general program of removing direct use of atomics
where they are not necessary to meet correctness or performance needs,
but in this case it's also an optimization. only the global locale
needs synchronization; allocated locales referenced with locale_t
handles are immutable during their lifetimes, and using atomics to
initialize them increases their cost of setup.

9 years agoadd rcrt1 start file for fully static-linked PIE
Rich Felker [Tue, 26 May 2015 07:37:41 +0000 (03:37 -0400)]
add rcrt1 start file for fully static-linked PIE

static-linked PIE files need startup code to relocate themselves, much
like the dynamic linker does. rcrt1.c reuses the code in dlstart.c,
stage 1 of the dynamic linker, which in turn reuses crt_arch.h, to
achieve static PIE with no new code. only relative relocations are
supported.

existing toolchains that don't yet support static PIE directly can be
repurposed by passing "-shared -Wl,-Bstatic -Wl,-Bsymbolic" instead of
"-static -pie" and substituting rcrt1.o in place of crt1.o.

all libraries being linked must be built as PIC/PIE; TEXTRELs are not
supported at this time.

9 years agofix incorrect application of visibility to Scrt1.o
Rich Felker [Tue, 26 May 2015 06:31:04 +0000 (02:31 -0400)]
fix incorrect application of visibility to Scrt1.o

commit de2b67f8d41e08caa56bf6540277f6561edb647f attempted to avoid
having vis.h affect crt files, but the Makefile variable used,
CRT_LIBS, refers to the final output copies in the lib directory, not
the copies in the crt build directory, and thus the -DCRT was not
applied.

while unlikely to be noticed, this regression probably broke
production of PIE executables whose main functions are not in the
executable but rather a shared library.

9 years agoreprocess all libc/ldso symbolic relocations in dynamic linking stage 3
Rich Felker [Tue, 26 May 2015 03:33:59 +0000 (23:33 -0400)]
reprocess all libc/ldso symbolic relocations in dynamic linking stage 3

commit f3ddd173806fd5c60b3f034528ca24542aecc5b9 introduced early
relocations and subsequent reprocessing as part of the dynamic linker
bootstrap overhaul, to allow use of arbitrary libc functions before
the main application and libraries are loaded, but only reprocessed
GOT/PLT relocation types.

commit c093e2e8201524db0d638920e76bcb6b1d925f3a added reprocessing of
non-GOT/PLT relocations to fix an actual regression that was observed
on powerpc, but only for RELA format tables with out-of-line addends.
REL table (inline addends at the relocation address) reprocessing is
trickier because the first relocation pass clobbers the addends.

this patch extends symbolic relocation reprocessing for libc/ldso to
support all relocation types, whether REL or RELA format tables are
used. it is believed not to alter behavior on any existing archs for
the current dynamic linker and libc code. the motivations for this
change are consistency and future-proofing. it ensures that behavior
does not differ depending on whether REL or RELA tables are used,
which could lead to undetected arch-specific bugs. it also ensures
that, if in the future code depending on additional relocation types
is added to libc.so, either at the source level or as part of the
compiler runtime that gets pulled in (for example, soft-float with TLS
for fenv), the new code will work properly.

the implementation concept is simple: stage 2 of the dynamic linker
counts the number of symbolic relocations in the libc/ldso REL table
and allocates a VLA to save their addends into; stage 3 then uses the
saved addends in place of the inline ones which were clobbered. for
stack safety, a hard limit (currently 4k) is imposed on the number of
such addends; this should be a couple orders of magnitude larger than
the actual need. this number is not a runtime variable that could
break fail-safety; it is constant for a given libc.so build.

9 years agomove call to dynamic linker stage-3 into stage-2 function
Rich Felker [Mon, 25 May 2015 23:15:17 +0000 (19:15 -0400)]
move call to dynamic linker stage-3 into stage-2 function

this move eliminates a duplicate "by-hand" symbol lookup loop from the
stage-1 code and replaces it with a call to find_sym, which can be
used once we're in stage 2. it reduces the size of the stage 1 code,
which is helpful because stage 1 will become the crt start file for
static-PIE executables, and it will allow stage 3 to access stage 2's
automatic storage, which will be important in an upcoming commit.

9 years agomark mips crt code as code
Rich Felker [Mon, 25 May 2015 20:02:49 +0000 (16:02 -0400)]
mark mips crt code as code

otherwise disassemblers treat it as data.

9 years agomark mips cancellable syscall code as code
Rich Felker [Mon, 25 May 2015 19:56:36 +0000 (15:56 -0400)]
mark mips cancellable syscall code as code

otherwise disassemblers treat it as data.

9 years agosimplify/shrink relocation processing in dynamic linker stage 1
Rich Felker [Mon, 25 May 2015 04:32:37 +0000 (00:32 -0400)]
simplify/shrink relocation processing in dynamic linker stage 1

the outer-loop approach made sense when we were also processing
DT_JMPREL, which might be in REL or RELA form, to avoid major code
duplication. commit 09db855b35709aa627d7055c57a98e1e471920ab removed
processing of DT_JMPREL, and in the remaining two tables, the format
(REL or RELA) is known by the name of the table. simply writing two
versions of the loop results in smaller and simpler code.

9 years agoremove processing of DT_JMPREL from dynamic linker stage 1 bootstrap
Rich Felker [Mon, 25 May 2015 04:25:56 +0000 (00:25 -0400)]
remove processing of DT_JMPREL from dynamic linker stage 1 bootstrap

the DT_JMPREL relocation table necessarily consists entirely of
JMP_SLOT (REL_PLT in internal nomenclature) relocations, which are
symbolic; they cannot be resolved in stage 1, so there is no point in
processing them.

9 years agofix stack alignment code in mips crt_arch.h
Rich Felker [Mon, 25 May 2015 03:03:47 +0000 (23:03 -0400)]
fix stack alignment code in mips crt_arch.h

the instruction used to align the stack, "and $sp, $sp, -8", does not
actually exist; it's expanded to 2 instructions using the 'at'
(assembler temporary) register, and thus cannot be used in a branch
delay slot. since alignment mod 16 commutes with subtracting 8, simply
swapping these two operations fixes the problem.

crt1.o was not affected because it's still being generated from a
dedicated asm source file. dlstart.lo was not affected because the
stack pointer it receives is already aligned by the kernel. but
Scrt1.o was affected in cases where the dynamic linker gave it a
misaligned stack pointer.

9 years agoadd .text section directive to all crt_arch.h files missing it
Rich Felker [Fri, 22 May 2015 05:50:05 +0000 (01:50 -0400)]
add .text section directive to all crt_arch.h files missing it

i386 and x86_64 versions already had the .text directive; other archs
did not. normally, top-level (file scope) __asm__ starts in the .text
section anyway, but problems were reported with some versions of
clang, and it seems preferable to set it explicitly anyway, at least
for the sake of consistency between archs.

9 years agoremove outdated and misleading comment in iconv.c
Rich Felker [Thu, 21 May 2015 21:06:28 +0000 (17:06 -0400)]
remove outdated and misleading comment in iconv.c

the comment claimed that EUC/GBK/Big5 are not implemented, which has
been incorrect since commit 19b4a0a20efc6b9df98b6a43536ecdd628ba4643.

9 years agoin iconv_open, accept "CHAR" and "" as aliases for "UTF-8"
Rich Felker [Thu, 21 May 2015 21:01:23 +0000 (17:01 -0400)]
in iconv_open, accept "CHAR" and "" as aliases for "UTF-8"

while not a requirement, it's common convention in other iconv
implementations to accept "CHAR" as an alias for nl_langinfo(CODESET),
meaning the encoding used for char[] strings in the current locale,
and also "" as an alternate form. supporting this is not costly and
improves compatibility.

9 years agofix inconsistency in a_and and a_or argument types on x86[_64]
Rich Felker [Wed, 20 May 2015 04:17:35 +0000 (00:17 -0400)]
fix inconsistency in a_and and a_or argument types on x86[_64]

conceptually, and on other archs, these functions take a pointer to
int, but in the i386, x86_64, and x32 versions of atomic.h, they took
a pointer to void instead.

9 years agoinline llsc atomics when building for sh4a
Bobby Bingham [Sun, 17 May 2015 18:46:38 +0000 (13:46 -0500)]
inline llsc atomics when building for sh4a

If we're building for sh4a, the compiler is already free to use
instructions only available on sh4a, so we can do the same and inline the
llsc atomics. If we're building for an older processor, we still do the
same runtime atomics selection as before.

9 years agoreprocess libc/ldso RELA relocations in stage 3 of dynamic linking
Rich Felker [Mon, 18 May 2015 20:51:54 +0000 (16:51 -0400)]
reprocess libc/ldso RELA relocations in stage 3 of dynamic linking

this fixes a regression on powerpc that was introduced in commit
f3ddd173806fd5c60b3f034528ca24542aecc5b9. global data accesses on
powerpc seem to be using a translation-unit-local GOT filled via
R_PPC_ADDR32 relocations rather than R_PPC_GLOB_DAT. being a non-GOT
relocation type, these were not reprocessed after adding the main
application and its libraries to the chain, causing libc code not to
see copy relocations in the main program, and therefore to use the
pre-copy-relocation addresses for global data objects (like environ).

the motivation for the dynamic linker only reprocessing GOT/PLT
relocation types in stage 3 is that these types always have a zero
addend, making them safe to process again even if the storage for the
addend has been clobbered. other relocation types which can be used
for address constants in initialized data objects may have non-zero
addends which will be clobbered during the first pass of relocation
processing if they're stored inline (REL form) rather than out-of-line
(RELA form).

powerpc generally uses only RELA, so this patch is sufficient to fix
the regression in practice, but is not fully general, and would not
suffice if an alternate toolchain generated REL for powerpc.

9 years agofix null pointer dereference in dcngettext under specific conditions
Rich Felker [Mon, 18 May 2015 16:11:25 +0000 (12:11 -0400)]
fix null pointer dereference in dcngettext under specific conditions

if setlocale has not been called, the current locale's messages_name
may be a null pointer. the code path where it's assumed to be non-null
was only reachable if bindtextdomain had already been called, which is
normally not done in programs which do not call setlocale, so the
omitted check went unnoticed.

patch from Void Linux, with description rewritten.